Saturday, June 30, 2007

Setting the time zone in FreeBSD

Couldn't figure out how to set the timezone on my FreeBSD router/server box. Found a mailing list post that suggested copying the appropriate file (in my case, PST8PDT) from /usr/share/zoneinfo to /etc/localtime. It worked!

Thursday, June 28, 2007

Protecting the server with mod_evasive

As I hinted in my report several days ago about this server suffering a DOS attack, I’ve taken some measures to prevent a repeat occurrence. One of them was to install the mod_evasive Apache module, which was suggested by a number of people.

(There’s also mod_security. It’s way more complex than I need right now, but would be worth looking at for a busier server.)

Initially I was skeptical, since mod_evasive doesn’t seem to be a very actively maintained project. But it looked so simple I decided to give it a try. Installing via FreeBSD ports was, as usual, nearly instantaneous. Configuration looks like this (I’ve omitted a few settings for simplicity’s sake, and these are not the actual numbers I’m using):


DOSPageCount 2
DOSPageInterval 1
DOSSiteCount 50
DOSSiteInterval 1
DOSBlockingPeriod 10

Simply put: “If any client makes more than two requests for a single URL per second, blacklist them for 10 seconds; if any client makes more than 50 requests total per second, blacklist them for 10 seconds.”

Additional requests during the blacklist period add another 10 seconds. DOSSiteCount is higher to accommodate media files; loading this single page has caused your browser to make seven separate requests to my server, for example, and many pages are more complex than that. But nobody has a legitimate reason to make multiple requests for the same resource more than once per second. Not with my sites, anyway.

When blacklisting is triggered, mod_evasive can send a notification email, write to a logfile, and/or pass the IP to a script for further processing (e.g adding the IP to firewall rules).

In the past four days, mod_evasive has blocked 42 IPs. Using my elite Unix shell skills I got the hostnames:

cat ips.txt | sort | xargs -L 1 host
The main thing I was looking for, and thankfully didn’t find, was search engine spiders — the last thing I want to do is block Google from crawling my sites. Otherwise, no really interesting patterns emerged. About half of the addresses were broadband connections, likely zombies.

One thing I like about having this measure in place is that it doesn’t privilege one form of stupidity over another: badly-written web crawlers, hyperactive blogspam scripts, and actual deliberate DOS attacks all get the same treatment.

Wednesday, June 27, 2007

Check Your Server Security

Sometimes it is possible that your server is compromised, but the actions made by attacker do not affect your server functionality, so you may never find that your machine was compromised.

So, is good from time to time to check your server security, to see if any strange activities/processes are in your system.

Check if your server resources are affected. You could check CPU usage by issuing top command. Look for applications/scripts that consume your CPU.

Check for strange processes with ps -awux command.

Check your /tmp directory and also your /var/tmp directory for scripts/binaries copied there.

When a server is compromised sometimes the attacker use it to host a IRC bot (like psybnc or eggdrop) that connects to port 6667. You could check if any of your applications connect to that port with sockstat:

#sockstat | grep 6667

If there's not much traffic on your server you could use netstat command to see if suspect connections are made.

#netstat -a

Install and run at regular period of times an rootkit finder application (for example /usr/ports/security/rkhunter).

Check your open ports with nmap. See if you have other open ports than the ones you use for your running services.

HTML Tips

Tip 1. Howto redirect a page to another webpage/website
---------------------------------------------------------------------------

Changing 'content' value to 5 will delay redirection with 5 seconds.
If you se time delay redirection is a good idea to put a message in tags
announcing your redirection in 5 seconds (or whaterver time period you want).


//html>
//head>
//meta http-equiv="REFRESH" content="0; URL=http://www.example.com">
///head>
///html>

Tuning for Web Server

Then you modify the following variables:

sysctl -w kern.ipc.nmbclusters=16384
sysctl -w kern.ipc.maxsockets=16384

Other tips:

set httpd simultaneous connections very high
you must know your performance characteristics, make graps with your performance, analyze your server parameters
use a dedicate server for your web server (do not mix with other server, like mail server)
httpd.conf (apache):StartServers should be high (default is 5, for a dedicate server make it higher

MaxRequestPerChild= 10000
Timeout (to get a TCP ACK for a GET request) should be 60 (default is 300)
MaxClients (FreeBSD) = 256
Tuning for a File Server
When tuning a FreeBSD Box for a File Server you must be aware that

large files are transferred
network connection live longer
less transfers are made

Then you modify the following variables.

sysctl -w kern.ipc.nmbclusters=1024Tuning for Mail Server
When tuning a FreeBSD Box for a Mail Server you must be aware that mail servers will need a very large number of network connections and small amount of data for a short period of time.

You can find how many network buffers you use:

netstat -m

Then you modify the following variables.

sysctl -w kern.ipc.nmbclusters=2048
sysctl -w kern.ipc.maxsockets=2048
Tuning a FreeBSD router
This is a work in progress mini howto. More informations will be added later. Also some aspects are about optimizing a pppoe server built with mpd.

If you've build a router with FreeBSD to serve a huge number of lan users some sysctl tunings can be done:

Add the following options to /etc/sysctl.conf

kern.polling.enable=1
kern.ipc.nmbcluster=32768
kern.ipc.maxsockbufs=2097152
kern.ipc.somaxconn=8192
kern.maxfiles=65536
kern.maxfilesperproc=32768
net.inet.tcp.delayed_ack=0
net.inet.tcp.sendspace=65535
net.inet.udp.recvspace=65535
net.inet.udp.maxdgram=57344
net.local.stream.recvspace=65535
net.local.stream.sendspace=65535

To be able to activate device polling you must recompile kernel with options DEVICE_POLLING and also your nic driver must support polling.

Also add the following options to /boot/loader.conf if you use pppoe server with mpd:

net.graph.maxalloc=512
net.graph.maxdgram=45000
net.graph.recvspace=45000

If you do not increase net.graph.maxdgram and net.graph.recvspace variables you will not be able to connect more than 130 pppoe users (with mpd).

If you've built your traffic shaper with pf packet filter and you use ALTQ HFSC algorythm you will have increase the maximum number of queues permitted by HFSC algorythm:

Edit file: /sys/contrib/altq/altq_hfsc.h
Modify #define HFSC_MAX_CLIENTS 64 to
#define HFSC_MAX_CLIENTS 500

And remember that HFSC is a linear algorythm, it will work fine for hundreads of queues but not for thousands.



sysctl -w kern.ipc.maxsockets=1024

Apache Tips

Tip 1. Configure Apache to require password for accessing a specific location
-------------------------------------------------------------------------------------------------------


Resource about configuring Apache to require password for accessing a specific location can be found here: http://www.freebsdonline.com/content/view/39/54/




Tip 2. Activate or deactivate listing of files within a directory
-------------------------------------------------------------------------------
To activate listing of files from your browser when accessing a specific directory from an Apache server,
within your tag for that specific path, add this:


Options Indexes FollowSymLinks


This will enable file listing for that directory.
If you have this enabled and you want to disable it change "Options" line with:


Options none


Tip 3. Howto Ignore .htaccess file for a specific directory
--------------------------------------------------------------------------
For example if you want Apache to ignore .htaccess file within a directory, between tags for that specific directory you will need the following line:


AllowOverride none

FreeBSD Hot Tips

Home Monitoring Hot Tips
FreeBSD Hot Tips
1. Show how big are files in a list of subdirectories, sorted by size (in the curent path)

du -s * |sort -rn | head


2. Show ICMP packets on interface fxp0:

tcpdump -i fxp0 'proto \icmp'


3. Display informations about Swap partition and other informations ("The pstat utility displays open file entry, swap space utilization, terminal state, and vnode data structures", from man page).

pstat -s


4. Display system statistics about your server (virtual memory usage, for example)

systat -vmstat

Administrator's way of monitoring

Monitoring a FreeBSD server from command line


netstat
systat
iftop and nload

Install nload to see your used bandwidth.
-----------------------------------------------
(/usr/ports/net/nload)

Usage:
#nload -i 1024 -o 1024 fxp0

where: -i 1024, incoming traffic, -o 1024 outgoing traffic, fxp0, your network interface. Change to your values.



Install iftop to see your server traffic.
------------------------------------------
(/usr/ports/net-mgmt/iftop)

Usage:
#iftop -i fxp0

where: fxp0 is your network interface.



Netstat
--------
Use netstat to find a lot of information regarding your server/network connections, routes.

#netstat -r # display your routing table

#netstat -a # display your active sockets for each network
protocol

for detalied informations please read man page: netstat(1).


Systat
-------
Use systat to display different statistics. Please read man page: systat(1).

Whitepaper - Secure Your FreeBSD Server

If you want to have a good security of your FreeBSD server, follow all of the following steps.


This article is new and will be updated on regular basis. If other articles from Security section are more general, this is desired to be a step by step howto secure your server.

If we are missing something please write us at
We asume that you've installed a FreeBSD server, cvsuped to last sources and recompiled the kernel and world (all sources).



Step 1. Secure your SSHd daemon
---------------------------------------------
There are few things that must be done to have to secure your SSH services.


a) First of all you must permit SSH access to your machine only for users you need:
This is done by adding the following line in /etc/ssh/sshd_config: AllowUsers john bob
After that restart your ssh service:


# /etc/rc.d/sshd restart


You could also permit SSH login to wheel group, adding in /etc/ssh/sshd_config the line:
AllowGroups wheel


b) Run your SSH service on other port. By default SSHd is running on port 22, which makes it vulnerable to a lot of automated tools (brute force exploits).
To acomplish this edit /etc/ssh/sshd_config, and add line
Port 456
Be carefull not to add a port that is already used for other service, otherwise won't work. Don't forget to restart the service after you've done modifications to config file but be aware that your shell will be disconnected, if you are doing it remotely and you will have to relogin to machine on the new port (456 for example).


c) Block multiple failed attempts to connect to ssh server. You can accomplish that by using an application available from ports.



d) Update SSH at regular times. Follow the security mailing list, and apply relevant security patches ASAP


e) If you login to your server via SSH only from known IPs, you could allow logins only from those IPs.


>>disabling password-interactive logins in ssh, allowing only publickeys


f) Always run SSH protocol 2 (which is enabled by default in SSH daemon).



g) Email you every time somebody log in as root. Another idea would be to edit /root/.cshrc file and add a line to email you when somebody log in as root, ading the date and time too.


h) If you offer SSH access to your users, enforce them to use secure passwords.
Passwords must be long, must contain letters and numbers, small and big cases, mixed, and not contain dictionary words. 8 characters usually at least is considered safe for a password, with lower/uppercase mixed latter and with numbers. Also change password at regular times, because old accounts/passwords can be compromised.


>>, there is some kind of PAM module that verifies the password's strength. you could give >>some info about this, and how to set it up



Step 2. Close services that you do not need
---------------------------------------------------------

Disable inetd, also close all unneeded processes. Scan your server with nmap (nmap -P0 server_ip) to see

if you have open ports to check if you have running services you are not aware of. Services can be stopped by disable them from /etc/rc.conf, by removing executable of scripts that launch them from /usr/local/etc/rc.d (chmod -x /usr/local/etc/rc.d/script_name.sh), or for some of them by commenting them in file /etc/inetd.conf,
then restarting inetd service, or if is possible removing ined service (by adding to /etc/rc.conf the following line: ined_enable="NO").
>>step2 is ain't done from rc.conf, it's done from the packet filter of the choice.





Step 3. Secure your console
-------------------------------------
a) Secure your console so nobody could boot into single mode and change root password in order to break in.

Edit /etc/ttys, change line
console none unknown off secure
to
console none unknown off insecure



>>step3 is not a so good idea. on large systems, there are often no users in the system, just the root>>account and they are protected phyisically




b) Disable reboot of machine using Ctrl+Alt+Del (kernel must be recompiled)
edit your configuration kernel file, add the following option and compile/reinstall the kernel:
options SC_DISABLE_REBOOT



Step 4. Scan for open ports
------------------------------------
To see if there are any open ports scan your server with a tool like nmap.
( /usr/ports/security/nmap). You will need to have ports open only for your needed services.
Do this process on regular basis.


Step 5. Setup server date and time and log advices
-------------------------------------------------------------------
I had to put this in because I've discovered many people forget to proper set date and time on a server and if incidents are reported date and time is crucial, otherwise all logs will have recorded a bad date. Setup a ntp service to syncronize time from a ntp server. Also do not use log rotate if you have a small volume of log files. If you have big size log files, use log rotate but implement log rotating at regular basis (weekly or monthly for example), setup log rotation to not override last logs, backup old logs, and use a Log server.


Step 6. Protect from DOS/DDOS.
------------------------------------
Some measures can be taken to add some level of protection to DOS attacks. Total protectin is almost impossible to achieve because when your server is flooded is already too late to do anything. You should contact your ISP. Also if you have multiple sources of attack is very hard to do something.

You will need to tune up some sysctl variable:
kern.ipc.somaxconn=32768 # to defend against SYN attacks

Increasing somaxconn variable SYN attacks to some level will have no effect (or low effect) on the availability of the server.

An attacker can use IP redirects to modify the routing table on your machine.
net.inet.icmp.drop_redirect=1
net.inet.icmp.log_redirect=1
net.inet.ip.redirect=0
net.inet6.ip6.redirect=0


Step 7. Make a checksum for your files
---------------------------------------------------
If your machine will be compromised, it will be useful to check the sum of your files, to see if was not modified. You can install an application like tripwire (/usr/ports/security/tripwire-131) to build a MD5 sum of your every file.


Step 8. Monitor server activities and email you an automated report once a day with security status, using Logwatch Perl Script (http://www2.logwatch.org:81/).



- don't use ftp services, instead use sftp to copy files


>>or step8 there is also gentoo's tenshi, and nagios, and cacti, and whatever


Step 9. Other security measures
------------------------------------------
net.inet.tcp.msl=7500
msl = maximum segment life = maximum amount of time to wait for an ACK in reply to SYN-ACK or FIN-ACK, in miliseconds

net.inet.tcp.blackhole=2
This variable defines what will happend when your machine receive a TCP packet on a closed port. (1 - SYN packets are dropped, 2 - all packets are dropped).

net.inet.udp.blackhole=1

net.inet.icmp.icmplim=50
This variable controls the maximum number of ICMP "Unreachable" and TCP RST to return at every second.

For the following NIC: dc, em, fxp, nge, rl, sis, turn on kernel DEVICE_POLLING option to reduce CPU time in processing inbound traffic.
After enabling in kernel config file and recompilling/installing the kernel the following sysctl variable must be configured.
kern.pooling.enable=1



>>and against SYN floods one can use pf's synproxy
>> security.bsd.see_other_uids=0

>>security.bsd.see_other_gids=0



>>grep jail /etc/defaults/rc.conf, finetuning if these, devfsing of thse


>> neutering the base system for targeted systems (such as dedicted webservers), check the example make.conf for this




Step 10. Setup a statefull firewall
--------------------------------------------
Using IPFW or PF you are able to setup a stateful firewall so only conections initiated from inside will pass the firewall when returning from outside.


Step 11. Use Jail whenever is possible (for Web Server or Mail server, or DNS Server)
---------------------------------------------------------------------------------------------------------
Jail helps you separating a web server filesystem and access from real server, so when is a security breach, the attacker will not have access to server's os, only to jailed machine. Setting up a Jail server in some cases is tricky but it worth the effort.


Step 12. Use a DMZ for your Web Server
----------------------------------------------------
Regarding step 11, Jail is good when you need a web server to run on your server, but the best way is to use DMZ. DMZ stands for Demilitarized Zone, and is another machine (or machines) connected to the server, on other network card (an isolated from LAN connection), with IP's from other subnet than your LAN. This machine will not be visible from LAN. On this machine will be run a web server. If you want that web server to be visible when accessing IP of your main server, then you can do port forwarding port 80 (or the whatever port is running the web server) from main server to the ip and port of DMZ machine.


Step 13. Check file permissions
------------------------------------------
Check setuid and setgid files on your server, to see if any unusual files are setup with that attributes. You can do that by issuing:


# find / -type f \ ( - perm 2000 -o perm -4000 \ ) -print


Step 14. Setup your kernel security level

-----------------------------------------------------
There are 5 security levels for FreeBSD from -1 to 3. The Level can be changed using kern.securelevel sysctl variable.


>>more to add here


Step 15. Remove unused options from Kernel

------------------------------------------------------------
Here are some options that can be removed from Kernel (unless you need them):

DEBUG - this is removed by default and shoud be left removed on a production server
IPv6, gif, faith - those must be enabled only if you need them
BPF - this is needed only if you have an IDS or tcpdump service on your server
KTRACE - this is used for debuging and unless you use it, it must be disabled
CD9660 - not needed on a secure server
MSDOSFS - not needed on a secure server
NFS - leave it only if you need it
USB - not needed on a server
UCONSOLE - not needed on a secure server


Step 16. Drop synfins

--------------------------

Configure your server to drop synfins. This is useful to hide from fingerprinting the OS, with tools like nmap. You must recompile kernel with option TCP_DROP_SYNFIN.
Then add in /etc/sysctl.conf:
net.inet.tcp.drop_synfin=1

Setting Up Jails in Freebsd 6

It seems that almost every year I need to update this tutorial. Some things change, and some things don't. This version is being done on FreeBSD 6.x. If you are using FreeBSD 5.x, feel free to look at my 5.x tutorial on Screaming Electron.



To start out, make sure you have your source tree installed for FreeBSD. If you do not have this, run /stand/sysinstall, go to Configure, Distributions, and then "src". After you have your system preped and ready for jails to be added, start planning out your virtual network.


In this tutorial, we are going to use our main interface as a switch. Each jail will be in the same collision domain, but they can be subnetted, or even put as their own networks. For now, we'll stick with the same network, and after this tutorial, you shouldn't have a problem changing the network to your needs.



First I'm going to set the IP to 10.0.0.86, and then run a jail off the main interface.





# ifconfig em0 10.0.0.86 255.255.255.255

# ifconfig em0 inet alias 10.0.0.88 netmask 255.255.255.255

# ifconfig em0



CODE:
em0: flags=8843 mtu 1500
options=8
inet6 fe80::204:5aff:fe6f:1d0c%dc0 prefixlen 64 scopeid 0x1
inet 10.0.0.86 netmask 0xffffff00 broadcast 192.168.115.255
inet 10.0.0.88 netmask 0xffffffff broadcast 192.168.115.181
ether 00:04:5a:6f:1d:0c
media: Ethernet autoselect (100baseTX )
status: active





Ok. So now we have our main interface at 10.0.0.86 and our aliased IP at 10.0.0.88. Since we don't want any inetd services listening on the aliased IP, we need to add a line to the /etc/rc.conf file.




inetd_flags="-wW -a 10.0.0.86"






Now to make the jail. First make the directory you want the jail in.



# mkdir /usr/jail/server1







Then we make the virtual system.



# cd /usr/src

# make world DESTDIR=/usr/jail/server1

# cd etc

# make distribution DESTDIR=/usr/jail/server1

# cd /usr/jail/server1

# ln -sf /dev/null kernel







Once this is all done your jail is built and ready to be set. First, a few minor details to the setup.




# touch /usr/jail/server1/etc/fstab

# cat /etc/resolv.conf > /usr/jail/server1/etc/resolv.conf







So now we are ready to configure the jail for the first time. We start the jail with the jail command, like so:



# jail /usr/jail/server1 jail1.prison.com 10.0.0.88 /bin/sh







You will then be dropped to a new shell inside the jail. First, set your root password with 'passwd' or with 'sysinstall'. Also setup a user account to use when using SSH to enter. Make sure to also run 'newaliases' while in this environment, otherwise you will have issues with your jail starting with sendmail. Next, add the SSH enable line into your /etc/rc.conf (in the jail).




sshd_enable="YES"






Once you have this done, type 'exit' to leave the jail. Now, we need to mount the proc and dev filesystems for our jail.



# mount -t procfs proc /usr/jail/server1/proc

# mount -t devfs dev /usr/jail/server1/dev

NOTE: If you are having trouble with SSH finding a console, make sure this is mounted







and now to start it all up:



# jail /usr/jail/server1 jail1.prison.com 10.0.0.88 /bin/sh /etc/rc







Now you should be able to ssh to your new jail, and start configuring the services you wish to run inside.



To double check that your jail is running, run 'jls'



# jls



CODE:
JID IP Address Hostname Path
1 10.0.0.88 jail1.prision.com /usr/jail/server1






Well, now we have a fully functioning jail. Now we need to set it up so we don't have to start it manually. We are going to add a few more values to the rc.conf. You can probably put this anywhere in the rc.conf, but in good practice, you should put it behind main host specific entries (i.e. hostname, ifconfig, defaultroute, etc).




ifconfig_em0_alias0="inet 10.0.0.88 netmask 0xffffffff"

jail_enable="YES"

jail_list="jail1"

jail_socket_unixproute_only="YES"

jail_jail1_rootdir="/usr/jail/server1"

jail_jail1_hostname="jail.prison.com"

jail_jail1_ip="10.0.0.88"

jail_jail1_exec_start="/bin/sh /etc/rc"

jail_jail1_devfs_enable="YES"

jail_jail1_devfs_ruleset="devfsrules_jail"





Here we set the jail config name inside rc.conf, and the settings for that jail "jail_jail1*". We also set the global setting, "jail_socket_unixproute_only", to only allow TCP/IP to be used inside the jail.




Now, if we want to administer the jail without using SSH, we can always use the jexec command.




CODE:
jexec




# jexec 1 /bin/sh



This will drop you right into a Bourne in the jail (If it doesn't, run jls, and make sure the JID is correct). Now that we have the environment setup, you might want to start installing some ports. Before you go and drop the ports collection into your jail, why not make it to where you don't have to use all of that space? Drop out of your jail shell, if you are in one, to setup the ports from the main to the jail. Since symlinks do not work in a jail (and we don't want them to), login with your root user, or use sudo to create a ports dir, and mount a nullfs copy of the ports.



# mkdir /usr/jail/server1/usr/ports

# mount_nullfs /usr/ports /usr/jail/server1/usr/ports
############

>Description:
In "Setting up a Jail Directory Tree", the following is mentioned:

mount_devfs devfs $D/dev

It should also be mentioned in "Starting the Jail":

ifconfig ed0 inet alias 192.168.11.100/32
mount_devfs devfs /data/jail/192.168.11.100/dev
mount -t procfs proc /data/jail/192.168.11.100/proc
jail /data/jail/192.168.11.100 testhostname 192.168.11.100 \
/bin/sh /etc/rc

######################


If for any reason that you need to find processes in the jail, do a "ps ax | grep J" in a shell of the main system.



Now you should be all ready to go with your jail, and many more to come. Be sure that your network service applications in the jail are listening to the aliased IP, otherwise you might have issues connecting to the server with those services. In this sort of setup, you shouldn't have too much of a problem.

Monday, June 25, 2007

Changing the root password on MySQL

Many distributions of Linux have an option to install MySQL. In this case, or even if you compile MySQL, the default password is blank. MySQL can also run on Windows boxen. When you install MySQL, make sure that you set the root password. You can do this:

root@u-1:/home/u-1# mysql -u root mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 1 to server version: 3.23.47
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
mysql> SET PASSWORD FOR root@localhost=PASSWORD('rubberchicken');
Query OK, 0 rows affected (0.06 sec)
mysql>



In this example, we set the root password to rubberchicken. Note from the above that the password wasn't set. If we try this again, we need to use the -p option to enter the password:

root@u-1:/home/u-1# mysql -u root mysql
ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO)
root@u-1:/home/u-1# mysql -u root -p mysql
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 3 to server version: 3.23.47
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
mysql>



To reset a root password that you forgot (using paths on our system):

[root@host root]#killall mysqld
[root@host root]#/usr/libexec/mysqld -Sg --user=root &



You may have better luck with:

mysqld --skip-grant-tables --user=root



Go back into MySQL with the client:

[root@host root]# mysql
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 1 to server version: 3.23.41
Type 'help;' or 'h' for help. Type 'c' to clear the buffer.
mysql> USE mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> UPDATE user
-> SET password=password("newpassword")
-> WHERE user="root";
Query OK, 2 rows affected (0.04 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
mysql> exit;
[root@host root]#killall mysqld



Start MySQL the normal way for your system, and all is good. For Red Hat this is:

/etc/init.d/mysqld start

Sunday, June 24, 2007

Creating a FreeBSD Jail

http://www.section6.net/wiki/index.php/Creating_a_FreeBSD_Jail

Introduction
Jails are a great way to secure your processes to a virtual system. Though they have more overhead than chroot, (which basically just restricts the root of a process) a jail uses a virtual machine to house your process or processes. This means that far more restrictions can be placed on the jail, and there's no "breaking out" as can be done with chroot (see links in references).

A few notes first of all. It's very true what they say in the man page about it being easier to make a fat jail, and scale down to a thin one than vice versa. A few weeks of research (and many make worlds) have helped me discover that.

Also note that as of FreeBSD 5.4 (and likely 6.0) there is no IPv6 support for jails. This is unfortunate because jails tend to monopolize address space after making quite a few of them and address space is what IPv6 is all about. Sure there's NAT but everyone knows NAT is an ugly hack these days. I can only hope that IPv6 will be supported soon.

[edit] Jail Creation Techniques
From what I've seen there are three primary ways of creating jails.

[edit] MiniBSD
I've heard reports of people using [https://neon1.net/misc/minibsd.html MiniBSD] to do this, but I haven't had much luck with it, and I have yet to see a howto explaining how they made it work, it's a great idea of making an initial thin jail but there's a million things that can go wrong since it's very minimal and the service(s) you are trying to run may have dependancy issues.

[edit] Using /stand/sysinstall
Other howtos tell to use /stand/sysinstall to go out to the net, download the system binaries, and install specific distributions from the installer. I've had little luck with this as well since you run into the problem of not having an interface set up for the installer to use. There's probably a way to do this but none of the howtos I tried did a very good job of explaining how.

[edit] Using make world
This is the way I'll use here in this tutorial and the way explained in the manpage. You can customize the make file to scale down your distribution and set some optomization flags for your system. The primary drawback is the time it takes to build the world which can be hours depending on your system.

[edit] Getting services to not listen to *
First off, we should make sure we get the system so that we have nothing listening on *, to check what what we need to modify issue this command

sockstat|grep "\*:[0-9]"
This should give you a synopsys of all the processes and ports you need to trim down. Here are some hints with your ipv4 addr being 10.0.0.1 and your ipv6 addr being 2002::7ea9

sshd:

edit /etc/ssh/sshd_config
change ListenAddress derivative
ListenAddress 10.0.0.1
ListenAddress 2002::7ea9
httpd

edit /usr/local/etc/apache/httpd.conf (and ssl.conf for https)
change Listen derivative
Listen 10.0.0.1:80
Listen [2002::7ea9]:80
slapd

edit /etc/rc.conf
change slapd_flags
slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://10.0.0.1/ ldap://127.0.0.1/ ldap://[2002::7ea9]/"'
inetd

edit /etc/rc.conf
change inetd_flags=
inetd_flags="-wW -a yourhost.example.com"
mysql

edit /etc/my.cnf
bind-address=10.0.0.1
postfix edit /usr/local/etc/postfix/main.cf

change inet_interfaces
inet_interfaces = [2002::7ea9], 10.0.0.242
samba (this will get you most of the way there)

edit /usr/local/etc/smb.conf
change the following:
interfaces = 10.0.0.242/24 127.0.0.1
socket address = 10.0.0.242
bind interfaces only = yes
note: if you don't need wins lookups and netbios name translation

you can safely disable nmbd. There doesn't seem to be a way
for nmb to not listen to *:138 anyhow.
To disable nmb go to /etc/rc.conf and replace samba_enable="YES" with smbd_enable="YES"

openntpd (xntpd listens on all and cannot be changed)

*edit /usr/local/etc/ntpd.conf
listen on 10.0.0.1
listen on 2002::7ea9
syslogd

*edit /etc/rc.conf
syslogd_flags="-s -s" #For no listening
syslogd_flags="-a 10.0.0.1"
bind

edit your named.conf (may be in /var/named/etc/named.conf)
In the options section:
listen-on { 10.0.0.242; };
listen-on-v6 port 53 { 2002:d8fe:10f1:6:202:b3ff:fea9:7ea9; };
query-source address 10.0.0.242 port *;
query-source-v6 address 2002:d8fe:10f1:6:202:b3ff:fea9:7ea9 port *;
Unrealircd

In the listen section:
listen[::ffff:10.0.0.1]:6667
listen[2002::7ea9]:6667
In the "set { dns {" section
bind-ip 10.0.0.242;
[edit] Building your jail for the first time
[edit] Creating an appropriate make.conf
You'll need to run make world (or make installworld) to create your jail. If you don't want to install the whole kitchen sink you can use the make.conf below. You can put it in your jail for future use and it'll be used by future port builds inside your jail. One thing I've noticed is that make installworld doesn't seem to respect and MAKE_CONF or __MAKE_CONF variables passed to it so we'll just put it in /etc/make.conf for now.

Lets first back our current make.conf up:

cp /etc/make.conf /etc/make.conf.bak
And new one in there. Keep in mind, depending on what you want to use this jail for you may want to modify this make.conf. For me this has worked on building a variety of services from ports (inside the jail). I like to name the below file make.conf.jail and copy it to make.conf, then copy make.conf.bak back to make.conf when I'm done building the jail.

NO_ACPI= true # do not build acpiconf(8) and related programs
NO_BOOT= true # do not build boot blocks and loader
NO_BLUETOOTH= true # do not build Bluetooth related stuff
NO_FORTRAN= true # do not build g77 and related libraries
NO_GDB= true # do not build GDB
NO_GPIB= true # do not build GPIB support
NO_I4B= true # do not build isdn4bsd package
NO_IPFILTER= true # do not build IP Filter package
NO_PF= true # do not build PF firewall package
NO_AUTHPF= true # do not build and install authpf (setuid/gid)
NO_KERBEROS= true # do not build and install Kerberos 5 (KTH Heimdal)
NO_LPR= true # do not build lpr and related programs
NO_MAILWRAPPER=true # do not build the mailwrapper(8) MTA selector
NO_MODULES= true # do not build modules with the kernel
NO_NETCAT= true # do not build netcat
NO_NIS= true # do not build NIS support and related programs
NO_SENDMAIL= true # do not build sendmail and related programs
NO_SHAREDOCS= true # do not build the 4.4BSD legacy docs
NO_USB= true # do not build usbd(8) and related programs
NO_VINUM= true # do not build Vinum utilities
NO_ATM= true # do not build ATM related programs and libraries
NO_CRYPT= true # do not build any crypto code
NO_GAMES= true # do not build games (games/ subdir)
NO_INFO= true # do not make or install info files
NO_MAN= true # do not build manual pages
NO_PROFILE= true # Avoid compiling profiled libraries

# BIND OPTIONS
NO_BIND= true # Do not build any part of BIND
NO_BIND_DNSSEC= true # Do not build dnssec-keygen, dnssec-signzone
NO_BIND_ETC= true # Do not install files to /etc/namedb
NO_BIND_LIBS_LWRES= true # Do not install the lwres library
NO_BIND_MTREE= true # Do not run mtree to create chroot directories
NO_BIND_NAMED= true # Do not build named, rndc, lwresd, etc.
[edit] Building the Jail
Now for actually building your jail...

I'm defining JAILDIR here because I'm going to use it in a shellscript style example throughout the rest of this howto.

# Let's first make some directories
JAILDIR=/home/jail
mkdir -p $JAILDIR/dev
mkdir -p $JAILDIR/etc
mkdir -p $JAILDIR/usr/tmp
chmod 777 $JAILDIR/usr/tmp

cd /usr/src/

# You can replace the below with make installworld if you've built your
# world previously
make buildworld
make installworld DESTDIR=$JAILDIR
cd /usr/src/etc
cp /etc/resolv.conf $JAILDIR

make distribution DESTDIR=$JAILDIR NO_OPENSSH=YES NO_OPENSSL=YES
cd $JAILDIR

# At this point we'll mount devfs, and then hide the unneeded devs
mount_devfs devfs $JAILDIR/dev
devfs -m $JAILDIR/dev rule -s 4 applyset

# Create a null kernel
ln -s dev/null kernel

# Quell warnings about fstab
touch $JAILDIR/etc/fstab

# Use our existing resolv.conf
cp /etc/resolv.conf $JAILDIR/etc/resolv.conf

# Copy our settings for ssl
mkdir -p $JAILDIR/etc/ssl
mkdir -p $JAILDIR/usr/local/openssl
cp /etc/ssl/openssl.cnf $JAILDIR/etc/ssl
cd $JAILDIR/usr/local/openssl/
ln -s ../../../etc/ssl/openssl.cnf openssl.cnf

Make a decent rc.conf:

hostname="jail.example.com" # Set this!
ifconfig_em0="inet 10.0.0.20 netmask 255.255.255.255"
defaultrouter="10.0.0.1" # Set to default gateway (or NO).
clear_tmp_enable="YES" # Clear /tmp at startup.
# Once you set your jail up you may want to consider adding a good securelevel:
# Same as sysctl -w kern.securelevel=3
kern_securelevel_enable="YES" # kernel security level (see init(8)),
kern_securelevel="3"

You'll also want to make an alias on your interface for the ip above so we'll do something like:

ifconfig em0 10.0.0.20 netmask 255.255.255.255 alias
Now you'll want to have devfs inside your jail, so to get it working for the first time do this:

mount_devfs devfs $JAILDIR/devfs
And finally, copy your original make.conf back.

cp /etc/make.conf.bak /etc/make.conf
[edit] Starting the jail for the first time
OPTIONAL (but probably necessary): You'll want to mount /usr/ports and /usr/src so you can install ports inside your jail, unless you have another way you want to do this (such as downloading packages).

mount_nullfs /usr/ports $JAILDIR
mount_nullfs /usr/src $JAILDIR
Now we can start our jail

jail $JAILDIR jail.example.com 10.0.0.20 /bin/sh
Once inside the jail you'll want to start services:

/bin/sh /etc/rc
While you're here you'll want to edit your password file since if someone breaks into your jail, and starts cracking it you won't want them to have the same passwords as your root system has. Also remove all users you don't need in the jail:

vipw
passwd root
From here, assuming all went well you can do something like:

cd /usr/ports/security/openssh
make install clean
And build your port(s) inside your jail. Once you're finished be sure to unmount the directories so a compromised jail can't build more ports.


If you have trouble getting your programs to start inside your jail you can use the methods I outlined in [Chrooting_an_Eggdrop#Figuring_out_what_eggdrop_needs | my chroot tutorial]]. I've verifed that truss works correctly in a jail so between ldd and truss you should be set.

Also note that if you try to start your jail with just:

jail $JAILDIR jail.example.com 10.0.0.20 /bin/sh /etc/rc
but you have no services/daemons/programs set to run, the jail will simply start and then exit since there's nothing running inside.

[edit] Getting it to start automatically
You'll now need to put your settings in /etc/rc.conf First put the alias you jail has in there:

ifconfig_em0_alias0="inet 10.0.0.20 netmask 0xffffffff"
[edit] Editing the rc.conf
For those of you that are looking to make your own rc script, I don't recommend it. I've found issues getting devfs rules to be applied with the a script, and really this way is much easier. It's also the standard way and you can attach to jails later on quite easily without using screen (read below).

Here's the standard rc.conf way of getting your jail to run at startup:

jail_enable="YES" # Set to NO to disable starting of any jails
jail_list="cell" # Space separated list of names of jails
jail_set_hostname_allow="NO" # Allow root user in a jail to change its hostname
jail_socket_unixiproute_only="YES" # Route only TCP/IP within a jail

jail_cell_rootdir="/usr/home/prison/cell"
jail_cell_hostname="cell.example.com"
jail_cell_ip="10.0.0.20"
jail_cell_exec_start="/bin/sh /etc/rc"
jail_cell_devfs_enable="YES"
jail_cell_devfs_ruleset="devfsrules_jail"
[edit] Jail maintenance
Of course from time to time you may have to upgrade ports in your jail, or the world in the jail itself. This isn't a big deal either. Instead of using jail (which makes its own IP address and everything) we can use chroot instead which is similar since all we're using is a simple shell and then we'll be done with it.

First mount the dirs so they're accessable in the chroot:

mount_nullfs /usr/ports $JAILDIR
mount_nullfs /usr/src $JAILDIR
Connect to your jail: find the jail id of the jail you are running with jls:

#jls
JID IP Address Hostname Path
1 10.0.0.20 cell.example.com /usr/home/prison/cell
Now connect to it using the JID:

jexec 1 /bin/sh
To upgrade your world:

cd /usr/src
make buildworld
make installworld
NOTE: If you've just done make buildworld previously you can do make installworld and install all the newly compiled binaries again.

To build a port:

cd /usr/ports/sysutils/example
make install clean
NOTE: You may also want to install portupgrade to make port management easier.

When you're done just exit:

exit
[edit] Integrating Portaudit
You'll notice that portaudit security check only checks the root server, but none of the jails. There are many ways around this, but here's one:

Create a shell script in a place you keep custom shell scripts. We'll use /root/bin/metaportaudit.sh

#!/bin/sh

JAILDIR=/usr/home/prison/
JAILS="irc www mysql"
TMPDIR="/tmp"

# First lets audit the root server
/usr/local/sbin/portaudit -a

# Now Lets create temp files of ports in the jails,
# audit the root server all jails
# and delete the temp files
cd $TMPDIR
for jail in $JAILS; do
echo ""
echo "Checking for packages with security vulnerabilities in jail \"$jail\":"
echo ""
ls -1 $JAILDIR/$jail/var/db/pkg > $TMPDIR/$jail.paf
/usr/local/sbin/portaudit -f $TMPDIR/$jail.paf
rm $TMPDIR/$jail.paf
done
Now lets edit /usr/local/etc/periodic/security on about line 55
you'll want to change:

echo
echo /usr/local/sbin/portaudit -a |
su -fm "${daily_status_security_portaudit_user:-nobody}" || rc=$?
to

echo
echo /root/bin/metaportaudit.sh -a |
su -fm "${daily_status_security_portaudit_user:-nobody}" || rc=$?



[edit] Jails in Linux
Now you may think "well I have to use Linux, because xapplication only works on Linux!" Well there's hope. You can mess around with the bsdjail patch, or you can install vserver (which has packages in Debian). There's a great tutorial on vserver in Debian here:
Running_Vservers_on_Debian

Advanced SSH security tips and tricks

http://www.linux.com/articles/61061?theme=print
In this article I'll show you some simple tricks to help you tighten security for your secure shell (SSH) service.
The SSH server configuration file is located in /etc/ssh/sshd_conf. You need to restart the SSH service after every change you make to that file in order for changes to take effect.

Change SSH listening port

By default, SSH listens for connections on port 22. Attackers use port scanner software to see whether hosts are running an SSH service. It's wise to change the SSH port to a number higher than 1024 because most port scanners (including nmap) by default don't scan high ports.

Open the /etc/ssh/sshd_config file and look for the line that says:

Port 22

Change the port number and restart the SSH service:

/etc/init.d/ssh restart

Allow only SSH protocol 2

There are two versions of the SSH protocol. Using SSH protocol 2 only is much more secure; SSH protocol 1 is subject to security issues including man-in-the-middle and insertion attacks. Edit /etc/ssh/sshd_config and look for the line that says:

Protocol 2,1

Change the line so it says only protocol 2.

Allow only specific users to log in via SSH

You should not permit root logins via SSH, because this is a big and unnecessary security risk. If an attacker gains root login for your system, he can do more damage than if he gains normal user login. Configure SSH server so that root user is not allowed to log in. Find the line that says:

PermitRootLogin yes

Change yes to no and restart the service. You can then log in with any other defined user and switch to user root if you want to become a superuser.

It is wise to create a dummy local user with absolutely no rights on the system and use that user to login into SSH. That way no harm can be done if the user account is compromised. When creating this user, make sure it's in the wheel group, so that you can switch to superuser.

If you would like to have a list of users who are the only ones able to log in via SSH, you can specify them in the sshd_config file. For example, let's say I want to allow users anze, dasa, and kimy to log in via SSH. At the end of sshd_config file I would add a line like this:

AllowUsers anze dasa kimy

Create a custom SSH banner

If you would like any user who connects to your SSH service to see a specific message, you can create a custom SSH banner. Simply create a text file (in my example in /etc/ssh-banner.txt) and put any kind of text message in it; for example:

*****************************************************************
*This is a private SSH service. You are not supposed to be here.*
*Please leave immediately. *
*****************************************************************

When done editing, save the file. In the sshd_conf file, find a line that says:

#Banner /etc/issue.net

Uncomment the line and change the path to your custom SSH banner text file.

Using DSA public key authentication

Instead of using login names and passwords for SSH authentication, you can use DSA public keys for authentication. Note that you can have both login names and DSA public key authentication enabled at the same time. Having a DSA public keys authentication enabled makes your system bulletproof against dictionary attacks, because you don't need a login name and password to log in into SSH service. Instead, you need a pair of DSA keys -- one public and one private. You keep the private key on your machine and copy the public key to the server. When you want to log in to an SSH session, the server checks the keys, and if they match, you are dropped into the shell. If the keys don't match, you are disconnected.

In this example the private machine (from which I will connect to the server) is station1 and the server machine is server1. On both machines I have the same home folder; this won't work if the home folders are different on client and server machine. First you need to create a pair of keys on your private machine with the command ~$ ssh-keygen -t dsa. You'll be prompted for a pass-phrase for your private key, but you can leave it blank because this is not a recommended method. A key pair is generated: your private key is located in ~/.ssh/id_dsa and your public key is located in .ssh/id_dsa.pub.

Next, copy the contents of ~/.ssh/id_dsa.pub to server1 into the ~/.ssh/authorized_keys file. The content of ~/.ssh/id_dsa.pub file should look something like this:

~$ cat .ssh/id_dsa.pub
ssh-dss AAAAB3NzaC1kc3MAAACBAM7K7vkK5C90RsvOhiHDUROvYbNgr7YEqtrdfFCUVwMWcJYDusNG
AIC0oZkBWLnmDu+y6ZOjNPOTtPnpEX0kRoH79maX8NZbBD4aUV91lbG7z604ZTdrLZVSFhCI/Fm4yROH
Ge0FO7FV4lGCUIlqa55+QP9Vvco7qyBdIpDuNV0LAAAAFQC/9ILjqII7nM7aKxIBPDrQwKNyPQAAAIEA
q+OJC8+OYIOeXcW8qcB6LDIBXJV0UT0rrUtFVo1BN39cAWz5puFe7eplmr6t7Ljl7JdkfEA5De0k3WDs
9/rD1tJ6UfqSRc2qPzbn0p0j89LPIjdMMSISQqaKO4m2fO2VJcgCWvsghIoD0AMRC7ngIe6btaNIhBbq
ri10RGL5gh4AAACAJj1/rV7iktOYuVyqV3BAz3JHoaf+H/dUDtX+wuTuJpl+tfDf61rbWOqrARuHFRF0
Tu/Rx4oOZzadLQovafqrDnU/No0Zge+WVXdd4ol1YmUlRkqp8vc20ws5mLVP34fST1amc0YNeBp28EQi
0xPEFUD0IXzZtXtHVLziA1/NuzY= anze@station1.example.com

If the file ~/.ssh/authorized_keys already exists, append the contents of the file ~/.ssh/id_dsa.pub to the file ~/.ssh/authorized_keys on server1. The only thing left to do is to set the correct permissions of ~/.ssh/authorized_keys file on server1:

~$ chmod 600 ~/.ssh/authorized_keys

Now, configure the sshd_conf file to use the DSA keys authentication. Make sure you have the following three lines uncommented:

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile %h/.ssh/authorized_keys

Restart the service. If you configured everything correctly, you should now be able to SSH to your server and fall directly into your home folder without any interaction.

If you would like to use DSA authentication only, make sure you uncomment and change the PasswordAuthentication line in sshd_config from yes to no:

PasswordAuthentication no

If anyone tries to connect to your SSH service and doesn't have a public key on the server, he will be rejected without even seeing the login prompt with this error:

Permission denied (publickey).

Using TCP wrappers to allow only specific hosts to connect

This approach is useful if you would like to allow only specific hosts on a network to be able to connect to your SSH service, but you don't want to use or mess up your iptables configuration. Instead, you can use TCP wrappers; in this case the sshd TCP wrapper. I will make a rule to allow only hosts on my local subnet 192.168.1.0/24 and remote host 193.180.177.13 to connect to my SSH service.

By default TCP wrappers first look in the /etc/hosts.deny file to see what hosts are denied for what service. Next, TCP wrapper looks in /etc/hosts.allow file to see if there are any rules that would allow hosts to connect to a specific service. I'll create a rule like this in /etc/hosts.deny:

sshd: ALL

This means that by default all hosts are forbidden to access the SSH service. This needs to be here, otherwise all hosts would have access to the SSH service, since TCP wrappers first looks into hosts.deny file and if there is no rule regarding blocking SSH service, any host can connect.

Next, create a rule in /etc/hosts.allow to allow only specific hosts (as defined earlier) to use the SSH service:

sshd: 192.168.1 193.180.177.13

Now only hosts from the 192.168.1.0/24 network and the 193.180.177.13 host can access the SSH service. All other hosts are disconnected before they even get to the login prompt, and receive an error like this:

ssh_exchange_identification: Connection closed by remote host

Using iptables to allow only specific hosts to connect

An alternative to TCP wrappers (although you can use both at the same time) is limiting SSH access with iptables. Here's a simple example of how you can allow only a specific host to connect to your SSH service:

~# iptables -A INPUT -p tcp -m state --state NEW --source 193.180.177.13 --dport 22 -j ACCEPT

And make sure no one else has access to SSH service:

~# iptables -A INPUT -p tcp --dport 22 -j DROP

Save your new rules and you're all done.

SSH time-lock tricks

You can also use different iptables parameters to limit connections to the SSH service for specific time periods. You can use the /second, /minute, /hour, or /day switch in any of the following examples.

In the first example, if a user enters the wrong password, access to the SSH service is blocked for one minute, and the user gets only one login try per minute from that moment on:

~# iptables -A INPUT -p tcp -m state --syn --state NEW --dport 22 -m limit --limit 1/minute --limit-burst 1 -j ACCEPT
~# iptables -A INPUT -p tcp -m state --syn --state NEW --dport 22 -j DROP

In a second example, iptables are set to allow only host 193.180.177.13 to connect to the SSH service. After three failed login tries, iptables allows the host only one login try per minute:

~# iptables -A INPUT -p tcp -s 193.180.177.13 -m state --syn --state NEW --dport 22 -m limit --limit 1/minute --limit-burst 1 -j ACCEPT
~# iptables -A INPUT -p tcp -s 193.180.177.13 -m state --syn --state NEW --dport 22 -j DROP

Conclusion

These features are not hard to configure, but they are very powerful techniques for securing your SSH service. It's a small price to pay for a good night's sleep.

Read in the original layout at: http://www.linux.com/articles/61061
If shutting off telnet access and insisting that all system-to-system connections use ssh isn't enough to toughen your system's hide, here's another way to make your servers just a little more difficult to access -- run ssh on a non-standard port. Unless unwelcome users are pointing port scanners at the system to detect active ports, they are not likely to figure out why they're not able to log in. While there are, of course, many ways to prevent normal users from logging into a system, this is one which provides a way to reduce access to a system while changing almost nothing about its configuration.

SSH servers almost always run on port 22. That port is, after all, the well known port that is assigned to the service. If you're not feeling particularly devious, you might run the service on port 2222 instead or you might run it on some seemingly random number such as 9140 or 6188. Any unused port above 1024 (and below 65537) will do.

To change the port that ssh runs on, edit its configuration file. You might find this file in /etc/ssh or /usr/local/etc/ssh or a similar directory. To make the switch, all you need to do is change the line that reads "Port 22" or "#Port 22" (a commented-out port indicates that the default port will be used) to your new value and then restart your ssh daemon, sshd.

Once ssh is running on a non-standard port, connection attempts to the system will fail with messages such as these:


boson> ssh fermion
ssh: connect to address ::1 port 22: Connection refused
ssh: connect to address 127.0.0.1 port 22: Connection refused


Most visitors will simply assume that the system is not in its normal multiuser mode or that ssh has been disabled entirely. Meanwhile, the group of people to whom the new port has been divulged can gain access to the system by using modified ssh commands.

To log into a system that is running ssh on an unusual port, include the port number in the ssh command like this:

boson> ssh -p 6188 fermion



The -p argument should specify the port that ssh is listening on. The scp command to use when your ssh daemon is running on an unusual port uses a similar syntax but, for some inexplicable reason, uses a capitalized P instead of a lowercase p to specify the connection port. An scp command for an unusual ssh port would, therefore, look something like this:


boson> scp -P 6188 fermion:/opt/data/config.conf .



If the group of people to whom you have provided the port have a hard time remembering to type the -p and -P arguments with their ssh and scp commands, you can advise them to establish an alias to accommodate the change. For example, typing this command in bash or related shells with redefine ssh to include the odd port number:


boson> alias ssh="ssh -p 6188"



This command does the same sort of thing for scp:
boson> alias scp="scp -P 6188"



With these aliases in place, your users can then go back to typing their regular commands.

Saturday, June 23, 2007

安裝subversion

這篇文件說明快速安裝的方法, 文章的版號及最後編修時間是:
$Id$

==============
以 root 的權限
==============

1. 打 vipw, 加入底下兩行

bbs::9999:99::0:0:Ptt BBS:/home/bbs:/home/bbs/bin/bbsrf
bbsadm::9999:99::0:0:Ptt BBS:/home/bbs:/bin/csh

2. 執行 passwd bbsadm 設 bbsadm的密碼
3. 在 /etc/group 中加入一行

bbs:*:99:

4. 執行 mkdir /home/bbs
5. 執行 chown bbs:bbs /home/bbs
6. 執行 chmod 700 /home/bbs

====================
以下用 bbsadm 的身份
====================

7. 您可以透過下列方式下載到本站的原始程式碼:
a.置於 https://OpenSVN.csie.org/pttbbs/trunk/
這是目前主要開發的版本, 也是批踢踢實業坊和批踢踢兔兩個站台
所使用的版本. 在這個版本中含有最新的程式, 但是可能會不穩定,
有 bug, 甚至和之前的版本不相容. 建議您有基礎的程式能力, 並
隨時注意 PttCurrent 看板 (在 telnet://ptt.cc中, 或可以使用
網頁版本 http://www.ptt.cc/bbs/PttCurrent/index.html) , 尤
其當您在更新程式的時候.
a)至 http://fs.ptt.cc 抓得每日自動製作的 snapshot ,
通常檔名長的會像是 pttbbs-DATE.tar.gz
再解開該檔即可: tar zxvf pttbbs-DATE.tar.gz

b)直接抓取 http://OpenSVN.csie.org/pttbbs/trunk/pttbbs下的所有資料.
如 wget -r -np http://OpenSVN.csie.org/pttbbs/trunk/pttbbs

c)透過 subversion 聯繫 pttbbs version control repository(註4)
再執行 svn checkout http://OpenSVN.csie.org/pttbbs/trunk/pttbbs

其中不論您以方式 a, b 取得源碼, 您都可以在該目錄下直接透過 svn update
更新至 pttbbs 最新的源碼. 如:
cd /home/bbs/pttbbs; svn update
(須先安裝 subversion, 見註4)

8. 切換到 pttbbs 的目錄下 ( cd ~bbs/pttbbs )
9. 如果您的 pttbbs.conf並不存在, 可以拷一份預設的來用:
cp sample/pttbbs.conf pttbbs.conf
10.依據您的須求, 修改 pttbbs.conf
請注意, 預設的 pttbbs.conf是給相當大規模的 bbs用的.
通常您須要進行修改以符合您的須求.

* 如果您是用 Linux系統, 請先安裝 pmake, 然後將 make alias 成 pmake *
11.在編譯 pttbbs 之前, 您需要先裝好 libiconv, libhz, pgp
如果您使用的是 FreeBSD, 可以直接透過 ports安裝:
cd /usr/ports/converters/libiconv; make install
cd /usr/ports/chinese/autoconvert; make install
cd /usr/ports/security/pgp; make install
12. (在 ~bbs/pttbbs 下) 執行 make BBSHOME=/home/bbs all install
13.如果是新架起來的站, 請執行 cd sample; make install
14.執行 cd /home/bbs; bin/initbbs -DoIt

其中第 13 以及 14 步是給第一次安裝的時候使用的,
如果您的 BBS中已經有資料了, 請務必不要執行這兩個步驟.
假如一切都很順利的話, 這樣子大概就安裝完了, 接下來是啟動 bbs 的部份.

15.執行 bin/shmctl init (*註1, *註2)
16.用 root 執行 bin/mbbsd 23 (註2)

17.測試整個系統是否完成:
telnet localhost 23 看看
new 一個帳號叫SYSOP, 然後 logout再 login, 這樣子就會擁有站長權限囉~
再 new一個帳號叫 guest , 這樣子別人就可以用 guest 參觀你的站了
開板, 開群組, 以及搬動群組的方法請看 PttSrc 板的文摘
18.新功能請參考 ADVANCE
19.為了讓開機的時候會自己把 bbs (以及所須要的程式) 跑起來,
若您使用 FreeBSD, 您可以將 sample/pttbbs.sh 拷貝到 /usr/local/etc/rc.d/
之後您可以重新開機試試看是不是在重開後可以正常運作 :)
20. pttbbs 須要定時執行一些小 tool 來維持系統正常運作,
reload cache, 備份, 特殊外部程式等等.
請用 bbs的權限, 執行 crontab -e , 內容請參照 sample/crontab
(在大部份的情況下, 直接將 sample/crontab 內容拷備進去即可)
21.在某些情況下, pttbbs會須要一些其他的程式來輔助.
下面列出所須要的程式, 預設的路徑, 以及在 FreeBSD ports內對映的路徑
tar /usr/bin/tar FreeBSD default install
gzip /usr/bin/gzip FreeBSD default install
rm /bin/rm FreeBSD default install
perl /usr/bin/perl /usr/ports/lang/perl5.8/
mutt /usr/local/bin/mutt /usr/ports/mail/mutt/
lynx /usr/local/bin/lynx /usr/ports/www/lynx/

我們大部份的 perl script會用到 LocalVars.pm , 該檔案內負責定義
各別機器的設定 (如外部程式的路徑) . 請將該檔拷份一份至 ~/bin/
下, 並修正該檔以符合貴環境的設定.

另外列出我們 perl script會用到的 perl module, 以 FreeBSD ports相對目錄.
Mail::Sender /usr/ports/mail/p5-Mail-Sender/
IO::All /usr/ports/devel/p5-IO-All/
22.若您有安裝 Blog 相關功能, 您需要先產生一個預設的 Blog 目錄
您可以參考批踢踢兔(telnet://ptt2.cc), Blog看板下的 Blog.Default 目錄,
並且拷貝一份或透過 symbolic link的方式放到 etc/Blog.Default.
同時將 sample/README.BLOG 拷貝到 etc/ 下.

註:
1. 這個程式是在 initial shared memory 用的, 只有開機後第一次執行, 或是
你手動清除 shm 後才需要執行

2. 如果您跑了 shmctl init 或 uhash_loader 並沒有看到
total XXXXX names loaded.
而是看到其他的錯誤訊息
(例如 [shmget error] key = 4cc, errno = 22: Invalid argument)
可能是您作業系統 shared-memory 上限不足,
請參考 FAQ中加大 shared-memory 部份的說明.

3. bin/mbbsd 23 是指定要 bind 23 port, 依照 UNIX 規定, 1024 以下的 port
須要有 root 權限, 所以如果要 bind 23 port 的話就要用 root 去執行,
3000 port 則不需要.
請參考 docs/ADVANCE , 安裝好 bbsctl ,
之後您就可以透過 bbsctl 直接在其他權限下 (如 bbsadm )
來啟動可以 bind port 23 的 mbbsd.
4. 您必須先安裝 subversion (請參考官方網站 http://subversion.tigris.org/ )
在 FreeBSD底下, 直接使用 ports 安裝即可:
cd /usr/ports/devel/subversion/; make all install
其他作業系統請參考 http://subversion.tigris.org/project_packages.html
或相關文件.
首先安装Freebsd系统,我安装的是6.2。建议只安装src,ports,binary,doc.其他ports里面的package先不要装,升级一下ports之后再装。因为前不久ports里面的xorg从6.9升级到7.2了。如果安装了升级比较麻烦。所以先不安装其他的package。

升级ports之后开始安装。


首先我们需要安装 Apache 和 Subversion 软件:

dev# cd /usr/ports/www/apache22dev# make WITH_AUTH_MODULES=yes WITH_DAV_MODULES=yes \ WITH_SSL_MODULES=yes WITH_BERKELEYDB=db42 install cleandev# cd /usr/ports/devel/subversiondev# make -DWITH_SVNSERVE_WRAPPER -DWITH_MOD_DAV_SVN \ -DWITH_APACHE2_APR install clean
安装完成后,我们来初始化仓库目录:

dev# mkdir -p /svn/reposdev# svnadmin create /svn/reposdev# chown -R www:www /svn/repos
这里,使用 www:www 用户/组是由于我们是通过 Apache 来提供访问支持。设置 Apache 的配置文件 /usr/local/etc/apache22/httpd.conf,以下只显示了主体部分:

.....LoadModule usertrack_module libexec/apache22/mod_usertrack.soLoadModule unique_id_module libexec/apache22/mod_unique_id.soLoadModule setenvif_module libexec/apache22/mod_setenvif.soLoadModule version_module libexec/apache22/mod_version.soLoadModule ssl_module libexec/apache22/mod_ssl.soLoadModule mime_module libexec/apache22/mod_mime.soLoadModule dav_module libexec/apache22/mod_dav.soLoadModule status_module libexec/apache22/mod_status.soLoadModule autoindex_module libexec/apache22/mod_autoindex.soLoadModule asis_module libexec/apache22/mod_asis.soLoadModule info_module libexec/apache22/mod_info.so.......LoadModule alias_module libexec/apache22/mod_alias.soLoadModule rewrite_module libexec/apache22/mod_rewrite.so#LoadModule dav_module libexec/apache22/mod_dav.soLoadModule dav_svn_module libexec/apache22/mod_dav_svn.soLoadModule authz_svn_module libexec/apache22/mod_authz_svn.so
重启apache的时候发现有一个dav_module的错误。后来发现是load了两次。我就把后面的那个dav_module注释掉了。注意注释前面的那个会出错的。
然后在/usr/local/etc/apache22/Includes 下编辑svn.conf

dev# vi /usr/local/etc/apache22/Includes/svn.confDAV svnSVNPath /svn/reposAuthType BasicAuthName "Feloo Subversion Repository"AuthUserFile /etc/svn-auth-fileRequire valid-user
使用 htpasswd 创建验证用户:

dev# htpasswd -cm /etc/svn-auth-file rory
最后,在 /etc/rc.conf 文件中设置:

apache22_enable="YES"
启动 Apache 后,可以通过 http://you.host.nameOrIP/svn 访问你的 Subversion 仓库了(这里假设你的 Apache 监听在 80 端口)。至于客户端,在 Windows 下可以使用 TortoiseSVNn,相当不错工具。以上步骤在 FreeBSD 6.1-RC 环境下试验成功,你可以进行适当的设置,让 Apache 支持 SSL,这样,你的 svn 将更加安全。

接下来安装trac


dev# cd /usr/ports/www/tracdev# make install clean

这样就安装好了,简单吧。接下来开始initevn

dev# mkdir -p /trac/projects/dev# trac-admin /trac/projects initenvdev# chown -R www:www /trac/projects/ (这一步很重要哦。如果没有修改owner下面和Apache集成之后会出现没有权限的错误不能正常显示)

操作中会提示一些信息,提示subversion 的 repository地址就是前面我们创建的repository /svn/repos 其他都不用设置这样就建立好了,启动standalone服务器tracd

dev# tracd --port 8000 /trac/projects
这样就可以通过http://you.host.nameOrIP:8000 查看到安装成功的trac了.这算是基本完成了。接下来就是使用apache来运行trac,需要mod_python 或者 mod_wsgi 的支持。这里我选择了mod_python,因为在ports里面有现成的。

dev# cd /usr/ports/www/mod_python3dev# make install clean
这里不能安装/usr/ports/www/mod_python 因为这里需要mod_python 3.1.3+ /usr/ports/www/mod_python 的版本是 2.7.11。
安装完成之后修改Apache的配置加载安装好的mod_python.

dev# vi /usr/local/etc/apache22/httpd.conf LoadModule python_module libexec/apache22/mod_python.so
添加trac的Location配置

dev# vi /usr/local/etc/apache22/Includes/trac.conf SetHandler mod_python PythonHandler trac.web.modpython_frontend PythonOption TracEnv /trac/projects PythonOption TracUriRoot /trac AuthType Basic AuthName "Feloo Trac Projects" AuthUserFile /etc/svn-auth-file Require valid-user
这里使用的认证文件和svn的相同。一切都ok了,重启Apache
dev# /usr/local/etc/rc.d/apache22 restart
查看http://you.host.nameOrIP/trac 一切正常,恭喜你安装成功了。

参考

在 FreeBSD 下架设 Subversion 作为版本控制系统

本文系 莫多泡泡(somebody) 原创,转载请注明地址和作者。谢谢。
http://jdkcn.com/entry/howto-install-apache22-subversion143-trac10-on-freebsd6.html

port update

Pkgtools:FreeBSD的智慧型應用程式管理工具組
● 過去的困惑 – 傳統方法的缺點
僅管FreeBSD提供ports及packages?砉芾響贸淌剑是有很多問題。最常
見的問題在於應用程式的重覆安裝、相依性及升級。
以我的個人電腦為例,雖然裝的應用程式不多,確發生了上述的問題。
我先安裝lynx,以提供文字模式下的網頁瀏覽工具。
# cd /usr/ports
# make update
# make index
# cd /usr/ports/www/lynx
# make install clean
後?戆惭bX window system,?K且使用mozilla瀏覽器,提供X的網頁瀏覽工具。
# cd /usr/ports/www/mozilla
# make install clean
但安裝完成後,我發現兩套應用程式都需要gettext,
# pkg_info | grep gettext
gettext-0.11.1_1 GNU gettext package
gettext-0.11.1_3 GNU gettext package
雖然lynx以及mozilla皆可以正常運作,但總覺得安裝兩套gettext有點浪費硬碟
空間,於是決定把其中一個移除。
先移除舊版的 gettext
# pkg_delete gettext-0.11.1_1
pkg_delete: package 'gettext-0.11.1_1' is required by these other packages
and may not be deinstalled:
lynx-2.8.5d7_1
發現和 lynx 有相依性存在,若要移除舊版的 gettext,必須先移除 lynx。
文字方塊: v 1.2
移除新版的試試看
# pkg_delete gettext-0.11.1_3
pkg_delete: package 'gettext-0.11.1_3' is required by these other packages
and may not be deinstalled:
ORBit-0.5.15_1
gmake-3.79.1_1
gtk-1.2.10_4
mozilla-1.0.rc3,1
windowmaker-0.80.0_1
zh-xcin-2.5.3.p2_1
zh-xmms-1.2.7_1
vim-6.1.48
mod_php4-4.2.1_1
AbiWord-1.0.1
zh-zhcon-0.2_4
真是糟糕,無論舊版或是新版都有相依性存在。看?砟壳爸缓孟葧簳r打消念頭。
三天後,我檢查是否有可以升級的應用程式。
先更新ports tree
# cd /usr/ports
# make update
# make index
root@polo [/usr/ports] # pkg_version -L =
gettext <
png <
顯示目前系統 gettext 及 png 的版本比 ports tree還舊。由於系統中有安裝二個
不同版本的 gettext,表示其中一套是需要升級的,而另一套符合目前最新的版
本。
首先我們先升級gettext。通常我們都會先移除舊版的應用程式,再安裝新版的應
用程式;因為新版的我們已經安裝了,所以只須移除舊版的即可。此時,問題就
發生了,和前述一樣,會發生相依性的關係,只好作罷。

接下?砦覀冊囍塸ng。
# pkg_delete png-1.2.2_4/
pkg_delete: package 'png-1.2.2_4' is required by these other packages
and may not be deinstalled:
mozilla-1.0.rc3,1
windowmaker-0.80.0_1
gd-2.0.1_3
mod_php4-4.2.1_1
AbiWord-1.0.1
和gettext一樣,發生相依性的關係。後?砦覜Q定改試?娭菩陨墸m然這種方
法危險性很大。
root@polo [/var/db/pkg] # pkg_delete -f png-1.2.2_4/
再安裝新版的png
root@polo [/usr/ports/graphics/png] # make install clean
但後?砦野l現原本和舊版png有相依性的應用程式,沒有因為我升級而將相依關
係取代為新版的png。
以上這些常見的問題,真是令人頭痛。
● 新世紀的交替 – 智慧型管理的時代
○ pkgtools的相關程式
lang/ruby - An object-oriented interpreted scripting language
devel/ruby-fnmatch - A Ruby module which provides File::fnmatch and File::FNM_*
devel/ruby-bdb1 - Ruby interface to Berkeley DB revision 1.8x with full feature support
devel/ruby-optparse - Yet another command line option parser for Ruby
sysutils/pkg_tarup - Generates binary package from installed package
(data from: pkgtools announce news)

安裝之前,確定ports tree是最新的,雖然portupgrade目前已經趨於成熟,但不
可避免有小問題發生,還是建議安裝最新版。
# cd /usr/ports/sysutils/portupgrade
# make install clean
○ pkgtools工具簡介
portupgrade
升級已經安裝的ports或packages的工具。提供直接升級,而不須要先移除相依
性套件,甚至可以將相依性套件一起升級。
portinstall
安裝尚未安裝的套件,相當於使用`portupgrade –N`。在安裝新套件之前,會先升
級所有required套件。
portversion
將目前安裝於系統中的套件版本和ports tree的套件版本比較。這個工具是取代
原本的pkg_version,而且因為是利用ports database,所以更有效率。
ports_glob
查詢ports database的檔案。能夠判斷萬用字元,?K且有能力列出特定ports的需
求、相依或主要的ports。
pkg_fetch
提供可以由遠端下載binary packages,?K且會遞迴的下載相依性的packages。
pkg_glob
查詢packages database的檔案。能夠判斷萬用字元,?K且有能力列出特定package
的需求、相依或主要的packages。
pkg_deinstall
這個工具是取代原本的pkg_delete。能夠判斷萬用字元,?K且有能力遞迴相依性
packages,也可以選擇保留共享的函式庫。
pkg_db
pkgdb建立?K升級packages的資料庫。使用了雜?(hash)映射(map)已經安裝的
packages的名稱,這種映射方式也包含packages的?碓矗?K將已安裝的packages

列表(list)。當安裝或移除packages的,建立好的資料庫會自動升級。
pkg_which
pkg_which會查詢packages的資料庫,?K找出package是由那個檔案安裝。如果
你沒有權限升級packages的資料庫,可以找這項工作委託給 pkg_iofo(1)。
portsclean
portsclean是一個可以清理(clean)Ports的工作目錄(working directories),不再參考
distfiles,過期的packages檔案,?K?U棄(obsolete)且單獨(orphan)的分享函式庫。
portcvsweb
portcvsweb可以立即經由CVSweb,瀏覽特定已知的檔案。他的功能可能比你想
像中的?姶螅囍S著src、www、doc、NetBSD pkgsrc和OpenBSD ports?硎
用他。
○ 開始使用 pkgtools
在使用 portupgrade 之前,先備份 /var/db/pkg。到目前為止筆者使用portupgrade
?K沒有發生任何問題,但為了保留重要資料,還是?娏医ㄗh做備份動作。
# tar –zcvf backup_pkg.tgz /var/db/pkg
接下?砀聀orts tree 的INDEX以及建立ports的資料庫INDEX.db。
# portsdb –Uu
Updating the ports index ...
…[略]
done
[Updating the portsdb in /usr/ports ... - 5997 port entries
found .........1000.........2000.........3000.........4000.........5000.............. done]
然後開始進要初始設定和做一些ports的清理動作。
# pkgdb –F
[Updating the pkgdb in /var/db/pkg ... - 94 packages found
(-2 +0) (...) done]
Checking the origin of AbiWord-1.0.1
Checking the origin of Hermes-1.3.2
Checking the origin of ORBit-0.5.15_1
…[略]

Duplicated origin: converters/libiconv - libiconv-1.7_3 libiconv-1.7_5
Unregister any of them? [no]
Unregister libiconv-1.7_3 keeping the installed files intact? [no]
-> libiconv-1.7_5 is kept.
--> Saving the libiconv-1.7_3's +CONTENTS file as
/var/db/pkg/libiconv-1.7_5/+CONTENTS.libiconv-1.7_3
--> Unregistering libiconv-1.7_3
--> Done.
[Updating the pkgdb in /var/db/pkg ... - 93 packages found (-1
+0) (...) done]
Stale dependency: AbiWord-1.0.1 -> png-1.2.2_4:
png-1.2.3 (score:83%) ? ([y]es/[n]o/[a]ll) [yes]
在這一步驟中,portdb發現了失效的相依性關係。原本在資料庫中的 AbiWord
是相依於 png-1.2.2_4,但後?硪驗橹?娭埔瞥f版的png,?K且更新png為
png-1.2.3,這些動作皆可以由portdb?膒ackages的資料庫中偵測出?恚?K且還
提供建議性的相容性程度 83%。
相依性的問題是我所預期的,而且希望能夠將任何和舊版png有相依性的,全部
更正為和新版的png相依。所以我選擇 a [all]。
○ 利用pkgtools升級應用程式
更新完ports tree後,我想和packages資料庫比對一下,是否有可以升級的應用
程式。
FreeBSD的傳統方法是使用pkg_version
# pkg_version -L =
而pkgtools提供的新方法,使用資料庫比對的方式,效率更高。
# portversion –L =
libiconv <
zh-ttfm <
zip <

由結果中,可以得知在系統上有三個已安裝的應用程式版本比ports tree中的版
本還要舊。我決定先升級zh-ttfm。
和zh-ttfm相依的有
# pkg_info -rR zh-ttfm-0.9.3_1
Information for zh-ttfm-0.9.3_1:
Depends on:
imake-4.2.0_1
freetype2-2.0.9
freetype-1.3.1_2
XFree86-libraries-4.2.0_1
XFree86-clients-4.2.0_2
Required by:
zh-arphicttf-2.11_1
若想把和zh-ttfm相關的所有套件一起更新,可使用以下指令。
# portupgrade -cCrRuv zh-ttfm
若只想單純升級zh-ttfm的話,則僅使用以下指令即可。
# portupgrade -cCuv zh-ttfm
在這種例子中,應該使用後?淼姆绞?砩墸驗橛芍皃ortversion發現僅有
zz-ttfm這個應用程式需要升級,而相依性的套件?K不需要升級,所以不用大費
周章升級所有相依套件。
其他範例:
.. 升級 glib
# portupgrade glib
.. 升級Xfree86和Mesa,?K傳遞 -DWANT_GGI 參數?韒ake Mesa
# portupgrade XFree86 -m '-DWANT_GGI' Mesa
.. 升級sawfish以及所有sawfish依靠(depend on)的應用程式,?K且建立
packages
# portupgrade -Rp sawfish
.. 升級glib,?K使用互動模式(interactive)

# portupgrade -ri glib
.. 升級所有依靠(depend on) glib的應用程式,但是glib本身則不升級
# portupgrade -rfx glib glib
.. 升級所有在2002/07/08日之前安裝的應用程式
# portupgrade -f '<2002-07-08'
.. 升級所有依靠(depend on) png的應用程式,而且該應用程式的安裝時間在
png安裝之前
# portupgrade -fr png -x '>=png'
.. 只取回所有需要升級應用程式的distfiles
# portupgrade –aFR
.. 升級glib,?K且以使用packages升級為優先,ports為次之
# portupgrade -P glib
.. 只使用packages,完全不考慮ports?砩壦袘贸淌剑覂H列出結果,
?K沒有真正執行
# env PKG_PATH=/mnt/cdrom/packages/All portupgrade –anPP
.. 以相依性排序,升級所有套件。
# portupgrade -scC '*'
○ pkgtools.conf
如果使用ports安裝portupgrade,/usr/local/etc下可找到pkgtools.conf.sample,這
是設定pkgtools的設定樣本檔,可以依照自己的需求建立一份。
# cd /usr/loca/etc
# cp pkgtools.conf.sampl pkgtools.conf
例如:以元智server為舉例
ENV['PORTSDIR'] ||= '/usr/ports'
ENV['PACKAGEROOT'] = 'ftp://freebsd.csie.nctu.edu.tw'

SANITY_CHECK = true
IGNORE_CATEGORIES = [
'french',
'german',
'hebrew',
'japanese',
'korean',
'russian',
'ukrainian',
'vietnamese',
'games',
'palm',
'print',
'x11*',
]
EXTRA_CATEGORIES = [
'outta-port',
]
HOLD_PKGS = [
'bsdpan-*',
]
MAKE_ARGS = {
'editors/vim' => '-DLITE CONF_OPT_MULTIBYTE=--enable-multibyte'
}
BEFOREBUILD = {
}
AFTERINSTALL = {
# Re-enable the X wrapper
'x11-servers/XFree86-4-Server' => sprintf(
'cd %s/bin && if [ -x Xwrapper-4 ]; then ln -sf Xwrapper-4 X; fi',
x11base()),
}

PKG_SITES = [
sprintf('ftp://freebsd.csie.nctu.edu.tw/pub/FreeBSD/ports/i386/packages-stable/'),
]
PORTUPGRADE_ARGS = ENV['PORTUPGRADE']
○ 使用pkgtools自動化升級應用程式
如果於pkgtools.conf中有設定在執行portupgrade之前,先更新ports tree,則以
有權限安裝應用程式的使用者,編寫crontab:
0 6 * * 1 /usr/loca/sbin/portsdb –Uu && /usr/local/sbin/portupgrade –a
若沒有於pkgtools.conf中有設定在執行portupgrade之前,先更新ports tree,則
以有權限安裝應用程式的使用者,編寫crontab:
0 6 * * 1 /usr/local/bin/cvsup –g –L 2 /usr/share/examples/cvsup/ports-supfile &&
/usr/local/sbin/portsdb –Uu && /usr/local/sbin/portupgrade –a
另外,在傳統自動化升級的方式,可使用pkg_version –c的方式,而在portupgrade
則以portversion –c方式取代。
0 6 * * 1 /usr/local/bin/cvsup –g –L 2 /usr/share/examples/cvsup/ports-supfile &&
/usr/local/sbin/portsdb –Uu && /usr/local/sbin/portversion –c >! /tmp/update_apps
&& sh /tmp/update_apps
注意:
在相同應用程式安裝兩套版本時,欲將其中舊版本?娭苿h除,而以新版本取代其
作用時,務必先確定其?碓唇?碇镣籶orts。
例如:發現在系統中安裝了兩個版本的gettext
gettext-0.10.35_2 GNU gettext package
gettext-0.11.2 GNU gettext package
先檢查是否?碜酝籶orts。
Port: gettext-0.11.1_3
Path: /usr/ports/devel/gettext
Info: GNU gettext package
Maint: portmgr@FreeBSD.org
Index: devel

B-deps: bison-1.35_1 expat-1.95.2 libiconv-1.7_5 libtool-1.3.4_3
R-deps: expat-1.95.2 libiconv-1.7_5
Port: gettext-0.10.35_2
Path: /usr/ports/devel/gettext-old
Info: GNU gettext package
Maint: portmgr@FreeBSD.org
Index: devel
B-deps: libtool-1.3.4_3
R-deps:
由結果可知,這兩個版本皆有不同的相依性軟體,且?碜圆煌膒orts,因此不
可將其中一個取代另一個的功能,否則相依的應用程式可能會發生錯誤。
參考文件
pkgtools manual
freebsd diary article – clean ports
勘誤
2002-07-04 v0.1 beta
2002-07-18 v1.0
2002-08-16 bug-fixs – v1.1
2002-09-18 pkgtools updated, changelog – v1.2
編者
元智大學資?管理學系 曾義峰 ( s882617@mail.yzu.edu.tw )
先更新 ports:cvsup -g -L 2 ports-supfile
再更新 ports 資料庫:/usr/local/sbin/portsdb -Uu
然後列出需升級的 port:/usr/local/sbin/portversion -l "<"
最後升級有裝的 port:/usr/local/sbin/portupgrade -arR
如果有提示就執行:/usr/local/sbin/pkgdb -F
如果天塌下來了就:/usr/local/sbin/pkgdb -fu
其他關於 portupgrade 的小筆記:


每次 cvsup 更新 ports 之後就要跑一次 portsdb -Uu
跑 pkgdb -fu 時無論如何都不要中斷動作
可以用 pkg_which 查詢各檔案所屬 ports:pkg_which filename
查某個 port 來源目錄:pkg_which -o kdemultimedia-3.1.3
只上網抓回所需檔案但尚不升級:portupgrade -aFrR
模擬而不實際升級:portupgrade -anrR
指定記錄檔:portupgrade -rR portname -l logfile
用 ports 安裝的軟體,遇有該軟體版本更新時如何處置?
請先做「ports-tree的更新」的動作,之後再分別執行下列三道指令:
portsdb -Uu

pkgdb -F

portupgrade -aWy

備註:執行 portsdb -Uu 時,會有令人覺得當機的味道。別耽心,耐心的稍等一下下就好。



--------------------------------------------------------------------------------

portupgrade時,改變預設的編譯安裝選項
編輯 /usr/local/etc/pkgtools.conf
MAKE_ARGS = {
'databases/mysql323-*' => 'WITH_CHARSET=big5',
'databases/mysql323-*' => 'SKIP_INSTALL_DB=yes',
'databases/phpmyadmin' => 'MYADMDIR?=www/data/phpMyAdmin',
'www/apache13' => 'WITH_APACHE_SUEXEC=yes',
}

mysql 安裝時,預設不支援中文;而phpMyAdmin預設的安裝路徑則在www/data.default/phpMyAdmin,與apache不同,害我裝了之後找好久才找到。

這只是舉例,更詳細的安裝選項,請查看每個 PORTS 中的 Makefile 檔案。



--------------------------------------------------------------------------------

版本衝突時
pkgdb -F
Duplicated origin: sysutils/portupgrade - portupgrade-20020706 portupgrade-20020805
Unregister any of them? [no] yes

Unregister portupgrade-20020706 keeping the installed files intact? [no] no



--------------------------------------------------------------------------------

portupgrade 強制更新 (操作於 FreeBSD 4.6.2-RELEASE )

未更新 PORTS-TREE 前,portupgrade 已安裝的版本:
pkg_info | grep portupgrade
portupgrade-20020429 Very powerful FreeBSD ports/packages upgrading tool and mor


更新 PORTS-TREE 之後,PORTS 中 portupgrade 的版本:
grep \PORTVERSION= /usr/ports/sysutils/portupgrade/Makefile

PORTVERSION= 20020805


執行 portupgrade 後,portupgrade 自己並未更新。

強制以新的portupgrade取代舊的portupgrade-20020429
portupgrade -o /usr/ports/sysutils/portupgrade portupgrade-20020429


再檢查一遍portupgrade 安裝的版本:
pkg_info | grep portupgrade

portupgrade-20020805 Very powerful FreeBSD ports/packages upgrading tool and mor


--------------------------------------------------------------------------------

升級 perl 之後及 openwebmail 安裝使用的相關問題
有太多的程式和 perl 相關,剛開始的時候它們「都認識」系統中預設的 perl
有天,我使用 PORTS 中的 /usr/ports/lang/perl5.8 來升級 perl
升級完,也依照指示
use.perl port
之後卻發現,新版的 perl 好像「誰都不認識」
因此,如果原本的系統跑得好好的,卻突然啥事都不對勁,大概就是和 perl 的升級有關。

其實,只要使用 portupgrade 就可解決此一問題。

portupgrade -f perl-5.8.\* -m "ENABLE_SUIDPERL=yes"

rehash

use.perl port

portupgrade \
-m "-DFORCE_PKG_REGISTER" \
-rf perl-5.8.\* \
-x perl-5.8.\* \
-l /tmp/portupgrade.log

說明:

-f "perl-5.8.*"
強迫更新,就算版本號碼相同,也會將 perl 重新編譯一次。

-m "ENABLE_SUIDPERL=yes"
在 make 時送出 ENABLE_SUIDPERL=yes 的參數,這個參數值在配合 openwebmail 使用時特別需要,否則 openwebmail 會 error
ps. 此部份的參數與值,建議寫入 pkgtools.conf 中。若是,則可省略此參數。

-r "perl-5.8.*"
把相依於 perl-5.8 的軟體一起更新
到底有多少軟體相依於 perl 呢?天知道,我一點概念也沒有,就讓 portupgrade 幫我做吧!



--------------------------------------------------------------------------------

FreshPorts
http://freshports.org/
每一個ports都有專人負責,其更新也是非常迅速,這兒有第一手資料。

Friday, June 22, 2007

cyrus_imap

http://www.onlamp.com/pub/a/onlamp/2005/10/06/cyrus_imap.html?page=2

Securing PHP

Securing PHP

Well PHP is one of the most popular applications that run on Linux and Windows servers today. It's also one of the main sources for servers and user accounts getting compromised. I want to go over some of the things you can do to help lock down PHP, securing php and securing php.ini

First off you want to figure out how you can edit php.ini This is the main configuration file for PHP. You can find it by logging into shell and typing in the following:

# php -i |grep php.ini

Turn on safe_mode

Safe mode is an easy way to lock down the security and functions you can use. PHP.net explains php safe_mode as, "The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now."

I highly recommend you enable safe_mode on production servers, especially in shared environments. This will stop exec functions and others that can easily prevent a security breach.

See our article on Customizing PHP Safe Mode


Disable Dangerous PHP Functions

PHP has a lot of potential to mess up your server and hack user accounts and even get root. I've seen many times where users use an insecure PHP script as an entry point to a server to start unleashing dangerous commands and taking control.

Search the php.ini file for:
disable_functions =

Add the following:

disable_functions = dl,system,exec,passthru,shell_exec


Turn off Register Globals

Register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier.
See http://us2.php.net/register_globals

register_globals = On

Replace it with

register_globals = Off

Run PHP through PHPsuexec Preventing Nobody Access

The biggest problem with PHP is that on cPanel servers is that PHP will run as nobody. When someone sets a script to 777 access that means the nobody user has write access to that file. So if someone on the same shared server wrote a script to search the system for 777 files they could inject anything they wanted, compromising the unsuspecting users account.

PHPsuexec makes PHP run as the user so 777 permissions are not allowed. There are a few downfalls to PHPsuexec but I think it's required on a shared environment for the security of everyone. Safe_mode doesn't prevent you from compromising other users files. This is where PHPsuexec comes in, it stops the user from being able to read another users files. It also makes it easier for you, the administrator, to track PHP mail function spamming and lots of other issues caused by PHP scripts because now you can easily track it ot the users account responsible.

For this you will need to recompile PHP with suexec. On cPanel /scripts/easyapach has this build in.


I hope this has summed up some of the things you can do to help secure PHP on your server. There's also open_base protection which you can use to prevent users from reading other users files.

About the Author:
Steven Leggett is the editor of the server resource and hosting tutorial site, www.webhostgear.com and specializes in system administration and web development.



New! - Need server help? Hire an Expert
Get professional help with your configuration, script installation or server issue.
Learn how we can help you with any server problem and make your server run like new. Professional staff will contact you, after submitting a quote request, by phone or email.

Freebsd Security

netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
The solution that I found for this problem was to boot the server with out the Xserve RAID attached, edit my fstab, and change all the devices /dev/da0 to /dev/da1 and the /dev/da1 to /dev/da2.

My fstab file looks now something like:


/dev/da1s1b none swap sw 0 0
/dev/da1s1a / ufs rw 1 1
/dev/da2s1e /home ufs rw,nodev,userquota,groupquota 2 2
/dev/da1s1f /tmp ufs rw,nosuid,noexec,nodev 2 2
/dev/da1s1g /usr ufs rw,nodev,userquota,groupquota 2 2
/dev/da1s1e /var ufs rw,nodev 2 2
/dev/acd0c /cdrom cd9660 ro,noauto 0 0
/dev/da0s1e /xraid ufs rw 2 2



Then I just rebooted the server again, and everything worked just fine. Maybe this is not the best solution, but it worked for me and I hope this can help someone else. If someone knows a better way for fixing this problem, please let me know.
http://www.webhostgear.com/

Installing on FreeBSD
The Suhosin-Patch and the Suhosin extension are both within the FreeBSD ports. Therefore installing it on FreeBSD is very simple. The Suhosin-Patch is an option which you can choose when you install the lang/php4 or lang/php5 port. To install the patch just do

#> cd /usr/ports/lang/php5
#> make
... now select the menu item that says: Enable Suhosin Protection
#> make install
To install the extension just do

#> cd /usr/ports/security/php-suhosin
#> make
#> make install
After these simple steps Suhosin-Patch is successfully installed on your system.

Upgrading
10 Steps to Securing your Server

So many people are getting their own dedicated servers but are completely clueless about security. Usually they leave it up to the company where they purchase it or hire someone. That's fine but make sure you have these 10 items covered.

1) Use a Firewall
Make absolutely sure that your server has a firewall running all the time. A firewall is like a screen door to your porch. It blocks out flies, rodents and other pests but you can still walk out and use your BBQ. If someone ever were to get into your server, which is very very likely, the first thing they're going to try and do is upload something to start a daemon or their own service like an IRC server or use a port to launch attacks to other systems. A firewall with egress and ingress protection can stop both incoming and outgoing attacks even when you're not aware of it. We recommend using APF on Linux systems or TinyFirewall on Windows Servers. These are software firewalls so there's no extra monthly cost like a hardware firewall. For very busy systems a hardware firewall is recommended so it takes the burden off your system CPU/RAM and resources to do the work.
Know what ports are open and why, know how to block and unblock an IP. These are basic things you need to understand in the daily security of your system. If someone from an IP begins a brute force attack you want to know how to stop them, right away. Installing APF Firewall, Preventing Brute Force Attacks, Installing KISS Firewall

2) Update your kernel and OS
Make sure your server is using current, updated software. Use the stable version which has been tested more than any beta and update as soon as possible. An old kernel can lead to an easy target for your server. If you're not sure then ask your provider for the latest update.


3) Monitor Logs
Do you know what logs record which activities? How often are they updated and rotated?
LogWatch is a great tool to email you the daily reports of your systems activity of anything it determines unusual, EG repeated failed logins. Besides using this you should check your logs manually to see what’s up. Tail –f /var/log/messages and view your Apache logs as well. Apache Log Files Explained

4) Backups
I still never understand why no one backs up their data yet you spend hundreds of hours working on your website or application then you absolutely must have a second hard drive for backups or use a remote back up system or a combination of these. Second Hard Drive Means Life or Death

5) Limit Access to a Minimum
Do not give users more access than the absolute minimum they require. Never give them shell access, restrict file access to a bare minimum and leave other services turned off by default until specifically requested and you determine that its safe to do so.


6) Lock down PHP and use Mod_Security with Apache
PHP is actually a large security risk but there are a few things to do to help lock it down. CGI has Suexec,which helps runs proccesess as the user and PHP has something similar called PHPSuexec but there are a few downfalls. You should also use open_base directory protection, have safe_mode on system wide, turn off register_globals, enable_dl and allow_url_open to help lock things down further.

You can use server wide protection with mod_security, a web server filter that can watch all requests to see if they match a rule and react by logging, denying the request or other programs. I highly recommend this on Apache based servers and can be extremely useful in blocking attacks and stopping hackers before they do any damage. Securing Safe Mode , Installing Mod_Security


7) Lock /tmp /var/tmp and /dev/shm partitions
On Linux each partition can have certain access restrictions. Since /tmp /var/tmp and /dev/shm are world writable directories they’re often home to uploads, sessions storage and hacker executables. Since anyone can read-write-excute anything from these directories it becomes a major security concern. With /etc/fstab however you can limit what can be done in these locations. If you see defaults beside the /tmp line remove it and replace it with noexec,nosuid this will stop any executables from being allowed to run. Do the same for /dev/shm and make /var/tmp and shortcut (symbolic link) to /tmp. Securing Your TMP Partition

8) Intrusion Detection System (IDS)
An intrusion detection system or IDS is like a burglar alarm on your server. It keeps a record of which files were changed when and alerts you of anything new or altered. This is critical because hackers usually try to replace binary applications like ps, top, netstat and others. This means when you run this new version of ps or top to see processes running they make it so it actually HIDES their hacker software, even though its running it won’t show up. Some IDS systems include TripWire, Snort and AIDE. Installing Chkrootkit

9) Review Processes Running and Remove Extra Software
You can’t protect a system if you don’t know what’s on it. If a hacker adds an extra process that you see in PS but you wouldn’t notice if you didn’t know what should be there usually. Know what runs on your system and why which user. How does Perl or Apache run, under which user? You can check your processes usually with top or ps auxfww which gives you a tree view. Check these every time you login to your server. Getting started with Shell (SSH) , Common Shell Commands

10) Keep an Eye on the Servers Performance
Know what speed your server is running at and how much bandwidth it uses on a daily basis. If an attacker compromises your system and you don’t know you’ll probably notice the system responding slowly or using a lot of bandwidth. If you don’t know what your system is usually like how will you notice something out of the ordinary. This is all common sense but some people never bother to check until they ask their provider after a system has been slow for 2 weeks – it’s usually to late then. Server Loads Explained

Knowing your system makes you one step ahead of an intruder. Check it often and ask an expert if you’re ever over your head. There are MANY other things you can and should do to ensure your server is secure but these are a few basics that everyone should use.

If you have anything you’d like to add please post in our forums or comment on this article.
http://www.devx.com/security/Article/22476/1954?pf=true

There are a few things you could do to minimize the damage of unknown vnlnerable scripts hosted.

To run you web server in a chroot jail.

To make gcc, wget, curl, etc only available to root user.

Thursday, June 21, 2007

PF-利用PF輕鬆達成NAT

【前言】
以下介紹為引用 [FreeBSD 使用手冊 第26章 防火牆 26.4 OpenBSD Packet Filter (PF) 和 ALTQ]

2003 年 7 月, OpenBSD 的防火牆, 也就是常說的 PF 被成功地移植到了 FreeBSD 上, 並可以通過 FreeBSD Ports Collection 來安裝了; 第一個將 PF 集成到基本系統中的版本是 2004 年 11 月發行的 FreeBSD 5.3。 PF 是一個完整的提供了大量功能的防火牆軟件, 並提供了可選的 ALTQ (交錯隊列, Alternate Queuing) 功能。 ALTQ 提供了服務品質 (QoS) 帶寬整形功能, 這個功能能夠以基於過濾規則的方式來保障不同服務的帶寬。 OpenBSD Project 在維護 PF 用戶指南方面已經做了非常卓越的工作,因此我們不打算在這本使用手冊中進行更進一步的闡述, 以避免不必要的重複勞動。

警告: 在瀏覽 pf 用戶手冊時,請時刻注意,在 FreeBSD 中所包含的 pf 的版本和 OpenBSD 中是不一樣的。 在 FreeBSD 5.X 中 pf 相當於 OpenBSD 3.5 中的版本, 而 FreeBSD 6.X 中則相當於 OpenBSD 3.7。

更多的詳細信息, 可以在[FreeBSD 版本的 PF 網站]上找到

【作業環境】

FreeBSD 6.1、6.2-RELEASE

【安裝及設定】

若您不需要 PF ALTQ 功能則可不用透過修改核心來支援 PF,請直接在 /etc/rc.conf 內加入 pf_enable="YES" 即可,並跳到 Step3 繼續,不過前提是您必須要確定你的核心檔內下列三個選項沒有被 mark 掉


options INET
options INET6
device bpf

Step1.修改核心來開啟支援 PF


device pf //啟動 Packet Filter 防火牆
device pflog //啟動 pflog0 網卡並以 bpf 格式來記錄網路流量
device pfsync //啟動 pfsync0 網卡用來監控「狀態的改變」
options ALTQ //啟動 ALTQ 功能 (注意不是所有網卡皆支援 ALTQ 功能)
options ALTQ_CBQ //啟動 Class Bases Queuing (CBQ) 功能

Step2.修改/etc/rc.conf

修改 /etc/rc.conf 中加入下列的設定,以便在系統啟動時啟用 PF


pf_enable="YES" # 啟用 PF (如果需要的話載入模組)
pflog_enable="YES" # 啟用 pflogd(8)
gateway_enable="YES" # 啟用 LAN Gateway (若要做 NAT 的話)

Step3.修改 pf.conf

Packet Filter {PF}防火牆特性為 Default Pass ALL、Last Match Rules 當撰寫適合自已的 pf.conf 時記得 pf.conf 語法順序如下


巨集 Macro:包含 IP 位址、介面名稱等自定變數
表格 Tables:包含 IP 位址列表的表格
選項 Options:各種控制 PF 運作的選項
清理 Traffic Normalization:正規化與重組分段封包等再處理
佇列 Queueing:提供頻寬控制與封包優先順序
轉譯 Translation:控制網路位址轉譯與封包轉向
過濾規則 Packet Filtering:當封包通過任何網路介面時,允許選擇性的過濾或阻擋封包

PF 設定範例(/etc/pf.conf)請自行視個人需求修改,以下僅列出[阻擋惡意 Try SSH/FTP IP]內容


#special rule for ssh/ftp
pass in on $ext_if proto tcp from any to ($ext_if) port { ftp ssh } flags S/SA keep state (max-src-conn-rate 3/30,
overload flush global)
#block the ssh bruteforce bastards
block drop in quick on $ext_if from

上面二條 Rules 運作流程大概是這樣


首先 pass 對外進來的流量
記錄連結 port {ftp ssh} 30秒內3次 (max-src-conn-rate 指定時間內允許連結次數)
若有符合這樣條件的 IP 就將該 IP 加入 Table
block 該 Table 內列表的 IP

#pfctl -t ssh-bruteforce -Tshow //可看到惡意 ip 已加入table內
61.95.172.140
61.177.147.97
62.29.248.240
203.129.254.212
210.192.98.99
222.122.60.205

當然你也可以手動把惡意 IP 加入 Table ssh-bruteforce 內


#pfctl -t ssh-bruteforce -T add 218.70.0.0/16

若想清除 Table 內列表的 IP方法

一、定期清除 Table 內 IP 列表


/usr/ports/security/expiretable //安裝 expiretable
*/5 * * * * /usr/local/sbin/expiretable -t 3600 ssh-bruteforce //定期清除 Table

二、手動清除 Table 內 IP 列表


#pfctl -t ssh-bruteforce -T delete 218.70.0.0/16

Step4.pf常用指令

修改完 PF 設定檔(pf.conf)後,常使用以下指令來控制 PF 更詳細的用法請參考[Man Page pf.conf]


#pfctl -f /etc/pf.conf //重新載入 pf.conf 設定檔
#pfctl -nf /etc/pf.conf //檢查 PF 語法是否正確 (未載入)
#pfctl -Nf /etc/pf.conf //僅載入 NAT 的設定檔
#pfctl -Rf /etc/pf.conf //僅載入防火牆的過濾設定檔
#pfctl -sn //顯示現階段 NAT 的規則
#pfctl -sr //顯示現階段過濾的規則
#pfctl -ss //顯示現階段封包運作狀態
#pfctl -si //顯示現階段過濾封包的統計資料
#pfctl -sa //顯示現階段所有統計的資料
#pfctl -vsr //顯示現階段過濾封包的統計資料
#pfctl -t ssh-bruteforce -Tshow //顯示 table 內資料

補充: PF 觀念導正

由於剛使用 PF 前 Firewall 是使用 IPF 於是以為只要將 ipf rule 貼到 pf.conf 內就可以了,但卻有些 rule不生效,經過 llwang 指導後就開通了 lol 以下為擷錄在 #bsdchat 內的談話


16:19 <@weithenn_> llwang:block out quick on $lan_if from 192.168.1.231/32 to any 下這樣1.231還是可以出去
16:19 <@weithenn_> llwang:block quick on $lan_if from 192.168.1.231/32 to any 下這樣1.231就出不去了
16:30 <@llwang> 192.168.1.231 在哪一個 interface 上?
16:30 <@weithenn_> llwang:$lan_if
16:31 <@llwang> 你要擋的是不讓它連到哪裡?
16:31 <@weithenn_> llwang:不讓它去任何地方
16:31 <@llwang> 那你應該用 block in 而不是 block out
16:32 <@llwang> 對 $lan_if 來說 192.168.1.231 是從這邊 進來 的
16:33 <@weithenn_> llwang:但不是應該是 $lan_if 不讓來源1.231 出去 ?
16:33 <@llwang> 因為你前面有 nat rule,進來的連線會 implicitly keep state
16:33 <@llwang> weithenn_: 不是
16:33 <@llwang> weithenn_: 你要從你這一台來看
16:34 <@weithenn_> llwang:從pf.conf這台角度來看是嗎?
16:34 <@llwang> weithenn_: 對你這一台來說,192.168.1.231 是從 $lan_if 進來,從 $ext_if1 或 $dmz_if 出去的
16:34 <@llwang> weithenn_: 對,pf 這台
16:34 <@llwang> weithenn_: 所以應該要用 block in
16:35 <@weithenn_> llwang:so~~一句話點醒我夢中人........
16:35 <@llwang> weithenn_: 用 block out 的話因為前面的 nat 會 keep state,所以 block out 會沒用
16:37 <@weithenn_> llwang:感謝指教

範例:Web Server

一個 Web Server 的基本 PF 設定內容如下(Service FTP、SSH、DNS、HTTP)


# Macros: define common values, so they can be referenced and changed easily.
ext_if="em0"
private_addr="{192.168.0.0/16, 192.168.0.0/16, 10.0.0.0/8, 127.0.0.0/8, 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}"
pass_in_service="{53 80}"
# Normalization: reassemble fragments and resolve or reduce traffic ambiguities.
scrub in all
# Filtering: the implicit first two rules are
#Pass Loopback
pass in quick on lo0 all
pass out quick on lo0 all
#Block the ftp ssh bruteforce bastards
block drop in quick on $ext_if from
#Pass Ping
pass in quick on $ext_if proto icmp all
#Special rule for FTP/SSH
pass in quick on $ext_if proto tcp from any to ($ext_if) port { ftp ssh } flags S/SA keep state (max-src-conn-rate 3/90,
overload flush global)
#Pass FTP
pass in quick on $ext_if proto tcp from any to $ext_if port > 49151 keep state
#Pass IN Service DNS HTTP
pass in quick on $ext_if proto { tcp, udp } from any to $ext_if port $pass_in_service keep state
#Pass Localhost to Any
#pass out quick on $ext_if all keep state
#Block Internet Private Address to Me
block in quick on $ext_if from $private_addr to any
#Block Another all
block return-rst in quick on $ext_if proto tcp all
block return-icmp(net-unr) in quick on $ext_if proto udp all
block in quick on $ext_if all

補充:遠端操作 PF 注意事項

當你在遠端操作 PF 若是沒有十足的把握最好不要亂動,因為可能動一動之後把自已擋掉了(我也有過慘痛的經驗~~ Orz)今天在 #bsdchat 上看到順便就記下來吧。


16:01 <@f0rth> pf -f 的時候不忘加上 ;sleep 10; pf -d
16:02 <@priv> f0rth: "pf設定已經變更,請問是否確認,二十秒鐘後恢復原設定值(Y/N)"
16:03 <@priv> 要這樣?

【參考】

[PF: The OpenBSD Packet Filter]

[PF: OpenBSD 封包過濾器]

[pf中文手冊(for openbsd,但同樣適用FREEBSD)]

[FreeBSD 使用手冊 第26章 防火牆 26.4 OpenBSD Packet Filter (PF) 和 ALTQ]

[Man Page pf.conf]

[Man Page altq(4)]

[FreeBSD packet filter Mail List]

[PF: The OpenBSD Packet Filter]

[PF: OpenBSD 封包過濾器]

[FreeBSD 5.3 Release PF 初體驗]

[FreeBSD + PF + Shell Scritp + Load Sharing + Redundant ]

[FreeBSD NAT 上接兩條 ADSL 若斷線時自動偵測切換路由]

[PF 防火牆及 NAT 初次架設]

[jail-pf memo]

[FreeBSD筆記:pf log]

[游志峰的網路架設筆記 pf 的紀錄檔]

[游志峰的網路架設筆記 pf設定]

[游志峰的網路架設筆記 pf 原廠範例]

[OpenBSD Taiwan openbsd & pf 的邂逅]

[Hi! I’m clsung » Blog Archive » pf 擋 ssh 惡意連線]

[Block ssh bruteforce attempts]

[FreeBSD PF 防火牆及 NAT 初次架設 < 月夜火]

[OpenBSD 超精簡版PF使用手冊]

[OpenBSD firewall using pf]

[openbsd+adsl+pf+qdns 配置过程 - fanqiang.com]

[OpenBSD下面自动block密码测试不法分子]

[FreeBSD with Packet Filter(PF) Firewall - (1) ]

[FreeBSD with Packet Filter(PF) Firewall - (2) ]

[FreeBSD with Packet Filter(PF) Firewall - (3) ]

[FreeBSD with Packet Filter(PF) Firewall - (4) ]

[FreeBSD with Packet Filter(PF) Firewall - (5) ]

[FreeBSD with Packet Filter(PF) Firewall - (6) ]

[Man Page expiretable -- removes PF table entries based on age]

【Log】