Infrastructure Machines: Difference between revisions

From JCWiki
Jump to navigation Jump to search
 
(130 intermediate revisions by 12 users not shown)
Line 3: Line 3:
== jail1 ==
== jail1 ==


os:  
* Location: castle, SHUTDOWN
disks:
* OS: FreeBSD 6.2 i386
* Networking: Priv IP: 10.1.4.101 (PCI nic), Pub IP: 69.55.230.107 (onboard)
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 74 GB (4 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
* Remote management: none
* Disk accounting: gvinum


= virts =
== jail2 ==


= mail =
* Location: castle, cab 6-16
== Summary ==
* OS: FreeBSD 7.2 amd64
This machine (mail) is the swiss army knife of the company, playing host to many services and functions.  
* Networking: Priv IP: 10.1.4.102, Pub IP: 69.55.228.53 (2 onboard nics)
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 146 GB (2 x 146GB) RAID1 array, two 300 GB (4 x 300GB) RAID1 arrays running on an LSI-based, Dell-branded (PERC 6/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.232
* Disk accounting: md


* Location: castle, cab 3-8
== jail3 ==
* OS: FreeBSD 4.10 x86
* Location: I2b  SHUTDOWN
* Networking: Priv IP: 10.1.4.5, Pub IPs: 69.55.230.2, 69.55.225.225 (ns1c jail), 69.55.230.9. 1 onboard and 1 PCI
* OS: FreeBSD 8.3 amd64
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.  
* Networking: Priv IP: 10.1.2.103, Pub IP: 69.55.229.7 (2 onboard nics)
* Drives: two 36 GB (2 x 36GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
* Hardware: Supermicro (custom build). 6 SATA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.  
* Drives: two 300 GB (2 x 300GB) RAID1 array running on a 3ware 8006-2LP RAID card.
* Remote management: none
* Disk accounting: md


== Services Provided ==
=== Notes ===
* mail
* '''We should not add users to this server since it is at I2B'''
* web
* must be ssh'd to from nat2
* mysql
* is a super jail for customer col01737
* bigbrother server/pager
* snmp


== email ==
== jail4 ==
This server hosts mail for johncompanies.com (mail.johncompanies.com). Sendmail 8.13.6/8.13.6 is listening on 69.55.230.2 port 25 for incoming mail. Relaying is allowed per /etc/mail/relay-domains
Other addresses (aliases) are defined per /etc/mail/aliases


The following active users have mail hosted on this server:
* Location: castle, cab 6-17
* dave
* OS: FreeBSD 9.1 x86_64
* linux
* Networking: Priv IP: 10.1.4.104, Pub IP: 69.55.228.104 (2 onboard nics)
* support
* Hardware: Dell 2850. 6 x 300GB SCSI drives (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* payments
* CPU:  2 x Intel(R) Xeon(TM) CPU 2.80GHz (8 virtual CPUs)
* sales
* RAM:  16 GB ( 4 x 4GB Reg ECC )
* tech1
* Drives: one 1.4 TB RAID 5 array (6 x 300GB SCSI) Dell-branded (PERC 4e)LSI megarc RAID card.
* info
* Remote management: None
* Disk accounting: md


Traditionally, mail is checked via shell apps (pine). qpopper (pop3s) is running to allow mail downloading. Checking mail in this way causes an opened INBOX in pine to lock read-only. For this reason, we tee incoming mail to support and linux to tech1.


Procmail rules are setup to filter spam and send text messages. They are enabled for info, support, linux, tech1, dave and can be found in ~/Procmail/, for example:
=== Notes ===
<pre># more ~support/Procmail/rc.emergency
Only FreeBSD 9.1 jail
:0c # use c only if you want to forward a copy and file the original later
Not upgraded to FBSD 9.2 or 9.3 because too many libraries modified (would require customers to rebuild apps).
* ^Subject:.*\<emergency\>
* ! ^Subject:\<re\>
  {
  :0h
  FROMANDSUBJECT=|formail -XFrom: -XSubject:


  :0fwh
== jail5 ==
  | /usr/local/bin/formail -I"Subject: " -I"To: pager@johncompanies.com" ; echo $FROMANDSUBJECT ; echo


  :0
* Location: castle, cab 3-6
  ! -t
* OS: FreeBSD 10.1 x86_64
  }
* Networking: Priv IP: 10.1.4.105, Pub IP: 69.55.230.105 (2 onboard nics)
* Hardware: Supermicro JC-14004 - Intel S1200BTL motherboard - 6 SATA/SAS drive bays (2 colums of 3), Dual power supply.
* CPU:  1 x Intel(R) Xeon(TM) E3-1230 V2 CPU 3.30 GHz (8 virtual CPUs)
* RAM:  32 GB ( 4 x 8GB ECC )
* Drives: 1x80 GB SATA SSD on motherboard + one 2.6 TB RAID 5 array 4x1 TB + 3ware 9650 RAID card.
* Remote management: Intel RMM 4 - 10.1.4.235
* Disk accounting: md


</pre>
=== Notes ===
Only FreeBSD 10.1 jail used for bhyve virtuals.


control: <tt>cd /etc/mail; make stop</tt> (stop), <tt>cd /etc/mail; make start</tt> (start)
Use ~+Ctrl-D to disconnect from console (vm attach colXXXXX).


The following aliases are also in place:
== jail6 ==


<pre>debian:         linux
* Location: castle, cab 6-16
jobs:   info
* OS: FreeBSD 10.3 x86_64
careers:       info
* Networking: Priv IP: 10.1.4.106, Pub IP: 69.55.230.106 (2 onboard nics)
#reboot:         6128102202@txt.att.net
* Hardware: Supermicro JC-14004 - Intel S1200BTL motherboard - 6 SATA/SAS drive bays (2 colums of 3), Dual power supply.
#reboot:         8582298897@vtext.com
* CPU: 1 x Intel(R) Xeon(TM) E3-1230 V2 CPU 3.30 GHz (8 virtual CPUs)
reboot:         pager
* RAM32 GB ( 4 x 8GB ECC )
#pager: 8582298897@vtext.com
* Drives: one 2.7 TB ZFS RAID 6 array 5x1 TB
pager4158718324@txt.att.net
* Remote management: Intel RMM 4 - 10.1.4.236
tech1on: "| /usr/local/sbin/tech1on.sh"
* Disk accounting: zfs
tech1off: "| /usr/local/sbin/tech1off.sh"</pre>
 
== jail7 ==


To change them, edit <tt>/etc/aliases</tt> and then run <tt>newaliases</tt>
* Location: castle, cab 3-5  SCHEUDLED SHUTDOWN 9/30/19
* OS: FreeBSD 6.3 i386
* Networking: Priv IP: 10.1.4.107, Pub IP: 69.55.230.108 (2 onboard nics)
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 146 GB (4 x 146GB) RAID1 arrays, one 74 GB (2 x 74GB) RAID1 array running on an LSI-based, Dell-branded (PERC 6/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.237
* Disk accounting: gvinum


Note on tech1: this address was setup as a read-only address to be mirrored on all email coming into support and linux. We set this up so we could easily check support mail via a pop client- popping email locks out the user in pine so checking support/linux directly via pop was not an option. When checking and responding to email that comes into tech1, care should be taken to make sure it is sent as/under an address other than tech1. This is cause tech1 is not monitored by support staff as closely as email to support/linux. Further, the tech on call may not be checking tech1. Lastly, because of the nature of the copying, you will sometimes notice certain automated email/notices are received 2x in support- this is because of/related to the tech1 mirror.
=== Notes ===
Do not run a verify while OS/jails running, will crash.


To enable it (on mail, run):
== jail8 ==


<tt>~support/tech1on.sh</tt>
* Location: castle, cab 3-6
* OS: FreeBSD 8.0 amd64
* Networking: Priv IP: 10.1.4.108, Pub IP: 69.55.234.2 (2 onboard nics)
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 146 GB (2 x 146GB) RAID1 array, one 300 GB (2 x 300GB) RAID1 array, one 400 GB (2 x 400GB) RAID1 array, running on an LSI-based, Dell-branded (PERC 6/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.238
* Disk accounting: md


To disable


<tt>~support/tech1off.sh</tt>
== jail9 ==


Or via email:
* Location: castle, cab 3-6
* OS: FreeBSD 8.2 amd64
* Networking: Priv IP: 10.1.4.109, Pub IP: 69.55.232.36 (2 onboard nics)
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 146 GB (2 x 146GB) RAID1 array, one 400 GB (2 x 300GB) RAID1 array running on an LSI-based, Dell-branded (PERC 5/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.239
* Disk accounting: md


<tt>tech1on@johncompanies.com
tech1off@johncompanies.com</tt>


== web ==  
== jail11 ==


See [[Management_System_/_Public_Website_/_Signup|Management System / Public Website / Signup]]
* Location: castle, cab 3-7
* OS: FreeBSD 4.7 i386
* Networking: Priv IP: 10.1.4.111 (PCI nic), Pub IP: 69.55.236.92 (onboard)
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 74 GB (4 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
* Remote management: none
* Disk accounting: vinum


== mysql ==
mysql 4.1.22 is running on port 3306


* datadir: <tt>/mnt/data1/db/mysql/</tt>
== mx1 ==
* config: <tt>/etc/my.cnf</tt>
* database: <tt>jc</tt>
* control: <tt>/usr/local/etc/rc.d/mysql-server.sh stop</tt> (stop), <tt>/usr/local/etc/rc.d/mysql-server.sh start</tt> (start)


== bigbrother ==
* Location: castle, SHUTDOWN AND SCRAPPED
There is a client running on mail (which monitors the services running on mail and mail itself), installed under <tt>/usr/home/bb/bbc1.9e-btf</tt><br>
* OS: FreeBSD 4.11 i386
And the big brother pager/server (which displays information gathered from all bb-monitored machines, including mail) is installed under <tt>/usr/home/bb/bbsrc/bb1.9i-btf</tt>
* Networking: Priv IP: 10.1.4.201 (PCI nic), Pub IP: 69.55.237.3 (onboard)
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 36 GB (2 x 36GB) RAID1 array, one 74 GB (2 x 74GB) RAID1 array running on an Adaptec-based, Dell-branded (perc) RAID card.
* Remote management: none
* Disk accounting: vinum


Both are running under the user <tt>bb</tt>
=== Notes ===
* is our (old) backup mail/dns vps service host


Refer to [[BigBrother]] for more about use.
== mx2 ==


== DNS (ns1c.johncompanies.com) ==
* Location: castle, SHUTDOWN AND SCRAPPED
ns1c is a jail running on the mail server, who's IP is 69.55.225.225
* OS: FreeBSD 7.1 i386
* Networking: Priv IP: 10.1.4.202 (PCI nic), Pub IP: 69.55.237.90 (onboard)
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 74 GB (4 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
* Disk accounting: gvinum


It's running from <tt>/mnt/data1/ns1c-dir</tt>
=== Notes ===
* is our latest backup mail/dns vps service host


See [[DNS]] for more details
== jail17 ==
* Location: castle, cab 3-7
* OS: FreeBSD 4.10 i386
* Networking: Priv IP: 10.1.4.117 (PCI nic), Pub IP: 69.55.228.2 (onboard nics)
* Hardware: Supermicro (custom build). 6 SCA SCSI drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 74 GB (4 x 74GB) RAID1 arrays, one 146 GB (2 x 146GB) RAID1 array, running on an Adaptec 2120S  RAID card.
* Remote management: none
* Disk accounting: vinum
* Host of devweb.johncompanies.com and www.utopian.com/mail.utopian.com


== Usage and Notes ==
== jail18 ==
* always mounted to backup1 and backup2 via nfs:  
* Location: castle, cab 3-5  SCHEDULED SHUTDOWN 9/30/19
<pre>backup2:/mnt/data1 on /backup (nfs)
* OS: FreeBSD 4.10 i386
backup2:/mnt/data2 on /backup2 (nfs)
* Networking: Priv IP: 10.1.4.118 (PCI nic), Pub IP: 69.55.228.2 (onboard nics)
backup2:/mnt/data3 on /backup3 (nfs)
* Hardware: Supermicro (custom build). 6 SCA SCSI drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
backup2:/mnt/data4 on /backup4 (nfs)
* Drives: two 74 GB (4 x 74GB) RAID1 arrays, one 146 GB (2 x 146GB) RAID1 array, running on an Adaptec 2120S  RAID card.
backup1:/data on /backup1 (nfs)
* Remote management: none
</pre>
* Disk accounting: vinum
* Host of ns2c.johncompanies.com (now on ns2c.johncompanies.com on ganeti)
 
== jail19 ==
* Location: castle, cab 3-5  SCHEDULED SHUTDOWN 9/30/19
* OS: FreeBSD 6.1 i386
* Networking: Priv IP: 10.1.4.119 (PCI nic), Pub IP: 69.55.228.200 (onboard nics)
* Hardware: Supermicro (custom build). 6 SCA SCSI drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 74 GB (2 x 74GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an Adaptec 2120S  RAID card.
* Remote management: none
* Disk accounting: gvinum


== Cronjobs ==
= virts =
* * * * * /usr/local/www/mgmt/mrtg/mrtg.sh > /dev/null 2>&1
Gathers up data for our mrtg/load graphs


*/5 * * * * /usr/local/bin/rsync -a root@nat2:/mnt/data1/mrtg/data/ /usr/local/www/mgmt/mrtg/data/
== quar1 ==
Gathers up data from i2b servers for our mrtg/load graphs


40 0 * * * /usr/local/bin/rsync -a root@nat2:"/mnt/data1/mrtg/*.cfg" /usr/local/www/mgmt/mrtg
* Location: castle, SHUTDOWN AND SCRAPPED
Gathers up mrtg configuration (port names) from i2b switches for our mrtg/load graphs
* OS: RedHat 7.3 x86
* Networking: Priv IP: 10.1.4.151 (PCI nic), Pub IP: 69.55.227.2 (onboard nic)
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.  
* Drives: one 36 GB (2 x 36GB) RAID1 array, one 74 GB (2 x 74GB) RAID1 array, running on an Adaptec-based, Dell-branded (perc) RAID card.
* Remote management: none
* Virtuozzo version: 2.6.1
* VZ license: hwid=23C0.C0E1.6FDD.08BA.8971.8E1C.EBD5.1EDC serial=0DE6.903E.E239.E23F.470C.4369.4104.A5A4


41 0 * * * for f in `grep -l "mnt\/data1" /usr/local/www/mgmt/mrtg/switch-p*.cfg`; do cat $f | sed s#\/mnt\/data1#\/usr\/local\/www\/mgmt# > $f.new; mv $f.new $f; done
=== Notes ===
Gathers up mrtg configuration (port names) from castle switches for our mrtg/load graphs
* used to be the home of customers who's VE's would just run out of control/badly
* has a max of 10 VE's allowed to run


1 0 1 * * cp /usr/local/www/mgmt/html/top20ip /usr/local/www/mgmt/html/top20ip_last
== virt9 ==
1 0 1 * * cp /usr/local/www/mgmt/html/top20customers /usr/local/www/mgmt/html/top20customers_last
2 * * * * /usr/local/www/cronjobs/top20ip.pl > /dev/null 2>&1
15 * * * * /usr/local/www/cronjobs/top20customer.pl > /dev/null 2>&1
1 0 1 * * rm /usr/local/www/mgmt/html/bandtrack
Archiving and generation of bandwidth statistics presented in mgmt -> Reference -> Bandwidth


1 0 * * * /usr/local/etc/rsync.backup
* Location: castle, cab 3-7
Nightly backup script
* OS: RedHat 7.3 x86
* Networking: Priv IP: 10.1.4.59 (PCI nic), Pub IP: 69.55.226.161 (onboard nic)
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 74 GB (2 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
* Remote management: none
* Virtuozzo version: 2.6.1
* VZ license: hwid=BC15.B4D6.0D25.A5FE.F3BA.D518.E351.AE3F serial=F6AD.B6B4.5650.8869.C97C.73EE.AF65.FA8B


0 1 * * * /usr/local/www/mgmt/awstats/wwwroot/cgi-bin/awstats.pl -config=jcpub -update
Public web traffic stats


15 0 * * * rm /usr/local/www/mgmt/bwgraphs/*.png
== virt11 ==
16 0 * * * rm /usr/local/www/am/bwgraphs/*
Cleanup for graph-related temp data generated by customers using the bandwidth reports via the AM


10 0 1 * * /usr/local/www/cronjobs/monthly_bandwidth_report.pl
* Location: castle, cab 3-6
Monthly bandwidth overage report
* OS: CentOS 5.4 x86
* Networking: Priv IP: 10.1.4.61, Pub IP: 69.55.238.3, 2 onboard nics
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 146 GB (2 x 146GB) RAID1 array, one 400 GB (2 x 400GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an LSI-based, Dell-branded (perc 6/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.211
* Virtuozzo version: 4.0.0
* VZ license: hwid="029D.A187.78E1.480F.49E3.E20A.7389.7F79" serial="163C.F3E2.195F.96B5.2D38.8937.9600.4A05"  key_number="VZ.00172378.0006"
  vzlicload -p A40R00-D8CS00-5D8817-A2RB23-8Y9J78


*/3 * * * * /usr/local/www/cronjobs/bbcheck.pl
== virt12 ==
Updates mgmt with bb monitoring issues


5 0 * * * /usr/local/www/cronjobs/shutdownreminder.pl
* Location: castle, cab 3-7
Emails customers reminding them of upcoming shutdown date
* OS: CentOS 5.2 x86
* Networking: Priv IP: 10.1.4.62, Pub IP: 69.55.227.70, 2 onboard nics
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 300 GB (2 x 300GB) RAID1 arrays one 400 GB (2 x 400GB) RAID1 array, running on an LSI-based, Dell-branded (perc 6/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.212
* Virtuozzo version: 4.0.0
* VZ license: hwid="0C53.A413.E095.B4F4.51BC.D740.6919.A77B" serial="84E5.9498.3759.E683.E24B.2514.CA72.DC31"


7 0 * * * /usr/local/www/cronjobs/invoice_email.pl
== virt13 ==
Emails customers who have invoices and are set to auto-email (currently no customer gets these)


  8 */4 * * * /usr/local/www/cronjobs/mysqlrepchk.pl
* Location: castle, cab 6-17
Checking that we are properly replicating (mysql) traffic data from bwdb to backup1
* Switch port: P13-
* OS: CentOS 6.2 x86_64
* Networking: Priv IP: 10.1.4.63, Pub IP: 69.55.226.2, 2 onboard nics
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* CPU:    2 x Intel(R) Xeon(R) CPU E5420  @ 2.50GHz  (8 virtual cores)
* RAM:    32 GB (8 x 4GB DDR2 FB-DIMM ECC 667MHz)
* Drives: one 146 GB (2 x 146GB) RAID1 array, one 600 GB (2 x 600GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an LSI-based, Dell-branded (perc 6/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.213
* Virtuozzo version: 4.7.0
* VZ license: hwid="7D07.93BE.0B1F.7D2B.B039.4B5B.48B6.453B" serial="60A4.A94C.44BB.DCD6.8D03.1778.605B.10FE"


16 0 1 * * /usr/local/www/cronjobs/purge_traffic.pl
=== Notes ===
Removed old traffic data from the traffic database (running on backup1)
* home to our latest/current signups
* currently the only 64bit vz host
 
== virt14 ==
 
* Location: castle, cab 6-16
* Switch Port: p13-
* OS: CentOS 6.4 x86_64
* Networking: Priv IP: 10.1.4.64 Pub IP: 69.55.225.14 2 onboard nics
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* CPU: 2 x Xeon 5140 Dual Core @ 2.33GHz (4 virtual CPUs)
* RAM: 32 GB  (8 x 4GB Reg ECC)
* Drives: one 146 GB (2 x 146 GB SAS) RAID1 array, and one 1TB RAID1 array (2 x 1 TB SATA), running on an LSI-based, Dell-branded (perc 5/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.214
* Virtuozzo version: 4.7.0
* VZ license: hwid="EA32.2CA0.2368.F5FC.DFBE.6724.5AC0.8ED0" serial="DA0D.F464.0BCE.35B8.C0C0.28B6.D921.F3FD" key_number="VZ.02634184.0070"
* Activation Key="A00E00-A0WC02-W1A863-482N41-BQAY84"
=== Notes ===
* our latest virt
* Temp server to offload Virt13 till we can get a Cloud going.
* virt 13 and 14 currently the only 64bit vz hosts


*/5 * * * * chmod 0700 /usr/local/www/ccard_orders/* && mv /usr/local/www/ccard_orders/* /usr/local/www/ccard_orders/done
== virt15 ==
Secure credit card data: set root-read-only


25 0 * * * /usr/local/www/cronjobs/biller.pl
* Location: SHUTDOWN
Enters service charges in customer billing ledgers
* OS: RedHat 9 x86
* Networking: Priv IP: 10.1.4.65, Pub IP: 69.55.232.160 (2 onboard nics)
* Hardware: Supermicro (custom build). 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 74 GB (2 x 74GB) RAID1 array, two 146 GB (2 x 146GB) RAID1 arrays, running on an LSI MegaRAID SCSI 320-1 RAID card.
* Remote management: none
* Virtuozzo version: 2.6.2
* VZ license: hwid=A90F.6F48.E723.D8BA.3025.184A.5B73.D11E serial=E94B.5164.C1E6.A67F.67D1.7D96.0B6C.5524


10 13 * * * /usr/local/www/cronjobs/pfp_batch_gather.pl
== virt16 ==
Looks for customers with balance due and active credit card on file, prepares a payflow batch


10 14 * * * /usr/local/www/cronjobs/pfp_batch_process.pl
* Location: castle, cab 3-7
Tries to collect ccard funds for items in payflow batch - communicates with payflow
* OS: Fedora Core 4 x86
* Networking: Priv IP: 10.1.4.66, Pub IP: 69.55.232.2 (2 onboard nics)
* Hardware: Supermicro (custom build). 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 74 GB (2 x 74GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an LSI MegaRAID SCSI 320-1 RAID card.
* Remote management: none
* Virtuozzo version: 3.0.0
* VZ license: hwid=DEFA.A325.7230.BBC8.9715.8B52.3FD7.27BE serial=66C0.41EA.3FBB.11D3.9CC6.55C7.09AE.14AB


15 13 * * * /usr/local/www/cronjobs/pb_batch_gather.pl
Looks for customers with balance due and active paypal billing agreement on file, prepares a paypal batch


15 14 * * * /usr/local/www/cronjobs/pb_batch_process.pl
== virt17 ==
Tries to collect paypal funds for items in paypal batch - communicates with paypal


0 7 * * 1 /usr/local/www/cronjobs/email_pmt_reminder.pl
* Location: castle, cab 3-6
Emails customers in arrears, reminding them to pay
* OS: CentOS 4.4 x86
* Networking: Priv IP: 10.1.4.67, Pub IP: 69.55.232.162, 2 onboard nics
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: two 146 GB (2 x 146GB) RAID1 arrays running on an LSI-based, Dell-branded (perc 5/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.217
* Virtuozzo version: 3.0.0
* VZ license: hwid=2E14.AED9.70B8.C26E.D99F.B0D3.BCD2.229C serial=2A11.DAD0.61DB.E889.8DF4.9AF7.CF82.3C37


0 0 1 * * /usr/bin/mail -s 'archive sent mail in pine' support@johncompanies.com < /dev/null
Reminds us to archive sent mail


0 3 * * * /usr/local/bin/rsync -a isys.e-monitoring.net:/var/mail /backup2/isys; /usr/local/bin/rsync -a isys.e-monitoring.net:/usr/home /backup2/isys
== virt19 ==
Backup data on isys


== Regular maintenance ==
* Location: castle, cab 3-6
*[[Routine_Maintenance#Adaptec_Controllers|Check RAID array]]
* OS: CentOS 5.2 x86
* Networking: Priv IP: 10.1.4.69, Pub IP: 69.55.236.2, 2 onboard nics
* Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: one 146 GB (2 x 146GB) RAID1 array, one 300 GB (2 x 300GB) RAID1 array, running on an LSI-based, Dell-branded (perc 5/i) RAID card.
* Remote management: [[DRAC/RMM|DRAC]] @ 10.1.4.219
* Virtuozzo version: 3.0.0
* VZ license: hwid=3968.13F7.B2AC.8952.8E19.13A9.6EF5.5822 serial=061D.84CD.CCE5.B213.15B5.C061.D6A7.B034


= nat =
= mail =
== Summary ==
== Summary ==
This is the main machine to which we ssh and runs all our screen sessions. Further, it's ip runs in a special block which is not routed through the firewall and this is somewhat immune to DoS attacks which hobble our firewall. Lastly, it acts as a nat server for certain/random devices on the private network.
This machine (mail) is the swiss army knife of the company, playing host to many services and functions.  


* Location: castle, cab 3-7
* Location: castle, cab 3-7
* OS: FreeBSD 4.10 x86
* OS: FreeBSD 4.10 x86
* Networking: Priv IP: 10.1.4.1, Pub IPs: 69.55.233.195, 69.55.233.196, 69.55.233.197, 69.55.233.198, 69.55.233.199. 1 onboard and 1 PCI
* Networking: Priv IP: 10.1.4.5, Pub IPs: 69.55.230.2, 69.55.225.225 (ns1c jail), 69.55.230.9. 1 onboard and 1 PCI
* Hardware: Custom 1U. single power supply.  
* Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.  
* Drives: one 8 GB IDE drive
* Drives: two 36 GB (2 x 36GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.


== Services Provided ==
== Services Provided ==
* nat
* mail
* web
* mysql
* bigbrother server/pager
* snmp
* named in a jail (ns1c)


== nat control ==
== email ==
All rules are contained in and look like:
This server hosts mail for johncompanies.com (mail.johncompanies.com). Sendmail 8.13.6/8.13.6 is listening on 69.55.230.2 port 25 for incoming mail. Relaying is allowed per /etc/mail/relay-domains
Other addresses (aliases) are defined per /etc/mail/aliases
 
The following active users have mail hosted on this server:
* dave
* linux
* support
* payments
* sales
* tech1
* info
 
Traditionally, mail is checked via shell apps (pine). qpopper (pop3s) is running to allow mail downloading. Checking mail in this way causes an opened INBOX in pine to lock read-only. For this reason, we tee incoming mail to support and linux to tech1.
 
Procmail rules are setup to filter spam and send text messages. They are enabled for info, support, linux, tech1, dave and can be found in ~/Procmail/, for example:
<pre># more ~support/Procmail/rc.emergency
:0c # use c only if you want to forward a copy and file the original later
* ^Subject:.*\<emergency\>
* ! ^Subject:\<re\>
  {
  :0h
  FROMANDSUBJECT=|formail -XFrom: -XSubject:


<pre>cat /etc/ipnat.rules
  :0fwh
# www (was 69.55.230.12)
  | /usr/local/bin/formail -I"Subject: " -I"To: pager@johncompanies.com" ; echo $FROMANDSUBJECT ; echo
# virt19
#bimap fxp0 10.1.4.209/32 -> 69.55.233.198/32
# virt18
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32
# virt13
#bimap fxp0 10.1.4.213/32 -> 69.55.233.196/32
# virt12
#bimap fxp0 10.1.4.212/32 -> 69.55.233.196/32
# virt17
bimap fxp0 10.1.4.217/32 -> 69.55.233.196/32
# virt11
#bimap fxp0 10.1.4.211/32 -> 69.55.233.196/32
# ASA
#bimap fxp0 10.1.4.172/32 -> 69.55.233.196/32
# P1A
bimap fxp0 10.1.4.240/32 -> 69.55.233.197/32
#bimap fxp0 10.1.4.238/32 -> 69.55.233.197/32
# developer (was 69.55.230.17)
# jail2
#bimap fxp0 10.1.4.232/32 -> 69.55.233.198/32
# jail8
#bimap fxp0 10.1.4.238/32 -> 69.55.233.198/32
# jail9
#bimap fxp0 10.1.4.239/32 -> 69.55.233.198/32
# POLL
#BIMAP EM0 10.1.6.134/32 -> 69.55.230.20/32
# 1U SUN
#BIMAP EM0 10.1.4.4/32 -> 69.55.227.46/32
# ??
#BIMAP EM0 10.1.6.3/32 -> 69.55.230.100/32
# random machine
#bimap fxp0 10.1.6.13/32 -> 69.55.233.199/32
#bimap fxp0 10.1.4.232/32 -> 69.55.233.199/32
# OFFICE OUTBOUND TRAFFIC
#map fxp0 10.1.6.0/24 -> 0.0.0.0/32 proxy port ftp ftp/tcp
#map fxp0 10.1.6.0/24 -> 0.0.0.0/32</pre>


A simple entry looks like:
  :0
bimap fxp0 10.1.4.240/32 -> 69.55.233.197/32
  ! -t
Which essentially means make private IP 10.1.4.240 reachable on 69.55.233.197 and allow 10.1.4.240 to communicate with the public internet via 69.55.233.197
  }


To reload new rule config:
</pre>
ipnat -C -F -f /etc/ipnat.rules


You may want to setup natting, as above, when you need to reach a DRAC card's web interface, wherin the DRAC card only has a private IP.
control: <tt>cd /etc/mail; make stop</tt> (stop), <tt>cd /etc/mail; make start</tt> (start)


= nat2 =
The following aliases are also in place:
== Summary ==
This is the main machine to which we ssh and runs all our screen sessions at i2b, and runs ns3c (this is kind of the what mail is to castle). Further, it's ip runs in IP space provided by i2b: 66.181.18.1 - 66.181.18.30, which is not routed through the firewall and this is somewhat immune to DoS attacks which hobble our firewall. Lastly, it acts as a nat server for certain/random devices on the private network.


* Location: i2b, cab 6
<pre>debian:         linux
* OS: FreeBSD 6.4 x86
jobs:   info
* Networking: Priv IP: 10.1.2.1, Pub IPs: 69.55.229.2, 69.55.229.3, 66.181.18.4, 66.181.18.5, 66.181.18.6, 66.181.18.7, 66.181.18.8, 66.181.18.9, 66.181.18.10, 66.181.18.11, 66.181.18.12, 66.181.18.13, 66.181.18.14 1 onboard and 1 PCI
careers:       info
* Hardware: Custom 2U. 6 drive bays, non-hot-swappable. single power supply.  
#reboot:         6128102202@txt.att.net
* Drives: one 150 GB (2 x 150GB) RAID1 array running on a 3ware 8006 RAID card.
#reboot:        8582298897@vtext.com
reboot:        pager
#pager: 8582298897@vtext.com
pager:  4158718324@txt.att.net
tech1on: "| /usr/local/sbin/tech1on.sh"
tech1off: "| /usr/local/sbin/tech1off.sh"</pre>


== Services Provided ==
To change them, edit <tt>/etc/aliases</tt> and then run <tt>newaliases</tt>
* nat
* bigbrother
* ns3c (jail)
* ntp


== nat config ==
Note on tech1: this address was setup as a read-only address to be mirrored on all email coming into support and linux. We set this up so we could easily check support mail via a pop client- popping email locks out the user in pine so checking support/linux directly via pop was not an option. When checking and responding to email that comes into tech1, care should be taken to make sure it is sent as/under an address other than tech1. This is cause tech1 is not monitored by support staff as closely as email to support/linux. Further, the tech on call may not be checking tech1. Lastly, because of the nature of the copying, you will sometimes notice certain automated email/notices are received 2x in support- this is because of/related to the tech1 mirror.
Here's what's currently nat'd on nat2:
<pre>cat /etc/ipnat.rules
# sample entry
#ATS-9
bimap em0 10.1.2.79/32 -> 66.181.18.14/32
#ATS-8
bimap em0 10.1.2.78/32 -> 66.181.18.13/32
#ATS-7
bimap em0 10.1.2.77/32 -> 66.181.18.12/32
#ATS-6
bimap em0 10.1.2.76/32 -> 66.181.18.6/32
#ATS-5
bimap em0 10.1.2.75/32 -> 66.181.18.7/32
#ATS-4
bimap em0 10.1.2.74/32 -> 66.181.18.8/32
#ATS-3
bimap em0 10.1.2.73/32 -> 66.181.18.9/32
#ATS-2
bimap em0 10.1.2.72/32 -> 66.181.18.10/32
#ATS-1
bimap em0 10.1.2.71/32 -> 66.181.18.11/32
#bwdb2
bimap em0 10.1.2.4/32 -> 66.181.18.5/32


# spare
To enable it (on mail, run):


map em0 10.1.2.0/24 -> 0.0.0.0/32 proxy port ftp ftp/tcp
<tt>~support/tech1on.sh</tt>


#bimap fxp0 10.1.6.49/32 -> 10.1.1.2/32
To disable
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32
</pre>


== build ==
<tt>~support/tech1off.sh</tt>


* partition map:
Or via email:
<pre>/ 512m
swap 1G
/var 256m
/tmp 256m
/usr 5g
/mnt/data1 ~</pre>


* edit /etc/make.conf
<tt>tech1on@johncompanies.com
<pre>echo "WITHOUT_X11=yes \
tech1off@johncompanies.com</tt>
KERNCONF=nat2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf</pre>


* add settings to /boot/loader.conf and /boot.config
== IP Blocking ==


<pre>echo "-Dh" >> /boot.config
<pre>
01000 deny ip from 188.92.72.5 to any
01003 deny ip from any to 122.49.31.50
01004 deny ip from 122.49.31.50 to any
01014 deny ip from 74.208.225.225 to any
01015 deny ip from any to 216.243.118.35
01016 deny ip from 216.243.118.35 to any
01017 deny ip from any to 216.243.118.36
01018 deny ip from 216.243.118.36 to any
01020 deny ip from 112.215.0.0/18 to any  2014-08-13 Blocked PT Excelcomindo Pratama (Indonesia) for fradulent credit card attempts
01020 deny ip from 112.215.64.0/20 to any  2014-08-13 Blocked PT Excelcomindo Pratama (Indonesia) for fradulent credit card attempts
01022 deny ip from 120.168.0.0/24 to any  2014-08-13 Blocked Indosat 3G Broadband (Indonesia) for fradulent credit card attempts
01022 deny ip from 120.175.213.0/24 to any 2014-08-13 Blocked Indosat 3G Broadband (Indonesia) for fradulent credit card attempts


echo 'console="comconsole,vidconsole" \
</pre>
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf</pre>


* turn off all ttyv's except 0 and 1 in /etc/ttys
== web ==
also turn on ttyd0, change type to vt100:
<pre>vi /etc/ttys


ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
See [[Management_System_/_Public_Website_/_Signup|Management System / Public Website / Signup]]
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
ttyv6  "/usr/libexec/getty Pc"        cons25  off secure
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0  "/usr/libexec/getty std.9600"  vt100  on  secure


kill -1 1</pre>
== mysql ==
mysql 4.1.22 is running on port 3306


on console server:
* datadir: <tt>/mnt/data1/db/mysql/</tt>
vi /etc/remote
* config: <tt>/etc/my.cnf</tt>
(rename port to jail8 depending on where and which digi plugged into)
* database: <tt>jc</tt>
test serial console
* control: <tt>/usr/local/etc/rc.d/mysql-server.sh stop</tt> (stop), <tt>/usr/local/etc/rc.d/mysql-server.sh start</tt> (start)


== bigbrother ==
There is a client running on mail (which monitors the services running on mail and mail itself), installed under <tt>/usr/home/bb/bbc1.9e-btf</tt><br>
And the big brother pager/server (which displays information gathered from all bb-monitored machines, including mail) is installed under <tt>/usr/home/bb/bbsrc/bb1.9i-btf</tt>


* populate hosts
Both are running under the user <tt>bb</tt>
<pre>echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.4 bwdb2" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts</pre>


* put key in authorized_keys on backup3
Refer to [[BigBrother]] for more about use.
<pre>cd
ssh-keygen -t dsa -b 1024</pre>
(default location, leave password blank)


<pre>cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'
== DNS (ns1c.johncompanies.com) ==
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
ns1c is a jail running on the mail server, who's IP is 69.55.225.225
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'</pre>


confirm that you can ssh to backup3 and backup 2 without getting a login prompt
It's running from <tt>/mnt/data1/ns1c-dir</tt>


ssh backup3 hostname
See [[DNS]] for more details


ssh backup2 hostname
== Usage and Notes ==
* always mounted to backup1 and backup2 via nfs:
<pre>backup2:/mnt/data1 on /backup (nfs)
backup2:/mnt/data2 on /backup2 (nfs)
backup2:/mnt/data3 on /backup3 (nfs)
backup2:/mnt/data4 on /backup4 (nfs)
backup1:/data on /backup1 (nfs)
</pre>


  ssh backup1 hostname
== Cronjobs ==
  * * * * * /usr/local/www/mgmt/mrtg/mrtg.sh > /dev/null 2>&1
Gathers up data for our mrtg/load graphs


*/5 * * * * /usr/local/bin/rsync -a root@nat2:/mnt/data1/mrtg/data/ /usr/local/www/mgmt/mrtg/data/
Gathers up data from i2b servers for our mrtg/load graphs


* edit root's path and login script:
40 0 * * * /usr/local/bin/rsync -a root@nat2:"/mnt/data1/mrtg/*.cfg" /usr/local/www/mgmt/mrtg
vi /root/.cshrc
Gathers up mrtg configuration (port names) from i2b switches for our mrtg/load graphs


Change alias entries (add G):
41 0 * * * for f in `grep -l "mnt\/data1" /usr/local/www/mgmt/mrtg/switch-p*.cfg`; do cat $f | sed s#\/mnt\/data1#\/usr\/local\/www\/mgmt# > $f.new; mv $f.new $f; done
<pre>alias la        ls -aG
Gathers up mrtg configuration (port names) from castle switches for our mrtg/load graphs
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm      mb mount
alias mbu      mb umount</pre>


and alter the prompt, set the following:
1 0 1 * * cp /usr/local/www/mgmt/html/top20ip /usr/local/www/mgmt/html/top20ip_last
  set prompt = "`/bin/hostname -s` %/# "
1 0 1 * * cp /usr/local/www/mgmt/html/top20customers /usr/local/www/mgmt/html/top20customers_last
2 * * * * /usr/local/www/cronjobs/top20ip.pl > /dev/null 2>&1
15 * * * * /usr/local/www/cronjobs/top20customer.pl > /dev/null 2>&1
  1 0 1 * * rm /usr/local/www/mgmt/html/bandtrack
Archiving and generation of bandwidth statistics presented in mgmt -> Reference -> Bandwidth


* install cvsup
1 0 * * * /usr/local/etc/rsync.backup
<pre>cd /usr/ports/net/cvsup-without-gui
Nightly backup script
make install clean; rehash; mail -s 'cvs installed' dave.boodman@vtext.com < /dev/null</pre>


* get latest sources for this release:
0 1 * * * /usr/local/www/mgmt/awstats/wwwroot/cgi-bin/awstats.pl -config=jcpub -update
<pre>cd /usr/src
Public web traffic stats
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
src-all" > sup


cvsup sup ; mail -s 'cvs sup done' dave.boodman@vtext.com < /dev/null</pre>
15 0 * * * rm /usr/local/www/mgmt/bwgraphs/*.png
16 0 * * * rm /usr/local/www/am/bwgraphs/*
Cleanup for graph-related temp data generated by customers using the bandwidth reports via the AM


10 0 1 * * /usr/local/www/cronjobs/monthly_bandwidth_report.pl
Monthly bandwidth overage report


* configure new kernel.  
*/3 * * * * /usr/local/www/cronjobs/bbcheck.pl
Updates mgmt with bb monitoring issues


  cd /usr/src/sys/i386/conf
  5 0 * * * /usr/local/www/cronjobs/shutdownreminder.pl
  scp backup2:/mnt/data4/build/freebsd/nat2-6.4 ./nat2
Emails customers reminding them of upcoming shutdown date
 
  7 0 * * * /usr/local/www/cronjobs/invoice_email.pl
Emails customers who have invoices and are set to auto-email (currently no customer gets these)


* build, install kernel and world
8 */4 * * * /usr/local/www/cronjobs/mysqlrepchk.pl
Checking that we are properly replicating (mysql) traffic data from bwdb to backup1


<pre>cd /boot
16 0 1 * * /usr/local/www/cronjobs/purge_traffic.pl
Removed old traffic data from the traffic database (running on backup1)


mv kernel kernel.GENERIC
*/5 * * * * chmod 0700 /usr/local/www/ccard_orders/* && mv /usr/local/www/ccard_orders/* /usr/local/www/ccard_orders/done
cd kernel.GENERIC
Secure credit card data: set root-read-only
cd /usr/src
make buildkernel installkernel


make buildworld ; mail -s 'buildworld done' support@johncompanies.com < /dev/null
25 0 * * * /usr/local/www/cronjobs/biller.pl
make installworld
Enters service charges in customer billing ledgers
mergemaster -i
</pre>


* populate /etc/rc.conf with IPs and NFS settings
10 13 * * * /usr/local/www/cronjobs/pfp_batch_gather.pl
<pre>vi /etc/rc.conf
Looks for customers with balance due and active credit card on file, prepares a payflow batch


hostname="nat2.johncompanies.com"
10 14 * * * /usr/local/www/cronjobs/pfp_batch_process.pl
kern_securelevel_enable="NO"
Tries to collect ccard funds for items in payflow batch - communicates with payflow
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"


xntpd_enable="YES"
15 13 * * * /usr/local/www/cronjobs/pb_batch_gather.pl
xntpd_flags="-A -p /var/run/ntpd.pid"
Looks for customers with balance due and active paypal billing agreement on file, prepares a paypal batch


nfs_client_enable="YES"
15 14 * * * /usr/local/www/cronjobs/pb_batch_process.pl
nfs_reserved_port_only="YES"
Tries to collect paypal funds for items in paypal batch - communicates with paypal
ifconfig_em0="inet 10.1.6.50 netmask 255.255.255.0"
 
#ifconfig_em0="inet 69.55.229.2 netmask 255.255.255.0"
0 7 * * 1 /usr/local/www/cronjobs/email_pmt_reminder.pl
#ifconfig_em0_alias0="inet 69.55.229.229 netmask 255.255.255.255"
Emails customers in arrears, reminding them to pay
ifconfig_fxp0="inet 69.55.229.2 netmask 255.255.255.0"
ifconfig_fxp0_alias0="inet 69.55.229.3 netmask 255.255.255.255"
ifconfig_fxp1="inet 10.1.2.1 netmask 255.255.255.0"
defaultrouter="10.1.6.1"
#defaultrouter=" 66.181.14.250"
snmpd_enable="YES"
ipnat_enable="YES"
ipnat_rules="/etc/ipnat.rules"
gateway_enable="YES"


inetd_enable="YES"
0 0 1 * * /usr/bin/mail -s 'archive sent mail in pine' support@johncompanies.com < /dev/null
inetd_flags="-wW -a 10.1.2.1"
Reminds us to archive sent mail
fsck_y_enable="YES"
background_fsck="NO"
sshd_enable="YES"</pre>


* reboot. Confirm new kernel is loaded
0 3 * * * /usr/local/bin/rsync -a isys.e-monitoring.net:/var/mail /backup2/isys; /usr/local/bin/rsync -a isys.e-monitoring.net:/usr/home /backup2/isys
Backup data on isys


uname -a
== Regular maintenance ==
*[[Routine_Maintenance#Adaptec_Controllers|Check RAID array]]


* update ports:
== Building a new Mail Server ==
<pre>cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup


cvsup sup; mail -s 'cvs sup ports done' dave.boodman@vtext.com < /dev/null</pre>
=== Installations ===


* Install raid mgmt tool
I used FreeBSD 11.2


<pre>cd /usr/local/sbin
The order is important especially for the Web Server.
fetch http://3ware.com/download/Escalade9690SA-Series/9.5.3/tw_cli-freebsd-x86-9.5.3.tgz
tar xzf tw_cli-freebsd-x86-9.5.3.tgz
rm tw_cli-freebsd-x86-9.5.3.tgz
chmod 0700 tw_cli</pre>


Test:
==== Web Server ====
./tw_cli info c0
 
I used FreeBSD 11.2
  perl 5.26
  OpenSSL 1.0.2o-freebsd
  pcre
  apache22
  mod_perl2
  PayflowPro
  mariadb 55 server and client


* install rsync from ports
Installation order is important
<pre>cd /usr/ports/net/rsync
make install clean</pre>
choose default options


* install perl from ports
install perl 5.26.2 from ports
<pre>cd /usr/ports/lang/perl5.8
make install clean</pre>


* install screen from ports
<ore>
<pre>cd /usr/ports/sysutils/screen
cd /usr/ports/lang/perl5.26/
make install clean</pre>
make
[X] PERL_64BITINT  Use 64 bit integers (on i386)
[X] USE_PERL      Rewrite links in /usr/bin
(the rest unchecked
make install
</pre>


* install bb client
install OpenSSL 1.0.2o-freebsd
<pre>adduser
Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes


cd /usr/home/bb
<pre>
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
cd /usr/ports/
tar xvf bb-freebsd.tar</pre>
make install
edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
</pre>
<pre>echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
 
10.1.2.1 nat2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
install pcre
vi /home/bb/bbc1.9e-btf/ext/openfiles
MACHINE="nat2,johncompanies,com"      # HAS TO BE IN A,B,C FORM


cd /usr/home/bb/bbc1.9e-btf/etc
<pre>
./bbchkcfg.sh
cd /usr/ports/
(y to questions)
make install
./bbchkhosts.sh
</pre>
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..


vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$


./runbb.sh start
install Apache22
more BBOUT
(look for errors)
exit


echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
<pre>
chmod +x /usr/local/etc/rc.d/bb.sh
cd /usr/ports/distfiles
</pre>
fetch http://archive.apache.org/dist/httpd/httpd-2.2.32.tar.gz


Punch a hole in the firewall to allow it to communicate with bb monitor (probably already exists):


ipfw add 96 allow ip from 66.181.18.0/27 to 69.55.230.2
cd /usr/ports/www/apache22/tmp
fetch --no-verify-peer http://mirror.nexcess.net/apache//httpd/httpd-2.2.34.tar.gz
tar xvzf httpd-2.2.34.tar.gz
./configure --prefix=/usr/local/apache --with-ssl=/usr/local/openssl/ --enable-ssl --enable-so --with-mpm=prefork --enable-threads --enable-mods-shared='mime alias setenvif dir' --enable-modules='mime alias setenvif dir' --with-pcre=/usr/local
make install
apachectl restart


* configure bb on mail:
cd /usr/ports/www/apache22
<pre>vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
echo "DEFAULT_VERSIONS+=apache=2.2" >> /etc/make.conf
64.163.14.48 nat2.johncompanies.com # ssh
make DISABLE_VULNERABILITIES=yes
make install
</pre>


su bb
cd
bbsrc/bb/runbb.sh restart ; exit</pre>


* configure ntp
install mod_perl2
<pre>echo "server 69.55.230.2
 
server 0.pool.ntp.org
<pre>
server 1.pool.ntp.org
cd /usr/ports/www/mod_perl2
server 2.pool.ntp.org
echo "DEFAULT_VERSIONS+=apache=2.2" >> /etc/make.conf
server 3.pool.ntp.org
make DISABLE_VULNERABILITIES=yes
server 66.187.233.4
make install
server 217.204.76.170
</pre>
server 64.112.189.11
server 66.69.112.130
server 80.85.129.25
server 80.237.234.15
server 130.60.7.44
server 134.99.176.3
server 198.144.202.250
server 202.74.170.194
server 204.17.42.199
server 204.87.183.6
server 213.15.3.1
server 213.239.178.33
server 217.114.97.97
server 69.55.230.2" > /etc/ntp.conf</pre>


<pre>/usr/sbin/ntpd -A -p /var/run/ntpd.pid
sleep 2; ntpq -p</pre>
(confirm it’s able to reach our time server)


echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
install mariadb
chmod 0700 /usr/local/etc/rc.d/ntp.sh


* fwd and reverse lookups on ns1c
<pre>
vr johncompanies.com
cd /usr/ports/databases/mariadb-103-server
(edit the PTR too)
echo "DEFAULT_VERSIONS+=apache=2.2" >> /etc/make.conf
make DISABLE_VULNERABILITIES=yes
make install


* setup backups, nfs mount


<pre>mkdir /backup3
</pre>
echo 'backup3:/data          /backup3        nfs    rw,bg          0      0' >> /etc/fstab


echo '#\!/bin/sh\
==== Mail Server ====
backupdir=/data/nat2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config</pre>


on backup3:
I used Postfix for email
setup backup dirs:
ssh backup3 mkdir -p /data/nat2/current


on backup3, add the system to
==== DNS Server (ns1c.johncompanies.com) ====
vi /usr/local/sbin/snapshot_archive


<pre>scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup
= ns2c =
vi /usr/local/etc/rsync.backup
== Summary ==
backup1 > backup3</pre>


  crontab -e
* Location: castle, on lamphost ganeti cloud
  1 0 * * * /usr/local/etc/rsync.backup
* OS: FreeBSD 11.2 x86_64
* Networking: Pub IP: 69.55.230.3  Private access: gnt-instance console ns2c.johncompanies.com
* Hardware: on ganeti cloud gn6.jcihosting.net secondary gn1.jcihosting.net
* CPU: 1
* RAM: 1 GB
* Drives: 10 GB
* Remote management:  gnt-instance console ns2c.johncompanies.com


* edit sshd_config for security
= nat =
<pre>vi /etc/ssh/sshd_config
== Summary ==
ListenAddress 66.181.18.1
This is the main machine to which we ssh and runs all our screen sessions. Further, it's ip runs in a special block which is not routed through the firewall and this is somewhat immune to DoS attacks which hobble our firewall. Lastly, it acts as a nat server for certain/random devices on the private network.
ListenAddress 69.55.229.2
ListenAddress 10.1.2.1


kill -1 `cat /var/run/sshd.pid`</pre>
* Location: castle, cab 3-7
* OS: FreeBSD 9.1 i386
* Networking: Priv IP: 10.1.4.1, Pub IPs: 69.55.233.195, 69.55.233.196, 69.55.233.197, 69.55.233.198, 69.55.233.199. 1 onboard and 1 PCI
* Hardware: Custom 1U. single power supply.
* Drives: one 8 GB IDE drive


* raid chk
== Services Provided ==
* nat


<pre>cat > /usr/local/sbin/lsiraidchk
== nat control ==
#!/usr/bin/perl
All rules are contained in and look like:


my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;
<pre>cat /etc/ipnat.rules
 
# www (was 69.55.230.12)
foreach (@out) {
# virt19
    if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#bimap fxp0 10.1.4.209/32 -> 69.55.233.198/32
#print $_;
# virt18
}</pre>
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32
# virt13
#bimap fxp0 10.1.4.213/32 -> 69.55.233.196/32
# virt12
#bimap fxp0 10.1.4.212/32 -> 69.55.233.196/32
# virt17
bimap fxp0 10.1.4.217/32 -> 69.55.233.196/32
# virt11
#bimap fxp0 10.1.4.211/32 -> 69.55.233.196/32
# ASA
#bimap fxp0 10.1.4.172/32 -> 69.55.233.196/32
# P1A
bimap fxp0 10.1.4.240/32 -> 69.55.233.197/32
#bimap fxp0 10.1.4.238/32 -> 69.55.233.197/32
# developer (was 69.55.230.17)
# jail2
#bimap fxp0 10.1.4.232/32 -> 69.55.233.198/32
# jail8
#bimap fxp0 10.1.4.238/32 -> 69.55.233.198/32
# jail9
#bimap fxp0 10.1.4.239/32 -> 69.55.233.198/32
# POLL
#BIMAP EM0 10.1.6.134/32 -> 69.55.230.20/32
# 1U SUN
#BIMAP EM0 10.1.4.4/32 -> 69.55.227.46/32
# ??
#BIMAP EM0 10.1.6.3/32 -> 69.55.230.100/32
# random machine
#bimap fxp0 10.1.6.13/32 -> 69.55.233.199/32
#bimap fxp0 10.1.4.232/32 -> 69.55.233.199/32
# OFFICE OUTBOUND TRAFFIC
#map fxp0 10.1.6.0/24 -> 0.0.0.0/32 proxy port ftp ftp/tcp
#map fxp0 10.1.6.0/24 -> 0.0.0.0/32</pre>


* netflow stuff
A simple entry looks like:
add crontab entries
bimap fxp0 10.1.4.240/32 -> 69.55.233.197/32
<pre>crontab -e
Which essentially means make private IP 10.1.4.240 reachable on 69.55.233.197 and allow 10.1.4.240 to communicate with the public internet via 69.55.233.197
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;
*/5 * * * * /usr/local/sbin/lsiraidchk


#10 0 * * * rm /var/spool/clientmqueue/*</pre>
To reload new rule config:
ipnat -C -F -f /etc/ipnat.rules


<pre>scp /etc/makefwrules.pl user@64.163.14.48:~
You may want to setup natting, as above, when you need to reach a DRAC card's web interface, wherin the DRAC card only has a private IP.
scp /etc/makepiperules.pl user@64.163.14.48:~
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
mkdir /etc/oldrules/</pre>


other binaries
= nat2 =
== Summary ==
<pre>scp /usr/local/bin/rulemaker user@64.163.14.48:~
This is the main machine to which we ssh and runs all our screen sessions at i2b, and runs ns3c (this is kind of the what mail is to castle). Further, it's ip runs in IP space provided by i2b: 66.181.18.1 - 66.181.18.30, which is not routed through the firewall and this is somewhat immune to DoS attacks which hobble our firewall. Lastly, it acts as a nat server for certain/random devices on the private network.
mv ~user/rulemaker /usr/local/sbin
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~</pre>


* add nat rules
* Location: i2b, cab 6
<pre>vi /etc/ipnat.rules
* OS: FreeBSD 6.4 x86
# sample entry
* Networking: Priv IP: 10.1.2.1, Pub IPs: 69.55.229.2, 69.55.229.3, 66.181.18.4, 66.181.18.5, 66.181.18.6, 66.181.18.7, 66.181.18.8, 66.181.18.9, 66.181.18.10, 66.181.18.11, 66.181.18.12, 66.181.18.13, 66.181.18.14 1 onboard and 1 PCI
bimap fxp0 10.1.6.70/32 -> 10.1.6.59/32
* Hardware: Custom 2U. 6 drive bays, non-hot-swappable. single power supply.  
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32
* Drives: one 150 GB (2 x 150GB) RAID1 array running on a 3ware 8006 RAID card.


ipnat -C -f /etc/ipnat.rules</pre>
== Services Provided ==
* nat
* bigbrother
* ns3c (jail)
* wiki (jail)
* ntp


* shell for user
== nat config ==
<pre>cp /root/.cshrc ~user/
Here's what's currently nat'd on nat2:
vi ~user/</pre>
<pre>cat /etc/ipnat.rules
change # to $
# sample entry
#ATS-9
bimap em0 10.1.2.79/32 -> 66.181.18.14/32
#ATS-8
bimap em0 10.1.2.78/32 -> 66.181.18.13/32
#ATS-7
bimap em0 10.1.2.77/32 -> 66.181.18.12/32
#ATS-6
bimap em0 10.1.2.76/32 -> 66.181.18.6/32
#ATS-5
bimap em0 10.1.2.75/32 -> 66.181.18.7/32
#ATS-4
bimap em0 10.1.2.74/32 -> 66.181.18.8/32
#ATS-3
bimap em0 10.1.2.73/32 -> 66.181.18.9/32
#ATS-2
bimap em0 10.1.2.72/32 -> 66.181.18.10/32
#ATS-1
bimap em0 10.1.2.71/32 -> 66.181.18.11/32
#bwdb2
bimap em0 10.1.2.4/32 -> 66.181.18.5/32


* mrtg
# spare


<pre>cd /usr/ports/net-mgmt/mrtg
map em0 10.1.2.0/24 -> 0.0.0.0/32 proxy port ftp ftp/tcp
make install clean</pre>
(no FONTCONFIG, v3)


this didn't work cause of libtool incompat
#bimap fxp0 10.1.6.49/32 -> 10.1.1.2/32
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32
</pre>


so manually moved files:
== build ==


<pre>scp /usr/local/bin/cfgmaker user@nat2:/usr/local/bin/cfgmaker
* partition map:
scp /usr/local/lib/perl5/site_perl/5.6.1/MRTG_lib.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
<pre>/ 512m
scp /usr/local/lib/perl5/site_perl/5.6.1/SNMP_util.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
swap 1G
scp /usr/local/lib/perl5/site_perl/5.6.1/BER.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
/var 256m
scp /usr/local/lib/perl5/site_perl/5.6.1/SNMP_Session.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
/tmp 256m
scp /usr/local/bin/mrtg root@nat2:/usr/local/bin/mrtg
/usr 5g
scp /usr/local/lib/perl5/site_perl/5.6.1/locales_mrtg.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/locales_mrtg.pm
/mnt/data1 ~</pre>
scp /usr/local/bin/rrdtool root@nat2:/usr/local/bin/rrdtool
scp /usr/local/lib/perl5/site_perl/5.6.1/mach/RRDs.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/mach/RRDs.pm
rsync -av /usr/local/lib/perl5/site_perl/5.6.1/mach/auto/RRDs/ root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/mach/auto/RRDs/
scp /usr/lib/libz.so.2 root@nat2:/usr/lib/libz.so.2
scp /usr/lib/libm.so.2 root@nat2:/usr/lib/libm.so.2
rsync -av /usr/local/lib/librrd* root@nat2:/usr/local/lib/
scp /usr/lib/libc.so.4 root@nat2:/usr/lib/libc.so.4


rsync -av /usr/ports/net/rrdtool root@nat2:/usr/ports/net
* edit /etc/make.conf
cd /usr/ports/net/rrdtool
<pre>echo "WITHOUT_X11=yes \
make install
KERNCONF=nat2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf</pre>


mkdir -p /mnt/data1/mrtg/data
* add settings to /boot/loader.conf and /boot.config
scp /usr/local/www/mgmt/mrtg/template.pl root@nat2:/mnt/data1/mrtg/
scp /usr/local/www/mgmt/mrtg/host.pl root@nat2:/mnt/data1/mrtg/


cfgmaker --if-template=template.pl --show-op-down --global "options[_]: growright,bits" --global 'WorkDir: /mnt/data1/mrtg/data' --global 'Interval: 1' --global 'LogFormat: rrdtool' --global 'PathAdd: /usr/local/bin' --global 'LibAdd: /usr/local/lib' --host-template=host.pl jc292401@10.1.2.50 --output=switch-p20.cfg
<pre>echo "-Dh" >> /boot.config


cat > /mnt/data1/mrtg/mrtg.sh
echo 'console="comconsole,vidconsole" \
#!/bin/sh
boot_multicons="YES" \
/usr/local/bin/mrtg /mnt/data1/mrtg/switch-p20.cfg
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf</pre>


chmod 0700 /mnt/data1/mrtg/mrtg.sh
* turn off all ttyv's except 0 and 1 in /etc/ttys
also turn on ttyd0, change type to vt100:
<pre>vi /etc/ttys


crontab -e
ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
* * * * * /mnt/data1/mrtg/mrtg.sh 2>&1 > /dev/null</pre>
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
ttyv6  "/usr/libexec/getty Pc"        cons25  off secure
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0  "/usr/libexec/getty std.9600"  vt100  on  secure


* snmp firewall block
kill -1 1</pre>
<pre>cat > /usr/local/etc/rc.d/boot.sh
ipfw add 10 allow udp from 69.55.230.2 to any 161
ipfw add 10 allow udp from 10.1.2.1 to any 161
ipfw add 11 deny udp from any to any 161
chmod 0700 /usr/local/etc/rc.d/boot.sh</pre>


= bwdb =
on console server:
== Summary ==
vi /etc/remote
This machine tracks and stores network traffic (netflow) at castle. It is our means to monitor customer bandwidth usage.
(rename port to jail8 depending on where and which digi plugged into)
test serial console


* Location: castle, cab 3-7
* OS: FreeBSD 4.10 x86
* Networking: Priv IP: 10.1.4.203 There are 2 onboard nic's, one of which is the "listener"
* Hardware: Custom 1U. Single power supply.
* Drives: one 250 GB (2 x 250GB) RAID1 array running on a Promise IDE RAID card.


== Services Provided ==
* populate hosts
* netflow
<pre>echo "69.55.230.10 backup2" >> /etc/hosts
* mysql
echo "69.55.230.11 backup1" >> /etc/hosts
* bigbrother
echo "10.1.2.4 bwdb2" >> /etc/hosts
* snmp
echo "10.1.2.3 backup3" >> /etc/hosts</pre>


== netflow ==
* put key in authorized_keys on backup3
<pre>cd
ssh-keygen -t dsa -b 1024</pre>
(default location, leave password blank)


The main function of this server is to run netflow on an eth device in promiscuous mode so as to hear everything happening on the port (wherein all network traffic is mirrored to that port via the cisco swith). Every 15min, it creates a flow file under <tt>/usr/home/flows/</tt> (organized by date). The flow file contains all traffic data for a 15min increment of time.
<pre>cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'</pre>


A cronjob moves that flow file (or files if there are multiple due to some delay)
confirm that you can ssh to backup3 and backup 2 without getting a login prompt
1,16,31,46 * * * * /usr/home/flowbin/queue.pl


into a processing queue:
ssh backup3 hostname
<tt>/usr/home/working</tt>


Then a separate file processes whatever flow files it finds there, inserting the data into the local mysql database:
ssh backup2 hostname
  2,17,32,47 * * * * /usr/home/flowbin/processflows.pl
 
ssh backup1 hostname
 
 
* edit root's path and login script:
vi /root/.cshrc
 
Change alias entries (add G):
<pre>alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm      mb mount
alias mbu      mb umount</pre>
 
and alter the prompt, set the following:
  set prompt = "`/bin/hostname -s` %/# "


== mysql ==
* install cvsup
<pre>cd /usr/ports/net/cvsup-without-gui
make install clean; rehash; mail -s 'cvs installed' dave.boodman@vtext.com < /dev/null</pre>


The database storing all the traffic data is named <tt>traffic</tt>
* get latest sources for this release:
Tables:
<pre>cd /usr/src
<pre>mysql> show tables;
echo "*default host=cvsup4.freebsd.org\
+---------------------------+
*default base=/usr\
| Tables_in_traffic        |
*default prefix=/usr\
+---------------------------+
*default release=cvs tag=RELENG_6_4\
| dailyIpTotals_69_55_224  |
*default delete use-rel-suffix\
| dailyIpTotals_69_55_225  |
*default compress\
| dailyIpTotals_69_55_226  |
src-all" > sup
| dailyIpTotals_69_55_227  |
 
| dailyIpTotals_69_55_228  |
cvsup sup ; mail -s 'cvs sup done' dave.boodman@vtext.com < /dev/null</pre>
| dailyIpTotals_69_55_229  |
 
| dailyIpTotals_69_55_230  |
 
| dailyIpTotals_69_55_231  |
* configure new kernel.
| dailyIpTotals_69_55_232  |
 
| dailyIpTotals_69_55_233  |
cd /usr/src/sys/i386/conf
| dailyIpTotals_69_55_234  |
scp backup2:/mnt/data4/build/freebsd/nat2-6.4 ./nat2
| dailyIpTotals_69_55_235  |
 
| dailyIpTotals_69_55_236  |
* build, install kernel and world
| dailyIpTotals_69_55_237  |
 
| dailyIpTotals_69_55_238  |
<pre>cd /boot
| dailyIpTotals_69_55_239  |
 
| dailyPortTotals_69_55_224 |
mv kernel kernel.GENERIC
| dailyPortTotals_69_55_225 |
cd kernel.GENERIC
| dailyPortTotals_69_55_226 |
cd /usr/src
| dailyPortTotals_69_55_227 |
make buildkernel installkernel
| dailyPortTotals_69_55_228 |
 
| dailyPortTotals_69_55_229 |
make buildworld ; mail -s 'buildworld done' support@johncompanies.com < /dev/null
| dailyPortTotals_69_55_230 |
make installworld
| dailyPortTotals_69_55_231 |
mergemaster -i
| dailyPortTotals_69_55_232 |
| dailyPortTotals_69_55_233 |
| dailyPortTotals_69_55_234 |
| dailyPortTotals_69_55_235 |
| dailyPortTotals_69_55_236 |
| dailyPortTotals_69_55_237 |
| dailyPortTotals_69_55_238 |
| dailyPortTotals_69_55_239 |
| ipTotals_69_55_224        |
| ipTotals_69_55_225        |
| ipTotals_69_55_226        |
| ipTotals_69_55_227        |
| ipTotals_69_55_228        |
| ipTotals_69_55_229        |
| ipTotals_69_55_230        |
| ipTotals_69_55_231        |
| ipTotals_69_55_232        |
| ipTotals_69_55_233        |
| ipTotals_69_55_234        |
| ipTotals_69_55_235        |
| ipTotals_69_55_236        |
| ipTotals_69_55_237        |
| ipTotals_69_55_238        |
| ipTotals_69_55_239        |
| portTotals_69_55_224      |
| portTotals_69_55_225      |
| portTotals_69_55_226      |
| portTotals_69_55_227      |
| portTotals_69_55_228      |
| portTotals_69_55_229      |
| portTotals_69_55_230      |
| portTotals_69_55_231      |
| portTotals_69_55_232      |
| portTotals_69_55_233      |
| portTotals_69_55_234      |
| portTotals_69_55_235      |
| portTotals_69_55_236      |
| portTotals_69_55_237      |
| portTotals_69_55_238      |
| portTotals_69_55_239      |
+---------------------------+
</pre>
</pre>


So as you see we store each class-C block in its own table, for efficiency. Further, we store and organize data in 4 ways: "daily" tables and 15-minute granularity tables, and for each of those we track simple IP traffic and port-specific traffic. The daily tables contains 2 entries (one for each direction) for each IP for each day. For the current day, the row data is incremented as the day goes on.  
* populate /etc/rc.conf with IPs and NFS settings
<pre>vi /etc/rc.conf


<pre>mysql> describe dailyIpTotals_69_55_224;
hostname="nat2.johncompanies.com"
+-----------+-------------+------+-----+---------+-------+
kern_securelevel_enable="NO"
| Field    | Type        | Null | Key | Default | Extra |
portmap_enable="NO"
+-----------+-------------+------+-----+---------+-------+
sendmail_enable="NO"
| id        | varchar(23) |      | PRI |        |      |
usbd_enable="YES"
| date      | date        | YES  |    | NULL    |      |
| ip        | varchar(15) | YES  | MUL | NULL    |      |
| direction | tinyint(1)  | YES  |    | NULL    |      |
| octets    | bigint(12)  | YES |    | NULL    |      |
| packets  | int(11)    | YES  |    | NULL    |      |
+-----------+-------------+------+-----+---------+-------+


mysql> select * from dailyIpTotals_69_55_224 limit 1\G
xntpd_enable="YES"
*************************** 1. row ***************************
xntpd_flags="-A -p /var/run/ntpd.pid"
      id: 6955224194-20100917-1
    date: 2010-09-17
      ip: 69.55.224.194
direction: 1
  octets: 8821
  packets: 91
</pre>


The <tt>id</tt> is a unique identifier (key), <tt>direction</tt> indicates incoming or outgoing traffic (outbound = 2, inbound = 1), <tt>octets</tt> are the amount of traffic in kilobytes, and <tt>packets</tt> is the total number of packets.
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
ifconfig_em0="inet 10.1.6.50 netmask 255.255.255.0"
#ifconfig_em0="inet 69.55.229.2 netmask 255.255.255.0"
#ifconfig_em0_alias0="inet 69.55.229.229 netmask 255.255.255.255"
ifconfig_fxp0="inet 69.55.229.2 netmask 255.255.255.0"
ifconfig_fxp0_alias0="inet 69.55.229.3 netmask 255.255.255.255"
ifconfig_fxp1="inet 10.1.2.1 netmask 255.255.255.0"
defaultrouter="10.1.6.1"
#defaultrouter=" 66.181.14.250"
snmpd_enable="YES"
ipnat_enable="YES"
ipnat_rules="/etc/ipnat.rules"
gateway_enable="YES"


The 15-minute table has similar information, but it's organized in 15 minute increments:
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.1"
fsck_y_enable="YES"
background_fsck="NO"
sshd_enable="YES"</pre>


<pre>mysql> describe ipTotals_69_55_224;
* reboot. Confirm new kernel is loaded
+-----------+------------+------+-----+---------+-------+
 
| Field    | Type      | Null | Key | Default | Extra |
  uname -a
+-----------+------------+------+-----+---------+-------+
| date      | datetime  | YES  |    | NULL    |      |
| ip        | char(15)  | YES  | MUL | NULL    |      |
| direction | tinyint(1) | YES  |    | NULL    |      |
| octets    | bigint(20) | YES  |    | NULL    |      |
| packets  | int(11)    | YES |    | NULL    |      |
+-----------+------------+------+-----+---------+-------+


mysql> select * from ipTotals_69_55_224 limit 2\G
* update ports:
*************************** 1. row ***************************
<pre>cd /usr/ports
    date: 2010-01-11 19:30:00
echo "*default host=cvsup4.FreeBSD.org\
      ip: 69.55.224.13
*default base=/usr\
direction: 1
*default prefix=/usr\
  octets: 288
*default release=cvs tag=RELENG_6_4\
  packets: 6
*default delete use-rel-suffix\
*************************** 2. row ***************************
*default compress\
    date: 2010-01-11 19:30:00
ports-all tag=." > sup
      ip: 69.55.224.12
direction: 1
  octets: 216
  packets: 4</pre>


So for a given IP, there will be 192 rows in a given day: 4 rows per hour, *2 for 2 directions, *24 for 24hours in a day. Obviously this table is large which is why we broke it down into a daily table for quick, easy, daily-summary access.
cvsup sup; mail -s 'cvs sup ports done' dave.boodman@vtext.com < /dev/null</pre>


That covers the simple traffic tabulation tables. We also track traffic by port:
* Install raid mgmt tool


<pre>mysql> describe dailyPortTotals_69_55_224;
<pre>cd /usr/local/sbin
+-----------+-------------+------+-----+---------+-------+
fetch http://3ware.com/download/Escalade9690SA-Series/9.5.3/tw_cli-freebsd-x86-9.5.3.tgz
| Field    | Type        | Null | Key | Default | Extra |
tar xzf tw_cli-freebsd-x86-9.5.3.tgz
+-----------+-------------+------+-----+---------+-------+
rm tw_cli-freebsd-x86-9.5.3.tgz
| id        | varchar(28) |      | PRI |        |      |
chmod 0700 tw_cli</pre>
| date      | date        | YES  |    | NULL    |      |
| ip        | varchar(15) | YES  | MUL | NULL    |      |
| direction | tinyint(1)  | YES  |    | NULL    |      |
| protocol  | smallint(3) | YES  |    | NULL    |      |
| port      | int(11)    | YES  |    | NULL    |      |
| octets    | bigint(11)  | YES  |    | NULL    |      |
| packets  | int(11)    | YES  |    | NULL    |      |
+-----------+-------------+------+-----+---------+-------+
8 rows in set (0.00 sec)


mysql> select * from dailyPortTotals_69_55_224 limit 1\G
Test:
*************************** 1. row ***************************
./tw_cli info c0
      id: 695522496-20091218-1-6-23
    date: 2009-12-18
      ip: 69.55.224.96
direction: 1
protocol: 6
    port: 23
  octets: 1796
  packets: 30


mysql> select * from portTotals_69_55_224 limit 1\G
* install rsync from ports
*************************** 1. row ***************************
<pre>cd /usr/ports/net/rsync
    date: 2010-09-07 18:45:00
make install clean</pre>
      ip: 69.55.224.254
choose default options
direction: 1
protocol: 6
    port: 99999
  octets: 144
  packets: 3


</pre>
* install perl from ports
<pre>cd /usr/ports/lang/perl5.8
make install clean</pre>


This is largely the same with 2 more additions: <tt>protocol</tt> (1=ICMP, 6=TCP, 17=UDP), and <tt>port</tt> which we set to 99999 if the traffic is return traffic and the port is above 1024. Obviously the potential for number of rows grows quickly when you consider the addition of port and protocol tracking per IP.
* install screen from ports
<pre>cd /usr/ports/sysutils/screen
make install clean</pre>


== Regular maintenance ==
* install bb client
*[[Routine_Maintenance#Adaptec_Controllers|Check RAID array]]
<pre>adduser
* archive data from database
Username: bb
archive_daily.pl 2012 09
Full name: bb
This will archive data for the given year and month from the daily summary tables. Generally we want to have a year of history in the database.
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes


archive_15min.pl 2012 09
cd /usr/home/bb
This will archive data for the given year and month from the 15min-increment tables. Generally, we want to have 6 months of history in the database.
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
tar xvf bb-freebsd.tar</pre>
edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
<pre>echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.1 nat2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
vi /home/bb/bbc1.9e-btf/ext/openfiles
MACHINE="nat2,johncompanies,com"      # HAS TO BE IN A,B,C FORM


* if space becomes tight, move flow files and exported data to a backup server, both located in <tt>/usr/home/flowbin/archive</tt> and <tt>/usr/home/exported</tt>, respectively
cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..


== Slaving ==
vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$


If we were going to setup traffic database slaving (we don't do this anymore), perhaps cause the bwdb machine gets busy and it cannot handle traffic requests and netflow, here's how it's done:
./runbb.sh start
more BBOUT
(look for errors)
exit


On the traffic master:
echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh
</pre>


GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.1.4.8' IDENTIFIED BY 'qERUG8wf';
Punch a hole in the firewall to allow it to communicate with bb monitor (probably already exists):


in my.cnf:
ipfw add 96 allow ip from 66.181.18.0/27 to 69.55.230.2
<pre>bin-log
server-id=1
max_binlog_size=500M
expire_logs_days = 3</pre>


on slave:
* configure bb on mail:
in my.cnf:
<pre>vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
<pre>server-id      = 2
64.163.14.48 nat2.johncompanies.com # ssh
master-host    =  10.1.4.203
master-user    =  repl
master-password =  qERUG8wf
master-connect-retry=60
replicate-wild-do-table=traffic.daily%
max_relay_log_size=500M
expire_logs_days = 3


replicate-wild-do-table=traffic.%</pre>
su bb
cd
bbsrc/bb/runbb.sh restart ; exit</pre>


on master:
* configure ntp
touch /usr/home/working/.lock
<pre>echo "server 69.55.230.2
(make sure processflows not running)
server 0.pool.ntp.org
server 1.pool.ntp.org
server 2.pool.ntp.org
server 3.pool.ntp.org
server 66.187.233.4
server 217.204.76.170
server 64.112.189.11
server 66.69.112.130
server 80.85.129.25
server 80.237.234.15
server 130.60.7.44
server 134.99.176.3
server 198.144.202.250
server 202.74.170.194
server 204.17.42.199
server 204.87.183.6
server 213.15.3.1
server 213.239.178.33
server 217.114.97.97
server 69.55.230.2" > /etc/ntp.conf</pre>


<pre>FLUSH TABLES WITH READ LOCK;
<pre>/usr/sbin/ntpd -A -p /var/run/ntpd.pid
cd /usr/home/database/traffic
sleep 2; ntpq -p</pre>
tar -czf mysql-traffic-snapshot.tgz ./daily*
(confirm it’s able to reach our time server)
(~1G)
SHOW MASTER STATUS;
+-----------------+-----------+--------------+------------------+
| File            | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+-----------------+-----------+--------------+------------------+
| bwdb-bin.000039 | 154432615 |              |                  |
+-----------------+-----------+--------------+------------------+


(write down info)
echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
UNLOCK TABLES;
chmod 0700 /usr/local/etc/rc.d/ntp.sh
scp mysql-traffic-snapshot.tgz 10.1.4.5:/mnt/data1/db/mysql/traffic/</pre>


on slave:
* fwd and reverse lookups on ns1c
<pre>mkdir /mnt/data1/db/mysql/traffic
vr johncompanies.com
cd /mnt/data1/db/mysql/traffic/
(edit the PTR too)
tar xzvf mysql-traffic-snapshot.tgz
(restart mysql)
CHANGE MASTER TO MASTER_HOST='10.1.4.203',MASTER_USER='repl',MASTER_PASSWORD='qERUG8wf',MASTER_LOG_FILE='bwdb-bin.000059',MASTER_LOG_POS=482502186;
START SLAVE;</pre>


<pre>cd /usr/home/database/traffic
* setup backups, nfs mount
scp *</pre>


<pre>optimize table dailyPortTotals_69_55_224;
<pre>mkdir /backup3
optimize table dailyPortTotals_69_55_225;
echo 'backup3:/data          /backup3        nfs    rw,bg          0      0' >> /etc/fstab
optimize table dailyPortTotals_69_55_226;
optimize table dailyPortTotals_69_55_227;
optimize table dailyPortTotals_69_55_228;
optimize table dailyPortTotals_69_55_229;
optimize table dailyPortTotals_69_55_230;
optimize table dailyPortTotals_69_55_231;
optimize table dailyPortTotals_69_55_232;
optimize table dailyPortTotals_69_55_233;
optimize table dailyPortTotals_69_55_234;
optimize table dailyPortTotals_69_55_235;
optimize table dailyPortTotals_69_55_236;
optimize table dailyPortTotals_69_55_237;
optimize table dailyPortTotals_69_55_238;
optimize table dailyPortTotals_69_55_239;</pre>


== Build ==
echo '#\!/bin/sh\
backupdir=/data/nat2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config</pre>


=== BIOS Config ===
on backup3:
disable quiet boot
setup backup dirs:
ssh backup3 mkdir -p /data/nat2/current


set to last state after power loss
on backup3, add the system to  
vi /usr/local/sbin/snapshot_archive


set date/time to GMT
<pre>scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup
vi /usr/local/etc/rsync.backup
backup1 > backup3</pre>


enable serial console output (baud rate 115200)
crontab -e
1 0 * * * /usr/local/etc/rsync.backup


=== Install OS ===
* edit sshd_config for security
<pre>vi /etc/ssh/sshd_config
ListenAddress 66.181.18.1
ListenAddress 69.55.229.2
ListenAddress 10.1.2.1


Install FreeBSD 8.3 amd64
kill -1 `cat /var/run/sshd.pid`</pre>


* partition map:
* raid chk
<pre>/ 500m
swap 4096m
/var 256m
/tmp 256m
/usr ~</pre>


* edit /etc/make.conf
<pre>cat > /usr/local/sbin/lsiraidchk
Castle:
#!/usr/bin/perl
<pre>echo "WITHOUT_X11=yes \
KERNCONF=bwdb \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf</pre>


i2b:
my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;
<pre>echo "WITHOUT_X11=yes \
KERNCONF=bwdb2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf</pre>


* add settings to /boot/loader.conf and /boot.config
foreach (@out) {
    if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#print $_;
}</pre>


<pre>echo "-Dh" >> /boot.config
* netflow stuff
add crontab entries
<pre>crontab -e
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;
*/5 * * * * /usr/local/sbin/lsiraidchk


echo 'console="comconsole,vidconsole" \
#10 0 * * * rm /var/spool/clientmqueue/*</pre>
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf</pre>


* turn off all ttyv's except 0 and 1 in /etc/ttys
<pre>scp /etc/makefwrules.pl user@64.163.14.48:~
also turn on ttyu0, change type to vt100:
scp /etc/makepiperules.pl user@64.163.14.48:~
<pre>vi /etc/ttys
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
mkdir /etc/oldrules/</pre>


ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
other binaries
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
<pre>scp /usr/local/bin/rulemaker user@64.163.14.48:~
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
mv ~user/rulemaker /usr/local/sbin
ttyv6  "/usr/libexec/getty Pc"        cons25  off secure
scp ~user/Sendmail.pm user@64.163.14.48:~
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
scp ~user/doswatch.pl user@64.163.14.48:~</pre>
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyu0  "/usr/libexec/getty std.9600"  vt100  on secure


kill -1 1</pre>
* add nat rules
<pre>vi /etc/ipnat.rules
# sample entry
bimap fxp0 10.1.6.70/32 -> 10.1.6.59/32
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32


on console server:
ipnat -C -f /etc/ipnat.rules</pre>
vi /etc/remote
(rename port to jail8 depending on where and which digi plugged into)
test serial console


* shell for user
<pre>cp /root/.cshrc ~user/
vi ~user/</pre>
change # to $


* populate hosts
* mrtg
i2b:
<pre>echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts</pre>


castle:
<pre>cd /usr/ports/net-mgmt/mrtg
<pre>echo "10.1.4.3 backup2 backup2.johncompanies.com" >> /etc/hosts
make install clean</pre>
echo "10.1.4.8 backup1 backup1.johncompanies.com" >> /etc/hosts
(no FONTCONFIG, v3)
echo "10.1.4.4 mail mail.johncompanies.com" >> /etc/hosts
</pre>


* put key in authorized_keys on backup1 and  backup2
this didn't work cause of libtool incompat
cd
ssh-keygen -t dsa -b 1024
(default location, leave password blank)


castle:
so manually moved files:
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'


i2b:
<pre>scp /usr/local/bin/cfgmaker user@nat2:/usr/local/bin/cfgmaker
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
scp /usr/local/lib/perl5/site_perl/5.6.1/MRTG_lib.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
scp /usr/local/lib/perl5/site_perl/5.6.1/SNMP_util.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'
scp /usr/local/lib/perl5/site_perl/5.6.1/BER.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
 
scp /usr/local/lib/perl5/site_perl/5.6.1/SNMP_Session.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
confirm that you can ssh to backup2 and backup1 (and backup3 if at i2b) without getting a login prompt
scp /usr/local/bin/mrtg root@nat2:/usr/local/bin/mrtg
scp /usr/local/lib/perl5/site_perl/5.6.1/locales_mrtg.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/locales_mrtg.pm
scp /usr/local/bin/rrdtool root@nat2:/usr/local/bin/rrdtool
scp /usr/local/lib/perl5/site_perl/5.6.1/mach/RRDs.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/mach/RRDs.pm
rsync -av /usr/local/lib/perl5/site_perl/5.6.1/mach/auto/RRDs/ root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/mach/auto/RRDs/
scp /usr/lib/libz.so.2 root@nat2:/usr/lib/libz.so.2
scp /usr/lib/libm.so.2 root@nat2:/usr/lib/libm.so.2
rsync -av /usr/local/lib/librrd* root@nat2:/usr/local/lib/
scp /usr/lib/libc.so.4 root@nat2:/usr/lib/libc.so.4
 
rsync -av /usr/ports/net/rrdtool root@nat2:/usr/ports/net
cd /usr/ports/net/rrdtool
make install


ssh backup1 hostname
mkdir -p /mnt/data1/mrtg/data
ssh backup2 hostname
scp /usr/local/www/mgmt/mrtg/template.pl root@nat2:/mnt/data1/mrtg/
scp /usr/local/www/mgmt/mrtg/host.pl root@nat2:/mnt/data1/mrtg/


* edit root's path and login script:
cfgmaker --if-template=template.pl --show-op-down --global "options[_]: growright,bits" --global 'WorkDir: /mnt/data1/mrtg/data' --global 'Interval: 1' --global 'LogFormat: rrdtool' --global 'PathAdd: /usr/local/bin' --global 'LibAdd: /usr/local/lib' --host-template=host.pl jc292401@10.1.2.50 --output=switch-p20.cfg
vi /root/.cshrc


Change alias entries (add G):
cat > /mnt/data1/mrtg/mrtg.sh
<pre>alias la        ls -aG
#!/bin/sh
alias lf        ls -FAG
/usr/local/bin/mrtg /mnt/data1/mrtg/switch-p20.cfg
alias ll        ls -lAG
alias ls        ls -AG
</pre>


and alter the prompt, set the following:
chmod 0700 /mnt/data1/mrtg/mrtg.sh
set prompt = "`/bin/hostname -s` %/# "


* install cvsup
crontab -e
cd /usr/ports/net/cvsup-without-gui
* * * * * /mnt/data1/mrtg/mrtg.sh 2>&1 > /dev/null</pre>
make install clean; rehash; mail -s 'cvs installed' support@johncompanies.com < /dev/null


* get latest sources for this release:
* snmp firewall block
<pre>cd /usr/src
<pre>cat > /usr/local/etc/rc.d/boot.sh
echo "*default host=cvsup4.freebsd.org\
ipfw add 10 allow udp from 69.55.230.2 to any 161
*default base=/usr\
ipfw add 10 allow udp from 10.1.2.1 to any 161
*default prefix=/usr\
ipfw add 11 deny udp from any to any 161
*default release=cvs tag=RELENG_8_3\
chmod 0700 /usr/local/etc/rc.d/boot.sh</pre>
*default delete use-rel-suffix\
*default compress\
src-all" > sup


cvsup sup ; mail -s 'cvs sup done' support@johncompanies.com < /dev/null</pre>
= bwdb =
== Summary ==
This machine tracks and stores network traffic (netflow) at castle. It is our means to monitor customer bandwidth usage.


* configure new kernel
* Location: castle, cab 3-7
* OS: FreeBSD 4.10 x86
* Networking: Priv IP: 10.1.4.203 There are 2 onboard nic's, one of which is the "listener"
* Hardware: Custom 1U. Single power supply.
* Drives: one 250 GB (2 x 250GB) RAID1 array running on a Promise IDE RAID card.


cd /usr/src/sys/amd64/conf
== Services Provided ==
scp backup2:/mnt/data4/build/freebsd/kern_config-bwdb-8.3-amd64 ./bwdb
* netflow
* mysql
* bigbrother
* snmp


Edit config and change name:
== netflow ==
vi bwdb
ident  bwdb


* build, install kernel and world
The main function of this server is to run netflow on an eth device in promiscuous mode so as to hear everything happening on the port (wherein all network traffic is mirrored to that port via the cisco swith). Every 15min, it creates a flow file under <tt>/usr/home/flows/</tt> (organized by date). The flow file contains all traffic data for a 15min increment of time.


<pre>cd /boot
A cronjob moves that flow file (or files if there are multiple due to some delay)
1,16,31,46 * * * * /usr/home/flowbin/queue.pl


mv kernel kernel.GENERIC
into a processing queue:
cd kernel.GENERIC
<tt>/usr/home/working</tt>
cd /usr/src
make buildkernel installkernel


make buildworld ; mail -s 'buildworld done' support@johncompanies.com < /dev/null
Then a separate file processes whatever flow files it finds there, inserting the data into the local mysql database:
(2450: 1:56min, supermicro: 59mins, 2950: 38mins)
2,17,32,47 * * * * /usr/home/flowbin/processflows.pl
make installworld
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i</pre>


* populate /etc/rc.conf with IPs and NFS settings
== mysql ==


castle:
The database storing all the traffic data is named <tt>traffic</tt>
<pre>vi /etc/rc.conf
Tables:
 
<pre>mysql> show tables;
hostname="bwdb.johncompanies.com"
+---------------------------+
kern_securelevel_enable="NO"
| Tables_in_traffic        |
portmap_enable="NO"
+---------------------------+
sendmail_enable="NO"
| dailyIpTotals_69_55_224  |
usbd_enable="YES"
| dailyIpTotals_69_55_225  |
 
| dailyIpTotals_69_55_226  |
xntpd_enable="YES"
| dailyIpTotals_69_55_227  |
nfs_client_enable="YES"
| dailyIpTotals_69_55_228  |
nfs_reserved_port_only="YES"
| dailyIpTotals_69_55_229  |
ifconfig_fxp0="inet 10.1.4.203 netmask 255.255.255.0"
| dailyIpTotals_69_55_230  |
ifconfig_em0="up promisc"
| dailyIpTotals_69_55_231  |
defaultrouter="10.1.4.1"
| dailyIpTotals_69_55_232  |
snmpd_enable="YES"
| dailyIpTotals_69_55_233  |
 
| dailyIpTotals_69_55_234  |
inetd_enable="YES"
| dailyIpTotals_69_55_235  |
inetd_flags="-wW -a 10.1.4.203"
| dailyIpTotals_69_55_236  |
fsck_y_enable="YES"
| dailyIpTotals_69_55_237  |
background_fsck="NO"
| dailyIpTotals_69_55_238  |
sshd_enable="YES"
| dailyIpTotals_69_55_239  |
ipfw_load="YES"</pre>
| dailyPortTotals_69_55_224 |
 
| dailyPortTotals_69_55_225 |
i2b:
| dailyPortTotals_69_55_226 |
<pre>vi /etc/rc.conf
| dailyPortTotals_69_55_227 |
 
| dailyPortTotals_69_55_228 |
hostname="bwdb2.johncompanies.com"
| dailyPortTotals_69_55_229 |
kern_securelevel_enable="NO"
| dailyPortTotals_69_55_230 |
portmap_enable="NO"
| dailyPortTotals_69_55_231 |
sendmail_enable="NO"
| dailyPortTotals_69_55_232 |
usbd_enable="YES"
| dailyPortTotals_69_55_233 |
 
| dailyPortTotals_69_55_234 |
xntpd_enable="YES"
| dailyPortTotals_69_55_235 |
nfs_client_enable="YES"
| dailyPortTotals_69_55_236 |
nfs_reserved_port_only="YES"
| dailyPortTotals_69_55_237 |
ifconfig_fxp0="inet 10.1.2.4 netmask 255.255.255.0"
| dailyPortTotals_69_55_238 |
ifconfig_em0="up promisc"
| dailyPortTotals_69_55_239 |
defaultrouter="10.1.2.1"
| ipTotals_69_55_224        |
snmpd_enable="YES"
| ipTotals_69_55_225        |
 
| ipTotals_69_55_226        |
inetd_enable="YES"
| ipTotals_69_55_227        |
inetd_flags="-wW -a 10.1.2.4"
| ipTotals_69_55_228        |
fsck_y_enable="YES"
| ipTotals_69_55_229        |
background_fsck="NO"
| ipTotals_69_55_230        |
sshd_enable="YES"
| ipTotals_69_55_231        |
ipfw_load="YES"</pre>
| ipTotals_69_55_232        |
| ipTotals_69_55_233        |
| ipTotals_69_55_234        |
| ipTotals_69_55_235        |
| ipTotals_69_55_236        |
| ipTotals_69_55_237        |
| ipTotals_69_55_238        |
| ipTotals_69_55_239        |
| portTotals_69_55_224      |
| portTotals_69_55_225      |
| portTotals_69_55_226      |
| portTotals_69_55_227      |
| portTotals_69_55_228      |
| portTotals_69_55_229      |
| portTotals_69_55_230      |
| portTotals_69_55_231      |
| portTotals_69_55_232      |
| portTotals_69_55_233      |
| portTotals_69_55_234      |
| portTotals_69_55_235      |
| portTotals_69_55_236      |
| portTotals_69_55_237      |
| portTotals_69_55_238      |
| portTotals_69_55_239      |
+---------------------------+
</pre>


* reboot. Confirm new kernel is loaded
So as you see we store each class-C block in its own table, for efficiency. Further, we store and organize data in 4 ways: "daily" tables and 15-minute granularity tables, and for each of those we track simple IP traffic and port-specific traffic. The daily tables contains 2 entries (one for each direction) for each IP for each day. For the current day, the row data is incremented as the day goes on.


uname -a
<pre>mysql> describe dailyIpTotals_69_55_224;
 
+-----------+-------------+------+-----+---------+-------+
* update ports:
| Field    | Type        | Null | Key | Default | Extra |
<pre>cd /usr/ports
+-----------+-------------+------+-----+---------+-------+
echo "*default host=cvsup4.FreeBSD.org\
| id        | varchar(23) |      | PRI |        |      |
*default base=/usr\
| date      | date        | YES  |    | NULL    |      |
*default prefix=/usr\
| ip        | varchar(15) | YES  | MUL | NULL    |      |
*default release=cvs tag=RELENG_8_3\
| direction | tinyint(1)  | YES  |    | NULL    |      |
*default delete use-rel-suffix\
| octets    | bigint(12)  | YES  |    | NULL    |      |
*default compress\
| packets  | int(11)    | YES  |    | NULL    |      |
ports-all tag=." > sup
+-----------+-------------+------+-----+---------+-------+


cvsup sup; mail -s 'cvs sup ports done' support@johncompanies.com < /dev/null</pre>
mysql> select * from dailyIpTotals_69_55_224 limit 1\G
*************************** 1. row ***************************
      id: 6955224194-20100917-1
    date: 2010-09-17
      ip: 69.55.224.194
direction: 1
  octets: 8821
  packets: 91
</pre>


* Install raid mgmt tool
The <tt>id</tt> is a unique identifier (key), <tt>direction</tt> indicates incoming or outgoing traffic (outbound = 2, inbound = 1), <tt>octets</tt> are the amount of traffic in kilobytes, and <tt>packets</tt> is the total number of packets.


<pre>cd /usr/local/sbin
The 15-minute table has similar information, but it's organized in 15 minute increments:
scp backup2:/d4/build/3ware/tw_cli-freebsd-x86_64-9.5.0.1.tgz .
tar xzf tw_cli-freebsd-x86_64-9.5.0.1.tgz
rm tw_cli-freebsd-x86_64-9.5.0.1.tgz
chmod 0700 tw_cli</pre>


Test:
<pre>mysql> describe ipTotals_69_55_224;
  ./tw_cli info c0
+-----------+------------+------+-----+---------+-------+
 
| Field    | Type      | Null | Key | Default | Extra |
Grab raid check script:
+-----------+------------+------+-----+---------+-------+
  scp backup1:/usr/local/sbin/3wraidchk /usr/local/etc
| date      | datetime  | YES  |    | NULL    |      |
| ip        | char(15)  | YES | MUL | NULL    |      |
| direction | tinyint(1) | YES  |    | NULL    |      |
| octets    | bigint(20) | YES  |    | NULL    |      |
| packets  | int(11)    | YES |    | NULL    |      |
+-----------+------------+------+-----+---------+-------+


Setup cronjob:
mysql> select * from ipTotals_69_55_224 limit 2\G
<pre>crontab -e
*************************** 1. row ***************************
*/5 * * * * /usr/local/etc/3wraidchk</pre>
    date: 2010-01-11 19:30:00
      ip: 69.55.224.13
direction: 1
  octets: 288
  packets: 6
*************************** 2. row ***************************
    date: 2010-01-11 19:30:00
      ip: 69.55.224.12
direction: 1
  octets: 216
  packets: 4</pre>


* install rsync from ports
So for a given IP, there will be 192 rows in a given day: 4 rows per hour, *2 for 2 directions, *24 for 24hours in a day. Obviously this table is large which is why we broke it down into a daily table for quick, easy, daily-summary access.
cd /usr/ports/net/rsync
make install clean


choose default options
That covers the simple traffic tabulation tables. We also track traffic by port:


* install perl from ports
<pre>mysql> describe dailyPortTotals_69_55_224;
  cd /usr/ports/lang/perl5.8
+-----------+-------------+------+-----+---------+-------+
  make install clean
| Field    | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| id        | varchar(28) |      | PRI |        |      |
| date      | date        | YES  |    | NULL    |      |
| ip        | varchar(15) | YES  | MUL | NULL    |      |
| direction | tinyint(1)  | YES  |    | NULL    |      |
| protocol | smallint(3) | YES  |    | NULL    |      |
| port      | int(11)    | YES  |    | NULL    |      |
| octets    | bigint(11)  | YES  |    | NULL    |      |
| packets  | int(11)    | YES |    | NULL    |      |
+-----------+-------------+------+-----+---------+-------+
8 rows in set (0.00 sec)


choose default options
mysql> select * from dailyPortTotals_69_55_224 limit 1\G
*************************** 1. row ***************************
      id: 695522496-20091218-1-6-23
    date: 2009-12-18
      ip: 69.55.224.96
direction: 1
protocol: 6
    port: 23
  octets: 1796
  packets: 30
 
mysql> select * from portTotals_69_55_224 limit 1\G
*************************** 1. row ***************************
    date: 2010-09-07 18:45:00
      ip: 69.55.224.254
direction: 1
protocol: 6
    port: 99999
  octets: 144
  packets: 3
 
</pre>


* install bb client
This is largely the same with 2 more additions: <tt>protocol</tt> (1=ICMP, 6=TCP, 17=UDP), and <tt>port</tt> which we set to 99999 if the traffic is return traffic and the port is above 1024. Obviously the potential for number of rows grows quickly when you consider the addition of port and protocol tracking per IP.


Compiling from source on AMD64 will not work. So, we use a linux-compiled version and rely on linux compat. Linux compat won't install on 8.x - libtool 2.4 need. So, instead we copy(ed) over linux:
== Regular maintenance ==
rsync -aSHv --exclude=proc --exclude=sys 10.1.4.108:/usr/compat/linux/ /usr/compat/linux/
*[[Routine_Maintenance#Adaptec_Controllers|Check RAID array]]
* archive data from database
archive_daily.pl 2012 09
This will archive data for the given year and month from the daily summary tables. Generally we want to have a year of history in the database.


  adduser
  archive_15min.pl 2012 09
This will archive data for the given year and month from the 15min-increment tables. Generally, we want to have 6 months of history in the database.


Output/response:
* if space becomes tight, move flow files and exported data to a backup server, both located in <tt>/usr/home/flowbin/archive</tt> and <tt>/usr/home/exported</tt>, respectively


<pre>Username: bb
== Slaving ==
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes</pre>


cd /usr/home/bb
If we were going to setup traffic database slaving (we don't do this anymore), perhaps cause the bwdb machine gets busy and it cannot handle traffic requests and netflow, here's how it's done:
scp backup2:/mnt/data4/build/bb/bb-freebsd_linuxcompat.tgz .
tar xzf bb-freebsd_linuxcompat.tgz


edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
On the traffic master:


  echo "10.1.4.5 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
  GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.1.4.8' IDENTIFIED BY 'qERUG8wf';
10.1.4.203 bwdb.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts


Edit for machine name and private IP.
in my.cnf:
<pre>bin-log
server-id=1
max_binlog_size=500M
expire_logs_days = 3</pre>


if this machine is at i2b:
on slave:
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
in my.cnf:
10.1.2.4 bwdb2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
<pre>server-id      = 2
master-host    =  10.1.4.203
master-user    =  repl
master-password =  qERUG8wf
master-connect-retry=60
replicate-wild-do-table=traffic.daily%
max_relay_log_size=500M
expire_logs_days = 3


<pre>vi /home/bb/bbc1.9e-btf/ext/openfiles
replicate-wild-do-table=traffic.%</pre>
 
on master:
touch /usr/home/working/.lock
(make sure processflows not running)


MACHINE="bwdb,johncompanies,com"      # HAS TO BE IN A,B,C FORM</pre>
<pre>FLUSH TABLES WITH READ LOCK;
Edit for machine name.
cd /usr/home/database/traffic
tar -czf mysql-traffic-snapshot.tgz ./daily*
(~1G)
SHOW MASTER STATUS;
+-----------------+-----------+--------------+------------------+
| File            | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+-----------------+-----------+--------------+------------------+
| bwdb-bin.000039 | 154432615 |              |                  |
+-----------------+-----------+--------------+------------------+


Have bb watch for flow-capture, mysql
(write down info)
<pre>cat >> /home/bb/bbc1.9e-btf/etc/bb-proctab
UNLOCK TABLES;
localhost: flow-capture :
scp mysql-traffic-snapshot.tgz 10.1.4.5:/mnt/data1/db/mysql/traffic/</pre>
localhost: mysqld :</pre>


on slave:
<pre>mkdir /mnt/data1/db/mysql/traffic
cd /mnt/data1/db/mysql/traffic/
tar xzvf mysql-traffic-snapshot.tgz
(restart mysql)
CHANGE MASTER TO MASTER_HOST='10.1.4.203',MASTER_USER='repl',MASTER_PASSWORD='qERUG8wf',MASTER_LOG_FILE='bwdb-bin.000059',MASTER_LOG_POS=482502186;
START SLAVE;</pre>


<pre>cd /usr/home/bb/bbc1.9e-btf/etc
<pre>cd /usr/home/database/traffic
./bbchkcfg.sh
scp *</pre>  
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf
./runbb.sh start
more BBOUT
(look for errors)
exit</pre>


Put in script to start bb @ boot:
<pre>optimize table dailyPortTotals_69_55_224;
echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
optimize table dailyPortTotals_69_55_225;
chmod +x /usr/local/etc/rc.d/bb.sh
optimize table dailyPortTotals_69_55_226;
optimize table dailyPortTotals_69_55_227;
optimize table dailyPortTotals_69_55_228;
optimize table dailyPortTotals_69_55_229;
optimize table dailyPortTotals_69_55_230;
optimize table dailyPortTotals_69_55_231;
optimize table dailyPortTotals_69_55_232;
optimize table dailyPortTotals_69_55_233;
optimize table dailyPortTotals_69_55_234;
optimize table dailyPortTotals_69_55_235;
optimize table dailyPortTotals_69_55_236;
optimize table dailyPortTotals_69_55_237;
optimize table dailyPortTotals_69_55_238;
optimize table dailyPortTotals_69_55_239;</pre>


== Build ==


If this is at i2b, punch a hole in the firewall to allow it to communicate with bb monitor:
=== BIOS Config ===
disable quiet boot


ipfw add 00096 allow tcp from 66.181.18.0/27 to 69.55.230.2
set to last state after power loss


set date/time to GMT


* configure bb on mail
enable serial console output (baud rate 115200)
<pre>vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
10.1.4.203 bwdb.johncompanies.com # ssh


su bb
=== Install OS ===
cd
bbsrc/bb/runbb.sh restart ; exit</pre>


* configure ntp server
Install FreeBSD 8.3 amd64
Castle:
echo "server 10.1.4.1" > /etc/ntp.conf


I2b:
* partition map:
echo "server 10.1.2.1" > /etc/ntp.conf
<pre>/ 500m
swap 4096m
/var 256m
/tmp 256m
/usr ~</pre>


<pre>/usr/sbin/ntpd -p /var/run/ntpd.pid
* edit /etc/make.conf
sleep 2; ntpq -p</pre>
Castle:
(confirm it’s able to reach our time server)
<pre>echo "WITHOUT_X11=yes \
KERNCONF=bwdb \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf</pre>


<pre>echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
i2b:
chmod 0700 /usr/local/etc/rc.d/ntp.sh</pre>
<pre>echo "WITHOUT_X11=yes \
KERNCONF=bwdb2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf</pre>


* fwd and reverse lookups on ns1c
* add settings to /boot/loader.conf and /boot.config
vr johncompanies.com
(edit the PTR too)


* setup backups
<pre>echo "-Dh" >> /boot.config
<pre>echo '#\!/bin/sh\
backupdir=/data/bwdb/current\
server=backup1\
\
## ENTRY /etc\
## ENTRY /usr/home/flowbin\
## ENTRY /usr/home/database' > /usr/local/etc/backup.config</pre>


Castle:
echo 'console="comconsole,vidconsole" \
setup backup dirs:
boot_multicons="YES" \
ssh backup1 mkdir -p /data/bwdb/current
boot_serial="YES" \
on backup1, add the system to
comconsole_speed="115200"' >> /boot/loader.conf</pre>
vi /usr/local/sbin/snapshot_rotate


I2b:
* turn off all ttyv's except 0 and 1 in /etc/ttys
setup backup dirs:
also turn on ttyu0, change type to vt100:
ssh backup3 mkdir -p /data/bwdb/current
<pre>vi /etc/ttys
on backup3, add the system to  
vi /usr/local/sbin/snapshot_archive


ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
ttyv6  "/usr/libexec/getty Pc"        cons25  off secure
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyu0  "/usr/libexec/getty std.9600"  vt100  on secure


Copy over the backup script:
kill -1 1</pre>
scp backup2:/d4/bin/freebsd8.x/rsync.backup /usr/local/etc/


Edit rsync.backup and change <tt>config</tt> var to point to correct config file location: <tt>/usr/local/etc/backup.config</tt>
on console server:
vi /etc/remote
(rename port to jail8 depending on where and which digi plugged into)
test serial console


<pre>crontab -e
5 0 * * * /usr/local/etc/rsync.backup</pre>


* make /root/logs
* populate hosts
mkdir /root/logs
i2b:
<pre>echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts</pre>


* edit sshd_config for security
castle:
<pre>echo "10.1.4.3 backup2 backup2.johncompanies.com" >> /etc/hosts
echo "10.1.4.8 backup1 backup1.johncompanies.com" >> /etc/hosts
echo "10.1.4.4 mail mail.johncompanies.com" >> /etc/hosts
</pre>


<pre>vi /etc/ssh/sshd_config
* put key in authorized_keys on backup1 and  backup2
ListenAddress 10.1.4.203
cd
PermitRootLogin yes
ssh-keygen -t dsa -b 1024
(default location, leave password blank)


kill -1 `cat /var/run/sshd.pid`</pre>
castle:
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'


Edit for private IP.
i2b:
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'


* snmp
confirm that you can ssh to backup2 and backup1 (and backup3 if at i2b) without getting a login prompt


(Before doing this you may need to take down the firewall and also add to resolv.conf 69.43.143.41)
ssh backup1 hostname
<pre>
ssh backup2 hostname
cd /usr/ports/net-mgmt/net-snmp
make install clean
(defaults)


cat >> /etc/rc.conf
* edit root's path and login script:
snmpd_enable="YES"
vi /root/.cshrc
snmpd_flags="-a"
snmpd_conffile="/usr/local/share/snmp/snmpd.conf"
snmptrapd_enable="YES"
snmptrapd_flags="-a -p /var/run/snmptrapd.pid"


cat > /usr/local/share/snmp/snmpd.conf
Change alias entries (add G):
rocommunity  jcread 10.1.4.5
<pre>alias la        ls -aG
rocommunity  jcread 10.1.4.202
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
</pre>
</pre>


=== netflow ===
and alter the prompt, set the following:
set prompt = "`/bin/hostname -s` %/# "


Install flow tools:
* install cvsup
<pre>cd /usr/ports/net-mgmt/flow-tools
cd /usr/ports/net/cvsup-without-gui
make install clean</pre>
make install clean; rehash; mail -s 'cvs installed' support@johncompanies.com < /dev/null
Defaults.


mkdir /usr/home/flows
* get latest sources for this release:
<pre>cd /usr/src
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_8_3\
*default delete use-rel-suffix\
*default compress\
src-all" > sup


Flow start script:
cvsup sup ; mail -s 'cvs sup done' support@johncompanies.com < /dev/null</pre>
echo "/usr/local/bin/flow-capture -w /usr/home/flows -S5 -N -2 0/10.1.4.203/4444" > /usr/local/etc/rc.d/flow-capture.sh


chmod 0700 /usr/local/etc/rc.d/flow-capture.sh
* configure new kernel


Edit for private IP.
cd /usr/src/sys/amd64/conf
scp backup2:/mnt/data4/build/freebsd/kern_config-bwdb-8.3-amd64 ./bwdb


Netgraph start script:
Edit config and change name:
<pre>
vi bwdb
cat > /usr/local/etc/rc.d/netgraph.sh
ident  bwdb


/usr/sbin/ngctl -f- <<-SEQ
* build, install kernel and world
mkpeer em0: netflow lower iface0
name em0:lower netflow
connect em0: netflow: upper out0
mkpeer netflow: ksocket export inet/dgram/udp
msg netflow:export connect inet/10.1.4.203:4444
SEQ


#/usr/sbin/ngctl -f- <<-SEQ
<pre>cd /boot
#shutdown netflow:
#SEQ


chmod 0700 /usr/local/etc/rc.d/netgraph.sh</pre>
mv kernel kernel.GENERIC
Edit for private IP.
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel


Confirm netflow is running after running scripts:
make buildworld ; mail -s 'buildworld done' support@johncompanies.com < /dev/null
<pre>newbwdb /usr/ports/net-mgmt/flow-tools# /usr/sbin/ngctl
(2450: 1:56min, supermicro: 59mins, 2950: 38mins)
Available commands:
make installworld
  config    get or set configuration of node at <path>
(2450: 3min, supermicro: 1min, 2950: :34)
  connect    Connects hook <peerhook> of the node at <relpath> to <hook>
mergemaster -i</pre>
  debug      Get/set debugging verbosity level
  dot        Produce a GraphViz (.dot) of the entire netgraph.
  help      Show command summary or get more help on a specific command
  list      Show information about all nodes
  mkpeer    Create and connect a new node to the node at "path"
  msg        Send a netgraph control message to the node at "path"
  name      Assign name <name> to the node at <path>
  read      Read and execute commands from a file
  rmhook    Disconnect hook "hook" of the node at "path"
  show      Show information about the node at <path>
  shutdown  Shutdown the node at <path>
  status    Get human readable status information from the node at <path>
  types      Show information about all installed node types
  write      Send a data packet down the hook named by "hook".
  quit      Exit program
+ show netflow:
  Name: netflow        Type: netflow        ID: 00000004  Num hooks: 3
  Local hook      Peer name      Peer type    Peer ID        Peer hook
  ----------      ---------      ---------    -------        ---------
  export          <unnamed>      ksocket      00000005        inet/dgram/udp
  out0            em0            ether        00000001        upper
  iface0          em0            ether        00000001        lower
+
</pre>


We notice that sometimes flow-capture is failing due to swap exhaustion (even after adding more swap). So we crontab flow-capture to restart (it's ok to start if it's already running, it just quits):
* populate /etc/rc.conf with IPs and NFS settings


<pre>
castle:
crontab -e
<pre>vi /etc/rc.conf
#restart flow-capture
*/15 * * * * /usr/local/etc/rc.d/flow-capture.sh
</pre>


==== process flow tools ====  
hostname="bwdb.johncompanies.com"
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"


<pre>mkdir /usr/home/flowbin
xntpd_enable="YES"
mkdir /usr/home/working</pre>
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
ifconfig_fxp0="inet 10.1.4.203 netmask 255.255.255.0"
ifconfig_em0="up promisc"
defaultrouter="10.1.4.1"
snmpd_enable="YES"


Install modules:
inetd_enable="YES"
<pre>cd /usr/ports/devel/p5-Date-Calc
inetd_flags="-wW -a 10.1.4.203"
make install clean
fsck_y_enable="YES"
cd /usr/ports/mail/p5-Mail-Sendmail
background_fsck="NO"
make install clean</pre>
sshd_enable="YES"
ipfw_load="YES"</pre>


Queue script:
i2b:
<pre>
<pre>vi /etc/rc.conf
cat > /usr/home/flowbin/queue.pl
#!/usr/bin/perl


use strict;
hostname="bwdb2.johncompanies.com"
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"


BEGIN {
xntpd_enable="YES"
    push @INC, "/usr/home/flowbin";
nfs_client_enable="YES"
}
nfs_reserved_port_only="YES"
 
ifconfig_fxp0="inet 10.1.2.4 netmask 255.255.255.0"
use date;
ifconfig_em0="up promisc"
defaultrouter="10.1.2.1"
snmpd_enable="YES"
 
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.4"
fsck_y_enable="YES"
background_fsck="NO"
sshd_enable="YES"
ipfw_load="YES"</pre>


my $flowbase = "/usr/home/flows";
* reboot. Confirm new kernel is loaded
#my $flowqueue = "/usr/home/queue";
my $flowqueue = "/usr/home/working";


my ($date, $time) = date::CurrentDateTime();
uname -a


my $flowdir = mkFlowDir($date);
* update ports:
`mv $flowdir/ft-* $flowqueue`;
<pre>cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_8_3\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup


if (date::DateWindow($date, $time, $date, "00:00:00", 600)) {
cvsup sup; mail -s 'cvs sup ports done' support@johncompanies.com < /dev/null</pre>
    my $newdate = date::AddDays($date, -1);
    my $flowdir = mkFlowDir($newdate);
    `mv $flowdir/ft-* $flowqueue`;
}


sub mkFlowDir {
* Install raid mgmt tool
    my $date = shift;
    $date =~ /([0-9]{4}-[0-9]{2})/;
    my $yearmonth = $1;
    return "$flowbase/$yearmonth/$date";
}
</pre>


Date.pm module:
<pre>cd /usr/local/sbin
<pre>
scp backup2:/d4/build/3ware/tw_cli-freebsd-x86_64-9.5.0.1.tgz .
cat > /usr/home/flowbin/date.pm
tar xzf tw_cli-freebsd-x86_64-9.5.0.1.tgz
#!/usr/local/bin/perl
rm tw_cli-freebsd-x86_64-9.5.0.1.tgz
#
chmod 0700 tw_cli</pre>
# $Header: /usr/cvs/newgw/lib/date.pm,v 1.2 2003/11/24 17:06:02 glenn Exp $
 
#
Test:
# Copyright (c) 2001, 2002, 2003
./tw_cli info c0
#      e-Monitoring Networks, Inc. All rights reserved.
#
#
#
# date.pl - Higher level functions written on top of Date::Calc


package date;
Grab raid check script:
scp backup1:/usr/local/sbin/3wraidchk /usr/local/etc


use strict;
Setup cronjob:
use Date::Calc qw(:all);
<pre>crontab -e
*/5 * * * * /usr/local/etc/3wraidchk</pre>


sub DayDiff { #calculate the difference in days from two dates
* install rsync from ports
    my $date1 = shift;
cd /usr/ports/net/rsync
    my $date2 = shift;
make install clean
    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my $diff = &Delta_Days($year1, $month1, $day1, $year2, $month2, $day2);
    return $diff;
}


sub AddDays { #adds specified number of days to the supplied date
choose default options
    my $date = shift;
 
    my $days = shift;
* install perl from ports
    my ($year, $month, $day) = &DateToymd($date);
cd /usr/ports/lang/perl5.8
    my ($nyear, $nmonth, $nday) = &Add_Delta_Days($year, $month, $day, $days);
make install clean
    my $ndate = &ymdToDate($nyear, $nmonth, $nday);
    return $ndate;
}


sub AddHours { #adds specified number of hours to the supplied date and time
choose default options
    my $date = shift;
    my $time = shift;
    my $addhours = shift;
    my $adddays = 0;
    if (abs($addhours / 24) >= 1) {
        $adddays = int($addhours / 24);
        $addhours -= $adddays * 24;
    }
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($ny, $nm, $nd, $nh, $nmin, $ns) = &Add_Delta_DHMS($year, $month, $day,
                                                          $hour, $minute, $second,
                                                          $adddays, $addhours, 0, 0);
    my $ndate = &ymdToDate($ny, $nm, $nd);
    my $ntime = &hmsToTime($nh, $nmin, $ns);
    return $ndate, $ntime;
}


sub AddMinutes {
* install bb client
    my $date = shift;
    my $time = shift;
    my $minutes = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($ny, $nm, $nd, $nh, $nmin, $ns) = &Add_Delta_DHMS($year, $month, $day,
                                                          $hour, $minute, $second,
                                                          0, 0, $minutes, 0);
    my $ndate = &ymdToDate($ny, $nm, $nd);
    my $ntime = &hmsToTime($nh, $nmin, $ns);
    return $ndate, $ntime;
}


sub CurrentDateTime { #return the current date and time
Compiling from source on AMD64 will not work. So, we use a linux-compiled version and rely on linux compat. Linux compat won't install on 8.x - libtool 2.4 need. So, instead we copy(ed) over linux:
    my ($y, $m, $d, $h, $min, $s, $z, $z, $z) = &System_Clock;
rsync -aSHv --exclude=proc --exclude=sys 10.1.4.108:/usr/compat/linux/ /usr/compat/linux/
    my $date = &ymdToDate($y, $m, $d);
    my $time = &hmsToTime($h, $min, $s);
    return $date, $time;
}


sub Currentymd { #return the current year, month and day as separate variables
adduser
    my ($y, $m, $d, $h, $min, $s, $z, $z, $z) = &System_Clock;
    return $y, $m, $d;
}


sub DateToymd { #takes a date and returns year, month, day as individual values
Output/response:
    my $date = shift;
    if ($date =~ /([0-9]{4})-([0-9]{2})-([0-9]{2})/) {
        my $day = $3;
        my $month = $2;
        my $year = $1;
        return $year, $month, $day;
    }
    return undef;
}


sub TimeTohms { #takes a time and return hours minutes and seconds as individual values
<pre>Username: bb
    my $time = shift;
Full name: bb
    if ($time =~ /([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/) {
Uid (Leave empty for default): 1984
        my $hour = $1;
Login group [bb]:
        my $minute = $2;
Login group is bb. Invite bb into other groups? []:
        my $second = $3;
Login class [default]:
        if ($hour !~ /[0-9]{2}/) { $hour = "0$hour"; }
Shell (sh csh tcsh nologin) [sh]:  
        if ($minute !~ /[0-9]{2}/) { $minute = "0$minute"; }
Home directory [/home/bb]:
        if ($second !~ /[0-9]{2}/) { $second = "0$second"; }
Use password-based authentication? [yes]:
        return $hour, $minute, $second;
Use an empty password? (yes/no) [no]:
    }
Use a random password? (yes/no) [no]: yes
    return undef;
Lock out the account after creation? [no]:
}
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes</pre>
 
cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd_linuxcompat.tgz .
tar xzf bb-freebsd_linuxcompat.tgz


sub ymdToDate { #takes year, month, day and assembles them into our date format
edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
    my $year = shift;
    my $month = shift;
    my $day = shift;
    if (defined($year) && defined($month) && defined ($day)) {
        $month = sprintf("%02d", $month);
        $day = sprintf("%02d", $day);
        return "$year-$month-$day";
    }
    return undef;
}


sub hmsToTime { #takes hour minute and second and assembles them into our time format
echo "10.1.4.5 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
    my $hour = shift;
10.1.4.203 bwdb.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
    my $minute = shift;
    my $second = shift;
    if (defined($hour) && defined($minute) && defined ($second)) {
        if ($hour !~ /[0-9]{2}/) { $hour = "0$hour"; }
        if ($minute !~ /[0-9]{2}/) { $minute = "0$minute"; }
        if ($second !~ /[0-9]{2}/) { $second = "0$second"; }
        return sprintf ("%02d:%02d:%02d", $hour, $minute, $second);
    }
    return undef;
}


sub CompareDates { #compares two date and time pairs
Edit for machine name and private IP.
    my $date1 = shift;
 
    my $time1 = shift;
if this machine is at i2b:
    my $date2 = shift;
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
    my $time2 = shift;
10.1.2.4 bwdb2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts


    my ($year1, $month1, $day1) = &DateToymd($date1);
<pre>vi /home/bb/bbc1.9e-btf/ext/openfiles
    my ($hour1, $minute1, $second1) = &TimeTohms($time1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my ($hour2, $minute2, $second2) = &TimeTohms($time2);


#    &debug("$year1, $month1, $day1, $year2, $month2, $day2");
MACHINE="bwdb,johncompanies,com"     # HAS TO BE IN A,B,C FORM</pre>
    my $days = &Delta_Days($year1, $month1, $day1, $year2, $month2, $day2);
Edit for machine name.
    if ($days > 0) { return 1;}
    if ($days < 0) { return -1;}
    if ($days == 0) { #same day, compare times
        my $seconds1 = $second1 + (60 * $minute1) + (3600 * $hour1);
        my $seconds2 = $second2 + (60 * $minute2) + (3600 * $hour2);
        if ($seconds1 < $seconds2) { return 1;}
        if ($seconds1 > $seconds2) { return -1;}
        if ($seconds1 == $seconds2) { return 0;}
    }
    return undef;
}


sub DateWindow { #compares two date time pairs to see if they are < X seconds apart
Have bb watch for flow-capture, mysql
    my $date1 = shift;
<pre>cat >> /home/bb/bbc1.9e-btf/etc/bb-proctab
    my $time1 = shift;
localhost: flow-capture :
    my $date2 = shift;
localhost: mysqld :</pre>
    my $time2 = shift;
    my $window = shift;


    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($hour1, $minute1, $second1) = &TimeTohms($time1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my ($hour2, $minute2, $second2) = &TimeTohms($time2);


    my ($day, $hour, $minute, $second) =
<pre>cd /usr/home/bb/bbc1.9e-btf/etc
        &Delta_DHMS($year1, $month1, $day1, $hour1, $minute1, $second1,
./bbchkcfg.sh
                    $year2, $month2, $day2, $hour2, $minute2, $second2);
(y to questions)
    $minute *= 60;
./bbchkhosts.sh
    $hour *= 3600;
(ignore ssh errors)
    $day *= 86400;
cd ../..
    my $total = $second + $minute + $hour + $day;
chown -R bb .
    if (abs($total) < $window) {
su bb
        return 1;
cd
    }
cd bbc1.9e-btf
    return 0;
./runbb.sh start
}
more BBOUT
(look for errors)
exit</pre>
 
Put in script to start bb @ boot:
echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh


sub CheckDateOrder { #takes three dates/times, returns true if they are in chronological order
    my $date1 = shift;
    my $time1 = shift;
    my $date2 = shift;
    my $time2 = shift;
    my $date3 = shift;
    my $time3 = shift;
    if (&CompareDates($date1, $time1, $date2, $time2) == -1) {
        return 0;
    }
    if (&CompareDates($date2, $time2, $date3, $time3) == -1) {
        return 0;
    }
    return 1;
}


sub EpochSeconds { #calculates number of seconds since the epoch for the given date/time
If this is at i2b, punch a hole in the firewall to allow it to communicate with bb monitor:
    my $date = shift;
    my $time = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($d, $h, $m, $s) = &Delta_DHMS(1970, 1, 1, 0, 0, 0,
                                      $year, $month, $day, $hour, $minute, $second);
    my $seconds = $s + (60 * $m) + (3600 * $h) + (86400 * $d);
    return $seconds;
}


sub SecondsToDateTime { #converts seconds since epoch to date/time
ipfw add 00096 allow tcp from 66.181.18.0/27 to 69.55.230.2
    my $seconds = shift;
    my $days = int($seconds / 86400);
    $seconds -= $days * 86400;
    my $hours = int($seconds / 3600);
    $seconds -= $hours * 3600;
    my $minutes = int($seconds / 60);
    $seconds -= $minutes * 60;
    my ($year, $month, $day, $hour, $minute, $second) =
        &Add_Delta_DHMS(1970, 1, 1, 0, 0, 0, $days, $hours, $minutes, $seconds);
    $month = sprintf("%02d", $month);
    $day = sprintf("%02d", $day);
    $hour = sprintf("%02d", $hour);
    $minute = sprintf("%02d", $minute);
    $second = sprintf("%02d", $second);
    return "$year-$month-$day", "$hour:$minute:$second";
}


sub DateToDayName {
    my $date = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my $name = &Day_of_Week_to_Text(&Day_of_Week($year, $month, $day));
    $name =~ /^[A-Za-z]{3}/;
    $name = $&;
    return $name;
}


sub ValiDate {
* configure bb on mail
    return @_;
<pre>vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
10.1.4.203 bwdb.johncompanies.com # ssh


su bb
cd
bbsrc/bb/runbb.sh restart ; exit</pre>


* configure ntp server
Castle:
echo "server 10.1.4.1" > /etc/ntp.conf


}
I2b:
echo "server 10.1.2.1" > /etc/ntp.conf


sub CheckBusinessDay { # checks to see if date is business day. 1=yes, 0=no
<pre>/usr/sbin/ntpd -p /var/run/ntpd.pid
    my $date = shift;
sleep 2; ntpq -p</pre>
    my ($year, $month, $day) = &DateToymd($date);
(confirm it’s able to reach our time server)
    if (Day_of_Week($year,$month,$day) < 6) { return 1; }
    else { return 0; }
}


1; #don't remove this line
<pre>echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
</pre>
chmod 0700 /usr/local/etc/rc.d/ntp.sh</pre>


  chmod 0700 /usr/home/flowbin/queue.pl
* fwd and reverse lookups on ns1c
vr johncompanies.com
  (edit the PTR too)


Setup cronjob:
* setup backups
<pre>crontab -e
<pre>echo '#\!/bin/sh\
#move flow data into the queue
backupdir=/data/bwdb/current\
1,16,31,46 * * * * /usr/home/flowbin/queue.pl</pre>
server=backup1\
\
## ENTRY /etc\
## ENTRY /usr/home/flowbin\
## ENTRY /usr/home/database' > /usr/local/etc/backup.config</pre>


==== flow processing: i2b ====
Castle:
<pre>cat > /usr/home/flowbin/processflows-sql.pl
setup backup dirs:
#!/usr/bin/perl
ssh backup1 mkdir -p /data/bwdb/current
on backup1, add the system to
vi /usr/local/sbin/snapshot_rotate


#use strict;
I2b:
#$debug=1;
setup backup dirs:
#$dry=1;
ssh backup3 mkdir -p /data/bwdb/current
on backup3, add the system to
vi /usr/local/sbin/snapshot_archive


my $log = '/usr/home/flowbin/discards.log';


use Data::Dumper;
Copy over the backup script:
scp backup2:/d4/bin/freebsd8.x/rsync.backup /usr/local/etc/


BEGIN {
Edit rsync.backup and change <tt>config</tt> var to point to correct config file location: <tt>/usr/local/etc/backup.config</tt>
    push @INC, "/usr/home/flowbin";
}


#my $queuedir = "/usr/home/queue";
<pre>crontab -e
my $queuedir = "/usr/home/working";
5 0 * * * /usr/local/etc/rsync.backup</pre>
my $archivedir = "/usr/home/archive";
my $sqldir = "/usr/home/sql";
my $sqldirworking = "/usr/home/sql/tmp";


unless ($dry) {
* make /root/logs
    if (-e "$queuedir/.lock") {
mkdir /root/logs
        open(FILE, "$queuedir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $queuedir/.lock`;
        }
    }
    open(FILE, "> $queuedir/.lock");
    print FILE "$$\n";
    close(FILE);
}


opendir(DIR, $queuedir);
* edit sshd_config for security
my @files = readdir(DIR);
closedir(DIR);


foreach my $file (sort @files) {
<pre>vi /etc/ssh/sshd_config
    unless($file =~ /^\./) {
ListenAddress 10.1.4.203
        $file =~ /([0-9]{4}-[0-9]{2}-[0-9]{2})\.([0-9]{2})([0-9]{2})([0-9]{2})/;
PermitRootLogin yes
        my $date = "$1 $2:$3:$4";
        my $outfile = "$1-$2:$3.sql";
        unless (open (SQL, "+> $sqldirworking/$outfile")) { die "cant open $sqldirworking/$outfile"; }
        my $condensedDate = $1;
        $condensedDate =~ s/-//g;
        my $iptotal = {};
        my $protototal = {};
        my $porttotal = {};


        &debug("started file $file at ");
kill -1 `cat /var/run/sshd.pid`</pre>
        &debug(`date`);
        &debug("getting raw flow data (flow-print)");
        `cat $queuedir/$file | /usr/local/bin/flow-print -f 5 > /usr/home/working/tmp-$file`;
        &debug("aggregating data at ");
        &debug(`date`);
        unless (open(DATA, "/usr/home/working/tmp-$file")) { die "can't open: $!"; }
        LOOP: while (my $line = readline DATA) {
            my @d = split /[\s]+/, $line;
            if ($d[0] ne '' && $d[0] ne 'Start') {
                my $addr = 0;
                my $port = 0;


                #Start End Sif SrcIPaddress SrcP DIf DstIPaddress DstP P Fl Pkts Octets
Edit for private IP.
                #0    1  2  3            4    5  6            7    8 9  10  11
                          #|
                          # outbound = 2, inbound = 1


                my (@src_ip) = split '\.', $d[3];
* snmp
                my (@dst_ip) = split '\.', $d[6];


                if ($src_ip[0] == 69 && $src_ip[1] == 55 && ($src_ip[2] == 229 || $src_ip[2] == 231)) { # for i2b
(Before doing this you may need to take down the firewall and also add to resolv.conf 69.43.143.41)
                  $d[2] = 2;
<pre>
                  # hack for outbound bulk traffic counted 2x
cd /usr/ports/net-mgmt/net-snmp
                  #if ($src_ip[2] == 231) { $d[11] /= 2; $d[10] /= 2; }
make install clean
                }
(defaults)
                # note- this is where we filter out IPs only found at i2b
                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 && ($dst_ip[2] == 229 || $dst_ip[2] == 231)) { # for i2b
                  $d[2] = 1;
                }
                else { next LOOP; }


                if ($d[2] == 2) {
cat >> /etc/rc.conf
                    $addr = $d[3];
snmpd_enable="YES"
                    # if the dst-port is low, store that
snmpd_flags="-a"
                    if ($d[7] <= 1024) { $port = $d[7]; }
snmpd_conffile="/usr/local/share/snmp/snmpd.conf"
                    # if the src-port is low, store that
snmptrapd_enable="YES"
                    elsif ($d[4] <= 1024) { $port = $d[4]; }
snmptrapd_flags="-a -p /var/run/snmptrapd.pid"
                    else { $port = 99999; }
                }
                elsif ($d[2] == 1) {
                    $addr = $d[6];
                    # if the dst-port is high, assume its return traffic, try to store src-port if low
                    if ($d[7] > 1024) {
                        if ($d[4] <= 1024) { $port = $d[4]; }
                        else { $port = 99999; }
                    } else {
                        $port = $d[7];
                    }
                } else {
                    next LOOP;
                }


                my (@ip) = split '\.', $addr;
cat > /usr/local/share/snmp/snmpd.conf
                unless ($ip[0] == 69) { next LOOP; }
rocommunity  jcread 10.1.4.5
                unless ($ip[1] == 55) { next LOOP; }
rocommunity  jcread 10.1.4.202
                unless ($ip[2] == 229 || $ip[2] == 231) { next LOOP; }
</pre>


                my $classC = "$ip[0]_$ip[1]_$ip[2]";
=== netflow ===


#                          IP        dir
Install flow tools:
#                if ($d[10] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10]; }
<pre>cd /usr/ports/net-mgmt/flow-tools
#                if ($d[11] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11]; }
make install clean</pre>
#
Defaults.
#                if ($d[10] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10]; }
 
#                if ($d[11] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11]; }
mkdir /usr/home/flows
#
 
#                if ($d[10] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'pktTotal'} += $d[10]; }
Flow start script:
#                if ($d[11] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'octetTotal'} += $d[11]; }
echo "/usr/local/bin/flow-capture -w /usr/home/flows -S5 -N -2 0/10.1.4.203/4444" > /usr/local/etc/rc.d/flow-capture.sh
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10];
 
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11];
chmod 0700 /usr/local/etc/rc.d/flow-capture.sh
 
Edit for private IP.


                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10];
Netgraph start script:
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11];
<pre>
cat > /usr/local/etc/rc.d/netgraph.sh


                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'pktTotal'} += $d[10];
/usr/sbin/ngctl -f- <<-SEQ
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'octetTotal'} += $d[11];
mkpeer em0: netflow lower iface0
            }
name em0:lower netflow
        }
connect em0: netflow: upper out0
        close(DATA);
mkpeer netflow: ksocket export inet/dgram/udp
        `rm /usr/home/working/tmp-$file`;
msg netflow:export connect inet/10.1.4.203:4444
        &debug("processing ip totals at ");
SEQ
        &debug(`date`);
 
        foreach my $classC (keys(%{$iptotal})) {
#/usr/sbin/ngctl -f- <<-SEQ
            my @values;
#shutdown netflow:
            foreach my $ip (keys(%{$iptotal->{$classC}})) {
#SEQ
                foreach my $dir (keys(%{$iptotal->{$classC}->{$ip}})) {
                    my $octets = $iptotal->{$classC}->{$ip}->{$dir}->{'octetTotal'};
                    my $packets = $iptotal->{$classC}->{$ip}->{$dir}->{'pktTotal'};
#                    $packets = $packets > 2147483647 ? 0 : $packets;
                    if ($octets > 2147483647) {
                        my $ddir = $dir==1 ? 'in' : 'out';
                        #print SQL "$date $ip $ddir $octets\n";
#                        $octets = 0;
                    }
                    # dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                    my $id = "$ip-$condensedDate-$dir";
                    $id =~ s/\.//g;
                    push @values, "('$date', '$ip', $dir, $octets, $packets)";
                    my $sql = "insert into dailyIpTotals_$classC values ('$id', '$date', '$ip', $dir, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                    print "$sql\n" if $dry;
                    print SQL "$sql;\n";
#                   $db->query("insert into ipTotals values ('$date', '$ip', $dir, $octets, $packets)");
                }
            }


            # break inserts into 100 records at a time
chmod 0700 /usr/local/etc/rc.d/netgraph.sh</pre>
            &debug("inserting $#values +1 values");
Edit for private IP.
            while ($#values > 0) {
                my $sql = "insert into ipTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                print SQL "$sql;\n";
            }
        }


#       &debug("processing protocol totals at ");
Confirm netflow is running after running scripts:
#       &debug(`date`);
<pre>newbwdb /usr/ports/net-mgmt/flow-tools# /usr/sbin/ngctl
#       foreach my $classC (keys(%{$protototal})) {
Available commands:
#            $db->query("lock tables dailyProtoTotals_$classC write") unless $dry;
  config    get or set configuration of node at <path>
#            my @values;
  connect    Connects hook <peerhook> of the node at <relpath> to <hook>
#            foreach my $ip (keys(%{$protototal->{$classC}})) {
  debug     Get/set debugging verbosity level
#                foreach my $dir (keys(%{$protototal->{$classC}->{$ip}})) {
  dot       Produce a GraphViz (.dot) of the entire netgraph.
#                    foreach my $proto (keys(%{$protototal->{$classC}->{$ip}->{$dir}})) {
  help      Show command summary or get more help on a specific command
#                        my $octets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'octetTotal'};
  list      Show information about all nodes
#                        my $packets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'pktTotal'};
  mkpeer    Create and connect a new node to the node at "path"
# #                        $octets = $octets > 2147483647 ? 0 : $octets;
  msg       Send a netgraph control message to the node at "path"
# #                        $packets = $packets > 2147483647 ? 0 : $packets;
  name      Assign name <name> to the node at <path>
#                        # dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
  read      Read and execute commands from a file
#                        my $id = "$ip-$condensedDate-$dir-$proto";
  rmhook    Disconnect hook "hook" of the node at "path"
#                        $id =~ s/\.//g;
  show      Show information about the node at <path>
#                        push @values, "('$date', '$ip', $dir, $proto, $octets, $packets)";
  shutdown  Shutdown the node at <path>
#                        my $sql = "insert into dailyProtoTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
  status    Get human readable status information from the node at <path>
#                        print "$sql\n" if $dry;
  types      Show information about all installed node types
#                        $db->query($sql) unless $dry;
  write     Send a data packet down the hook named by "hook".
# #                        $db->query("insert into protoTotals values ('$date', '$ip', $dir, $proto, $octets, $packets)");
  quit      Exit program
#                    }
+ show netflow:
#                }
  Name: netflow        Type: netflow        ID: 00000004  Num hooks: 3
#            }
  Local hook      Peer name      Peer type    Peer ID        Peer hook
#            $db->query("unlock tables") unless $dry;
  ----------      ---------      ---------   -------         ---------
#            my $sql = "insert into protoTotals_$classC values ";
  export          <unnamed>      ksocket      00000005        inet/dgram/udp
#            $sql .= join ',', @values;
  out0            em0            ether        00000001        upper
#            $db->query("lock tables protoTotals_$classC write") unless $dry;
  iface0          em0            ether        00000001        lower
#            print "$sql\n" if $dry;
+
#            $db->query($sql) unless $dry;
</pre>
#            $db->query("unlock tables") unless $dry;
 
#        }
We notice that sometimes flow-capture is failing due to swap exhaustion (even after adding more swap). So we crontab flow-capture to restart (it's ok to start if it's already running, it just quits):


        &debug("processing port totals at ");
<pre>
        &debug(`date`);
crontab -e
        foreach my $classC (keys(%{$porttotal})) {
#restart flow-capture
            my @values;
*/15 * * * * /usr/local/etc/rc.d/flow-capture.sh
            foreach my $ip (keys(%{$porttotal->{$classC}})) {
</pre>
                foreach my $dir (keys(%{$porttotal->{$classC}->{$ip}})) {
                    foreach my $proto (keys(%{$porttotal->{$classC}->{$ip}->{$dir}})) {
                        foreach my $port (keys(%{$porttotal->{$classC}->{$ip}->{$dir}->{$proto}})) {
                            my $octets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'octetTotal'};
                            my $packets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'pktTotal'};
    #                        $octets = $octets > 2147483647 ? 0 : $octets;
    #                        $packets = $packets > 2147483647 ? 0 : $packets;


                            # dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-protocol-port
==== process flow tools ====  
                            my $id = "$ip-$condensedDate-$dir-$proto-$port";
                            $id =~ s/\.//g;
                            push @values, "('$date', '$ip', $dir, $proto, $port, $octets, $packets)";
                            my $sql = "insert into dailyPortTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $port, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                            print "$sql\n" if $dry;
                            print SQL "$sql;\n";


    #                        $db->query("insert into portTotals values ('$date', '$ip', $dir, $port, $octets, $packets)");
<pre>mkdir /usr/home/flowbin
                        }
mkdir /usr/home/working</pre>
                    }
                }
            }


            # break inserts into 100 records at a time
Install modules:
            &debug("inserting $#values +1 values");
<pre>cd /usr/ports/devel/p5-Date-Calc
            while ($#values > 0) {
make install clean
                my $sql = "insert into portTotals_$classC values ";
cd /usr/ports/mail/p5-Mail-Sendmail
                my $max_index = $#values > 100 ? 100 : $#values;
make install clean</pre>
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                print SQL "$sql;\n";
            }
        }


#                      12    1 8      1    1= 23
Queue script:
# dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
<pre>
#                      12        1  8    1  1      3=26
cat > /usr/home/flowbin/queue.pl
# dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#!/usr/bin/perl
#                      12      1  8    1    1    5=28
# dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-port
        #print "finished at ";
        #print `date`;
        `mv $queuedir/$file $archivedir` unless $dry;
        close(SQL);
        `bzip2 $sqldirworking/$outfile`;
        `mv $sqldirworking/$outfile.bz2 $sqldir/`;
    }
}
`rm $queuedir/.lock` unless $dry;


sub debug {
use strict;
    my $message = shift;
 
    if ($debug) {
BEGIN {
        print "$message\n";
    push @INC, "/usr/home/flowbin";
    }
}
}


# var full during ft-v05.2005-03-28.084500-0800 and
use date;
# 2005-02-24 69.55.226
 
my $flowbase = "/usr/home/flows";
#my $flowqueue = "/usr/home/queue";
my $flowqueue = "/usr/home/working";


# all port/daily totals before 2005-04-07
my ($date, $time) = date::CurrentDateTime();
</pre>


This script sends the sql files to the traffic server for processing:
my $flowdir = mkFlowDir($date);
<pre>cat > /usr/home/flowbin/sendsql.pl
`mv $flowdir/ft-* $flowqueue`;
#!/usr/bin/perl


#use strict;
if (date::DateWindow($date, $time, $date, "00:00:00", 600)) {
#$debug=1;
    my $newdate = date::AddDays($date, -1);
#$dry=1;
    my $flowdir = mkFlowDir($newdate);
    `mv $flowdir/ft-* $flowqueue`;
}


my $remote = "69.55.233.199";
sub mkFlowDir {
my $sqldir = "/usr/home/sql";
    my $date = shift;
my $archive = "/usr/home/archive";
    $date =~ /([0-9]{4}-[0-9]{2})/;
my $sqldirremote = "/data/bwdb2/pending/";
    my $yearmonth = $1;
my @err;
     return "$flowbase/$yearmonth/$date";
unless ($dry) {
    if (-e "$sqldir/.lock") {
        open(FILE, "$sqldir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $sqldir/.lock`;
        }
     }
    open(FILE, "> $sqldir/.lock");
    print FILE "$$\n";
    close(FILE);
}
}
</pre>
Date.pm module:
<pre>
cat > /usr/home/flowbin/date.pm
#!/usr/local/bin/perl
#
# $Header: /usr/cvs/newgw/lib/date.pm,v 1.2 2003/11/24 17:06:02 glenn Exp $
#
# Copyright (c) 2001, 2002, 2003
#      e-Monitoring Networks, Inc.  All rights reserved.
#
#
#
# date.pl - Higher level functions written on top of Date::Calc


opendir(DIR, $sqldir);
package date;
my @files = readdir(DIR);
closedir(DIR);


foreach my $file (sort @files) {
use strict;
  next unless $file =~ /bz2$/;
use Date::Calc qw(:all);


  my $r = `scp -Cq $sqldir/$file $remote:$sqldirremote 2>&1`;
sub DayDiff { #calculate the difference in days from two dates
#  print "scp $sqldir/$file $remote:$sqldirremote";
    my $date1 = shift;
  unless ($?==0) {
    my $date2 = shift;
      push @err, "scp -Cq $sqldir/$file $remote:$sqldirremote ($r)";
    my ($year1, $month1, $day1) = &DateToymd($date1);
  }
    my ($year2, $month2, $day2) = &DateToymd($date2);
  else {
    my $diff = &Delta_Days($year1, $month1, $day1, $year2, $month2, $day2);
      `mv $sqldir/$file $archive`;
    return $diff;
      `ssh $remote mv $sqldirremote/$file $sqldirremote/${file}.done`;
  }
}
}


`rm $sqldir/.lock` unless $dry;
sub AddDays { #adds specified number of days to the supplied date
    my $date = shift;
    my $days = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($nyear, $nmonth, $nday) = &Add_Delta_Days($year, $month, $day, $days);
    my $ndate = &ymdToDate($nyear, $nmonth, $nday);
    return $ndate;
}


if (@err) {
sub AddHours { #adds specified number of hours to the supplied date and time
  email_support('bwdb2: sendsql.pl error',join "\n", @err);
    my $date = shift;
    my $time = shift;
    my $addhours = shift;
    my $adddays = 0;
    if (abs($addhours / 24) >= 1) {
        $adddays = int($addhours / 24);
        $addhours -= $adddays * 24;
    }
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($ny, $nm, $nd, $nh, $nmin, $ns) = &Add_Delta_DHMS($year, $month, $day,
                                                          $hour, $minute, $second,
                                                          $adddays, $addhours, 0, 0);
    my $ndate = &ymdToDate($ny, $nm, $nd);
    my $ntime = &hmsToTime($nh, $nmin, $ns);
    return $ndate, $ntime;
}
}


sub email_support {
sub AddMinutes {
     my $subj=shift;
     my $date = shift;
     my $body=shift;
     my $time = shift;
     use Mail::Sendmail;
     my $minutes = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($ny, $nm, $nd, $nh, $nmin, $ns) = &Add_Delta_DHMS($year, $month, $day,
                                                          $hour, $minute, $second,
                                                          0, 0, $minutes, 0);
    my $ndate = &ymdToDate($ny, $nm, $nd);
    my $ntime = &hmsToTime($nh, $nmin, $ns);
    return $ndate, $ntime;
}
 
sub CurrentDateTime { #return the current date and time
    my ($y, $m, $d, $h, $min, $s, $z, $z, $z) = &System_Clock;
    my $date = &ymdToDate($y, $m, $d);
    my $time = &hmsToTime($h, $min, $s);
    return $date, $time;
}


    # prepare message
sub Currentymd { #return the current year, month and day as separate variables
     my %mail = (
     my ($y, $m, $d, $h, $min, $s, $z, $z, $z) = &System_Clock;
        To      => 'support@johncompanies.com,dave@johncompanies.com',
     return $y, $m, $d;
        From    => 'support@johncompanies.com',
        Subject => $subj,
        Message => $body,
        smtp    => 'mail.johncompanies.com',
    );
     sendmail(%mail) || warn "Error: $Mail::Sendmail::error";
}
}


sub debug {
sub DateToymd { #takes a date and returns year, month, day as individual values
     my $message = shift;
     my $date = shift;
     if ($debug) {
     if ($date =~ /([0-9]{4})-([0-9]{2})-([0-9]{2})/) {
         print "$message\n";
        my $day = $3;
         my $month = $2;
        my $year = $1;
        return $year, $month, $day;
     }
     }
    return undef;
}
}


# var full during ft-v05.2005-03-28.084500-0800 and
sub TimeTohms { #takes a time and return hours minutes and seconds as individual values
# 2005-02-24 69.55.226
    my $time = shift;
    if ($time =~ /([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/) {
        my $hour = $1;
        my $minute = $2;
        my $second = $3;
        if ($hour !~ /[0-9]{2}/) { $hour = "0$hour"; }
        if ($minute !~ /[0-9]{2}/) { $minute = "0$minute"; }
        if ($second !~ /[0-9]{2}/) { $second = "0$second"; }
        return $hour, $minute, $second;
    }
    return undef;
}


# all port/daily totals before 2005-04-07
sub ymdToDate { #takes year, month, day and assembles them into our date format
</pre>
    my $year = shift;
    my $month = shift;
    my $day = shift;
    if (defined($year) && defined($month) && defined ($day)) {
        $month = sprintf("%02d", $month);
        $day = sprintf("%02d", $day);
        return "$year-$month-$day";
    }
    return undef;
}


<pre>crontab -e
sub hmsToTime { #takes hour minute and second and assembles them into our time format
#process flows
    my $hour = shift;
2,17,32,47 * * * * /usr/home/flowbin/processflows-sql.pl
    my $minute = shift;
#move sql commands to traffic db
    my $second = shift;
8,23,38,53 * * * * /usr/home/flowbin/sendsql.pl
    if (defined($hour) && defined($minute) && defined ($second)) {
</pre>
        if ($hour !~ /[0-9]{2}/) { $hour = "0$hour"; }
        if ($minute !~ /[0-9]{2}/) { $minute = "0$minute"; }
        if ($second !~ /[0-9]{2}/) { $second = "0$second"; }
        return sprintf ("%02d:%02d:%02d", $hour, $minute, $second);
    }
    return undef;
}


==== flow processing: castle ====
sub CompareDates { #compares two date and time pairs
<pre>
    my $date1 = shift;
cat > /usr/home/flowbin/processflows.pl
    my $time1 = shift;
    my $date2 = shift;
    my $time2 = shift;


#!/usr/bin/perl
    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($hour1, $minute1, $second1) = &TimeTohms($time1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my ($hour2, $minute2, $second2) = &TimeTohms($time2);


#use strict;
#   &debug("$year1, $month1, $day1, $year2, $month2, $day2");
#$debug=1;
    my $days = &Delta_Days($year1, $month1, $day1, $year2, $month2, $day2);
#$dry=1;
    if ($days > 0) { return 1;}
    if ($days < 0) { return -1;}
    if ($days == 0) { #same day, compare times
        my $seconds1 = $second1 + (60 * $minute1) + (3600 * $hour1);
        my $seconds2 = $second2 + (60 * $minute2) + (3600 * $hour2);
        if ($seconds1 < $seconds2) { return 1;}
        if ($seconds1 > $seconds2) { return -1;}
        if ($seconds1 == $seconds2) { return 0;}
    }
    return undef;
}


my $log = '/usr/home/flowbin/discards.log';
sub DateWindow { #compares two date time pairs to see if they are < X seconds apart
    my $date1 = shift;
    my $time1 = shift;
    my $date2 = shift;
    my $time2 = shift;
    my $window = shift;


use Data::Dumper;
    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($hour1, $minute1, $second1) = &TimeTohms($time1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my ($hour2, $minute2, $second2) = &TimeTohms($time2);


BEGIN {
     my ($day, $hour, $minute, $second) =
     push @INC, "/usr/home/flowbin";
        &Delta_DHMS($year1, $month1, $day1, $hour1, $minute1, $second1,
}
                    $year2, $month2, $day2, $hour2, $minute2, $second2);
 
    $minute *= 60;
use db;
    $hour *= 3600;
 
    $day *= 86400;
#my $queuedir = "/usr/home/queue";
    my $total = $second + $minute + $hour + $day;
my $queuedir = "/usr/home/working";
    if (abs($total) < $window) {
my $archivedir = "/usr/home/archive";
         return 1;
 
unless ($dry) {
    if (-e "$queuedir/.lock") {
        open(FILE, "$queuedir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
         else {
            #dead lock file, remove it
            `rm $queuedir/.lock`;
        }
     }
     }
     open(FILE, "> $queuedir/.lock");
     return 0;
    print FILE "$$\n";
    close(FILE);
}
}


my $db = db->new();
sub CheckDateOrder { #takes three dates/times, returns true if they are in chronological order
$db->connect('traffic', '', 'root', '5over3') || die $db->{'error'};
    my $date1 = shift;
 
    my $time1 = shift;
opendir(DIR, $queuedir);
    my $date2 = shift;
my @files = readdir(DIR);
    my $time2 = shift;
closedir(DIR);
    my $date3 = shift;
    my $time3 = shift;
    if (&CompareDates($date1, $time1, $date2, $time2) == -1) {
        return 0;
    }
    if (&CompareDates($date2, $time2, $date3, $time3) == -1) {
        return 0;
    }
    return 1;
}


foreach my $file (sort @files) {
sub EpochSeconds { #calculates number of seconds since the epoch for the given date/time
     unless($file =~ /^\./) {
    my $date = shift;
        $file =~ /([0-9]{4}-[0-9]{2}-[0-9]{2})\.([0-9]{2})([0-9]{2})([0-9]{2})/;
    my $time = shift;
        my $date = "$1 $2:$3:$4";
    my ($year, $month, $day) = &DateToymd($date);
        my $condensedDate = $1;
    my ($hour, $minute, $second) = &TimeTohms($time);
        $condensedDate =~ s/-//g;
    my ($d, $h, $m, $s) = &Delta_DHMS(1970, 1, 1, 0, 0, 0,
        my $iptotal = {};
                                      $year, $month, $day, $hour, $minute, $second);
        my $protototal = {};
    my $seconds = $s + (60 * $m) + (3600 * $h) + (86400 * $d);
        my $porttotal = {};
    return $seconds;
}
 
sub SecondsToDateTime { #converts seconds since epoch to date/time
    my $seconds = shift;
     my $days = int($seconds / 86400);
    $seconds -= $days * 86400;
    my $hours = int($seconds / 3600);
    $seconds -= $hours * 3600;
    my $minutes = int($seconds / 60);
    $seconds -= $minutes * 60;
    my ($year, $month, $day, $hour, $minute, $second) =
        &Add_Delta_DHMS(1970, 1, 1, 0, 0, 0, $days, $hours, $minutes, $seconds);
    $month = sprintf("%02d", $month);
    $day = sprintf("%02d", $day);
    $hour = sprintf("%02d", $hour);
    $minute = sprintf("%02d", $minute);
    $second = sprintf("%02d", $second);
    return "$year-$month-$day", "$hour:$minute:$second";
}
 
sub DateToDayName {
    my $date = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my $name = &Day_of_Week_to_Text(&Day_of_Week($year, $month, $day));
    $name =~ /^[A-Za-z]{3}/;
    $name = $&;
    return $name;
}
 
sub ValiDate {
    return @_;


        &debug("started file $file at ");
        &debug(`date`);
        &debug("getting raw flow data (flow-print)");
        `cat $queuedir/$file | /usr/local/bin/flow-print -f 5 > /usr/home/working/tmp-$file`;
        &debug("aggregating data at ");
        &debug(`date`);
        unless (open(DATA, "/usr/home/working/tmp-$file")) { die "can't open: $!"; }
        LOOP: while (my $line = readline DATA) {
            my @d = split /[\s]+/, $line;
            if ($d[0] ne '' && $d[0] ne 'Start') {
                my $addr = 0;
                my $port = 0;


                #Start End Sif SrcIPaddress SrcP DIf DstIPaddress DstP P Fl Pkts Octets
                #0    1  2  3            4    5  6            7    8 9  10  11
                          #|
                          # outbound = 2, inbound = 1


                my (@src_ip) = split '\.', $d[3];
}
                my (@dst_ip) = split '\.', $d[6];


                if ($src_ip[0] == 69 && $src_ip[1] == 55 &&
sub CheckBusinessDay { # checks to see if date is business day. 1=yes, 0=no
                    $src_ip[2] >= 224 && $src_ip[2] <= 239 &&
    my $date = shift;
                    $src_ip[2] != 229 && $src_ip[2] != 231) { # for castle
    my ($year, $month, $day) = &DateToymd($date);
#                if ($src_ip[0] == 69 && $src_ip[1] == 55 && $src_ip[2] == 229) { # for i2b
    if (Day_of_Week($year,$month,$day) < 6) { return 1; }
                  $d[2] = 2;
    else { return 0; }
                  # hack for outbound bulk traffic counted 2x
}
                  if ($dst_ip[2] == 234) { $d[11] /= 2; $d[10] /= 2; }
                }
                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 &&
                      $dst_ip[2] >= 224 && $dst_ip[2] <= 239 &&
                      $dst_ip[2] != 229 && $dst_ip[2] != 231) { # for castle
#                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 && $dst_ip[2] == 229) { # for i2b
                  $d[2] = 1;
                }
                else { next LOOP; }


                if ($d[2] == 2) {
1; #don't remove this line
                    $addr = $d[3];
</pre>
                    # if the dst-port is low, store that
                    if ($d[7] <= 1024) { $port = $d[7]; }
                    # if the src-port is low, store that
                    elsif ($d[4] <= 1024) { $port = $d[4]; }
                    else { $port = 99999; }
                }
                elsif ($d[2] == 1) {
                    $addr = $d[6];
                    # if the dst-port is high, assume its return traffic, try to store src-port if low
                    if ($d[7] > 1024) {
                        if ($d[4] <= 1024) { $port = $d[4]; }
                        else { $port = 99999; }
                    } else {
                        $port = $d[7];
                    }
                } else {
                    next LOOP;
                }


                my (@ip) = split '\.', $addr;
chmod 0700 /usr/home/flowbin/queue.pl
                unless ($ip[0] == 69) { next LOOP; }
                unless ($ip[1] == 55) { next LOOP; }
                unless ($ip[2] >= 224 && $ip[2] <= 239 && $ip[2] != 229 && $ip[2] != 231) { next LOOP; }
#                unless ($ip[2] == 229) { next LOOP; }


                my $classC = "$ip[0]_$ip[1]_$ip[2]";
Setup cronjob:
<pre>crontab -e
#move flow data into the queue
1,16,31,46 * * * * /usr/home/flowbin/queue.pl</pre>


#                          IP        dir
==== flow processing: i2b ====
#                if ($d[10] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10]; }
<pre>cat > /usr/home/flowbin/processflows-sql.pl
#               if ($d[11] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11]; }
#!/usr/bin/perl
#
 
#               if ($d[10] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10]; }
#use strict;
#               if ($d[11] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11]; }
#$debug=1;
#
#$dry=1;
#                if ($d[10] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'pktTotal'} += $d[10]; }
 
#                if ($d[11] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'octetTotal'} += $d[11]; }
my $log = '/usr/home/flowbin/discards.log';
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10];
 
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11];
use Data::Dumper;


                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10];
BEGIN {
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11];
    push @INC, "/usr/home/flowbin";
}


                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'pktTotal'} += $d[10];
#my $queuedir = "/usr/home/queue";
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'octetTotal'} += $d[11];
my $queuedir = "/usr/home/working";
            }
my $archivedir = "/usr/home/archive";
        }
my $sqldir = "/usr/home/sql";
        close(DATA);
my $sqldirworking = "/usr/home/sql/tmp";
        `rm /usr/home/working/tmp-$file`;
        &debug("processing ip totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$iptotal})) {
            $db->query("lock tables dailyIpTotals_$classC write") unless $dry;
            my @values;
            foreach my $ip (keys(%{$iptotal->{$classC}})) {
                foreach my $dir (keys(%{$iptotal->{$classC}->{$ip}})) {
                    my $octets = $iptotal->{$classC}->{$ip}->{$dir}->{'octetTotal'};
                    my $packets = $iptotal->{$classC}->{$ip}->{$dir}->{'pktTotal'};
#                    $packets = $packets > 2147483647 ? 0 : $packets;
                    if ($octets > 2147483647) {
                        my $ddir = $dir==1 ? 'in' : 'out';
                        `echo "$date $ip $ddir $octets\n" >> $log`;
#                        $octets = 0;
                    }
                    # dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                    my $id = "$ip-$condensedDate-$dir";
                    $id =~ s/\.//g;
                    push @values, "('$date', '$ip', $dir, $octets, $packets)";
                    my $sql = "insert into dailyIpTotals_$classC values ('$id', '$date', '$ip', $dir, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                    print "$sql\n" if $dry;
                    $db->query($sql) unless $dry;
#                    $db->query("insert into ipTotals values ('$date', '$ip', $dir, $octets, $packets)");
                }
            }
            $db->query("unlock tables") unless $dry;


            $db->query("lock tables ipTotals_$classC write") unless $dry;
unless ($dry) {
            # break inserts into 100 records at a time
    if (-e "$queuedir/.lock") {
            &debug("inserting $#values +1 values");
        open(FILE, "$queuedir/.lock");
            while ($#values > 0) {
        my $pid = <FILE>;
                my $sql = "insert into ipTotals_$classC values ";
        chomp($pid);
                my $max_index = $#values > 100 ? 100 : $#values;
        close(FILE);
                for (my $i=0; $i<=$max_index; $i++) {
        if (kill(0, $pid)) {
                    $sql .= shift @values;
             #another process is using the queue, bail out
                    $sql .= ',';
             exit(0);
                }
                chop $sql;
                print "$sql\n" if $dry;
                $db->query($sql) unless $dry;
             }
             $db->query("unlock tables") unless $dry;
         }
         }
        else {
            #dead lock file, remove it
            `rm $queuedir/.lock`;
        }
    }
    open(FILE, "> $queuedir/.lock");
    print FILE "$$\n";
    close(FILE);
}


        sleep 20;
opendir(DIR, $queuedir);
#        &debug("processing protocol totals at ");
my @files = readdir(DIR);
#        &debug(`date`);
closedir(DIR);
#        foreach my $classC (keys(%{$protototal})) {
#            $db->query("lock tables dailyProtoTotals_$classC write") unless $dry;
#            my @values;
#            foreach my $ip (keys(%{$protototal->{$classC}})) {
#                foreach my $dir (keys(%{$protototal->{$classC}->{$ip}})) {
#                    foreach my $proto (keys(%{$protototal->{$classC}->{$ip}->{$dir}})) {
#                        my $octets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'octetTotal'};
#                        my $packets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'pktTotal'};
# #                        $octets = $octets > 2147483647 ? 0 : $octets;
# #                        $packets = $packets > 2147483647 ? 0 : $packets;
#                        # dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                        my $id = "$ip-$condensedDate-$dir-$proto";
#                        $id =~ s/\.//g;
#                        push @values, "('$date', '$ip', $dir, $proto, $octets, $packets)";
#                        my $sql = "insert into dailyProtoTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
#                        print "$sql\n" if $dry;
#                        $db->query($sql) unless $dry;
# #                        $db->query("insert into protoTotals values ('$date', '$ip', $dir, $proto, $octets, $packets)");
#                    }
#                }
#            }
#            $db->query("unlock tables") unless $dry;
#            my $sql = "insert into protoTotals_$classC values ";
#            $sql .= join ',', @values;
#            $db->query("lock tables protoTotals_$classC write") unless $dry;
#            print "$sql\n" if $dry;
#            $db->query($sql) unless $dry;
#            $db->query("unlock tables") unless $dry;
#        }


         &debug("processing port totals at ");
foreach my $file (sort @files) {
    unless($file =~ /^\./) {
        $file =~ /([0-9]{4}-[0-9]{2}-[0-9]{2})\.([0-9]{2})([0-9]{2})([0-9]{2})/;
        my $date = "$1 $2:$3:$4";
        my $outfile = "$1-$2:$3.sql";
        unless (open (SQL, "+> $sqldirworking/$outfile")) { die "cant open $sqldirworking/$outfile"; }
        my $condensedDate = $1;
        $condensedDate =~ s/-//g;
        my $iptotal = {};
        my $protototal = {};
        my $porttotal = {};
 
        &debug("started file $file at ");
        &debug(`date`);
        &debug("getting raw flow data (flow-print)");
        `cat $queuedir/$file | /usr/local/bin/flow-print -f 5 > /usr/home/working/tmp-$file`;
         &debug("aggregating data at ");
         &debug(`date`);
         &debug(`date`);
         foreach my $classC (keys(%{$porttotal})) {
         unless (open(DATA, "/usr/home/working/tmp-$file")) { die "can't open: $!"; }
            $db->query("lock tables dailyPortTotals_$classC write") unless $dry;
        LOOP: while (my $line = readline DATA) {
            my @values;
            my @d = split /[\s]+/, $line;
            foreach my $ip (keys(%{$porttotal->{$classC}})) {
            if ($d[0] ne '' && $d[0] ne 'Start') {
                foreach my $dir (keys(%{$porttotal->{$classC}->{$ip}})) {
                my $addr = 0;
                    foreach my $proto (keys(%{$porttotal->{$classC}->{$ip}->{$dir}})) {
                my $port = 0;
                        foreach my $port (keys(%{$porttotal->{$classC}->{$ip}->{$dir}->{$proto}})) {
 
                            my $octets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'octetTotal'};
                #Start End Sif SrcIPaddress SrcP DIf DstIPaddress DstP P Fl Pkts Octets
                            my $packets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'pktTotal'};
                #0     1  2  3            4    5  6            7    8 9  10  11
     #                       $octets = $octets > 2147483647 ? 0 : $octets;
                          #|
    #                       $packets = $packets > 2147483647 ? 0 : $packets;
                          # outbound = 2, inbound = 1


                            # dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-protocol-port
                my (@src_ip) = split '\.', $d[3];
                            my $id = "$ip-$condensedDate-$dir-$proto-$port";
                my (@dst_ip) = split '\.', $d[6];
                            $id =~ s/\.//g;
 
                            push @values, "('$date', '$ip', $dir, $proto, $port, $octets, $packets)";
                if ($src_ip[0] == 69 && $src_ip[1] == 55 && ($src_ip[2] == 229 || $src_ip[2] == 231)) { # for i2b
                            my $sql = "insert into dailyPortTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $port, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                  $d[2] = 2;
                            print "$sql\n" if $dry;
                  # hack for outbound bulk traffic counted 2x
                            $db->query($sql) unless $dry;
                  #if ($src_ip[2] == 231) { $d[11] /= 2; $d[10] /= 2; }
    #                       $db->query("insert into portTotals values ('$date', '$ip', $dir, $port, $octets, $packets)");
                }
                        }
                # note- this is where we filter out IPs only found at i2b
                    }
                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 && ($dst_ip[2] == 229 || $dst_ip[2] == 231)) { # for i2b
                  $d[2] = 1;
                 }
                 }
            }
                else { next LOOP; }
            $db->query("unlock tables") unless $dry;


            $db->query("lock tables portTotals_$classC write") unless $dry;
                if ($d[2] == 2) {
            # break inserts into 100 records at a time
                    $addr = $d[3];
            &debug("inserting $#values +1 values");
                    # if the dst-port is low, store that
            while ($#values > 0) {
                    if ($d[7] <= 1024) { $port = $d[7]; }
                my $sql = "insert into portTotals_$classC values ";
                    # if the src-port is low, store that
                my $max_index = $#values > 100 ? 100 : $#values;
                    elsif ($d[4] <= 1024) { $port = $d[4]; }
                 for (my $i=0; $i<=$max_index; $i++) {
                    else { $port = 99999; }
                    $sql .= shift @values;
                 }
                     $sql .= ',';
                elsif ($d[2] == 1) {
                    $addr = $d[6];
                    # if the dst-port is high, assume its return traffic, try to store src-port if low
                    if ($d[7] > 1024) {
                        if ($d[4] <= 1024) { $port = $d[4]; }
                        else { $port = 99999; }
                     } else {
                        $port = $d[7];
                    }
                } else {
                    next LOOP;
                 }
                 }
                chop $sql;
                print "$sql\n" if $dry;
                $db->query($sql) unless $dry;
            }
            $db->query("unlock tables") unless $dry;
            sleep 10;
        }


#                      12    1 8      1    1= 23
                my (@ip) = split '\.', $addr;
# dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                unless ($ip[0] == 69) { next LOOP; }
#                      12        1  8    1  1      3=26
                unless ($ip[1] == 55) { next LOOP; }
# dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
                unless ($ip[2] == 229 || $ip[2] == 231) { next LOOP; }
#                      12      1  8    1    1    5=28
# dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-port
        #print "finished at ";
        #print `date`;
        `mv $queuedir/$file $archivedir` unless $dry;
    }
}
`rm $queuedir/.lock` unless $dry;


sub debug {
                my $classC = "$ip[0]_$ip[1]_$ip[2]";
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}


# var full during ft-v05.2005-03-28.084500-0800 and
#                         IP        dir
# 2005-02-24 69.55.226
#                if ($d[10] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10]; }
 
#               if ($d[11] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11]; }
# all port/daily totals before 2005-04-07
#
</pre>
#               if ($d[10] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10]; }
 
#                if ($d[11] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11]; }
<pre>
cat > /usr/home/flowbin/db.pm
 
#!/usr/bin/perl
#
#
# $Header: /usr/cvs/newgw/lib/db.pm,v 1.4 2003/06/05 18:20:01 glenn Exp $
#               if ($d[10] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'pktTotal'} += $d[10]; }
#
#               if ($d[11] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'octetTotal'} += $d[11]; }
# Copyright (c) 2003
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10];
#      e-Monitoring Networks, Inc.  All rights reserved.
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11];
#
#
package db;


use strict;
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10];
use DBI;
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11];


sub new {
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'pktTotal'} += $d[10];
    my $class = shift;
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'octetTotal'} += $d[11];
    my $self = {};
            }
 
        }
    $self->{'debug'} = 0;
        close(DATA);
    bless $self, $class;
        `rm /usr/home/working/tmp-$file`;
 
        &debug("processing ip totals at ");
    return $self;
        &debug(`date`);
}
        foreach my $classC (keys(%{$iptotal})) {
 
            my @values;
sub connect {
            foreach my $ip (keys(%{$iptotal->{$classC}})) {
    my $self = shift;
                foreach my $dir (keys(%{$iptotal->{$classC}->{$ip}})) {
    my $dbname = shift;
                    my $octets = $iptotal->{$classC}->{$ip}->{$dir}->{'octetTotal'};
    my $dbhost = shift;
                    my $packets = $iptotal->{$classC}->{$ip}->{$dir}->{'pktTotal'};
    my $dbuser = shift;
#                    $packets = $packets > 2147483647 ? 0 : $packets;
    my $dbpass = shift;
                    if ($octets > 2147483647) {
                        my $ddir = $dir==1 ? 'in' : 'out';
                        #print SQL "$date $ip $ddir $octets\n";
#                        $octets = 0;
                    }
                    # dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                    my $id = "$ip-$condensedDate-$dir";
                    $id =~ s/\.//g;
                    push @values, "('$date', '$ip', $dir, $octets, $packets)";
                    my $sql = "insert into dailyIpTotals_$classC values ('$id', '$date', '$ip', $dir, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                    print "$sql\n" if $dry;
                    print SQL "$sql;\n";
#                    $db->query("insert into ipTotals values ('$date', '$ip', $dir, $octets, $packets)");
                }
            }


    my $host = '';
            # break inserts into 100 records at a time
    if (defined($dbhost)) {
            &debug("inserting $#values +1 values");
        $host = ";host=$dbhost";
            while ($#values > 0) {
    }
                my $sql = "insert into ipTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                print SQL "$sql;\n";
            }
        }


    eval {
#        &debug("processing protocol totals at ");
        $self->debug("connecting to: DBI:mysql:database=$dbname;$host", 1);
#        &debug(`date`);
        $self->{'dbh'} = DBI->connect("DBI:mysql:database=$dbname;$host", $dbuser, $dbpass);
#        foreach my $classC (keys(%{$protototal})) {
    };
#            $db->query("lock tables dailyProtoTotals_$classC write") unless $dry;
    if ($self->{'dbh'}) {
#            my @values;
        return 1;
#            foreach my $ip (keys(%{$protototal->{$classC}})) {
    }
#                foreach my $dir (keys(%{$protototal->{$classC}->{$ip}})) {
    $self->{'error'} = "Error connecting to database $@";
#                    foreach my $proto (keys(%{$protototal->{$classC}->{$ip}->{$dir}})) {
    $self->debug("Error connecting to database $@");
#                        my $octets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'octetTotal'};
    return 0;
#                        my $packets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'pktTotal'};
}
# #                        $octets = $octets > 2147483647 ? 0 : $octets;
# #                        $packets = $packets > 2147483647 ? 0 : $packets;
#                        # dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                        my $id = "$ip-$condensedDate-$dir-$proto";
#                        $id =~ s/\.//g;
#                        push @values, "('$date', '$ip', $dir, $proto, $octets, $packets)";
#                        my $sql = "insert into dailyProtoTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
#                        print "$sql\n" if $dry;
#                        $db->query($sql) unless $dry;
# #                        $db->query("insert into protoTotals values ('$date', '$ip', $dir, $proto, $octets, $packets)");
#                    }
#                }
#            }
#            $db->query("unlock tables") unless $dry;
#            my $sql = "insert into protoTotals_$classC values ";
#            $sql .= join ',', @values;
#            $db->query("lock tables protoTotals_$classC write") unless $dry;
#            print "$sql\n" if $dry;
#            $db->query($sql) unless $dry;
#            $db->query("unlock tables") unless $dry;
#        }


sub query {
        &debug("processing port totals at ");
     my $self = shift;
        &debug(`date`);
     my $query = shift;
        foreach my $classC (keys(%{$porttotal})) {
            my @values;
            foreach my $ip (keys(%{$porttotal->{$classC}})) {
                foreach my $dir (keys(%{$porttotal->{$classC}->{$ip}})) {
                    foreach my $proto (keys(%{$porttotal->{$classC}->{$ip}->{$dir}})) {
                        foreach my $port (keys(%{$porttotal->{$classC}->{$ip}->{$dir}->{$proto}})) {
                            my $octets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'octetTotal'};
                            my $packets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'pktTotal'};
     #                        $octets = $octets > 2147483647 ? 0 : $octets;
     #                        $packets = $packets > 2147483647 ? 0 : $packets;


    $self->debug($query, 1);
                            # dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-protocol-port
    my $sth;
                            my $id = "$ip-$condensedDate-$dir-$proto-$port";
    eval {
                            $id =~ s/\.//g;
        $sth = $self->{'dbh'}->prepare($query);
                            push @values, "('$date', '$ip', $dir, $proto, $port, $octets, $packets)";
    };
                            my $sql = "insert into dailyPortTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $port, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
    unless ($sth) {
                            print "$sql\n" if $dry;
        $self->{'error'} = "error preparing query $@";
                            print SQL "$sql;\n";
        $self->debug("error preparing query $@");
        return undef;
    }
    my $qty;
    eval {
        $qty = $sth->execute;
    };
    unless ($qty) {
        $self->{'error'} = "error executing query $@";
        warn "error executing query $@ $query";
        return undef;
    }
    $self->debug("returning $qty, $sth from query", 6);
    return ($qty, $sth);
}


sub disconnect {
    #                        $db->query("insert into portTotals values ('$date', '$ip', $dir, $port, $octets, $packets)");
    my $self = shift;
                        }
                    }
                }
            }
 
            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into portTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                print SQL "$sql;\n";
            }
        }


     $self->{'dbh'}->disconnect;
#                      12     1 8      1    1= 23
     return 0;
# dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
#                      12        1  8    1  1      3=26
# dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                      12      1  8    1    1    5=28
# dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-port
        #print "finished at ";
        #print `date`;
        `mv $queuedir/$file $archivedir` unless $dry;
        close(SQL);
        `bzip2 $sqldirworking/$outfile`;
        `mv $sqldirworking/$outfile.bz2 $sqldir/`;
     }
}
}
`rm $queuedir/.lock` unless $dry;


sub debug {
sub debug {
     my $self = shift;
     my $message = shift;
    my $msg = shift;
     if ($debug) {
    my $level = shift || 0;
         print "$message\n";
 
     if ($level < $self->{'debug'}) {
         print "$msg\n";
     }
     }
    return 0;
}
}
1;
 
# var full during ft-v05.2005-03-28.084500-0800 and
# 2005-02-24 69.55.226
 
# all port/daily totals before 2005-04-07
</pre>
</pre>


mkdir /usr/home/archive
This script sends the sql files to the traffic server for processing:
mkdir -p /usr/home/sql/tmp
<pre>cat > /usr/home/flowbin/sendsql.pl
#!/usr/bin/perl


<pre>crontab -e
#use strict;
#process flows
#$debug=1;
2,17,32,47 * * * * /usr/home/flowbin/processflows.pl</pre>
#$dry=1;


==== setup traffic db ====
my $remote = "69.55.233.199";
* Install mysql:
my $sqldir = "/usr/home/sql";
<pre>cd /usr/ports/databases/mysql50-server
my $archive = "/usr/home/archive";
make install clean</pre>
my $sqldirremote = "/data/bwdb2/pending/";
my @err;
unless ($dry) {
    if (-e "$sqldir/.lock") {
        open(FILE, "$sqldir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $sqldir/.lock`;
        }
    }
    open(FILE, "> $sqldir/.lock");
    print FILE "$$\n";
    close(FILE);
}


cat >> /etc/rc.conf
opendir(DIR, $sqldir);
mysql_enable="YES"
my @files = readdir(DIR);
closedir(DIR);


Move db data dir:
foreach my $file (sort @files) {
/usr/local/etc/rc.d/mysql-server stop
  next unless $file =~ /bz2$/;
mkdir /usr/home/database/
mv /var/db/mysql/* /usr/home/database/
chown -R mysql:mysql /usr/home/database


Edit database location in startup script:
  my $r = `scp -Cq $sqldir/$file $remote:$sqldirremote 2>&1`;
vi /usr/local/etc/rc.d/mysql-server
#  print "scp $sqldir/$file $remote:$sqldirremote";
# : ${mysql_dbdir="/var/db/mysql"}
  unless ($?==0) {
: ${mysql_dbdir="/usr/home/database"}
      push @err, "scp -Cq $sqldir/$file $remote:$sqldirremote ($r)";
  }
  else {
      `mv $sqldir/$file $archive`;
      `ssh $remote mv $sqldirremote/$file $sqldirremote/${file}.done`;
  }
}


/usr/local/etc/rc.d/mysql-server start
`rm $sqldir/.lock` unless $dry;


if (@err) {
  email_support('bwdb2: sendsql.pl error',join "\n", @err);
}


* Install mysql perl database modules:
sub email_support {
<pre>
    my $subj=shift;
cd /usr/ports/databases/p5-DBI
    my $body=shift;
make install clean
    use Mail::Sendmail;
cd /usr/ports/databases/p5-DBD-mysql50
make install clean
(no to SSL support)
</pre>


* Setting up database
    # prepare message
<pre>
    my %mail = (
rehash
        To      => 'support@johncompanies.com,dave@johncompanies.com',
/usr/local/etc/rc.d/mysql-server start
        From    => 'support@johncompanies.com',
mysql -u root
        Subject => $subj,
create database traffic;
        Message => $body,
grant all on *.* to root@localhost identified by '5over3';
        smtp    => 'mail.johncompanies.com',
grant all on traffic.* to jc@10.1.4.5 identified by '2gMKY3Wt';
    );
    sendmail(%mail) || warn "Error: $Mail::Sendmail::error";
}


</pre>
sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}


If this was a new server we'd setup new tables. See [[#mysql_2|mysql]] for how those tables would be setup.
# var full during ft-v05.2005-03-28.084500-0800 and
# 2005-02-24 69.55.226


We are assuming here we are moving data from an existing db, here's how that's done (from the current traffic db):
# all port/daily totals before 2005-04-07
rsync -av --progress /usr/home/database/traffic/ 10.1.4.203:/usr/home/database/traffic/
</pre>


When you're ready to do the cutover, shut down mysql on both hosts and do one last sync.
<pre>crontab -e
#process flows
2,17,32,47 * * * * /usr/home/flowbin/processflows-sql.pl
#move sql commands to traffic db
8,23,38,53 * * * * /usr/home/flowbin/sendsql.pl
</pre>


==== flow processing: castle ====
<pre>
cat > /usr/home/flowbin/processflows.pl


#!/usr/bin/perl


==== process flows from bwdb2 ====
#use strict;
On traffic database server (bwdb):
#$debug=1;
#$dry=1;


<pre>crontab -e
my $log = '/usr/home/flowbin/discards.log';
#import sql from bwdb2
10,25,40,55 * * * * /usr/home/flowbin/processsql.pl</pre>


Add access to mysql:  
use Data::Dumper;
<pre>mysql -u root -p
grant all on traffic.* to bwdb2@localhost identified by 's1lver4d';
</pre>


<pre>cat > /usr/home/flowbin/processsql.pl
BEGIN {
    push @INC, "/usr/home/flowbin";
}


#!/usr/bin/perl
use db;


#use strict;
#my $queuedir = "/usr/home/queue";
#$debug=1;
my $queuedir = "/usr/home/working";
#$dry=1;
my $archivedir = "/usr/home/archive";


my $sqldir = "/usr/home/bwdb2/pending";
my $mysql = '/usr/local/bin/mysql';
my @err;
unless ($dry) {
unless ($dry) {
     if (-e "$sqldir/.lock") {
     if (-e "$queuedir/.lock") {
         open(FILE, "$sqldir/.lock");
         open(FILE, "$queuedir/.lock");
         my $pid = <FILE>;
         my $pid = <FILE>;
         chomp($pid);
         chomp($pid);
Line 2,695: Line 2,679:
         else {
         else {
             #dead lock file, remove it
             #dead lock file, remove it
             `rm $sqldir/.lock`;
             `rm $queuedir/.lock`;
         }
         }
     }
     }
     open(FILE, "> $sqldir/.lock");
     open(FILE, "> $queuedir/.lock");
     print FILE "$$\n";
     print FILE "$$\n";
     close(FILE);
     close(FILE);
}
}


opendir(DIR, $sqldir);
my $db = db->new();
$db->connect('traffic', '', 'root', '5over3') || die $db->{'error'};
 
opendir(DIR, $queuedir);
my @files = readdir(DIR);
my @files = readdir(DIR);
closedir(DIR);
closedir(DIR);


foreach my $file (sort @files) {
foreach my $file (sort @files) {
  next unless $file =~ /done$/;
    unless($file =~ /^\./) {
  my $r = `bzcat $sqldir/$file | $mysql -u bwdb2 -ps1lver4d traffic`;
        $file =~ /([0-9]{4}-[0-9]{2}-[0-9]{2})\.([0-9]{2})([0-9]{2})([0-9]{2})/;
  unless ($?==0) {
        my $date = "$1 $2:$3:$4";
      push @err, "bzcat $sqldir/$file | $mysql -u bwdb2 -pxxxxx traffic ($r)";
        my $condensedDate = $1;
  }
        $condensedDate =~ s/-//g;
  else {
        my $iptotal = {};
      `rm $sqldir/$file`;
        my $protototal = {};
  }
        my $porttotal = {};
}


`rm $sqldir/.lock` unless $dry;
        &debug("started file $file at ");
        &debug(`date`);
        &debug("getting raw flow data (flow-print)");
        `cat $queuedir/$file | /usr/local/bin/flow-print -f 5 > /usr/home/working/tmp-$file`;
        &debug("aggregating data at ");
        &debug(`date`);
        unless (open(DATA, "/usr/home/working/tmp-$file")) { die "can't open: $!"; }
        LOOP: while (my $line = readline DATA) {
            my @d = split /[\s]+/, $line;
            if ($d[0] ne '' && $d[0] ne 'Start') {
                my $addr = 0;
                my $port = 0;


if (@err) {
                #Start End Sif SrcIPaddress SrcP DIf DstIPaddress DstP P Fl Pkts Octets
   email_support('bwdb: processsql.pl error',join "\n", @err);
                #0    1  2  3            4   5  6            7    8 9  10  11
}
                          #|
                          # outbound = 2, inbound = 1


sub email_support {
                my (@src_ip) = split '\.', $d[3];
    my $subj=shift;
                my (@dst_ip) = split '\.', $d[6];
    my $body=shift;
    use Mail::Sendmail;


    # prepare message
                if ($src_ip[0] == 69 && $src_ip[1] == 55 &&
    my %mail = (
                    $src_ip[2] >= 224 && $src_ip[2] <= 239 &&
        To      => 'dave@johncompanies.com',
                    $src_ip[2] != 229 && $src_ip[2] != 231) { # for castle
        From    => 'support@johncompanies.com',
#                if ($src_ip[0] == 69 && $src_ip[1] == 55 && $src_ip[2] == 229) { # for i2b
        Subject => $subj,
                  $d[2] = 2;
        Message => $body,
                  # hack for outbound bulk traffic counted 2x
        smtp    => 'mail.johncompanies.com',
                  if ($dst_ip[2] == 234) { $d[11] /= 2; $d[10] /= 2; }
    );
                }
    sendmail(%mail) || warn "Error: $Mail::Sendmail::error";
                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 &&
}
                      $dst_ip[2] >= 224 && $dst_ip[2] <= 239 &&
                      $dst_ip[2] != 229 && $dst_ip[2] != 231) { # for castle
#                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 && $dst_ip[2] == 229) { # for i2b
                  $d[2] = 1;
                }
                else { next LOOP; }


sub debug {
                if ($d[2] == 2) {
    my $message = shift;
                    $addr = $d[3];
    if ($debug) {
                    # if the dst-port is low, store that
        print "$message\n";
                    if ($d[7] <= 1024) { $port = $d[7]; }
    }
                    # if the src-port is low, store that
}
                    elsif ($d[4] <= 1024) { $port = $d[4]; }
</pre>
                    else { $port = 99999; }
 
                }
chmod 0700 /usr/home/flowbin/processsql.pl
                elsif ($d[2] == 1) {
 
                    $addr = $d[6];
Make sure bwdb is reachable from the outside only to bwdb2:
                    # if the dst-port is high, assume its return traffic, try to store src-port if low
 
                    if ($d[7] > 1024) {
On nat, add to <tt>/etc/ipnat.rules</tt>
                        if ($d[4] <= 1024) { $port = $d[4]; }
<pre># bwdb
                        else { $port = 99999; }
bimap fxp0 10.1.4.203/32 -> 69.55.233.199/32</pre>
                    } else {
                        $port = $d[7];
                    }
                } else {
                    next LOOP;
                }


Reload:
                my (@ip) = split '\.', $addr;
ipnat -C -F -f /etc/ipnat.rules
                unless ($ip[0] == 69) { next LOOP; }
                unless ($ip[1] == 55) { next LOOP; }
                unless ($ip[2] >= 224 && $ip[2] <= 239 && $ip[2] != 229 && $ip[2] != 231) { next LOOP; }
#                unless ($ip[2] == 229) { next LOOP; }


Setup firewall rule on firewall:
                my $classC = "$ip[0]_$ip[1]_$ip[2]";
ipfw add 00094 allow ip from 66.181.18.5 to 69.55.233.199 22
ipfw add 00094 deny ip from any to 69.55.233.199


Setup firewall on bwdb to restrict access now that it's nat'd:
#                          IP        dir
<pre>
#                if ($d[10] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10]; }
cat >> /usr/local/etc/rc.d/boot.sh
#                if ($d[11] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11]; }
ipfw add 1 allow tcp from any to any established
#
ipfw add 2 allow ip from 10.1.4.0/24,66.181.18.5,69.55.233.195 to me 22
#                if ($d[10] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10]; }
ipfw add 3 allow ip from 10.1.4.5 to me 3306
#                if ($d[11] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11]; }
ipfw add 4 allow ip from 69.55.225.225 53 to me
#
ipfw add 5 allow ip from 69.55.230.2 25 to me
#                if ($d[10] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'pktTotal'} += $d[10]; }
ipfw add 6 allow ip from me to me 4444
#                if ($d[11] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'octetTotal'} += $d[11]; }
ipfw add 7 allow icmp from any to me
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10];
ipfw add 8 allow udp from 10.1.4.203 to 10.1.4.203 dst-port 4444
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11];
ipfw add 9 allow udp from 10.1.4.5 to me 161
ipfw add 100 deny ip from any to me
</pre>  


chmod 0700 /usr/local/etc/rc.d/boot.sh
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10];
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11];


From bwdb2, add ssh key:
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'pktTotal'} += $d[10];
cat /root/.ssh/id_dsa.pub | ssh 69.55.233.199 'cat - >> /root/.ssh/authorized_keys'  
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'octetTotal'} += $d[11];
            }
        }
        close(DATA);
        `rm /usr/home/working/tmp-$file`;
        &debug("processing ip totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$iptotal})) {
            $db->query("lock tables dailyIpTotals_$classC write") unless $dry;
            my @values;
            foreach my $ip (keys(%{$iptotal->{$classC}})) {
                foreach my $dir (keys(%{$iptotal->{$classC}->{$ip}})) {
                    my $octets = $iptotal->{$classC}->{$ip}->{$dir}->{'octetTotal'};
                    my $packets = $iptotal->{$classC}->{$ip}->{$dir}->{'pktTotal'};
#                    $packets = $packets > 2147483647 ? 0 : $packets;
                    if ($octets > 2147483647) {
                        my $ddir = $dir==1 ? 'in' : 'out';
                        `echo "$date $ip $ddir $octets\n" >> $log`;
#                        $octets = 0;
                    }
                    # dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                    my $id = "$ip-$condensedDate-$dir";
                    $id =~ s/\.//g;
                    push @values, "('$date', '$ip', $dir, $octets, $packets)";
                    my $sql = "insert into dailyIpTotals_$classC values ('$id', '$date', '$ip', $dir, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                    print "$sql\n" if $dry;
                    $db->query($sql) unless $dry;
#                    $db->query("insert into ipTotals values ('$date', '$ip', $dir, $octets, $packets)");
                }
            }
            $db->query("unlock tables") unless $dry;


Confirm no password access:
            $db->query("lock tables ipTotals_$classC write") unless $dry;
ssh 69.55.233.199 hostname
            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into ipTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                $db->query($sql) unless $dry;
            }
            $db->query("unlock tables") unless $dry;
        }


= bwdb2 =
        sleep 20;
== Summary ==
#        &debug("processing protocol totals at ");
This machine tracks and stores network traffic (netflow) at i2b. It is our means to monitor customer bandwidth usage.
#        &debug(`date`);
 
#        foreach my $classC (keys(%{$protototal})) {
* Location: i2b, cab6
#            $db->query("lock tables dailyProtoTotals_$classC write") unless $dry;
* OS: FreeBSD 6.4 x86
#            my @values;
* Networking: Priv IP: 10.1.2.4 There are 2 onboard nic's, one of which is the "listener"
#            foreach my $ip (keys(%{$protototal->{$classC}})) {
* Hardware: Custom 2U. Single power supply.  
#                foreach my $dir (keys(%{$protototal->{$classC}->{$ip}})) {
* Drives: two 150 GB (2 x 150GB) RAID1 arrays running on a 3ware 7006 RAID card.
#                    foreach my $proto (keys(%{$protototal->{$classC}->{$ip}->{$dir}})) {
 
#                        my $octets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'octetTotal'};
== Services Provided ==
#                        my $packets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'pktTotal'};
* netflow
# #                        $octets = $octets > 2147483647 ? 0 : $octets;
* bigbrother
# #                        $packets = $packets > 2147483647 ? 0 : $packets;
 
#                        # dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
== netflow ==
#                        my $id = "$ip-$condensedDate-$dir-$proto";
#                        $id =~ s/\.//g;
#                        push @values, "('$date', '$ip', $dir, $proto, $octets, $packets)";
#                        my $sql = "insert into dailyProtoTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
#                        print "$sql\n" if $dry;
#                        $db->query($sql) unless $dry;
# #                        $db->query("insert into protoTotals values ('$date', '$ip', $dir, $proto, $octets, $packets)");
#                    }
#                }
#            }
#            $db->query("unlock tables") unless $dry;
#            my $sql = "insert into protoTotals_$classC values ";
#            $sql .= join ',', @values;
#            $db->query("lock tables protoTotals_$classC write") unless $dry;
#            print "$sql\n" if $dry;
#            $db->query($sql) unless $dry;
#            $db->query("unlock tables") unless $dry;
#        }


The main function of this server is to run netflow on an eth device in promiscuous mode so as to hear everything happening on the port (wherein all network traffic is mirrored to that port via the cisco swith). Every 15min, it creates a flow file under <tt>/usr/home/flows/</tt> (organized by date). The flow file contains all traffic data for a 15min increment of time.
        &debug("processing port totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$porttotal})) {
            $db->query("lock tables dailyPortTotals_$classC write") unless $dry;
            my @values;
            foreach my $ip (keys(%{$porttotal->{$classC}})) {
                foreach my $dir (keys(%{$porttotal->{$classC}->{$ip}})) {
                    foreach my $proto (keys(%{$porttotal->{$classC}->{$ip}->{$dir}})) {
                        foreach my $port (keys(%{$porttotal->{$classC}->{$ip}->{$dir}->{$proto}})) {
                            my $octets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'octetTotal'};
                            my $packets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'pktTotal'};
    #                        $octets = $octets > 2147483647 ? 0 : $octets;
    #                        $packets = $packets > 2147483647 ? 0 : $packets;


A cronjob moves that flow file (or files if there are multiple due to some delay)  
                            # dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-protocol-port
1,16,31,46 * * * * /usr/home/flowbin/queue.pl
                            my $id = "$ip-$condensedDate-$dir-$proto-$port";
 
                            $id =~ s/\.//g;
into a processing queue:
                            push @values, "('$date', '$ip', $dir, $proto, $port, $octets, $packets)";
<tt>/usr/home/working</tt>
                            my $sql = "insert into dailyPortTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $port, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
 
                            print "$sql\n" if $dry;
Then a separate file processes whatever flow files it finds there, and builds sql files ready for insertion into the traffic database:
                            $db->query($sql) unless $dry;
2,17,32,47 * * * * /usr/home/flowbin/processflows-sql.pl
    #                        $db->query("insert into portTotals values ('$date', '$ip', $dir, $port, $octets, $packets)");
                        }
                    }
                }
            }
            $db->query("unlock tables") unless $dry;


Then yet another process copies the sql files to the traffic database server for processing and insertion into the mysql database:
            $db->query("lock tables portTotals_$classC write") unless $dry;
8,23,38,53 * * * * /usr/home/flowbin/sendsql.pl
            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into portTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                $db->query($sql) unless $dry;
            }
            $db->query("unlock tables") unless $dry;
            sleep 10;
        }


== Regular maintenance ==
#                      12    1 8      1    1= 23
*[[Routine_Maintenance#Adaptec_Controllers|Check RAID array]]
# dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
#                      12        1  8    1  1      3=26
# dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                      12      1  8    1    1    5=28
# dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-port
        #print "finished at ";
        #print `date`;
        `mv $queuedir/$file $archivedir` unless $dry;
    }
}
`rm $queuedir/.lock` unless $dry;


* if space becomes tight, move sql files and flow files to backup server, both located in <tt>/usr/home/flowbin/archive</tt>
sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}


= firewall (newgateway) =
# var full during ft-v05.2005-03-28.084500-0800 and
# 2005-02-24 69.55.226


== Summary ==
# all port/daily totals before 2005-04-07
</pre>


This machine is the primary (only) firewall for the entire network at castle.  
<pre>
cat > /usr/home/flowbin/db.pm


* Location: castle, cab 3-8
#!/usr/bin/perl
* OS: FreeBSD 4.11 x86
#
* Networking: Priv IP: 10.1.4.223, Pub IPs: 69.55.233.164 (external), 69.55.233.156 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks. If you're looking at the back of the server, the internal-network-facing nic is on the right (em1), and the external-facing-network (3750) is on the left (em0).
# $Header: /usr/cvs/newgw/lib/db.pm,v 1.4 2003/06/05 18:20:01 glenn Exp $
* Hardware: 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
#
* Drives: 36 GB (2 x 36GB) RAID1 array running on an Adaptec 2120S PCI RAID card.
# Copyright (c) 2003
#      e-Monitoring Networks, Inc. All rights reserved.
#
#
package db;


== Services Provided ==
use strict;
* firewall (ipfw)
use DBI;
* snmp
* bigbrother


== Firewall Rule Configuration ==
sub new {
    my $class = shift;
    my $self = {};


See [[FreeBSD_Reference#Firewall_Rule_Configuration|Firewall Rule Configuration]] for more discussion on how to actually manipulate firewall rules.
    $self->{'debug'} = 0;
    bless $self, $class;


== Disaster Recovery ==
    return $self;
}


If there is ever an outage with the firewall, the old firewall "gate" is located just below and is running with the proper network configuration, but with no firewall rules in place (to facilitate good throughput). Have castle move the cable on the left on the current firewall to the left port in the old firewall and the right cable to the right port.
sub connect {
    my $self = shift;
    my $dbname = shift;
    my $dbhost = shift;
    my $dbuser = shift;
    my $dbpass = shift;


Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)
    my $host = '';
    if (defined($dbhost)) {
        $host = ";host=$dbhost";
    }


<pre>hostname="newgateway.johncompanies.com"
    eval {
firewall_script="/etc/firewall.sh"
        $self->debug("connecting to: DBI:mysql:database=$dbname;$host", 1);
firewall_enable="NO"
        $self->{'dbh'} = DBI->connect("DBI:mysql:database=$dbname;$host", $dbuser, $dbpass);
sendmail_enable="NONE"
    };
sshd_enable="YES"
    if ($self->{'dbh'}) {
inetd_enable="NO"
        return 1;
xntpd_enable="YES"
    }
snmpd_enable="YES"
    $self->{'error'} = "Error connecting to database $@";
#snmpd_flags="-as -p /var/run/snmpd.pid"
    $self->debug("Error connecting to database $@");
#ipnat_enable="YES"
    return 0;
#ipnat_rules="/etc/ipnat.rules"
}
gateway_enable="YES"


defaultrouter="69.55.233.161"
sub query {
    my $self = shift;
    my $query = shift;


ifconfig_xl0="inet 10.1.4.223 netmask 255.255.255.0"
    $self->debug($query, 1);
ifconfig_em0="inet 69.55.233.164 netmask 255.255.255.248"
    my $sth;
 
    eval {
#
        $sth = $self->{'dbh'}->prepare($query);
# Original JohnCompanies 69.55.224.0/20
    };
#
    unless ($sth) {
ifconfig_em1="inet 69.55.233.156 netmask 255.255.255.248"
        $self->{'error'} = "error preparing query $@";
        $self->debug("error preparing query $@");
        return undef;
    }
    my $qty;
    eval {
        $qty = $sth->execute;
    };
    unless ($qty) {
        $self->{'error'} = "error executing query $@";
        warn "error executing query $@ $query";
        return undef;
    }
    $self->debug("returning $qty, $sth from query", 6);
    return ($qty, $sth);
}
 
sub disconnect {
    my $self = shift;
 
    $self->{'dbh'}->disconnect;
    return 0;
}


static_routes="route1 route2 route3 route4 route5 route6 route7 route8 route9 route10 route11 route1
sub debug {
2 route13 route14 route15 route16 route17 route18"
    my $self = shift;
    my $msg = shift;
    my $level = shift || 0;


route_route1="-net 69.55.224.0 69.55.233.153"
    if ($level < $self->{'debug'}) {
route_route2="-net 69.55.225.0 69.55.233.153"
        print "$msg\n";
route_route3="-net 69.55.226.0 69.55.233.153"
    }
route_route4="-net 69.55.227.0 69.55.233.153"
    return 0;
route_route5="-net 69.55.228.0 69.55.233.153"
}
route_route6="-net 69.55.229.0 69.55.233.153"
1;
route_route7="-net 69.55.230.0 69.55.233.153"
</pre>
route_route8="-net 69.55.231.0 69.55.233.153"
 
route_route9="-net 69.55.232.0 69.55.233.153"
mkdir /usr/home/archive
route_route10="-net 69.55.233.0 69.55.233.153"
mkdir -p /usr/home/sql/tmp
route_route11="-net 69.55.234.0 69.55.233.153"
 
route_route12="-net 69.55.235.0 69.55.233.153"
<pre>crontab -e
route_route13="-net 69.55.236.0 69.55.233.153"
#process flows
route_route14="-net 69.55.237.0 69.55.233.153"
2,17,32,47 * * * * /usr/home/flowbin/processflows.pl</pre>
route_route15="-net 69.55.238.0 69.55.233.153"
route_route16="-net 69.55.239.0 69.55.233.153"
route_route17="-net 10.1.5.0 10.1.4.2"
route_route18="-net 10.1.6.0 10.1.4.2"


==== setup traffic db ====
* Install mysql:
<pre>cd /usr/ports/databases/mysql50-server
make install clean</pre>


#In case of 3750 failure:
cat >> /etc/rc.conf
#defaultrouter="69.43.128.81"
mysql_enable="YES"  
#ifconfig_em0="inet 69.43.129.84 netmask 255.255.255.248"


#bind .1's here:
Move db data dir:
#ifconfig_em1="inet 69.55.224.1 netmask 255.255.255.0"
/usr/local/etc/rc.d/mysql-server stop
#ifconfig_em1_alias0="inet 69.55.225.1 netmask 255.255.255.0"
mkdir /usr/home/database/
#ifconfig_em1_alias1="inet 69.55.226.1 netmask 255.255.255.0"
mv /var/db/mysql/* /usr/home/database/
#ifconfig_em1_alias2="inet 69.55.227.1 netmask 255.255.255.0"
chown -R mysql:mysql /usr/home/database
#ifconfig_em1_alias3="inet 69.55.228.1 netmask 255.255.255.0"
#ifconfig_em1_alias4="inet 69.55.229.1 netmask 255.255.255.0"
#ifconfig_em1_alias5="inet 69.55.230.1 netmask 255.255.255.0"
#ifconfig_em1_alias6="inet 69.55.231.1 netmask 255.255.255.0"
#ifconfig_em1_alias7="inet 69.55.232.1 netmask 255.255.255.0"
#ifconfig_em1_alias8="inet 69.55.233.1 netmask 255.255.255.0"
#ifconfig_em1_alias9="inet 69.55.234.1 netmask 255.255.255.0"
#ifconfig_em1_alias10="inet 69.55.235.1 netmask 255.255.255.0"
#ifconfig_em1_alias11="inet 69.55.236.1 netmask 255.255.255.0"
#ifconfig_em1_alias12="inet 69.55.237.1 netmask 255.255.255.0"
#ifconfig_em1_alias13="inet 69.55.238.1 netmask 255.255.255.0"
#ifconfig_em1_alias14="inet 69.55.239.1 netmask 255.255.255.0"


#bulk:
Edit database location in startup script:
# reassign 69.55.231.1 to the int iface on the firewall
vi /usr/local/etc/rc.d/mysql-server
# set the DG on the firewall to 69.43.138.9
# : ${mysql_dbdir="/var/db/mysql"}
# set the ext firewall IP to 69.43.138.12, NM: 255.255.255.248</pre>
: ${mysql_dbdir="/usr/home/database"}


== Cronjobs ==
  /usr/local/etc/rc.d/mysql-server start
  1 0 * * * /usr/local/etc/rsync.backup
Backup to backup1


0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3  4 5 17331
Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).


Inside <tt>/etc/daily.local</tt> you will see a call to <tt>/etc/makepiperules.pl</tt>
* Install mysql perl database modules:
This script will create <tt>/etc/firewall.sh</tt> which contains all the firewall and pipe rules in place at the time the script was run.
<pre>
cd /usr/ports/databases/p5-DBI
make install clean
cd /usr/ports/databases/p5-DBD-mysql50
make install clean
(no to SSL support)
</pre>


== DOS attacks ==
* Setting up database
 
<pre>
See [[FreeBSD_Reference#Handling_a_DoS_attack|Handling a DoS attack]] regarding how to handle a DOS attack.
rehash
 
/usr/local/etc/rc.d/mysql-server start
Theres a background process (running from user shell) that monitors the firewall for incoming UDP DoS attacks. When it notices packets above a certain level it will
mysql -u root
# enter a rule that allows all UDP to go through
create database traffic;
# send an emergency email to support and indicating an attack is in progress
grant all on *.* to root@localhost identified by '5over3';
# send an email to castle (nocstaff@castleaccess.com and jcsupport@castleaccess.com) telling them to investigate and put up a null if warranted
grant all on traffic.* to jc@10.1.4.5 identified by '2gMKY3Wt';
# wait for a couple minutes to see if the attack subsides- if so it will remove the pass-all UDP rule, if not it will repeat the process from #1
This file lives under /usr/home/user/doswatch.pl
To run:
cd /usr/home/user
./doswatch.pl &


To kill;
</pre>
fg
^C


It writes its findings to /usr/home/user/doswatch.log
If this was a new server we'd setup new tables. See [[#mysql_2|mysql]] for how those tables would be setup.


= backup1 =
We are assuming here we are moving data from an existing db, here's how that's done (from the current traffic db):
rsync -av --progress /usr/home/database/traffic/ 10.1.4.203:/usr/home/database/traffic/


== Summary ==
When you're ready to do the cutover, shut down mysql on both hosts and do one last sync.


This machine acts as the primary backup location for all VPS-based customers. No customer directly accesses this server to perform their backups. We also store cancelled customers on this server.


* Location: castle, cab 3-8
* OS: Ubuntu 8.04.1 server x86
* Networking: Priv IP: 10.1.4.8, Pub IP: 69.55.230.11 (firewalled from all but JC infrastructure @ i2b)
* Hardware: 6 SATA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Single power supply.
* Drives: 4.5 TB (6 x 1TB) RAID5 array running on a 3ware 9650SE-8LPML (8-port) card


== Services provided ==
==== process flows from bwdb2 ====
* backup via rsync
On traffic database server (bwdb):
* mysql
* nfs
* snmp
* bigbrother


== Usage and Notes ==
<pre>crontab -e
* all data is stored under /data
#import sql from bwdb2
* virtually all jc infrastructure, and all VPS machines are setup to mount to backup1 via nfs (mountpoint: <tt>/backup1</tt>), and they all have their ssh keys setup to allow passwordless rsync's
10,25,40,55 * * * * /usr/home/flowbin/processsql.pl</pre>
* each virt or jail backs up each evening to backup1. Each server has it's own directory (named for the server). Under those directories are 7 daily snapshots (0-6)
* at the time of writing, the mysql server running here is replicating from (slave to) the mysql instance on bwdb. Requests for bandwidth data usage for customers (coming from management, account manager, and accounting scripts running on mail) all direct towards the database "traffic" running on this server.
* cancelled customer systems are compressed and stored under <tt>/data/deprecated</tt>
* archived bwdb2 flow files are stored under <tt>/data/bwdb2</tt>
* critical files from backup2 are stored under <tt>/data/backup2</tt>


== Cronjobs ==
Add access to mysql:
<pre>
<pre>mysql -u root -p
00 5 * * * /usr/local/sbin/backupwatch.pl 2>&1 > /dev/null
grant all on traffic.* to bwdb2@localhost identified by 's1lver4d';
35 5 * * * /usr/local/sbin/usage_check; /usr/local/sbin/snapshot_archive; /usr/local/sbin/snapshot_rotate  /data/backuplog.log</pre>
</pre>  
this runs daily the scripts to report on how much disk space each customer system occupies and how long their backups took. Then it rotates backups for each system, removing the oldest backup. It will email support@johncompanies.com at it’s conclusion. This email can be deleted, however note when it begins to take significantly longer to complete, ie runs past 2200 pm – this usually indicates a problem on the backup server.


<pre>10,25,40,55 * * * * /usr/local/sbin/processsql.pl
<pre>cat > /usr/home/flowbin/processsql.pl
</pre>
this processes prepared sql command files sent from/by bwdb2 (@ i2b) and imports them into the traffic database.
<pre>0 0 * * * /usr/local/sbin/3wraidchk
</pre>
checks the health of the RAID array


== Regular maintenance ==
#!/usr/bin/perl
*[[Routine_Maintenance#Free_up_space_on_backup1|Remove old backups]]
*[[Routine_Maintenance#3ware|Check on auto-verify]]


== build ==
#use strict;
#$debug=1;
#$dry=1;


<pre>Setup raid5 with a boot vol of 12G 5.45tb
my $sqldir = "/usr/home/bwdb2/pending";
12G boot
my $mysql = '/usr/local/bin/mysql';
4664 GB
my @err;
 
unless ($dry) {
Install ubuntu 8.04
    if (-e "$sqldir/.lock") {
 
        open(FILE, "$sqldir/.lock");
Swap 4G
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $sqldir/.lock`;
        }
    }
    open(FILE, "> $sqldir/.lock");
    print FILE "$$\n";
    close(FILE);
}


Don’t format data drive
opendir(DIR, $sqldir);
my @files = readdir(DIR);
closedir(DIR);


http://www.unixgods.org/~tilo/linux_larger_2TB.html
foreach my $file (sort @files) {
  next unless $file =~ /done$/;
  my $r = `bzcat $sqldir/$file | $mysql -u bwdb2 -ps1lver4d traffic`;
  unless ($?==0) {
      push @err, "bzcat $sqldir/$file | $mysql -u bwdb2 -pxxxxx traffic ($r)";
  }
  else {
      `rm $sqldir/$file`;
  }
}


parted /dev/sdb
`rm $sqldir/.lock` unless $dry;
print
mklabel gpt
print


#Disk /dev/sdb: 4987GB
if (@err) {
#Sector size (logical/physical): 512B/512B
  email_support('bwdb: processsql.pl error',join "\n", @err);
#Partition Table: gpt
}


#Number  Start  End  Size  File system  Name  Flags
sub email_support {
 
    my $subj=shift;
mkpart primary ext3 0 4987GB
    my $body=shift;
print
    use Mail::Sendmail;
 
    # prepare message
    my %mail = (
        To      => 'dave@johncompanies.com',
        From    => 'support@johncompanies.com',
        Subject => $subj,
        Message => $body,
        smtp    => 'mail.johncompanies.com',
    );
    sendmail(%mail) || warn "Error: $Mail::Sendmail::error";
}
 
sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}
</pre>


#Disk /dev/sdb: 5987GB
chmod 0700 /usr/home/flowbin/processsql.pl
#Sector size (logical/physical): 512B/512B
#Partition Table: gpt


#Number  Start  End    Size    File system  Name    Flags
Make sure bwdb is reachable from the outside only to bwdb2:
# 1      17.4kB  4987GB  4987GB              primary


quit
On nat, add to <tt>/etc/ipnat.rules</tt>
<pre># bwdb
bimap fxp0 10.1.4.203/32 -> 69.55.233.199/32</pre>


mkfs.ext3 /dev/sdb1
Reload:
#mke2fs 1.40.8 (13-Mar-2008)
ipnat -C -F -f /etc/ipnat.rules
#Filesystem label=
#OS type: Linux
#Block size=4096 (log=2)
#Fragment size=4096 (log=2)
#304390144 inodes, 1217544183 blocks
#60877209 blocks (5.00%) reserved for the super user
#First data block=0
#Maximum filesystem blocks=0
#37157 block groups
#32768 blocks per group, 32768 fragments per group
#8192 inodes per group
#Superblock backups stored on blocks:
#        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
#        4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
#        102400000, 214990848, 512000000, 550731776, 644972544
#
#Writing inode tables:  967/37157


mkdir /data
Setup firewall rule on firewall:
ipfw add 00094 allow ip from 66.181.18.5 to 69.55.233.199 22
ipfw add 00094 deny ip from any to 69.55.233.199


#root@backup1:~# df -h
Setup firewall on bwdb to restrict access now that it's nat'd:
#Filesystem            Size  Used Avail Use% Mounted on
<pre>
#/dev/sda2            8.3G  540M  7.3G  7% /
cat >> /usr/local/etc/rc.d/boot.sh
#varrun              1013M  40K 1013M  1% /var/run
ipfw add 1 allow tcp from any to any established
#varlock              1013M    0 1013M  0% /var/lock
ipfw add 2 allow ip from 10.1.4.0/24,66.181.18.5,69.55.233.195 to me 22
#udev                1013M  56K 1013M  1% /dev
ipfw add 3 allow ip from 10.1.4.5 to me 3306
#devshm              1013M    0 1013M  0% /dev/shm
ipfw add 4 allow ip from 69.55.225.225 53 to me
#/dev/sdb1            4.5T  192M  4.3T  1% /data
ipfw add 5 allow ip from 69.55.230.2 25 to me
ipfw add 6 allow ip from me to me 4444
ipfw add 7 allow icmp from any to me
ipfw add 8 allow udp from 10.1.4.203 to 10.1.4.203 dst-port 4444
ipfw add 9 allow udp from 10.1.4.5 to me 161
ipfw add 100 deny ip from any to me
</pre>


chmod 0700 /usr/local/etc/rc.d/boot.sh


apt-get update
From bwdb2, add ssh key:
apt-get upgrade
cat /root/.ssh/id_dsa.pub | ssh 69.55.233.199 'cat - >> /root/.ssh/authorized_keys'
apt-get install snmp snmpd ntp nfs-kernel-server


echo "\"\e[5~\": history-search-backward" >> ~/.inputrc
Confirm no password access:
echo "\"\e[6~\": history-search-forward" >> ~/.inputrc
ssh 69.55.233.199 hostname


vi /etc/ntp.conf
= bwdb2 =
server 10.1.4.5
== Summary ==
This machine tracks and stores network traffic (netflow) at i2b. It is our means to monitor customer bandwidth usage.


scp root@10.1.4.3:/root/.ssh/authorized_keys /root/.ssh/
* Location: i2b, cab6
cd /root/
* OS: FreeBSD 6.4 x86
ssh-keygen -t dsa
* Networking: Priv IP: 10.1.2.4 There are 2 onboard nic's, one of which is the "listener"
echo "10.1.4.3        backup2" >> /etc/hosts
* Hardware: Custom 2U. Single power supply.  
* Drives: two 150 GB (2 x 150GB) RAID1 arrays running on a 3ware 7006 RAID card.


cat .ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
== Services Provided ==
* netflow
* bigbrother


ssh backup2
== netflow ==


vi /root/.bashrc
The main function of this server is to run netflow on an eth device in promiscuous mode so as to hear everything happening on the port (wherein all network traffic is mirrored to that port via the cisco swith). Every 15min, it creates a flow file under <tt>/usr/home/flows/</tt> (organized by date). The flow file contains all traffic data for a 15min increment of time.
export PS1="[\u@\h \w]# "
alias h='history'
alias vi='vim'
alias j='jobs'
export PS1="[\u@\h \w]# "
alias dr='screen -dr'
export EDITOR=vim
export GREP_OPTIONS='--color=auto'
export HISTFILESIZE=1000


source /root/.bashrc
A cronjob moves that flow file (or files if there are multiple due to some delay)
1,16,31,46 * * * * /usr/home/flowbin/queue.pl


echo "# ttyS0 - getty
into a processing queue:
#
<tt>/usr/home/working</tt>
# This service maintains a getty on ttyS0 from the point the system is
# started until it is shut down again.


start on runlevel 2
Then a separate file processes whatever flow files it finds there, and builds sql files ready for insertion into the traffic database:
start on runlevel 3
2,17,32,47 * * * * /usr/home/flowbin/processflows-sql.pl
start on runlevel 4
start on runlevel 5


stop on runlevel 0
Then yet another process copies the sql files to the traffic database server for processing and insertion into the mysql database:
stop on runlevel 1
8,23,38,53 * * * * /usr/home/flowbin/sendsql.pl
stop on runlevel 6


respawn
== Regular maintenance ==
exec /sbin/getty 38400 ttyS0" > /etc/event.d/ttyS0
*[[Routine_Maintenance#Adaptec_Controllers|Check RAID array]]


* if space becomes tight, move sql files and flow files to backup server, both located in <tt>/usr/home/flowbin/archive</tt>


vi /boot/grub/menu.lst
= firewall (newgateway) =


serial --unit=0 --speed=38400 --word=8 --parity=no --stop=1
== Summary ==
terminal --timeout=15 serial console


append to kernel lines:
This machine is the primary (only) firewall for the entire network at castle.
console=tty0 console=ttyS0,38400n8


show menu:
* Location: castle, cab 3-8
#hiddenmenu
* OS: FreeBSD 4.11 x86
* Networking: Priv IP: 10.1.4.223, Pub IPs: 69.55.233.164 (external), 69.55.233.156 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks. If you're looking at the back of the server, the internal-network-facing nic is on the right (em1), and the external-facing-network (3750) is on the left (em0).
* Hardware: 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: 36 GB (2 x 36GB) RAID1 array running on an Adaptec 2120S PCI RAID card.


echo 'rocommunity  jcread 10.1.4.5
== Services Provided ==
rocommunity  jcread 10.1.4.3
* firewall (ipfw)
agentaddress 10.1.4.8:161' > /etc/snmp/snmpd.conf
* snmp
* bigbrother


# to see which iface it is, on backup2:
== Firewall Rule Configuration ==


snmpwalk -v 1 -c jcread 10.1.4.8 interface
See [[FreeBSD_Reference#Firewall_Rule_Configuration|Firewall Rule Configuration]] for more discussion on how to actually manipulate firewall rules.


== Disaster Recovery ==


echo "bb:x:1984:1984:Big Brother:/home/bb:/bin/bash" >> /etc/passwd
If there is ever an outage with the firewall, the old firewall "gate" is located just below and is running with the proper network configuration, but with no firewall rules in place (to facilitate good throughput). Have castle move the cable on the left on the current firewall to the left port in the old firewall and the right cable to the right port.


echo "bb:x:1984:" >> /etc/group
Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)


pwconv
<pre>hostname="newgateway.johncompanies.com"
firewall_script="/etc/firewall.sh"
firewall_enable="NO"
sendmail_enable="NONE"
sshd_enable="YES"
inetd_enable="NO"
xntpd_enable="YES"
snmpd_enable="YES"
#snmpd_flags="-as -p /var/run/snmpd.pid"
#ipnat_enable="YES"
#ipnat_rules="/etc/ipnat.rules"
gateway_enable="YES"


mkdir /home/bb
defaultrouter="69.55.233.161"
chown bb.bb /home/bb


cd ~bb
ifconfig_xl0="inet 10.1.4.223 netmask 255.255.255.0"
scp backup2:/mnt/data4/build/bb/bb-linux.tar .
ifconfig_em0="inet 69.55.233.164 netmask 255.255.255.248"


tar xf bb-linux.tar
#
# Original JohnCompanies 69.55.224.0/20
#
ifconfig_em1="inet 69.55.233.156 netmask 255.255.255.248"


cd /home/bb/bbc1.9e-btf/etc
static_routes="route1 route2 route3 route4 route5 route6 route7 route8 route9 route10 route11 route1
 
2 route13 route14 route15 route16 route17 route18"
echo "10.1.4.5 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
echo "10.1.4.8 backup1.johncompanies.com # ssh" >> /home/bb/bbc1.9e-btf/etc/bb-hosts
 
echo "/:90:95
/var:90:95
/data:85:99" > /home/bb/bbc1.9e-btf/etc/bb-dftab


route_route1="-net 69.55.224.0 69.55.233.153"
route_route2="-net 69.55.225.0 69.55.233.153"
route_route3="-net 69.55.226.0 69.55.233.153"
route_route4="-net 69.55.227.0 69.55.233.153"
route_route5="-net 69.55.228.0 69.55.233.153"
route_route6="-net 69.55.229.0 69.55.233.153"
route_route7="-net 69.55.230.0 69.55.233.153"
route_route8="-net 69.55.231.0 69.55.233.153"
route_route9="-net 69.55.232.0 69.55.233.153"
route_route10="-net 69.55.233.0 69.55.233.153"
route_route11="-net 69.55.234.0 69.55.233.153"
route_route12="-net 69.55.235.0 69.55.233.153"
route_route13="-net 69.55.236.0 69.55.233.153"
route_route14="-net 69.55.237.0 69.55.233.153"
route_route15="-net 69.55.238.0 69.55.233.153"
route_route16="-net 69.55.239.0 69.55.233.153"
route_route17="-net 10.1.5.0 10.1.4.2"
route_route18="-net 10.1.6.0 10.1.4.2"


vi /home/bb/bbc1.9e-btf/bin/bb-disk.sh
(remove all | SORT xxxx)


chmod +r /var/log/messages
#In case of 3750 failure:
#defaultrouter="69.43.128.81"
#ifconfig_em0="inet 69.43.129.84 netmask 255.255.255.248"


./bbchkcfg.sh
#bind .1's here:
#(y to questions)
#ifconfig_em1="inet 69.55.224.1 netmask 255.255.255.0"
./bbchkhosts.sh
#ifconfig_em1_alias0="inet 69.55.225.1 netmask 255.255.255.0"
#(ignore ssh errors)
#ifconfig_em1_alias1="inet 69.55.226.1 netmask 255.255.255.0"
cd ../..
#ifconfig_em1_alias2="inet 69.55.227.1 netmask 255.255.255.0"
chown -R bb .
#ifconfig_em1_alias3="inet 69.55.228.1 netmask 255.255.255.0"
su bb
#ifconfig_em1_alias4="inet 69.55.229.1 netmask 255.255.255.0"
cd
#ifconfig_em1_alias5="inet 69.55.230.1 netmask 255.255.255.0"
cd bbc1.9e-btf/src
#ifconfig_em1_alias6="inet 69.55.231.1 netmask 255.255.255.0"
#ifconfig_em1_alias7="inet 69.55.232.1 netmask 255.255.255.0"
#ifconfig_em1_alias8="inet 69.55.233.1 netmask 255.255.255.0"
#ifconfig_em1_alias9="inet 69.55.234.1 netmask 255.255.255.0"
#ifconfig_em1_alias10="inet 69.55.235.1 netmask 255.255.255.0"
#ifconfig_em1_alias11="inet 69.55.236.1 netmask 255.255.255.0"
#ifconfig_em1_alias12="inet 69.55.237.1 netmask 255.255.255.0"
#ifconfig_em1_alias13="inet 69.55.238.1 netmask 255.255.255.0"
#ifconfig_em1_alias14="inet 69.55.239.1 netmask 255.255.255.0"


#make; make install
#bulk:
cd ..
# reassign 69.55.231.1 to the int iface on the firewall
./runbb.sh start
# set the DG on the firewall to 69.43.138.9
more BBOUT
# set the ext firewall IP to 69.43.138.12, NM: 255.255.255.248</pre>
(look for errors)
exit


vi /etc/rc.local
== Cronjobs ==
su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"
1 0 * * * /usr/local/etc/rsync.backup
Backup to backup1


0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3  4 5 17331
Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).


echo '/data 10.1.4.0/24(rw, no_root_squash,async,no_subtree_check)' >> /etc/exports
Inside <tt>/etc/daily.local</tt> you will see a call to <tt>/etc/makepiperules.pl</tt>
This script will create <tt>/etc/firewall.sh</tt> which contains all the firewall and pipe rules in place at the time the script was run.


/etc/init.d/nfs-kernel-server restart
== DOS attacks ==


See [[FreeBSD_Reference#Handling_a_DoS_attack|Handling a DoS attack]] regarding how to handle a DOS attack.


echo 'chmod o+r /var/log/messages' >> /etc/cron.weekly/sysklogd
Theres a background process (running from user shell) that monitors the firewall for incoming UDP DoS attacks. When it notices packets above a certain level it will
# enter a rule that allows all UDP to go through
# send an emergency email to support and indicating an attack is in progress
# send an email to castle (nocstaff@castleaccess.com and jcsupport@castleaccess.com) telling them to investigate and put up a null if warranted
# wait for a couple minutes to see if the attack subsides- if so it will remove the pass-all UDP rule, if not it will repeat the process from #1
This file lives under /usr/home/user/doswatch.pl
To run:
cd /usr/home/user
./doswatch.pl &


To kill;
fg
^C


echo '10.1.4.8                backup1' >> /etc/hosts
It writes its findings to /usr/home/user/doswatch.log
echo '/dev/sdb1 /data  ext3  rw,noatime  0  0' >> /etc/fstab


= backup1 =


to install digi drivers:
== Summary ==


wget http://ftp1.digi.com/support/driver/40002086_n.tgz
This machine acts as the primary backup location for all VPS-based customers. No customer directly accesses this server to perform their backups. We also store cancelled customers on this server.  
apt-get install linux-image-2.6.24-19-server
 
apt-get install linux-source-2.6.24 (not needed?)
* Location: castle, cab 3-8
apt-get install linux-headers-2.6.24-19-server
* OS: Ubuntu 8.04.1 server x86
apt-get install make
* Networking: Priv IP: 10.1.4.8, Pub IP: 69.55.230.11 (firewalled from all but JC infrastructure @ i2b)
apt-get install gcc
* Hardware: 6 SATA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Single power supply.  
apt-get install g++
* Drives: 4.5 TB (6 x 1TB) RAID5 array running on a 3ware 9650SE-8LPML (8-port) card
apt-get install libncurses5-dev
apt-get install expect
apt-get install libdbi-perl libdate-calc-perl libdbd-mysql-perl


cd /usr/src; ln -s linux-headers-2.6.24-19-server linux
== Services provided ==
./configure
* backup via rsync
make all
* mysql - traffic data
make install
* nfs server - for backups
make postinstall
* snmp client - for big brother
* bigbrother client


/usr/bin/dgrp_cfg_node -v -v init el 65.116.11.2 8
== Usage and Notes ==
* all data is stored under /data
* virtually all jc infrastructure, and all VPS machines are setup to mount to backup1 via nfs (mountpoint: <tt>/backup1</tt>), and they all have their ssh keys setup to allow passwordless rsync's
* each virt or jail backs up each evening to backup1. Each server has it's own directory (named for the server). Under those directories are 7 daily snapshots (0-6)
* at the time of writing, the mysql server running here is replicating from (slave to) the mysql instance on bwdb. Requests for bandwidth data usage for customers (coming from management, account manager, and accounting scripts running on mail) all direct towards the database "traffic" running on this server.
* cancelled customer systems are compressed and stored under <tt>/data/deprecated</tt>
* archived bwdb2 flow files are stored under <tt>/data/bwdb2</tt>
* critical files from backup2 are stored under <tt>/data/backup2</tt>


apt-get install mysql
== Cronjobs ==
<pre>
00 5 * * * /usr/local/sbin/backupwatch.pl 2>&1 > /dev/null
35 5 * * * /usr/local/sbin/usage_check; /usr/local/sbin/snapshot_archive; /usr/local/sbin/snapshot_rotate  /data/backuplog.log</pre>
this runs daily the scripts to report on how much disk space each customer system occupies and how long their backups took. Then it rotates backups for each system, removing the oldest backup. It will email support@johncompanies.com at it’s conclusion. This email can be deleted, however note when it begins to take significantly longer to complete, ie runs past 2200 pm – this usually indicates a problem on the backup server.


mkdir /data/mysql
<pre>10,25,40,55 * * * * /usr/local/sbin/processsql.pl
chown mysql:mysql /data/mysql
</pre>
/etc/init.d/mysql stop
this processes prepared sql command files sent from/by bwdb2 (@ i2b) and imports them into the traffic database.
mv /var/lib/mysql/* /data/mysql/
<pre>0 0 * * * /usr/local/sbin/3wraidchk
mv /data/mysql/ib_* /var/lib/mysql/
</pre>
vi /etc/mysql/my.cnf
checks the health of the RAID array
(change datadir to /data/mysql)
 
vi /etc/apparmor.d/usr.sbin.mysqld
== Regular maintenance ==
add:
*[[Routine_Maintenance#Free_up_space_on_backup1|Remove old backups]]
  /data/mysql/ r,
*[[Routine_Maintenance#3ware|Check on auto-verify]]
  /data/mysql/** rwk,
Comment out:
# /var/lib/mysql/ r,
# /var/lib/mysql/** rwk,


/etc/init.d/apparmor restart
== build ==
/etc/init.d/mysql start


tw_cli /c0/u0 set ignoreECC=on
<pre>Setup raid5 with a boot vol of 12G 5.45tb
tw_cli /c0/u0 set storsave=balance
12G boot
tw_cli /c0/u0 set cache=on
4664 GB


Install ubuntu 8.04


0 0 * * * /usr/local/sbin/3wraidchk
Swap 4G
</pre>


= backup2 =
Don’t format data drive


== Summary ==
http://www.unixgods.org/~tilo/linux_larger_2TB.html


This machine is used for archiving data and is a backup server for colo customers. It was the former primary backup location for all VPS-based customers before backup1 was installed. Only dedicated customers directly accesses this server to perform their backups. NOTE: power button is broken, so the reset button (paper clip) was rewired to be the power button.
parted /dev/sdb
print
mklabel gpt
print


* Location: castle, cab 3-7
#Disk /dev/sdb: 4987GB
* OS: FreeBSD 6.1 x86
#Sector size (logical/physical): 512B/512B
* Networking: Priv IP: 10.1.4.3, Pub IP: 69.55.230.10 (firewalled from all but JC infrastructure @ i2b)
#Partition Table: gpt
* Hardware: 16 IDE drive bays (4 columns of 4, drive 0-0 top left, drive 0-1 just to the right TODO) all hot-swap. Triple power supply.
* Drives:  
**3ware 7500-8:
***200 GB JBOD (1 x 200G) labeled 0-0
***500 GB RAID5 (3 x 250G) 0-1 thru 0-3
***700 GB RAID5 (4 x 250G) 0-4 thru 0-7
**3ware 7500-8:
***700 GB RAID5 (4 x 250G) 1-0 thru 1-3
***700 GB RAID5 (4 x 250G) 1-4 thru 1-7


All drives MUST be western digital IDE drives. Other brands will not fit.
#Number  Start  End  Size  File system  Name  Flags


In case of an outage, nfs will hang on all connected servers until the nfs service returns. If you can't get backup2 back online, you can get nfs running elsewhere and fake backup2's MAC's: priv: 00:0e:0c:59:c1:a6, pub: 00:07:e9:5b:c6:45
mkpart primary ext3 0 4987GB
print


To configure:
#Disk /dev/sdb: 5987GB
ifconfig fxp0 link 00:90:27:f9:0a:d9
#Sector size (logical/physical): 512B/512B
#Partition Table: gpt


== Services provided ==
#Number  Start  End    Size    File system  Name    Flags
* backup via rsync and nfs
# 1      17.4kB  4987GB  4987GB              primary
* samba
* nfs
* snmp
* bigbrother


== Usage ==
quit
* all data is stored under 4 mount points, corresponding to the 4 large RAID5 arrays: <tt>/mnt/data1 /mnt/data2 /mnt/data3 /mnt/data4</tt>
* iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under <tt>/mnt/data2/iso</tt>
* this used to be our primary backup server so you will see old backups from virt and jails around- missing customer data though, just the machine's data
* this server serves as an archive for exported db data from bwdb and old flow files.
* isys backs up here
* customers are nfs-moutned under /mnt/data3/customers as file-backed md devices
* in <tt>/mnt/data4</tt> there are lots of useful things used for building our vps servers, customer servers, and management scripts:
** <tt>/bin</tt>: the master repository of scripts and custom binaries we use on jails and virts. Each night every virt and jail rsync's what's in here to update the local files. So any global updates to scripts would need to be made here (or will be overwritten with what's in here)
** <tt>/build</tt>: files we use for setting up big brother, 3ware cli and scripts for colo's, vzcp customized setup files and so on
** <tt>/vzrpms</tt>: contains the OS templates for many-to-most of the OS's we offer on vz systems


== Cronjobs ==
mkfs.ext3 /dev/sdb1
* backs itself up nightly to nfs-mounted backup1 (mountpoint: <tt>/backup2</tt>)
#mke2fs 1.40.8 (13-Mar-2008)
#Filesystem label=
#OS type: Linux
#Block size=4096 (log=2)
#Fragment size=4096 (log=2)
#304390144 inodes, 1217544183 blocks
#60877209 blocks (5.00%) reserved for the super user
#First data block=0
#Maximum filesystem blocks=0
#37157 block groups
#32768 blocks per group, 32768 fragments per group
#8192 inodes per group
#Superblock backups stored on blocks:
#        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
#        4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
#        102400000, 214990848, 512000000, 550731776, 644972544
#
#Writing inode tables:  967/37157


== Regular maintenance ==
mkdir /data
*[[Routine_Maintenance#3ware|Check on health]]
 
#root@backup1:~# df -h
#Filesystem            Size  Used Avail Use% Mounted on
#/dev/sda2            8.3G  540M  7.3G  7% /
#varrun              1013M  40K 1013M  1% /var/run
#varlock              1013M    0 1013M  0% /var/lock
#udev                1013M  56K 1013M  1% /dev
#devshm              1013M    0 1013M  0% /dev/shm
#/dev/sdb1            4.5T  192M  4.3T  1% /data


= backup3 =
== Summary ==
This machine is used for archiving data, is a backup server for colo customers, runs a samba server to make available iso's to the IPKVMs, and allows us to connect to the digi serial multiplexer at i2b. Only dedicated customers directly accesses this server to perform their backups.


* Location: i2b, cab 6
apt-get update
* OS: Ubuntu 10.04.1 server amd64
apt-get upgrade
* Networking: Priv IP: 10.1.2.3, Pub IPs: 69.55.229.4 AND 69.55.231.2
apt-get install snmp snmpd ntp nfs-kernel-server
* Hardware: 16 drive SATA bays (4 columns of 4, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: 5 TB (6 x 1TB) RAID5 array running on an Areca Technology Corp. ARC-1160 16-Port


== Services provided ==
echo "\"\e[5~\": history-search-backward" >> ~/.inputrc
* backup via rsync and nfs
echo "\"\e[6~\": history-search-forward" >> ~/.inputrc
* samba
* nfs
* digi realport
* snmp
* bigbrother


== Usage ==
vi /etc/ntp.conf
* all data is stored under /data
server 10.1.4.5
* iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under <tt>/data/iso</tt>
* this server serves as an archive for exported db data from bwdb and old flow files.
* inftrastructure machines at i2b back up here
* customers are nfs-moutned under /data/customers as file-backed loopback devices


== management scripts ==
scp root@10.1.4.3:/root/.ssh/authorized_keys /root/.ssh/
* mkbackups
cd /root/
ssh-keygen -t dsa
echo "10.1.4.3        backup2" >> /etc/hosts


== Cronjobs ==
cat .ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
0 0 * * * /usr/local/sbin/arecaraidchk
RAID checks


35 4 * * * /usr/local/sbin/snapshot_archive
ssh backup2
Rotate daily snapshots for infrastructure machine backups


== Regular maintenance ==
vi /root/.bashrc
*[[Routine_Maintenance#Areca|Check on RAID health]]
export PS1="[\u@\h \w]# "
alias h='history'
alias vi='vim'
alias j='jobs'
export PS1="[\u@\h \w]# "
alias dr='screen -dr'
export EDITOR=vim
export GREP_OPTIONS='--color=auto'
export HISTFILESIZE=1000


== Build ==
source /root/.bashrc


=== BIOS Config ===
echo "# ttyS0 - getty
disable quiet boot
#
# This service maintains a getty on ttyS0 from the point the system is
# started until it is shut down again.
 
start on runlevel 2
start on runlevel 3
start on runlevel 4
start on runlevel 5
 
stop on runlevel 0
stop on runlevel 1
stop on runlevel 6


set to last state after power loss
respawn
exec /sbin/getty 38400 ttyS0" > /etc/event.d/ttyS0


set date/time to GMT


enable serial console output (baud rate 115200)
vi /boot/grub/menu.lst


=== Install OS ===
serial --unit=0 --speed=38400 --word=8 --parity=no --stop=1
<pre>Ubuntu 10.04.1 amd64 (couldn't get 12.04 to load cause the H/W was incompat)
terminal --timeout=15 serial console
10G / ext3
2G swap
~ /data ext4


Install packages:
append to kernel lines:  
openssh
console=tty0 console=ttyS0,38400n8
samba</pre>


=== DNS and private IP ===
show menu:
#hiddenmenu


  echo "nameserver 69.55.225.225" >> /etc/resolv.conf
echo 'rocommunity  jcread 10.1.4.5
rocommunity jcread 10.1.4.3
agentaddress 10.1.4.8:161' > /etc/snmp/snmpd.conf


Add a 2nd IP to eth0 and setup priv net
# to see which iface it is, on backup2:
<pre>vi /etc/network/interfaces
 
snmpwalk -v 1 -c jcread 10.1.4.8 interface


auto eth0
iface eth0 inet static
        address 69.55.229.4
        netmask 255.255.255.0
        network 69.55.229.0
        broadcast 69.55.229.255
        gateway 69.55.229.1
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 69.55.229.3 66.181.0.2
        dns-search johncompanies.com


auto eth0:1
echo "bb:x:1984:1984:Big Brother:/home/bb:/bin/bash" >> /etc/passwd
iface eth0:1 inet static
        address 69.55.231.2
        netmask 255.255.255.0
        network 69.55.231.0
        broadcast 69.55.231.255


auto eth1
echo "bb:x:1984:" >> /etc/group
iface eth1 inet static
        address 10.1.2.3
        netmask 255.255.255.0
        network 10.1.2.0
        broadcast 10.1.2.255


</pre>
pwconv


=== Install packages ===
mkdir /home/bb
<pre>apt-get update
chown bb.bb /home/bb
apt-get upgrade
apt-get install gcc
apt-get install libssl-dev
apt-get install libncurses5-dev
apt-get install cu
apt-get install unzip
apt-get install snmp snmpd ntp nfs-kernel-server</pre>


=== tweak grub, enable serial ===
cd ~bb
scp backup2:/mnt/data4/build/bb/bb-linux.tar .


<pre>vi /etc/default/grub
tar xf bb-linux.tar
#GRUB_HIDDEN_TIMEOUT=0
GRUB_CMDLINE_LINUX_DEFAULT="max_loop=64"
GRUB_CMDLINE_LINUX="console=tty0 console=ttyS0"
update-grub</pre>


<pre>echo "start on stopped rc RUNLEVEL=[2345]
cd /home/bb/bbc1.9e-btf/etc
stop on runlevel [!2345]
respawn
exec /sbin/getty -L ttyS0 38400 vt102" > /etc/init/ttyS0.conf</pre>


=== install realport (digi) driver ===
echo "10.1.4.5 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
echo "10.1.4.8 backup1.johncompanies.com # ssh" >> /home/bb/bbc1.9e-btf/etc/bb-hosts


give the digi an ip with DgIpServ.exe
echo "/:90:95
/var:90:95
/data:85:99" > /home/bb/bbc1.9e-btf/etc/bb-dftab


<pre>cd /usr/src/
wget ftp://ftp1.digi.com/support/beta/linux/dgrp/dgrp-1.9.tgz
tar xzf dgrp-1.9.tgz
cd dgrp-1.9/
./configure
make
make install
make postinstall
update-rc.d dgrp_daemon defaults</pre>


configure ports:
vi /home/bb/bbc1.9e-btf/bin/bb-disk.sh
dgrp_cfg_node init el 10.1.2.10 16
(remove all | SORT xxxx)


try connecting with:
chmod +r /var/log/messages
cu -l /dev/ttyel00 -s 38400


=== shell, ntp, ssh key, hosts ===
./bbchkcfg.sh
#(y to questions)
./bbchkhosts.sh
#(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src


Shell autocompletion search:
#make; make install
<pre>echo "\"\e[5~\": history-search-backward" >> ~/.inputrc
cd ..
echo "\"\e[6~\": history-search-forward" >> ~/.inputrc</pre>
./runbb.sh start
more BBOUT
(look for errors)
exit
 
vi /etc/rc.local
su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"


Setup ntp:
<pre>vi /etc/ntp.conf
server 10.1.2.1
server ntp.ubuntu.com</pre>


Generate ssh keys:
echo '/data 10.1.4.0/24(rw, no_root_squash,async,no_subtree_check)' >> /etc/exports
<pre>cd /root/
 
ssh-keygen -t dsa</pre>
/etc/init.d/nfs-kernel-server restart
Defaults, no password
 


Setup hosts:
echo 'chmod o+r /var/log/messages' >> /etc/cron.weekly/sysklogd
<pre>echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.4 bwdb2" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts</pre>


Copy keys to servers where we need passwordless login:
<pre>cat .ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
cat .ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'</pre>


Setup shell:
echo '10.1.4.8                backup1' >> /etc/hosts
<pre>vi /root/.bashrc
echo '/dev/sdb1 /data  ext3  rw,noatime  0  0' >> /etc/fstab
(add to bottom)
alias h='history'
alias vi='vim'
alias j='jobs'
export PS1="[\u@\h \w]# "
alias dr='screen -dr'
export EDITOR=vim
export GREP_OPTIONS='--color=auto'
export HISTFILESIZE=1000


alias tip-switch-p20='cu -l ttyel00 -s 9600'
alias tip-switch-p21='cu -l ttyel15 -s 9600'
alias tip-switch-p22='cu -l ttyel14 -s 9600'
alias tip-switch-p23='cu -l ttyel05 -s 9600'
alias tip-switch-p24='cu -l ttyel06 -s 9600'
alias tip-switch-p25='cu -l ttyel09 -s 9600'
alias tip-switch-p26='cu -l ttyel07 -s 9600'
alias tip-switch-p27='cu -l ttyel08 -s 9600'
alias tip-firewall2='cu -l ttyel01 -s 115200'
alias tip-nat2='cu -l /dev/ttyel02 -s 115200'
alias tip-backup3='cu -l ttyel04 -s 38400'
alias tip-bwdb2='cu -l ttyel03 -s 115200'
alias tip-backup4='cu -l ttyel13 -s 115200'
alias tip-jail3='cu -l ttyel11 -s 115200'


Load new shell:
to install digi drivers:
source /root/.bashrc


Setup snmpd (this is only valid for a server at castle):
wget http://ftp1.digi.com/support/driver/40002086_n.tgz
echo 'rocommunity  jcread 10.1.4.5
apt-get install linux-image-2.6.24-19-server
rocommunity  jcread 10.1.4.3
apt-get install linux-source-2.6.24 (not needed?)
agentaddress 10.1.4.8:161' > /etc/snmp/snmpd.conf
apt-get install linux-headers-2.6.24-19-server
apt-get install make
apt-get install gcc
apt-get install g++
apt-get install libncurses5-dev
apt-get install expect
apt-get install libdbi-perl libdate-calc-perl libdbd-mysql-perl


to see which iface it is, on backup2:
cd /usr/src; ln -s linux-headers-2.6.24-19-server linux
./configure
make all
make install
make postinstall


snmpwalk -v 1 -c jcread 10.1.4.8 interface
/usr/bin/dgrp_cfg_node -v -v init el 65.116.11.2 8


=== nfs ===
apt-get install mysql


Allow mounts from private net:
mkdir /data/mysql
echo '/data 10.1.2.0/24(rw,no_root_squash,async,no_subtree_check)' >> /etc/exports
chown mysql:mysql /data/mysql
 
/etc/init.d/mysql stop
Restart nfsd:
mv /var/lib/mysql/* /data/mysql/
  /etc/init.d/nfs-kernel-server restart
mv /data/mysql/ib_* /var/lib/mysql/
vi /etc/mysql/my.cnf
(change datadir to /data/mysql)
vi /etc/apparmor.d/usr.sbin.mysqld
add:
  /data/mysql/ r,
  /data/mysql/** rwk,
Comment out:
#  /var/lib/mysql/ r,
# /var/lib/mysql/** rwk,


=== bb ===
/etc/init.d/apparmor restart
/etc/init.d/mysql start


Add user, group:
tw_cli /c0/u0 set ignoreECC=on
echo "bb:x:1984:1984:Big Brother:/home/bb:/bin/bash" >> /etc/passwd
tw_cli /c0/u0 set storsave=balance
echo "bb:x:1984:" >> /etc/group
tw_cli /c0/u0 set cache=on
pwconv


Create home:
mkdir /home/bb
chown bb.bb /home/bb
cd ~bb


Copy over and install files:
0 0 * * * /usr/local/sbin/3wraidchk
<pre>scp backup2:/mnt/data4/build/bb/bb-linux.tar .
</pre>
tar xf bb-linux.tar
cd /home/bb/bbc1.9e-btf/etc</pre>


Configure main bb server:
= backup2 =
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
echo "10.1.2.3 backup3.johncompanies.com # ssh" >> /home/bb/bbc1.9e-btf/etc/bb-hosts


Configure low disk alerts:
== Summary ==
<pre>echo "/:90:95
/var:90:95
/data:85:99" > /home/bb/bbc1.9e-btf/etc/bb-dftab</pre>


vi /home/bb/bbc1.9e-btf/bin/bb-disk.sh
THIS SERVER IS OUT OF SERVICE AND REPLACED BY BACKUP4
(remove all | SORT xxxx since SORT is broken)


chmod +r /var/log/messages
This machine is used for archiving data and is a backup server for colo customers. It was the former primary backup location for all VPS-based customers before backup1 was installed. Only dedicated customers directly accesses this server to perform their backups. NOTE: power button is broken, so the reset button (paper clip) was rewired to be the power button.


./bbchkcfg.sh
* Location: castle, cab 3-7
(y to questions)
* OS: FreeBSD 6.1 x86
./bbchkhosts.sh
* Networking: Priv IP: 10.1.4.3, Pub IP: 69.55.230.10 (firewalled from all but JC infrastructure @ i2b)
(ignore ssh errors)
* Hardware: 16 IDE drive bays (4 columns of 4, drive 0-0 top left, drive 0-1 just to the right TODO) all hot-swap. Triple power supply.  
<pre>cd ../..
* Drives:
chown -R bb .
**3ware 7500-8:
su bb
***200 GB JBOD (1 x 200G) labeled 0-0
cd
***500 GB RAID5 (3 x 250G) 0-1 thru 0-3
cd bbc1.9e-btf/src</pre>
***700 GB RAID5 (4 x 250G) 0-4 thru 0-7
**3ware 7500-8:
***700 GB RAID5 (4 x 250G) 1-0 thru 1-3
***700 GB RAID5 (4 x 250G) 1-4 thru 1-7


<pre>make; make install
All drives MUST be western digital IDE drives. Other brands will not fit.
cd ..
./runbb.sh start
more BBOUT</pre>
(look for errors)
exit


<pre>vi /etc/rc.local
In case of an outage, nfs will hang on all connected servers until the nfs service returns. If you can't get backup2 back online, you can get nfs running elsewhere and fake backup2's MAC's: priv: 00:0e:0c:59:c1:a6, pub: 00:07:e9:5b:c6:45
su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"
</pre>
(before the exit 0)


  echo 'chmod o+r /var/log/messages' >> /etc/cron.weekly/sysklogd
To configure:
  ifconfig fxp0 link 00:90:27:f9:0a:d9


Add f/w rule:
== Services provided ==
ipfw add 00096 allow ip from { 69.55.229.4 or 69.55.229.3 } to 69.55.230.2 1984
* backup via rsync and nfs
* samba
* nfs
* snmp
* bigbrother


<pre>vi ~bb/bbc1.9e-btf/etc/bbdef-client.sh
== Usage ==
DFWARN=199
* all data is stored under 4 mount points, corresponding to the 4 large RAID5 arrays: <tt>/mnt/data1 /mnt/data2 /mnt/data3 /mnt/data4</tt>
DFPANIC=199</pre>
* iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under <tt>/mnt/data2/iso</tt>
* this used to be our primary backup server so you will see old backups from virt and jails around- missing customer data though, just the machine's data
* this server serves as an archive for exported db data from bwdb and old flow files.
* isys backs up here
* customers are nfs-moutned under /mnt/data3/customers as file-backed md devices
* in <tt>/mnt/data4</tt> there are lots of useful things used for building our vps servers, customer servers, and management scripts:
** <tt>/bin</tt>: the master repository of scripts and custom binaries we use on jails and virts. Each night every virt and jail rsync's what's in here to update the local files. So any global updates to scripts would need to be made here (or will be overwritten with what's in here)
** <tt>/build</tt>: files we use for setting up big brother, 3ware cli and scripts for colo's, vzcp customized setup files and so on
** <tt>/vzrpms</tt>: contains the OS templates for many-to-most of the OS's we offer on vz systems


== Cronjobs ==
* backs itself up nightly to nfs-mounted backup1 (mountpoint: <tt>/backup2</tt>)


=== raid check ===
== Regular maintenance ==
*[[Routine_Maintenance#3ware|Check on health]]


==== 3ware ====
= backup3 =
<pre>
== Summary ==
scp backup1:/usr/local/sbin/tw_cli /usr/local/sbin/tw_cli
This machine is used for archiving data, is a backup server for colo customers, runs a samba server to make available iso's to the IPKVMs, and allows us to connect to the digi serial multiplexer at i2b. Only dedicated customers directly accesses this server to perform their backups.  
scp backup1:/usr/local/sbin/checkraid.sh /usr/local/sbin/checkraid.sh
scp backup1:/usr/local/sbin/3wraidchk /usr/local/sbin/3wraidchk
vi /usr/local/sbin/checkraid.sh
:%s/c0/c2/g


crontab -e
* Location: i2b, cab 6
0 0 * * * /usr/local/sbin/3wraidchk</pre>
* OS: Ubuntu 10.04.1 server amd64
* Networking: Priv IP: 10.1.2.3, Pub IPs: 69.55.229.4 AND 69.55.231.2
* Hardware: 16 drive SATA bays (4 columns of 4, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: 5 TB (6 x 1TB) RAID5 array running on an Areca Technology Corp. ARC-1160 16-Port


==== areca ====
== Services provided ==
<pre>
* backup via rsync and nfs
cd /tmp
* samba
wget http://www.areca.us/support/s_linux/cli/linuxcli_V1.10.0_120815.zip
* nfs
unzip linuxcli_V1.10.0_120815.zip
* digi realport
cp linuxcli_V1.10.0_120815/x86_64/cli64 /usr/local/sbin/
* snmp
chmod 0700 /usr/local/sbin/cli64
* bigbrother
cli64 rsf info
</pre>


<pre>scp backup2:/data4/bin/arecaraidchk /usr/local/sbin
== Usage ==
scp backup1:/usr/local/sbin/Sendmail.pm /usr/local/sbin
* all data is stored under /data
* iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under <tt>/data/iso</tt>
* this server serves as an archive for exported db data from bwdb and old flow files.
* inftrastructure machines at i2b back up here
* customers are nfs-moutned under /data/customers as file-backed loopback devices


crontab -e
== management scripts ==
0 0 * * * /usr/local/sbin/arecaraidchk
* mkbackups
</pre>


<pre>cat > /root/verify.sh
mkbackup <cid> GB <ip>
cli64 vsf info
cli64 rsf info
cli64 disk info
cli64 event info
echo press enter when ready to run verify ; read x


cli64 vsf check vol=1
== Cronjobs ==
</pre>
0 0 * * * /usr/local/sbin/arecaraidchk
RAID checks


=== misc binaries ===
35 4 * * * /usr/local/sbin/snapshot_archive
Rotate daily snapshots for infrastructure machine backups


scp backup1:/usr/local/sbin/snapshot_archive /usr/local/sbin/snapshot_archive
== Regular maintenance ==
vi /usr/local/sbin/snapshot_archive
*[[Routine_Maintenance#Areca|Check on RAID health]]
(remove entries)


crontab -e
== Build ==
35 4 * * * /usr/local/sbin/snapshot_archive


scp backup1:/usr/local/sbin/pagedave /usr/local/sbin/pagedave
=== BIOS Config ===
scp backup1:/usr/local/sbin/taskdone /usr/local/sbin/taskdone
disable quiet boot


Since installing /bin/mail requires all sorts of packages (lame) we write a simple one here...which can only email johncompanies.com addr's unless you add relaying for this host:
set to last state after power loss


<pre>
set date/time to GMT
cat > /bin/mail
#!/usr/bin/perl
use strict;
use warnings;


use lib '/usr/local/sbin';
enable serial console output (baud rate 115200)
use Sendmail qw(sendmail);


my $sub = $ARGV[1];
=== Install OS ===
my $to = $ARGV[2];
<pre>Ubuntu 10.04.1 amd64 (couldn't get 12.04 to load cause the H/W was incompat)
10G / ext3
2G swap
~ /data ext4


Install packages:
openssh
samba</pre>


my %mail = (
=== DNS and private IP ===
  To      => $to,
  From    => $to,
  Subject => $sub,
  Message => '',
  smtp    => 'mail.johncompanies.com'
);
sendmail(%mail) || print "Error: $Sendmail::error";


</pre>
echo "nameserver 69.55.225.225" >> /etc/resolv.conf


chmod 0700 /bin/mail
Add a 2nd IP to eth0 and setup priv net
<pre>vi /etc/network/interfaces


=== mkbackup ===
auto eth0
 
iface eth0 inet static
mkdir /data/customers
        address 69.55.229.4
        netmask 255.255.255.0
        network 69.55.229.0
        broadcast 69.55.229.255
        gateway 69.55.229.1
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 69.55.229.3 66.181.0.2
        dns-search johncompanies.com


<pre>cat > /usr/local/sbin/mkbackup
auto eth0:1
#!/bin/sh
iface eth0:1 inet static
        address 69.55.231.2
        netmask 255.255.255.0
        network 69.55.231.0
        broadcast 69.55.231.255


if test $1; then
auto eth1
  cid=$1
iface eth1 inet static
else
        address 10.1.2.3
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
        netmask 255.255.255.0
  exit
        network 10.1.2.0
fi
        broadcast 10.1.2.255


if test $2; then
</pre>
  gb=$2
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi


if test $3; then
=== Install packages ===
  ip=$3
<pre>apt-get update
else
apt-get upgrade
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
apt-get install gcc
  exit
apt-get install libssl-dev
fi
apt-get install libncurses5-dev
apt-get install cu
apt-get install unzip
apt-get install snmp snmpd ntp nfs-kernel-server</pre>
 
=== tweak grub, enable serial ===


<pre>vi /etc/default/grub
#GRUB_HIDDEN_TIMEOUT=0
GRUB_CMDLINE_LINUX_DEFAULT="max_loop=64"
GRUB_CMDLINE_LINUX="console=tty0 console=ttyS0"
update-grub</pre>


if test -e /data/customers/${cid}-file; then
<pre>echo "start on stopped rc RUNLEVEL=[2345]
  echo "ERROR: /data/customers/${cid}-file exists"
stop on runlevel [!2345]
  exit
respawn
else
exec /sbin/getty -L ttyS0 38400 vt102" > /etc/init/ttyS0.conf</pre>
  echo "touch /data/customers/${cid}-file"
  touch /data/customers/${cid}-file
  count=`echo $gb|awk '{print $1*1000}'`
  echo "dd if=/dev/zero of=/data/customers/${cid}-file bs=1024K count=$count"
  dd if=/dev/zero of=/data/customers/${cid}-file bs=1024K count=$count
  echo "/sbin/mkfs -t ext3 -F -j -q /data/customers/${cid}-file"
  /sbin/mkfs -t ext3 -F -j -q /data/customers/${cid}-file
fi


if test -e /data/customers/$cid; then
=== install realport (digi) driver ===
  echo "ERROR: /data/customers/$cid exists"
  exit
else
  echo "mkdir /data/customers/${cid}"
  mkdir /data/customers/${cid}
  echo "mount -o loop /data/customers/${cid}-file /data/customers/$cid"
  mount -o loop /data/customers/${cid}-file /data/customers/$cid
  df -h /data/customers/$cid


  echo "fsck -y /data/customers/${cid}-file" >> /etc/nfs_backup_mounts.sh
give the digi an ip with DgIpServ.exe
  echo "mount -o loop /data/customers/${cid}-file /data/customers/$cid" >> /etc/nfs_backup_mounts.sh
  echo "" >> /etc/nfs_backup_mounts.sh


  echo "/data/customers/$cid $ip/32(rw,no_root_squash,async,no_subtree_check)" >> /etc/exports
<pre>cd /usr/src/
  /etc/init.d/nfs-kernel-server restart
wget ftp://ftp1.digi.com/support/beta/linux/dgrp/dgrp-1.9.tgz
  tail /var/log/messages
tar xzf dgrp-1.9.tgz
fi</pre>
cd dgrp-1.9/
./configure
make
make install
make postinstall
update-rc.d dgrp_daemon defaults</pre>


  chmod 0700 /usr/local/sbin/mkbackup
configure ports:
  dgrp_cfg_node init el 10.1.2.10 16


vi /etc/rc.local
try connecting with:
add:
  cu -l /dev/ttyel00 -s 38400
  /etc/nfs_backup_mounts.sh


=== samba ===
=== shell, ntp, ssh key, hosts ===


apt-get install samba
Shell autocompletion search:
<pre>echo "\"\e[5~\": history-search-backward" >> ~/.inputrc
echo "\"\e[6~\": history-search-forward" >> ~/.inputrc</pre>


vi /etc/samba/smb.conf
Setup ntp:
<pre>vi /etc/ntp.conf
server 10.1.2.1
server ntp.ubuntu.com</pre>


; comment out any mounts, add:
Generate ssh keys:
<pre>cd /root/
ssh-keygen -t dsa</pre>
Defaults, no password


<pre>[data]
Setup hosts:
  read only = yes
<pre>echo "69.55.230.10 backup2" >> /etc/hosts
  locking = no
echo "69.55.230.11 backup1" >> /etc/hosts
  path = /data/iso
echo "10.1.2.4 bwdb2" >> /etc/hosts
  guest ok = yes</pre>
echo "10.1.2.3 backup3" >> /etc/hosts</pre>


/etc/init.d/smbd restart
Copy keys to servers where we need passwordless login:
<pre>cat .ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
cat .ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'</pre>


mkdir /data/iso
Setup shell:
<pre>vi /root/.bashrc
(add to bottom)
alias h='history'
alias vi='vim'
alias j='jobs'
export PS1="[\u@\h \w]# "
alias dr='screen -dr'
export EDITOR=vim
export GREP_OPTIONS='--color=auto'
export HISTFILESIZE=1000


Bring over some stuff from backup2
alias tip-switch-p20='cu -l ttyel00 -s 9600'
alias tip-switch-p21='cu -l ttyel15 -s 9600'
alias tip-switch-p22='cu -l ttyel14 -s 9600'
alias tip-switch-p23='cu -l ttyel05 -s 9600'
alias tip-switch-p24='cu -l ttyel06 -s 9600'
alias tip-switch-p25='cu -l ttyel09 -s 9600'
alias tip-switch-p26='cu -l ttyel07 -s 9600'
alias tip-switch-p27='cu -l ttyel08 -s 9600'
alias tip-firewall2='cu -l ttyel01 -s 115200'
alias tip-nat2='cu -l /dev/ttyel02 -s 115200'
alias tip-backup3='cu -l ttyel04 -s 38400'
alias tip-bwdb2='cu -l ttyel03 -s 115200'
alias tip-backup4='cu -l ttyel13 -s 115200'
alias tip-jail3='cu -l ttyel11 -s 115200'


<pre>cd /data/iso
Load new shell:
scp backup2:/d2/iso/3wfirmware.iso .
source /root/.bashrc
scp backup2:/d2/iso/MD5SUMS .
scp backup2:/d2/iso/bootimg.iso .
scp backup2:/d2/iso/systemrescuecd-x86-0.2.19.iso .
scp backup2:/d2/iso/win98bootcd.iso .
scp backup2:/d2/iso/acronis_bootdisk.iso .
scp backup2:/d2/iso/memtest86-3.2.iso .</pre>


=== Moving from one server to another ===
Setup snmpd (this is only valid for a server at castle):
echo 'rocommunity  jcread 10.1.4.5
rocommunity  jcread 10.1.4.3
agentaddress 10.1.4.8:161' > /etc/snmp/snmpd.conf


Here are the steps you would take to move settings and data from one server to a new backup server:
to see which iface it is, on backup2:


* rsync over all /data/customers (we do this cause if we didn't use *-file it would copy over the files AND the data in the mountpoint)
snmpwalk -v 1 -c jcread 10.1.4.8 interface
rsync -av --progress --ignore-times *-file root@10.1.2.33:/data/customers/
after umounting all the customers, copy over the (empty) directories separately:
for f in `find .  -type d`; do rsync -av $f root@69.55.229.25:/data/customers; done


* copy mount script
=== nfs ===
[root@backup3 /data/customers]# scp /etc/nfs_backup_mounts.sh root@69.55.229.25:/etc/nfs_backup_mounts.sh


* copy rc.local
Allow mounts from private net:
  [root@backup3 /data/customers]# scp /etc/rc.local root@69.55.229.25:/etc/rc.local
  echo '/data 10.1.2.0/24(rw,no_root_squash,async,no_subtree_check)' >> /etc/exports


* copy /etc/exports
Restart nfsd:
  [root@backup3 /data/customers]# scp /etc/exports root@69.55.229.25:/etc/exports
  /etc/init.d/nfs-kernel-server restart


* edit /etc/hostname on both machines (set current to oldbackup3)
=== bb ===


* edit /etc/network/interfaces (swap IPs).
Add user, group:
echo "bb:x:1984:1984:Big Brother:/home/bb:/bin/bash" >> /etc/passwd
echo "bb:x:1984:" >> /etc/group
pwconv


* stop mounts from mounting on old and new servers so it doesnt start with reboot right away:
Create home:
  chmod 000 /etc/nfs_backup_mounts.sh
  mkdir /home/bb
chown bb.bb /home/bb
cd ~bb


* reboot both servers @ same time
Copy over and install files:
<pre>scp backup2:/mnt/data4/build/bb/bb-linux.tar .
tar xf bb-linux.tar
cd /home/bb/bbc1.9e-btf/etc</pre>


* check everything out
Configure main bb server:
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
echo "10.1.2.3 backup3.johncompanies.com # ssh" >> /home/bb/bbc1.9e-btf/etc/bb-hosts


* run /etc/nfs_backup_mounts.sh on new server
Configure low disk alerts:
<pre>echo "/:90:95
/var:90:95
/data:85:99" > /home/bb/bbc1.9e-btf/etc/bb-dftab</pre>


* if switch port changed update mrtg to reflect correct port pub nic is on (on p20):
  vi /home/bb/bbc1.9e-btf/bin/bb-disk.sh
  vi /usr/local/www/mgmt/mrtg/mrtg1.cfg
(remove all | SORT xxxx since SORT is broken)


= console =
chmod +r /var/log/messages


== Summary ==
./bbchkcfg.sh
This box's only purpose is to serve as a means to connect to the digi serial multiplexer boxes at castle. Connect to it using the blue (cisco) ribbon cable with the beige RJ-45 to serial connector, 9600 8N1.
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
<pre>cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src</pre>


* Location: castle, cab 3-8
<pre>make; make install
* OS: SunOS 5.8 (solaris)
cd ..
* Networking: Priv IP: 10.1.4.4
./runbb.sh start
* Hardware: Sun Netra
more BBOUT</pre>
(look for errors)
exit


<pre>vi /etc/rc.local
su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"
</pre>
(before the exit 0)


To connect to consoles, ssh in as user 'console' and use the <tt>tip</tt> command to connect to devices listed in <tt>/etc/remote</tt>
echo 'chmod o+r /var/log/messages' >> /etc/cron.weekly/sysklogd


i.e.
Add f/w rule:
tip switch-p1
ipfw add 00096 allow ip from { 69.55.229.4 or 69.55.229.3 } to 69.55.230.2 1984
tip jail1


== Configuring digi/ports ==
<pre>vi ~bb/bbc1.9e-btf/etc/bbdef-client.sh
DFWARN=199
DFPANIC=199</pre>


=== /etc/remote ===
This is where the configuration/mapping for ports and custom names which we use along with the tip command to connect to various ports on the digi switches.


We have 2 digi's at castle we connect to:
=== raid check ===


#3-7 10.1.4.10
==== 3ware ====
virt15:dv=/dev/dty/CO001s:br#38400:el=^C^S^Q^U^D:ie=%$:oe=^D:
<pre>
virt13:dv=/dev/dty/CO002s:br#115200:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:
scp backup1:/usr/local/sbin/tw_cli /usr/local/sbin/tw_cli
scp backup1:/usr/local/sbin/checkraid.sh /usr/local/sbin/checkraid.sh
scp backup1:/usr/local/sbin/3wraidchk /usr/local/sbin/3wraidchk
vi /usr/local/sbin/checkraid.sh
:%s/c0/c2/g


and
crontab -e
0 0 * * * /usr/local/sbin/3wraidchk</pre>


#3-6 10.1.4.11
==== areca ====
jail4:dv=/dev/dty/CP001s:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:
<pre>
jail16:dv=/dev/dty/CP002s:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:
cd /tmp
wget http://www.areca.us/support/s_linux/cli/linuxcli_V1.10.0_120815.zip
unzip linuxcli_V1.10.0_120815.zip
cp linuxcli_V1.10.0_120815/x86_64/cli64 /usr/local/sbin/
chmod 0700 /usr/local/sbin/cli64
cli64 rsf info
</pre>


The only things you need to edit are the first part (i.e. <tt>jail4</tt>) and the speed (i.e. <tt>9600</tt>). You can decipher which port on the digi each line corresponds to by the <tt>CP001s or CO001s</tt> (port 1 on digi1 and digi2), <tt>CP002s or CO002s</tt> (port 2 on digi1 and digi2)
<pre>scp backup2:/data4/bin/arecaraidchk /usr/local/sbin
scp backup1:/usr/local/sbin/Sendmail.pm /usr/local/sbin


=== drpadmin ===
crontab -e
The tool you use to configure a device to a digi box is drpadmin:
0 0 * * * /usr/local/sbin/arecaraidchk
</pre>


<pre>bash-2.03$ su
<pre>cat > /root/verify.sh
Password:
cli64 vsf info
# drpadmin
cli64 rsf info
cli64 disk info
cli64 event info
echo press enter when ready to run verify ; read x


Please select an option (a)dd (d)elete (s)how (r)eset (q)uit : s
cli64 vsf check vol=1
0      10.1.4.10      32      CO      771    never  1027
</pre>
1      10.1.4.11      32      CP      771    never  1027
2      65.116.11.2    8      el      771    never  1027


Please select an option (a)dd (d)elete (s)how (r)eset (q)uit :</pre>
=== misc binaries ===


Use those commands above to modify the devices available.
scp backup1:/usr/local/sbin/snapshot_archive /usr/local/sbin/snapshot_archive
vi /usr/local/sbin/snapshot_archive
(remove entries)


== Switching IP/hostname ==
crontab -e
35 4 * * * /usr/local/sbin/snapshot_archive


Edit:
scp backup1:/usr/local/sbin/pagedave /usr/local/sbin/pagedave
/etc/defaultrouter
  scp backup1:/usr/local/sbin/taskdone /usr/local/sbin/taskdone
/etc/hosts
/etc/hostname.hme0
/etc/nodename
  Maybe needed to run: # ifconfig hme0 10.1.4.4 up


= devweb =
Since installing /bin/mail requires all sorts of packages (lame) we write a simple one here...which can only email johncompanies.com addr's unless you add relaying for this host:


We do web development on devweb.johncompanies.com
<pre>
cat > /bin/mail
#!/usr/bin/perl
use strict;
use warnings;


Currently this is a jail running on jail17 / 69.55.230.8
use lib '/usr/local/sbin';
use Sendmail qw(sendmail);


If the jail is restarted, you will need to manually restart the web service with:
my $sub = $ARGV[1];
httpsdctl restart
my $to = $ARGV[2];


All website development work should be done here first. It works exactly like and is setup like our [[Management_System_/_Public_Website_/_Signup_/_Account_Manager|main site]].


my %mail = (
  To      => $to,
  From    => $to,
  Subject => $sub,
  Message => '',
  smtp    => 'mail.johncompanies.com'
);
sendmail(%mail) || print "Error: $Sendmail::error";


= firewall2 =
</pre>


== Summary ==
chmod 0700 /bin/mail


This machine is the primary (only) firewall for the entire network at i2b.
=== mkbackup ===


* Location: i2b, cab 6
mkdir /data/customers
* OS: FreeBSD 6.4 x86
* Networking: Priv IP: 10.1.2.2, Pub IPs: 66.181.18.3 (external), 69.55.229.1 & 69.55.231.1 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks. TODO: describe NIC location/orientation


* Hardware: 2 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
<pre>cat > /usr/local/sbin/mkbackup
* Drives: 73 GB (2 x 73GB) RAID1 array running on an LSI MegaRAID SCSI 320 PCI RAID card.
#!/bin/sh


== Services Provided ==
if test $1; then
* firewall (ipfw)
  cid=$1
* bigbrother
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi


== Firewall Rule Configuration ==
if test $2; then
  gb=$2
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi


See [[FreeBSD_Reference#Firewall_Rule_Configuration|Firewall Rule Configuration]] for more discussion on how to actually manipulate firewall rules.
if test $3; then
  ip=$3
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi


== Disaster Recovery ==


TODO: need backup f/w and instructions on how to move cables.
if test -e /data/customers/${cid}-file; then
  echo "ERROR: /data/customers/${cid}-file exists"
  exit
else
  echo "touch /data/customers/${cid}-file"
  touch /data/customers/${cid}-file
  count=`echo $gb|awk '{print $1*1000}'`
  echo "dd if=/dev/zero of=/data/customers/${cid}-file bs=1024K count=$count"
  dd if=/dev/zero of=/data/customers/${cid}-file bs=1024K count=$count
  echo "/sbin/mkfs -t ext3 -F -j -q /data/customers/${cid}-file"
  /sbin/mkfs -t ext3 -F -j -q /data/customers/${cid}-file
fi


Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)
if test -e /data/customers/$cid; then
  echo "ERROR: /data/customers/$cid exists"
  exit
else
  echo "mkdir /data/customers/${cid}"
  mkdir /data/customers/${cid}
  echo "mount -o loop /data/customers/${cid}-file /data/customers/$cid"
  mount -o loop /data/customers/${cid}-file /data/customers/$cid
  df -h /data/customers/$cid


TODO
  echo "fsck -y /data/customers/${cid}-file" >> /etc/nfs_backup_mounts.sh
  echo "mount -o loop /data/customers/${cid}-file /data/customers/$cid" >> /etc/nfs_backup_mounts.sh
  echo "" >> /etc/nfs_backup_mounts.sh


Here's the config on the live firewall:
  echo "/data/customers/$cid $ip/32(rw,no_root_squash,async,no_subtree_check)" >> /etc/exports
  /etc/init.d/nfs-kernel-server restart
  tail /var/log/messages
fi</pre>


<pre>kern_securelevel_enable="NO"
chmod 0700 /usr/local/sbin/mkbackup
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"


xntpd_enable="YES"
vi /etc/rc.local
nfs_client_enable="YES"
add:
nfs_reserved_port_only="YES"
/etc/nfs_backup_mounts.sh
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.2"


fsck_y_enable="YES"
=== samba ===
background_fsck="NO"


defaultrouter="66.181.18.2"
  apt-get install samba
hostname="firewall2.johncompanies.com"
ifconfig_bge0="inet 66.181.18.3 netmask 255.255.255.224"
ifconfig_bge1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_bge1_alias0="inet 69.55.231.1 netmask 255.255.255.0"
ifconfig_bge1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
ifconfig_bge1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
ifconfig_bge1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
ifconfig_bge1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
ifconfig_bge1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
ifconfig_bge1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
ifconfig_bge1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
ifconfig_bge1_alias8="inet 65.50.235.1  netmask 255.255.255.0"
ifconfig_fxp0="inet 10.1.2.2 netmask 255.255.255.0"
sshd_enable="YES"
usbd_enable="YES"
</pre>


vi /etc/samba/smb.conf


== Cronjobs ==
; comment out any mounts, add:
30 3 * * * /usr/local/etc/rsync.backup
Backup to backup3


0 0 1 * * /sbin/ipfw zero
<pre>[data]
0 0 1 * * /sbin/ipfw del 3 4 5
  read only = yes
Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).
  locking = no
  path = /data/iso
  guest ok = yes</pre>


  59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
  /etc/init.d/smbd restart
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
Capture counts periodically


  0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;
  mkdir /data/iso
This script will create <tt>/etc/firewall.sh</tt> which contains all the firewall and pipe rules in place at the time the script was run.


*/5 * * * * /usr/local/sbin/lsiraidchk
Bring over some stuff from backup2
Checking the health of the RAID array
 
<pre>cd /data/iso
scp backup2:/d2/iso/3wfirmware.iso .
scp backup2:/d2/iso/MD5SUMS .
scp backup2:/d2/iso/bootimg.iso .
scp backup2:/d2/iso/systemrescuecd-x86-0.2.19.iso .
scp backup2:/d2/iso/win98bootcd.iso .
scp backup2:/d2/iso/acronis_bootdisk.iso .
scp backup2:/d2/iso/memtest86-3.2.iso .</pre>


=== Moving from one server to another ===


== DOS attacks ==
Here are the steps you would take to move settings and data from one server to a new backup server:


See [[FreeBSD_Reference#Handling_a_DoS_attack|Handling a DoS attack]] regarding how to handle a DOS attack.
* rsync over all /data/customers (we do this cause if we didn't use *-file it would copy over the files AND the data in the mountpoint)
rsync -av --progress --ignore-times *-file root@10.1.2.33:/data/customers/
after umounting all the customers, copy over the (empty) directories separately:
for f in `find .  -type d`; do rsync -av $f root@69.55.229.25:/data/customers; done


* copy mount script
[root@backup3 /data/customers]# scp /etc/nfs_backup_mounts.sh root@69.55.229.25:/etc/nfs_backup_mounts.sh


== build ==
* copy rc.local
[root@backup3 /data/customers]# scp /etc/rc.local root@69.55.229.25:/etc/rc.local


<pre>partition map:
* copy /etc/exports
/ 58g
[root@backup3 /data/customers]# scp /etc/exports root@69.55.229.25:/etc/exports
swap 4g
/var 512m
/tmp 512m
/usr 5.5g


4. edit /etc/make.conf
* edit /etc/hostname on both machines (set current to oldbackup3)
echo "WITHOUT_X11=yes \
KERNCONF=firewall2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf


5. add settings to /boot/loader.conf and /boot.config
* edit /etc/network/interfaces (swap IPs).  


echo "-Dh" >> /boot.config
* stop mounts from mounting on old and new servers so it doesnt start with reboot right away:
chmod 000 /etc/nfs_backup_mounts.sh


echo 'console="comconsole,vidconsole" \
* reboot both servers @ same time
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf


* check everything out


6. turn off all ttyv's except 0 and 1 in /etc/ttys
* run /etc/nfs_backup_mounts.sh on new server
also turn on ttyd0, change type to vt100:
vi /etc/ttys


ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
* if switch port changed update mrtg to reflect correct port pub nic is on (on p20):
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
  vi /usr/local/www/mgmt/mrtg/mrtg1.cfg
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
ttyv6  "/usr/libexec/getty Pc"        cons25 off secure
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0  "/usr/libexec/getty std.9600"  vt100  on  secure


kill -1 1
= backup4 =
== Summary ==
This machine is used for archiving data, is a backup server for colo customers, runs a samba server to make available iso's to the IPKVMs.  Only FreeBSD virt customers directly accesses this server to perform their backups.


on console server:
* Location: castle, cab 3-7
vi /etc/remote
* OS: FreeNAS 9.3 (FreeBSD 9.3)
(rename port to jail8 depending on where and which digi plugged into)
* Networking: Priv IP: 10.1.2.9/24 AND 10.1.7.9/24,  Pub IPs: 69.55.230.6/24
test serial console
* Hardware: JC-08014
            Intel S5000VSA Motherboard
            1 x Intel Xeon E5410  @ 2.33GHz CPU
            3ware 9690SA-8I RAID Card w BBU
            16GB RAM
            Dual power supply.
* Drives: 7 TB (6 x 2TB) ZFS RAIDZ2 array running on JBOD
      1 128 GB SSD system drive and 6 drive SATA bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap.


* GUI management at http://backup4.johncompanies.com


7. populate hosts
== Services provided ==
echo "69.55.230.10 backup2" >> /etc/hosts
* backup via rsync and nfs
echo "69.55.230.11 backup1" >> /etc/hosts
* samba
echo "10.1.2.3 backup3" >> /etc/hosts
* nfs
* snmp?
* bigbrother?


8. put key in authorized_keys on backup3
== Usage ==
cd
* all data is stored under /data
ssh-keygen -t dsa -b 1024
* iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under <tt>/data/iso</tt>  ??
(default location, leave password blank)
* this server serves as an archive for exported db data from bwdb and old flow files. ??
* customers are nfs-moutned under /data/users (/mnt/zfs/users) as zfs ?


Punch a hole in firewall1 to allow traffic to backup servers @ castle:
== management scripts ==
* mkbackups?


ipfw add 99 allow ip from 66.181.18.0/27 to 69.55.230.10 22
mkbackup <cid> GB <ip>
ipfw add 95 allow ip from 66.181.18.0/27 to 69.55.230.11 22


cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'
== Cronjobs ==
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
0 0 * * * /usr/local/sbin/arecaraidchk 
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
RAID checks ?


confirm that you can ssh to backup3 and backup 2 without getting a login prompt
35 4 * * * /usr/local/sbin/snapshot_archive
Rotate daily snapshots for infrastructure machine backups


ssh backup3 hostname
00 15 * * * /usr/local/sbin/snapshot_rotate
Rotate daily snapshots for customer machine backups


ssh backup2 hostname
== Regular maintenance ==
*[[Routine_Maintenance#A|Check on RAID health]]


ssh backup1 hostname
== Build ==


= console =


10. edit root's path and login script:
== Summary ==
vi /root/.cshrc
This box's only purpose is to serve as a means to connect to the digi serial multiplexer boxes at castle. Connect to it using the blue (cisco) ribbon cable with the beige RJ-45 to serial connector, 9600 8N1.


Change alias entries (add G):
OBSOLETE
alias la        ls -aG
* Location: castle, cab 3-8
alias lf        ls -FAG
* OS: SunOS 5.8 (solaris)
alias ll        ls -lAG
* Networking: Priv IP: 10.1.4.4
alias ls        ls -AG
* Hardware: Sun Netra
alias mbm      mb mount
alias mbu      mb umount


and alter the prompt, set the following:
set prompt = "`/bin/hostname -s` %/# "


11. install cvsup
To connect to consoles, ssh in as user 'console' and use the <tt>tip</tt> command to connect to devices listed in <tt>/etc/remote</tt>
cd /usr/ports/net/cvsup-without-gui
make install clean; rehash; mail -s 'cvs installed' dave.boodman@vtext.com < /dev/null


12. get latest sources for this release:
SSH WORK ~2021
cd /usr/src
ssh user@console.johncompanies.com <br>
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
src-all" > sup


cvsup sup ; mail -s 'cvs sup done' dave.boodman@vtext.com < /dev/null
PW: 674*****


13. configure new kernel.  
i.e.
tip switch-p1
tip jail1


cd /usr/src/sys/i386/conf
== Configuring digi/ports ==
scp backup2:/mnt/data4/build/freebsd/firewall2-6.4 ./firewall2


15. build, install kernel and world
=== /etc/remote ===
This is where the configuration/mapping for ports and custom names which we use along with the tip command to connect to various ports on the digi switches.


cd /boot
We have 2 digi's at castle we connect to:


mv kernel kernel.GENERIC
#3-7 10.1.4.10
cd kernel.GENERIC
virt15:dv=/dev/dty/CO001s:br#38400:el=^C^S^Q^U^D:ie=%$:oe=^D:
cd /usr/src
virt13:dv=/dev/dty/CO002s:br#115200:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:
make buildkernel installkernel


make buildworld ; mail -s 'buildworld done' dave.boodman@vtext.com < /dev/null
and
(2450: 1:56min, supermicro: 59mins, 2950: 38mins)
make installworld
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i


17. populate /etc/rc.conf with IPs and NFS settings
#3-6 10.1.4.11
vi /etc/rc.conf
jail4:dv=/dev/dty/CP001s:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:
jail16:dv=/dev/dty/CP002s:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:


kern_securelevel_enable="NO"
The only things you need to edit are the first part (i.e. <tt>jail4</tt>) and the speed (i.e. <tt>9600</tt>). You can decipher which port on the digi each line corresponds to by the <tt>CP001s or CO001s</tt> (port 1 on digi1 and digi2), <tt>CP002s or CO002s</tt> (port 2 on digi1 and digi2)
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"


xntpd_enable="YES"
=== drpadmin ===
nfs_client_enable="YES"
The tool you use to configure a device to a digi box is drpadmin:
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.2"


ifconfig_bce1="inet 10.1.2.2 netmask 255.255.255.0"
<pre>bash-2.03$ su
fsck_y_enable="YES"
Password:
background_fsck="NO"
# drpadmin


defaultrouter="66.181.18.2"
Please select an option (a)dd (d)elete (s)how (r)eset (q)uit : s
hostname="firewall2.johncompanies.com"
0      10.1.4.10      32      CO      771    never  1027
ifconfig_bge0="inet 66.181.18.3  netmask 255.255.255.224"
1       10.1.4.11      32      CP      771    never  1027
ifconfig_bge1="inet 69.55.229.1 netmask 255.255.255.0"
2       65.116.11.2    8      el      771    never  1027
ifconfig_fxp0="inet 10.1.2.2 netmask 255.255.255.0"
sshd_enable="YES"
usbd_enable="YES"


20. reboot. Confirm new kernel is loaded
Please select an option (a)dd (d)elete (s)how (r)eset (q)uit :</pre>


uname -a
Use those commands above to modify the devices available.


21. update ports:
== Switching IP/hostname ==
cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup


cvsup sup; mail -s 'cvs sup ports done' dave.boodman@vtext.com < /dev/null
Edit:
/etc/defaultrouter
/etc/hosts
/etc/hostname.hme0
/etc/nodename
Maybe needed to run: # ifconfig hme0 10.1.4.4 up


22. Install raid mgmt tool
= devweb =


# linux base
We do web development on devweb.johncompanies.com
cd /usr/ports/devel/libtool22
make install base


cd /usr/ports/emulators/linux_base-fc4
Currently this is a jail running on jail17 / 69.55.230.8
make install clean


#linux-megamgr-5.20
If the jail is restarted, you will need to manually restart the web service with:
cd /usr/ports/sysutils/linux-megamgr
httpsdctl restart
make install clean


# megarc-1.51
All website development work should be done here first. It works exactly like and is setup like our [[Management_System_/_Public_Website_/_Signup_/_Account_Manager|main site]].
cd /usr/ports/sysutils/megarc
make install clean


Test:
rehash; megarc -ldInfo -a0 -l0


23. install rsync from ports
= firewall2 =
cd /usr/ports/net/rsync
make install clean


choose default options
== Summary ==


25. install bb client
This machine is the primary firewall for the entire network at i2b.   firewall3 is a hot standby replacement for  
adduser
firewall2. Both firewall2 and firewall3 should not be connected at the same time since they use the same internal
Username: bb
and external IP addresses.
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes


cd /usr/home/bb
* Location: i2b, cab 6
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
* OS: FreeBSD 6.4 x86
tar xvf bb-freebsd.tar
* Networking: Priv IP: 10.1.2.2, Pub IPs: 66.181.18.3 (external), 69.55.229.1 & 69.55.231.1 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks. TODO: describe NIC location/orientation


edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
* Hardware: 2 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.  
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
* Drives: 73 GB (2 x 73GB) RAID1 array running on an LSI MegaRAID SCSI 320 PCI RAID card.
10.1.2.1 firewall2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts


vi /home/bb/bbc1.9e-btf/ext/openfiles
== Services Provided ==
MACHINE="firewall2,johncompanies,com"      # HAS TO BE IN A,B,C FORM
* firewall (ipfw)
* bigbrother for customer machines


cd /usr/home/bb/bbc1.9e-btf/etc
== Firewall Rule Configuration ==
./bbchkcfg.sh
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..


vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
See [[FreeBSD_Reference#Firewall_Rule_Configuration|Firewall Rule Configuration]] for more discussion on how to actually manipulate firewall rules.
        $1 $TOPARGS > $BBTMP/TOP.$$
#       /usr/local/jail/bin/jtop > $BBTMP/TOP.$$


./runbb.sh start
== Disaster Recovery ==
more BBOUT
(look for errors)
exit


echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
TODO: need backup f/w and instructions on how to move cables.
chmod +x /usr/local/etc/rc.d/bb.sh


Punch a hole in the firewall to allow it to communicate with bb monitor:
Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)


ipfw add 00096 allow ip from 66.181.18.0/27 to 69.55.230.2
TODO


Here's the config on the live firewall:


27. configure bb on mail:
<pre>kern_securelevel_enable="NO"
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
portmap_enable="NO"
66.181.18.3 firewall2.johncompanies.com # ssh
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"


su bb
xntpd_enable="YES"
cd
nfs_client_enable="YES"
bbsrc/bb/runbb.sh restart ; exit
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.2"


29. configure ntp
fsck_y_enable="YES"
echo "server 10.1.2.1" > /etc/ntp.conf
background_fsck="NO"


/usr/sbin/ntpd -p /var/run/ntpd.pid
defaultrouter="66.181.18.2"
sleep 2; ntpq -p
hostname="firewall2.johncompanies.com"
(confirm it’s able to reach our time server)
ifconfig_bge0="inet 66.181.18.3  netmask 255.255.255.224"
ifconfig_bge1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_bge1_alias0="inet 69.55.231.1 netmask 255.255.255.0"
ifconfig_bge1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
ifconfig_bge1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
ifconfig_bge1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
ifconfig_bge1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
ifconfig_bge1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
ifconfig_bge1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
ifconfig_bge1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
ifconfig_bge1_alias8="inet 65.50.235.1  netmask 255.255.255.0"
ifconfig_fxp0="inet 10.1.2.2 netmask 255.255.255.0"
sshd_enable="YES"
usbd_enable="YES"
</pre>


echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh


30. fwd and reverse lookups on ns1c
== Cronjobs ==
vr johncompanies.com
30 3 * * * /usr/local/etc/rsync.backup
(edit the PTR too)
Backup to backup3


0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).


33. setup backups
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
echo '#\!/bin/sh\
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
backupdir=/data/firewall2/current\
Capture counts periodically
\
## ENTRY /etc ' > /usr/local/etc/backup.config


on backup3:
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;
setup backup dirs:
This script will create <tt>/etc/firewall.sh</tt> which contains all the firewall and pipe rules in place at the time the script was run.
ssh backup3 mkdir -p /data/firewall2/current


on backup3, add the system to
*/5 * * * * /usr/local/sbin/lsiraidchk
vi /usr/local/sbin/snapshot_archive
Checking the health of the RAID array


scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup
vi /usr/local/etc/rsync.backup
backup1 > backup3


crontab -e
== DOS attacks ==
1 0 * * * /usr/local/etc/rsync.backup


See [[FreeBSD_Reference#Handling_a_DoS_attack|Handling a DoS attack]] regarding how to handle a DOS attack.


34. mkdir /root/logs


35. edit sshd_config for security
== build ==
vi /etc/ssh/sshd_config
ListenAddress 66.181.18.3
ListenAddress 10.1.2.1


kill -1 `cat /var/run/sshd.pid`
<pre>partition map:
/ 58g
swap 4g
/var 512m
/tmp 512m
/usr 5.5g


35. raid chk
4. edit /etc/make.conf
echo "WITHOUT_X11=yes \
KERNCONF=firewall2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf
 
5. add settings to /boot/loader.conf and /boot.config
 
echo "-Dh" >> /boot.config
 
echo 'console="comconsole,vidconsole" \
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf
 
 
6. turn off all ttyv's except 0 and 1 in /etc/ttys
also turn on ttyd0, change type to vt100:
vi /etc/ttys
 
ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
ttyv6  "/usr/libexec/getty Pc"        cons25  off secure
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0  "/usr/libexec/getty std.9600"  vt100  on  secure
 
kill -1 1
 
on console server:
vi /etc/remote
(rename port to jail8 depending on where and which digi plugged into)
test serial console


cat > /usr/local/sbin/lsiraidchk
#!/usr/bin/perl


my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;
7. populate hosts
echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts
 
8. put key in authorized_keys on backup3
cd
ssh-keygen -t dsa -b 1024
(default location, leave password blank)
 
Punch a hole in firewall1 to allow traffic to backup servers @ castle:
 
ipfw add 99 allow ip from 66.181.18.0/27 to 69.55.230.10 22
ipfw add 95 allow ip from 66.181.18.0/27 to 69.55.230.11 22
 
cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
 
confirm that you can ssh to backup3 and backup 2 without getting a login prompt
 
ssh backup3 hostname
 
ssh backup2 hostname
 
ssh backup1 hostname
 
 
10. edit root's path and login script:
vi /root/.cshrc
 
Change alias entries (add G):
alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm      mb mount
alias mbu      mb umount
 
and alter the prompt, set the following:
set prompt = "`/bin/hostname -s` %/# "
 
11. install cvsup
cd /usr/ports/net/cvsup-without-gui
make install clean; rehash; mail -s 'cvs installed' dave.boodman@vtext.com < /dev/null
 
12. get latest sources for this release:
cd /usr/src
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
src-all" > sup
 
cvsup sup ; mail -s 'cvs sup done' dave.boodman@vtext.com < /dev/null
 
13. configure new kernel.
 
cd /usr/src/sys/i386/conf
scp backup2:/mnt/data4/build/freebsd/firewall2-6.4 ./firewall2
 
15. build, install kernel and world
 
cd /boot
 
mv kernel kernel.GENERIC
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel
 
make buildworld ; mail -s 'buildworld done' dave.boodman@vtext.com < /dev/null
(2450: 1:56min, supermicro: 59mins, 2950: 38mins)
make installworld
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i
 
17. populate /etc/rc.conf with IPs and NFS settings
vi /etc/rc.conf
 
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"
 
xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.2"
 
ifconfig_bce1="inet 10.1.2.2 netmask 255.255.255.0"
fsck_y_enable="YES"
background_fsck="NO"
 
defaultrouter="66.181.18.2"
hostname="firewall2.johncompanies.com"
ifconfig_bge0="inet 66.181.18.3  netmask 255.255.255.224"
ifconfig_bge1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_fxp0="inet 10.1.2.2 netmask 255.255.255.0"
sshd_enable="YES"
usbd_enable="YES"
 
20. reboot. Confirm new kernel is loaded
 
uname -a
 
21. update ports:
cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup
 
cvsup sup; mail -s 'cvs sup ports done' dave.boodman@vtext.com < /dev/null
 
22. Install raid mgmt tool
 
# linux base
cd /usr/ports/devel/libtool22
make install base
 
cd /usr/ports/emulators/linux_base-fc4
make install clean
 
#linux-megamgr-5.20
cd /usr/ports/sysutils/linux-megamgr
make install clean
 
# megarc-1.51
cd /usr/ports/sysutils/megarc
make install clean
 
Test:
rehash; megarc -ldInfo -a0 -l0
 
23. install rsync from ports
cd /usr/ports/net/rsync
make install clean
 
choose default options
 
25. install bb client
adduser
Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes
 
cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
tar xvf bb-freebsd.tar
 
edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.1 firewall2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
 
vi /home/bb/bbc1.9e-btf/ext/openfiles
MACHINE="firewall2,johncompanies,com"      # HAS TO BE IN A,B,C FORM
 
cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..
 
vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$
 
./runbb.sh start
more BBOUT
(look for errors)
exit
 
echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh
 
Punch a hole in the firewall to allow it to communicate with bb monitor:
 
ipfw add 00096 allow ip from 66.181.18.0/27 to 69.55.230.2
 
 
27. configure bb on mail:
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
66.181.18.3 firewall2.johncompanies.com # ssh
 
su bb
cd
bbsrc/bb/runbb.sh restart ; exit
 
29. configure ntp
echo "server 10.1.2.1" > /etc/ntp.conf
 
/usr/sbin/ntpd -p /var/run/ntpd.pid
sleep 2; ntpq -p
(confirm it’s able to reach our time server)
 
echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh
 
30. fwd and reverse lookups on ns1c
vr johncompanies.com
(edit the PTR too)
 
 
33. setup backups
echo '#\!/bin/sh\
backupdir=/data/firewall2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config
 
on backup3:
setup backup dirs:
ssh backup3 mkdir -p /data/firewall2/current
 
on backup3, add the system to
vi /usr/local/sbin/snapshot_archive
 
scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup
vi /usr/local/etc/rsync.backup
backup1 > backup3
 
crontab -e
1 0 * * * /usr/local/etc/rsync.backup
 
 
34. mkdir /root/logs
 
35. edit sshd_config for security
vi /etc/ssh/sshd_config
ListenAddress 66.181.18.3
ListenAddress 10.1.2.1
 
kill -1 `cat /var/run/sshd.pid`
 
35. raid chk
 
cat > /usr/local/sbin/lsiraidchk
#!/usr/bin/perl
 
my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;


foreach (@out) {
foreach (@out) {
     if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
     if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#print $_;
#print $_;
}
}
 
 
36. add crontab entries
36. add crontab entries
crontab -e
crontab -e
30 3 * * * /usr/local/etc/rsync.backup
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;  
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;  
*/5 * * * * /usr/local/sbin/lsiraidchk
*/5 * * * * /usr/local/sbin/lsiraidchk
 
 
#10 0 * * * rm /var/spool/clientmqueue/*
#10 0 * * * rm /var/spool/clientmqueue/*
 
 
scp /etc/makefwrules.pl user@64.163.14.48:~
scp /etc/makefwrules.pl user@64.163.14.48:~
scp /etc/makepiperules.pl user@64.163.14.48:~
scp /etc/makepiperules.pl user@64.163.14.48:~
mv /home/user/makefwrules.pl /etc
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
touch /etc/firewall.sh
mkdir /etc/oldrules/
mkdir /etc/oldrules/
 
 
other binaries
other binaries
scp /usr/local/bin/rulemaker user@64.163.14.48:~
scp /usr/local/bin/rulemaker user@64.163.14.48:~
mv ~user/rulemaker /usr/local/sbin
mv ~user/rulemaker /usr/local/sbin
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~
 
 
Setup basic ruleset
Setup basic ruleset
 
 
ipfw add 00009 count udp from any to any
ipfw add 00009 count udp from any to any
ipfw add 00010 allow tcp from any to any established
ipfw add 00010 allow tcp from any to any established
ipfw add 00012 deny tcp from any to any tcpflags syn tcpoptions !mss
ipfw add 00012 deny tcp from any to any tcpflags syn tcpoptions !mss
ipfw add 00012 deny icmp from any to any icmptypes 4,5,9,10,12,13,14,15,16,17,18
ipfw add 00012 deny icmp from any to any icmptypes 4,5,9,10,12,13,14,15,16,17,18
ipfw add 00012 deny tcp from any to any tcpflags syn,fin
ipfw add 00012 deny tcp from any to any tcpflags syn,fin
ipfw add 00012 deny tcp from any to any tcpflags fin,psh,rst,urg
ipfw add 00012 deny tcp from any to any tcpflags fin,psh,rst,urg
ipfw add 00012 allow icmp from any to any
ipfw add 00012 allow icmp from any to any
ipfw add 00014 deny tcp from any to any dst-port 135
ipfw add 00014 deny tcp from any to any dst-port 135
ipfw add 00150 skipto 65535 ip from any to any via em1 in
ipfw add 00150 skipto 65535 ip from any to any via em1 in
 
IPKVM3:
00098 allow ip from { 69.55.230.6 or 69.55.230.7 } to 69.55.230.10 dst-port 139
00098 deny ip from any to 69.55.230.10 dst-port 139
</pre>
 
 
= firewall3 =
 
== Summary ==
 
This machine is the backup firewall for the network at i2b.
 
* Location: i2b, cab ?
* OS: FreeBSD 9.1 amd64
* Networking: Priv IP: 10.1.2.5, Pub IPs: 66.181.18.3 (external), 69.55.229.1 & 69.55.231.1 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks.
 
<pre>
 
The internal network NIC is the left one on the motherboard (69.55.229.1/24, ...).
The external network NIC is the right one on the motherboard (66.181.18.3/28).
The PCI ethernet card is connected to our private network (10.1.2.5/24).
 
</pre>
 
* Hardware: 2 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
* Drives: 160 GB (2 x 160GB) RAID1 array running on an LSI MegaRAID SCSI 320 PCI RAID card.
 
== Services Provided ==
* firewall (ipfw)
* bigbrother
 
== Firewall Rule Configuration ==
 
See [[FreeBSD_Reference#Firewall_Rule_Configuration|Firewall Rule Configuration]] for more discussion on how to actually manipulate firewall rules.
 
== Disaster Recovery ==
 
'''To put the backup firewall3 into service:'''
 
<pre>
Move the internal cable (to our networks) from firewall2 to em1 which is the left most ethernet port (69.55.229.1).
Move the external cable (to outside world) from firewall2 to em0 which is the port to the right on the motherboard (66.181.18.3).
The PCI ethernet port (fxp0) should already be connected to private network (10.1.2.5).
</pre>
 
Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)
 
<pre>
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"
 
xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.5"
 
fsck_y_enable="YES"
background_fsck="NO"
 
defaultrouter="66.181.18.2"
hostname="firewall3.johncompanies.com"
ifconfig_em0="inet 66.181.18.3  netmask 255.255.255.224"
 
ifconfig_em1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_em1_alias0="inet 69.55.231.1 netmask 255.255.255.0"
 
# ifconfig_em1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
# ifconfig_em1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
# ifconfig_em1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
# ifconfig_em1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
# ifconfig_em1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
# ifconfig_em1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
# ifconfig_em1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
# ifconfig_em1_alias8="inet 65.50.235.1  netmask 255.255.255.0"
 
ifconfig_fxp0="inet 10.1.2.5 netmask 255.255.255.0"
 
sshd_enable="YES"
usbd_enable="YES"
</pre>
 
== Cronjobs ==
30 3 * * * /usr/local/etc/rsync.backup
Backup to backup3
 
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).
 
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
Capture counts periodically
 
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;
This script will create <tt>/etc/firewall.sh</tt> which contains all the firewall and pipe rules in place at the time the script was run.
 
*/5 * * * * /usr/local/sbin/lsiraidchk
Checking the health of the RAID array
 
 
== DOS attacks ==
 
See [[FreeBSD_Reference#Handling_a_DoS_attack|Handling a DoS attack]] regarding how to handle a DOS attack.
 
 
== build ==
 
<pre>partition map:
/ 58g
swap 4g
/var 512m
/tmp 512m
/usr 5.5g
 
4. edit /etc/make.conf
echo "WITHOUT_X11=yes \
KERNCONF=firewall3 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf
 
5. add settings to /boot/loader.conf and /boot.config
 
echo "-Dh" >> /boot.config
 
echo 'console="comconsole,vidconsole" \
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf
 
 
6. turn off all ttyv's except 0 and 1 in /etc/ttys
also turn on ttyd0, change type to vt100:
vi /etc/ttys
 
ttyv2  "/usr/libexec/getty Pc"        cons25  off secure
ttyv3  "/usr/libexec/getty Pc"        cons25  off secure
ttyv4  "/usr/libexec/getty Pc"        cons25  off secure
ttyv5  "/usr/libexec/getty Pc"        cons25  off secure
ttyv6  "/usr/libexec/getty Pc"        cons25  off secure
ttyv7  "/usr/libexec/getty Pc"        cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0  "/usr/libexec/getty std.9600"  vt100  on  secure
 
kill -1 1
 
on console server:
vi /etc/remote
(rename port to jail8 depending on where and which digi plugged into)
test serial console
 
 
7. populate hosts
echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts
 
8. put key in authorized_keys on backup3
cd
ssh-keygen -t dsa -b 1024
(default location, leave password blank)
 
Punch a hole in firewall1 to allow traffic to backup servers @ castle:
 
ipfw add 99 allow ip from 66.181.18.0/27 to 69.55.230.10 22
ipfw add 95 allow ip from 66.181.18.0/27 to 69.55.230.11 22
 
cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys'
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'
 
confirm that you can ssh to backup3 and backup 2 without getting a login prompt
 
ssh backup3 hostname
 
ssh backup2 hostname
 
ssh backup1 hostname
 
 
10. edit root's path and login script:
vi /root/.cshrc
 
Change alias entries (add G):
alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm      mb mount
alias mbu      mb umount
 
and alter the prompt, set the following:
set prompt = "`/bin/hostname -s` %/# "
 
11. install cvsup
cd /usr/ports/net/cvsup-without-gui
make install clean; rehash; mail -s 'cvs installed' 8583619553@vtext.com < /dev/null
 
12. get latest sources for this release:
cd /usr/src
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_9_1\
*default delete use-rel-suffix\
*default compress\
src-all" > sup
 
cvsup sup ; mail -s 'cvs sup done' 8583619553@vtext.com < /dev/null
 
13. configure new kernel.
 
cd /usr/src/sys/amd64/conf
scp backup2:/mnt/data4/build/freebsd/firewall3-9.1 ./firewall3
 
15. build, install kernel and world
 
cd /boot
 
mv kernel kernel.GENERIC
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel
 
make buildworld ; mail -s 'buildworld done' 8583619553@vtext.com < /dev/null
(supermicro: 2:15 mins, 2950: 38? mins)
make installworld
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i
 
17. populate /etc/rc.conf with IPs and NFS settings
vi /etc/rc.conf
 
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"
 
xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
 
fsck_y_enable="YES"
background_fsck="NO"
 
hostname="firewall3.johncompanies.com"
#  external network
ifconfig_em0="inet 66.181.18.3  netmask 255.255.255.224"
 
#  internal network
ifconfig_em1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_em1_alias0="inet 69.55.231.1  netmask 255.255.255.0"
 
ifconfig_em1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
ifconfig_em1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
ifconfig_em1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
ifconfig_em1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
ifconfig_em1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
ifconfig_em1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
ifconfig_em1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
ifconfig_em1_alias8="inet 65.50.235.1  netmask 255.255.255.0"
 
defaultrouter="66.181.18.2"
 
#  private network
ifconfig_fxp0="inet 10.1.2.5 netmask 255.255.255.0"
 
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.5"
 
sshd_enable="YES"
usbd_enable="YES"
ntpd_enable="YES"
# powerd_enable="YES"
 
 
20. reboot. Confirm new kernel is loaded
 
uname -a
 
21. update ports:
cd /usr/ports
 
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_9_1\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup
 
cvsup sup; mail -s 'cvs sup ports done' 8583619553@vtext.com < /dev/null
 
22. Install raid mgmt tool
 
# linux base
cd /usr/ports/devel/libtool22
make install base
 
cd /usr/ports/emulators/linux_base-fc4
make install clean
 
scp backup2:/d4/build/3ware/tw_cli-freebsd-x86_64-9.5.0.1.tgz /usr/local/sbin
cd /usr/local/sbin
tar xzvf tw_cli-freebsd-x86_64-9.5.0.1.tgz
rm tw_cli-freebsd-x86_64-9.5.0.1.tgz
 
23. install rsync from ports
cd /usr/ports/net/rsync
make install clean
 
choose default options
 
25. install bb client
adduser
Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username  : bb
Password  : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups    : bb
Home      : /home/bb
Shell      : /bin/sh
Locked    : no
OK? (yes/no): yes
 
cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
tar xvf bb-freebsd.tar
 
edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.5 firewall3.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
 
vi /home/bb/bbc1.9e-btf/ext/openfiles
MACHINE="firewall3,johncompanies,com"      # HAS TO BE IN A,B,C FORM
 
cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..
 
vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$
 
./runbb.sh start
more BBOUT
(look for errors)
exit
 
echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh
 
Punch a hole in the firewall to allow it to communicate with bb monitor:
 
ipfw add 00096 allow ip from 66.181.18.0/27 to 69.55.230.2
 
 
27. configure bb on mail:
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
66.181.18.3 firewall3.johncompanies.com # ssh
 
su bb
cd
bbsrc/bb/runbb.sh restart ; exit
 
29. configure ntp
echo "server 10.1.2.1" > /etc/ntp.conf
 
/usr/sbin/ntpd -p /var/run/ntpd.pid
sleep 2; ntpq -p
(confirm it’s able to reach our time server)
 
echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh
 
30. fwd and reverse lookups on ns1c
vr johncompanies.com
(edit the PTR too)
 
 
33. setup backups
echo '#\!/bin/sh\
backupdir=/data/firewall2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config
 
on backup3:
setup backup dirs:
ssh backup3 mkdir -p /data/firewall2/current
 
on backup3, add the system to
vi /usr/local/sbin/snapshot_archive
 
scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup
vi /usr/local/etc/rsync.backup
backup1 > backup3
 
crontab -e
1 0 * * * /usr/local/etc/rsync.backup
 
 
34. mkdir /root/logs
 
35. edit sshd_config for security
vi /etc/ssh/sshd_config
ListenAddress 66.181.18.3
ListenAddress 10.1.2.5
 
kill -1 `cat /var/run/sshd.pid`
 
35. raid chk
 
cat > /usr/local/sbin/lsiraidchk
#!/usr/bin/perl
 
my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;
 
foreach (@out) {
    if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#print $_;
}
 
36. add crontab entries
crontab -e
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;
*/5 * * * * /usr/local/sbin/lsiraidchk
 
#10 0 * * * rm /var/spool/clientmqueue/*
 
scp /etc/makefwrules.pl user@64.163.14.48:~
scp /etc/makepiperules.pl user@64.163.14.48:~
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
mkdir /etc/oldrules/
 
other binaries
scp /usr/local/bin/rulemaker user@64.163.14.48:~
mv ~user/rulemaker /usr/local/sbin
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~
 
Setup basic ruleset
 
ipfw add 00009 count udp from any to any
ipfw add 00010 allow tcp from any to any established
ipfw add 00012 deny tcp from any to any tcpflags syn tcpoptions !mss
ipfw add 00012 deny icmp from any to any icmptypes 4,5,9,10,12,13,14,15,16,17,18
ipfw add 00012 deny tcp from any to any tcpflags syn,fin
ipfw add 00012 deny tcp from any to any tcpflags fin,psh,rst,urg
ipfw add 00012 allow icmp from any to any
ipfw add 00014 deny tcp from any to any dst-port 135
ipfw add 00150 skipto 65535 ip from any to any via em1 in
 
IPKVM3:
00098 allow ip from { 69.55.230.6 or 69.55.230.7 } to 69.55.230.10 dst-port 139
00098 deny ip from any to 69.55.230.10 dst-port 139
</pre>
 
= wiki =
 
The wiki (mediawiki) runs on nat2 in a jail running off 69.55.229.8
 
The backup wiki lives on virt13 in CT 5 / 69.55.230.18
 
== Setup jail ==
 
<pre>
mkdir /mnt/data1/wiki-dir
cd /usr/src
make installworld DESTDIR=/mnt/data1/wiki-dir
cd etc
make distribution DESTDIR=/mnt/data1/wiki-dir
 
mount -t devfs devfs /mnt/data1/wiki-dir/dev
devfs -m /mnt/data1/wiki-dir/dev rule -s 3 applyset
 
cd /mnt/data1/wiki-dir
 
ln -sf dev/null kernel
 
scp jail9:/usr/local/sbin/jkill /mnt/data1/wiki-dir/sbin
 
jail /mnt/data1/wiki-dir wiki.johncompanies.com 69.55.229.8 /bin/sh
csh
 
touch /etc/fstab
echo 'network_interfaces=""\
hostname="wiki.johncompanies.com"\
kern_securelevel_enable="NO"\
sendmail_enable="YES"\
sshd_enable="YES"' > /etc/rc.conf
 
echo "nameserver 69.55.229.3\
nameserver 69.55.225.225" >> /etc/resolv.conf
 
vi /etc/crontab
(remove the adjkerntz lines )
vi /etc/periodic/security/100.chksetuid
replace: MP=`mount -t ufs | grep -v " nosuid" | awk '{ print $3 }' | sort`
with: MP='/' (use single quotes)
 
mkdir -p /usr/compat/linux/dev
adduser
 
Username: user
Full name: user
Uid (Leave empty for default):
Login group [user]:
Login group is user. Invite user into other groups? []: wheel
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/user]:
Home directory permissions (Leave empty for default):
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: y
Lock out the account after creation? [no]:
Username  : user
Password  : <random>
Full Name  : user
Uid        : 1001
Class      :
Groups    : user
Home      : /home/user
Home Mode  :
Shell      : /bin/sh
Locked    : no
OK? (yes/no): y
adduser: INFO: Successfully added (user) to the user database.
adduser: INFO: Password for (user) is: 901gmYjO
Add another user? (yes/no): n
Goodbye!
 
vi /usr/home/user/.profile
TERM=vt100;    export TERM
tzsetup
newaliases
rm /sbin/halt /sbin/reboot
ln /sbin/jkill /sbin/halt
ln /sbin/jkill /sbin/reboot
vi /etc/syslog.conf
#*.err;kern.warning;auth.notice;mail.crit              /dev/console
*.err;kern.warning;auth.notice;mail.crit                /var/log/messages
 
exit
exit
cd libexec
chflags noschg ld-elf32.so.1
chflags noschg ld-elf.so.1
mv ld-elf32.so.1 ld-elf32.so.1-orig
ln ld-elf.so.1 ld-elf32.so.1
chflags schg ld-elf.so.1
chflags schg ld-elf32.so.1
cp -r /usr/ports /mnt/data1/wiki-dir/usr
 
cat > /usr/local/etc/rc.d/wiki.sh
mount -t devfs devfs /mnt/data1/wiki-dir/dev/
devfs -m /mnt/data1/wiki-dir/dev rule -s 3 applyset
jail /mnt/data1/wiki-dir wiki.johncompanies.com 69.55.229.8 /bin/sh /etc/rc
 
chmod 0700 /usr/local/etc/rc.d/wiki.sh
</pre>
 
== mediawiki setup ==
 
<pre>
 
cd /usr/ports/net/rsync
make install clean
 
cd /usr/ports/distfiles/
fetch http://downloads.mysql.com/archives/mysql-5.5/mysql-5.5.4-m3.tar.gz
cd /usr/ports/databases/mysql55-server
make install clean
 
cd /usr/ports/distfiles/
fetch http://downloads.php.net/johannes/php-5.3.2.tar.bz2
cd /usr/ports/lang/php52
make install clean
(build apache module)
 
cd /usr/ports/lang/php5-extensions
make install clean
 
cd /usr/ports/www/apache22
make install clean
 
cd /usr/local/www/
fetch http://download.wikimedia.org/mediawiki/1.19/mediawiki-1.19.2.tar.gz
tar xzf mediawiki-1.19.2.tar.gz
mv mediawiki-1.19.2 wiki
 
vi /usr/local/etc/apache22/httpd.conf
DocumentRoot "/usr/local/www/"
 
Include etc/apache22/extra/vhost-wiki.conf
Listen 443
 
<IfModule mod_php5.c>
    <FilesMatch "\.ph(p3?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>
    <FilesMatch "\.phps$">
        SetHandler application/x-httpd-php-source
    </FilesMatch>
    # To re-enable php in user directories comment the following lines
    # (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
    # prevents .htaccess files from disabling it.
    <IfModule mod_userdir.c>
        <Directory /home/*/public_html>
            php_admin_value engine Off
        </Directory>
    </IfModule>
</IfModule>
 
 
cat > /usr/local/etc/apache22/extra/vhost-wiki.conf
<VirtualHost *:443>
        ServerAdmin support@johncompanies.com
 
        DocumentRoot /usr/local/www/wiki
#        <Directory />
#                Options FollowSymLinks
#                AllowOverride None
#                Order deny,allow
#        </Directory>
        <Directory /usr/local/www/wiki>
                Options Indexes FollowSymLinks MultiViews
                Deny from all
                AllowOverride AuthConfig
                Order allow,deny
                DirectoryIndex index.php
                #Allow from 69.55.233.195
                #Allow from boody.dyndns.org
        </Directory>
 
        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>
 
        ErrorLog /var/log/httpd-error.log
 
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn
 
        CustomLog /var/log/httpd-access.log combined
 
    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>
 
    SSLEngine on
    SSLCertificateFile /usr/local/etc/apache22/ssl/server.crt
    SSLCertificateKeyFile /usr/local/etc/apache22/ssl/server.key
 
</VirtualHost>
 
mkdir ssl
cd ssl
 
openssl req -days 1999 -new -x509 -nodes -out server.crt -keyout server.key
US
CA
San Diego
johncompanies.com
johncompanies.com
wiki.johncompanies.com
support@johncompanies.com
 
cat > /usr/local/www/wiki/.htaccess
AuthType Basic
AuthUserFile /usr/local/etc/apache22/wiki.passwd
AuthName wiki
require valid-user
satisfy any
 
cd /usr/local/etc/apache22
htpasswd -c wiki.passwd admin
 
https://69.55.229.8/index.php
 
use mysql (innodb)
wiki name: JCWiki
Support / (mail pass) / support@johncompanies.com
 
cat > /usr/local/www/wiki/LocalSettings.php
 
<?php
# This file was automatically generated by the MediaWiki 1.19.2
# installer. If you make manual changes, please keep track in case you
# need to recreate them later.
#
# See includes/DefaultSettings.php for all configurable settings
# and their default values, but don't forget to make changes in _this_
# file, not there.
#
# Further documentation for configuration settings may be found at:
# http://www.mediawiki.org/wiki/Manual:Configuration_settings
 
# Protect against web entry
if ( !defined( 'MEDIAWIKI' ) ) {
exit;
}
 
## Uncomment this to disable output compression
# $wgDisableOutputCompression = true;
 
$wgSitename      = "JCWiki";
 
## The URL base path to the directory containing the wiki;
## defaults for all runtime URL paths are based off of this.
## For more information on customizing the URLs please see:
## http://www.mediawiki.org/wiki/Manual:Short_URL
$wgScriptPath      = "";
$wgScriptExtension  = ".php";
 
## The protocol and server name to use in fully-qualified URLs
$wgServer          = "https://69.55.229.8";
 
## The relative URL path to the skins directory
$wgStylePath        = "$wgScriptPath/skins";
 
## The relative URL path to the logo.  Make sure you change this from the default,
## or else you'll overwrite your logo when you upgrade!
#$wgLogo            = "$wgStylePath/common/images/wiki.png";
$wgLogo            = "$wgStylePath/common/images/jclogo.gif";
 
## UPO means: this is also a user preference option
 
$wgEnableEmail      = true;
$wgEnableUserEmail  = true; # UPO
 
$wgEmergencyContact = "apache@69.55.229.8";
$wgPasswordSender  = "apache@69.55.229.8";
 
$wgEnotifUserTalk      = false; # UPO
$wgEnotifWatchlist    = false; # UPO
$wgEmailAuthentication = true;
 
## Database settings
$wgDBtype          = "mysql";
$wgDBserver        = "localhost";
$wgDBname          = "my_wiki";
$wgDBuser          = "root";
$wgDBpassword      = "";
 
# MySQL specific settings
$wgDBprefix        = "";
 
# MySQL table options to use during installation or update
$wgDBTableOptions  = "ENGINE=InnoDB, DEFAULT CHARSET=binary";
 
# Experimental charset support for MySQL 5.0.
$wgDBmysql5 = false;
 
## Shared memory settings
$wgMainCacheType    = CACHE_NONE;
$wgMemCachedServers = array();
 
## To enable image uploads, make sure the 'images' directory
## is writable, then set this to true:
$wgEnableUploads  = false;
#$wgUseImageMagick = true;
#$wgImageMagickConvertCommand = "/usr/bin/convert";
 
# InstantCommons allows wiki to use images from http://commons.wikimedia.org
$wgUseInstantCommons  = false;
 
## If you use ImageMagick (or any other shell command) on a
## Linux server, this will need to be set to the name of an
## available UTF-8 locale
$wgShellLocale = "en_US.utf8";
 
## If you want to use image uploads under safe mode,
## create the directories images/archive, images/thumb and
## images/temp, and make them all writable. Then uncomment
## this, if it's not already uncommented:
#$wgHashedUploadDirectory = false;
 
## Set $wgCacheDirectory to a writable directory on the web server
## to make your wiki go slightly faster. The directory should not
## be publically accessible from the web.
#$wgCacheDirectory = "$IP/cache";
 
# Site language code, should be one of the list in ./languages/Names.php
$wgLanguageCode = "en";
 
$wgSecretKey = "abc699ef26890b49b4055430f8ebbd25e84cce21a7e53aeaec4d4313af4c9739";
 
# Site upgrade key. Must be set to a string (default provided) to turn on the
# web installer while LocalSettings.php is in place
$wgUpgradeKey = "3196710f4a7d7332";
 
## Default skin: you can change the default skin. Use the internal symbolic
## names, ie 'standard', 'nostalgia', 'cologneblue', 'monobook', 'vector':
$wgDefaultSkin = "vector";
 
## For attaching licensing metadata to pages, and displaying an
## appropriate copyright notice / icon. GNU Free Documentation
## License and Creative Commons licenses are supported so far.
$wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
$wgRightsUrl  = "";
$wgRightsText = "";
$wgRightsIcon = "";
 
# Path to the GNU diff3 utility. Used for conflict resolution.
$wgDiff3 = "/usr/bin/diff3";
 
# Query string length limit for ResourceLoader. You should only set this if
# your web server has a query string length limit (then set it to that limit),
# or if you have suhosin.get.max_value_length set in php.ini (then set it to
# that value)
$wgResourceLoaderMaxQueryLength = -1;
 
 
 
# End of automatically generated settings.
# Add more configuration options below.
 
 
</pre>
 
== copy/backup wiki ==
on main/primary wiki:
<pre>
/usr/local/etc/rc.d/mysql-server stop
ssh 69.55.230.18 "/etc/init.d/mysql stop"
rsync -av /var/db/mysql/my_wiki/ 69.55.230.18:/var/lib/mysql/my_wiki/
rsync -av /var/db/mysql/ib* 69.55.230.18:/var/lib/mysql/
/usr/local/etc/rc.d/mysql-server start
ssh 69.55.230.18 "/etc/init.d/mysql start"


IPKVM3:
00098 allow ip from { 69.55.230.6 or 69.55.230.7 } to 69.55.230.10 dst-port 139
00098 deny ip from any to 69.55.230.10 dst-port 139
</pre>
</pre>

Latest revision as of 15:05, 3 October 2023

jails[edit]

jail1[edit]

  • Location: castle, SHUTDOWN
  • OS: FreeBSD 6.2 i386
  • Networking: Priv IP: 10.1.4.101 (PCI nic), Pub IP: 69.55.230.107 (onboard)
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 74 GB (4 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
  • Remote management: none
  • Disk accounting: gvinum

jail2[edit]

  • Location: castle, cab 6-16
  • OS: FreeBSD 7.2 amd64
  • Networking: Priv IP: 10.1.4.102, Pub IP: 69.55.228.53 (2 onboard nics)
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 146 GB (2 x 146GB) RAID1 array, two 300 GB (4 x 300GB) RAID1 arrays running on an LSI-based, Dell-branded (PERC 6/i) RAID card.
  • Remote management: DRAC @ 10.1.4.232
  • Disk accounting: md

jail3[edit]

  • Location: I2b SHUTDOWN
  • OS: FreeBSD 8.3 amd64
  • Networking: Priv IP: 10.1.2.103, Pub IP: 69.55.229.7 (2 onboard nics)
  • Hardware: Supermicro (custom build). 6 SATA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 300 GB (2 x 300GB) RAID1 array running on a 3ware 8006-2LP RAID card.
  • Remote management: none
  • Disk accounting: md

Notes[edit]

  • We should not add users to this server since it is at I2B
  • must be ssh'd to from nat2
  • is a super jail for customer col01737

jail4[edit]

  • Location: castle, cab 6-17
  • OS: FreeBSD 9.1 x86_64
  • Networking: Priv IP: 10.1.4.104, Pub IP: 69.55.228.104 (2 onboard nics)
  • Hardware: Dell 2850. 6 x 300GB SCSI drives (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • CPU: 2 x Intel(R) Xeon(TM) CPU 2.80GHz (8 virtual CPUs)
  • RAM: 16 GB ( 4 x 4GB Reg ECC )
  • Drives: one 1.4 TB RAID 5 array (6 x 300GB SCSI) Dell-branded (PERC 4e)LSI megarc RAID card.
  • Remote management: None
  • Disk accounting: md


Notes[edit]

Only FreeBSD 9.1 jail Not upgraded to FBSD 9.2 or 9.3 because too many libraries modified (would require customers to rebuild apps).

jail5[edit]

  • Location: castle, cab 3-6
  • OS: FreeBSD 10.1 x86_64
  • Networking: Priv IP: 10.1.4.105, Pub IP: 69.55.230.105 (2 onboard nics)
  • Hardware: Supermicro JC-14004 - Intel S1200BTL motherboard - 6 SATA/SAS drive bays (2 colums of 3), Dual power supply.
  • CPU: 1 x Intel(R) Xeon(TM) E3-1230 V2 CPU 3.30 GHz (8 virtual CPUs)
  • RAM: 32 GB ( 4 x 8GB ECC )
  • Drives: 1x80 GB SATA SSD on motherboard + one 2.6 TB RAID 5 array 4x1 TB + 3ware 9650 RAID card.
  • Remote management: Intel RMM 4 - 10.1.4.235
  • Disk accounting: md

Notes[edit]

Only FreeBSD 10.1 jail used for bhyve virtuals.

Use ~+Ctrl-D to disconnect from console (vm attach colXXXXX).

jail6[edit]

  • Location: castle, cab 6-16
  • OS: FreeBSD 10.3 x86_64
  • Networking: Priv IP: 10.1.4.106, Pub IP: 69.55.230.106 (2 onboard nics)
  • Hardware: Supermicro JC-14004 - Intel S1200BTL motherboard - 6 SATA/SAS drive bays (2 colums of 3), Dual power supply.
  • CPU: 1 x Intel(R) Xeon(TM) E3-1230 V2 CPU 3.30 GHz (8 virtual CPUs)
  • RAM: 32 GB ( 4 x 8GB ECC )
  • Drives: one 2.7 TB ZFS RAID 6 array 5x1 TB
  • Remote management: Intel RMM 4 - 10.1.4.236
  • Disk accounting: zfs

jail7[edit]

  • Location: castle, cab 3-5 SCHEUDLED SHUTDOWN 9/30/19
  • OS: FreeBSD 6.3 i386
  • Networking: Priv IP: 10.1.4.107, Pub IP: 69.55.230.108 (2 onboard nics)
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 146 GB (4 x 146GB) RAID1 arrays, one 74 GB (2 x 74GB) RAID1 array running on an LSI-based, Dell-branded (PERC 6/i) RAID card.
  • Remote management: DRAC @ 10.1.4.237
  • Disk accounting: gvinum

Notes[edit]

Do not run a verify while OS/jails running, will crash.

jail8[edit]

  • Location: castle, cab 3-6
  • OS: FreeBSD 8.0 amd64
  • Networking: Priv IP: 10.1.4.108, Pub IP: 69.55.234.2 (2 onboard nics)
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 146 GB (2 x 146GB) RAID1 array, one 300 GB (2 x 300GB) RAID1 array, one 400 GB (2 x 400GB) RAID1 array, running on an LSI-based, Dell-branded (PERC 6/i) RAID card.
  • Remote management: DRAC @ 10.1.4.238
  • Disk accounting: md


jail9[edit]

  • Location: castle, cab 3-6
  • OS: FreeBSD 8.2 amd64
  • Networking: Priv IP: 10.1.4.109, Pub IP: 69.55.232.36 (2 onboard nics)
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 146 GB (2 x 146GB) RAID1 array, one 400 GB (2 x 300GB) RAID1 array running on an LSI-based, Dell-branded (PERC 5/i) RAID card.
  • Remote management: DRAC @ 10.1.4.239
  • Disk accounting: md


jail11[edit]

  • Location: castle, cab 3-7
  • OS: FreeBSD 4.7 i386
  • Networking: Priv IP: 10.1.4.111 (PCI nic), Pub IP: 69.55.236.92 (onboard)
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 74 GB (4 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
  • Remote management: none
  • Disk accounting: vinum


mx1[edit]

  • Location: castle, SHUTDOWN AND SCRAPPED
  • OS: FreeBSD 4.11 i386
  • Networking: Priv IP: 10.1.4.201 (PCI nic), Pub IP: 69.55.237.3 (onboard)
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 36 GB (2 x 36GB) RAID1 array, one 74 GB (2 x 74GB) RAID1 array running on an Adaptec-based, Dell-branded (perc) RAID card.
  • Remote management: none
  • Disk accounting: vinum

Notes[edit]

  • is our (old) backup mail/dns vps service host

mx2[edit]

  • Location: castle, SHUTDOWN AND SCRAPPED
  • OS: FreeBSD 7.1 i386
  • Networking: Priv IP: 10.1.4.202 (PCI nic), Pub IP: 69.55.237.90 (onboard)
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 74 GB (4 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
  • Disk accounting: gvinum

Notes[edit]

  • is our latest backup mail/dns vps service host

jail17[edit]

  • Location: castle, cab 3-7
  • OS: FreeBSD 4.10 i386
  • Networking: Priv IP: 10.1.4.117 (PCI nic), Pub IP: 69.55.228.2 (onboard nics)
  • Hardware: Supermicro (custom build). 6 SCA SCSI drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 74 GB (4 x 74GB) RAID1 arrays, one 146 GB (2 x 146GB) RAID1 array, running on an Adaptec 2120S RAID card.
  • Remote management: none
  • Disk accounting: vinum
  • Host of devweb.johncompanies.com and www.utopian.com/mail.utopian.com

jail18[edit]

  • Location: castle, cab 3-5 SCHEDULED SHUTDOWN 9/30/19
  • OS: FreeBSD 4.10 i386
  • Networking: Priv IP: 10.1.4.118 (PCI nic), Pub IP: 69.55.228.2 (onboard nics)
  • Hardware: Supermicro (custom build). 6 SCA SCSI drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 74 GB (4 x 74GB) RAID1 arrays, one 146 GB (2 x 146GB) RAID1 array, running on an Adaptec 2120S RAID card.
  • Remote management: none
  • Disk accounting: vinum
  • Host of ns2c.johncompanies.com (now on ns2c.johncompanies.com on ganeti)

jail19[edit]

  • Location: castle, cab 3-5 SCHEDULED SHUTDOWN 9/30/19
  • OS: FreeBSD 6.1 i386
  • Networking: Priv IP: 10.1.4.119 (PCI nic), Pub IP: 69.55.228.200 (onboard nics)
  • Hardware: Supermicro (custom build). 6 SCA SCSI drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 74 GB (2 x 74GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an Adaptec 2120S RAID card.
  • Remote management: none
  • Disk accounting: gvinum

virts[edit]

quar1[edit]

  • Location: castle, SHUTDOWN AND SCRAPPED
  • OS: RedHat 7.3 x86
  • Networking: Priv IP: 10.1.4.151 (PCI nic), Pub IP: 69.55.227.2 (onboard nic)
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 36 GB (2 x 36GB) RAID1 array, one 74 GB (2 x 74GB) RAID1 array, running on an Adaptec-based, Dell-branded (perc) RAID card.
  • Remote management: none
  • Virtuozzo version: 2.6.1
  • VZ license: hwid=23C0.C0E1.6FDD.08BA.8971.8E1C.EBD5.1EDC serial=0DE6.903E.E239.E23F.470C.4369.4104.A5A4

Notes[edit]

  • used to be the home of customers who's VE's would just run out of control/badly
  • has a max of 10 VE's allowed to run

virt9[edit]

  • Location: castle, cab 3-7
  • OS: RedHat 7.3 x86
  • Networking: Priv IP: 10.1.4.59 (PCI nic), Pub IP: 69.55.226.161 (onboard nic)
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 74 GB (2 x 74GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.
  • Remote management: none
  • Virtuozzo version: 2.6.1
  • VZ license: hwid=BC15.B4D6.0D25.A5FE.F3BA.D518.E351.AE3F serial=F6AD.B6B4.5650.8869.C97C.73EE.AF65.FA8B


virt11[edit]

  • Location: castle, cab 3-6
  • OS: CentOS 5.4 x86
  • Networking: Priv IP: 10.1.4.61, Pub IP: 69.55.238.3, 2 onboard nics
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 146 GB (2 x 146GB) RAID1 array, one 400 GB (2 x 400GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an LSI-based, Dell-branded (perc 6/i) RAID card.
  • Remote management: DRAC @ 10.1.4.211
  • Virtuozzo version: 4.0.0
  • VZ license: hwid="029D.A187.78E1.480F.49E3.E20A.7389.7F79" serial="163C.F3E2.195F.96B5.2D38.8937.9600.4A05" key_number="VZ.00172378.0006"
 vzlicload -p A40R00-D8CS00-5D8817-A2RB23-8Y9J78

virt12[edit]

  • Location: castle, cab 3-7
  • OS: CentOS 5.2 x86
  • Networking: Priv IP: 10.1.4.62, Pub IP: 69.55.227.70, 2 onboard nics
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 300 GB (2 x 300GB) RAID1 arrays one 400 GB (2 x 400GB) RAID1 array, running on an LSI-based, Dell-branded (perc 6/i) RAID card.
  • Remote management: DRAC @ 10.1.4.212
  • Virtuozzo version: 4.0.0
  • VZ license: hwid="0C53.A413.E095.B4F4.51BC.D740.6919.A77B" serial="84E5.9498.3759.E683.E24B.2514.CA72.DC31"

virt13[edit]

  • Location: castle, cab 6-17
  • Switch port: P13-
  • OS: CentOS 6.2 x86_64
  • Networking: Priv IP: 10.1.4.63, Pub IP: 69.55.226.2, 2 onboard nics
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • CPU: 2 x Intel(R) Xeon(R) CPU E5420 @ 2.50GHz (8 virtual cores)
  • RAM: 32 GB (8 x 4GB DDR2 FB-DIMM ECC 667MHz)
  • Drives: one 146 GB (2 x 146GB) RAID1 array, one 600 GB (2 x 600GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an LSI-based, Dell-branded (perc 6/i) RAID card.
  • Remote management: DRAC @ 10.1.4.213
  • Virtuozzo version: 4.7.0
  • VZ license: hwid="7D07.93BE.0B1F.7D2B.B039.4B5B.48B6.453B" serial="60A4.A94C.44BB.DCD6.8D03.1778.605B.10FE"

Notes[edit]

  • home to our latest/current signups
  • currently the only 64bit vz host

virt14[edit]

  • Location: castle, cab 6-16
  • Switch Port: p13-
  • OS: CentOS 6.4 x86_64
  • Networking: Priv IP: 10.1.4.64 Pub IP: 69.55.225.14 2 onboard nics
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • CPU: 2 x Xeon 5140 Dual Core @ 2.33GHz (4 virtual CPUs)
  • RAM: 32 GB (8 x 4GB Reg ECC)
  • Drives: one 146 GB (2 x 146 GB SAS) RAID1 array, and one 1TB RAID1 array (2 x 1 TB SATA), running on an LSI-based, Dell-branded (perc 5/i) RAID card.
  • Remote management: DRAC @ 10.1.4.214
  • Virtuozzo version: 4.7.0
  • VZ license: hwid="EA32.2CA0.2368.F5FC.DFBE.6724.5AC0.8ED0" serial="DA0D.F464.0BCE.35B8.C0C0.28B6.D921.F3FD" key_number="VZ.02634184.0070"
  • Activation Key="A00E00-A0WC02-W1A863-482N41-BQAY84"

Notes[edit]

  • our latest virt
  • Temp server to offload Virt13 till we can get a Cloud going.
  • virt 13 and 14 currently the only 64bit vz hosts

virt15[edit]

  • Location: SHUTDOWN
  • OS: RedHat 9 x86
  • Networking: Priv IP: 10.1.4.65, Pub IP: 69.55.232.160 (2 onboard nics)
  • Hardware: Supermicro (custom build). 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 74 GB (2 x 74GB) RAID1 array, two 146 GB (2 x 146GB) RAID1 arrays, running on an LSI MegaRAID SCSI 320-1 RAID card.
  • Remote management: none
  • Virtuozzo version: 2.6.2
  • VZ license: hwid=A90F.6F48.E723.D8BA.3025.184A.5B73.D11E serial=E94B.5164.C1E6.A67F.67D1.7D96.0B6C.5524

virt16[edit]

  • Location: castle, cab 3-7
  • OS: Fedora Core 4 x86
  • Networking: Priv IP: 10.1.4.66, Pub IP: 69.55.232.2 (2 onboard nics)
  • Hardware: Supermicro (custom build). 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 74 GB (2 x 74GB) RAID1 array, one 146 GB (2 x 146GB) RAID1 array, running on an LSI MegaRAID SCSI 320-1 RAID card.
  • Remote management: none
  • Virtuozzo version: 3.0.0
  • VZ license: hwid=DEFA.A325.7230.BBC8.9715.8B52.3FD7.27BE serial=66C0.41EA.3FBB.11D3.9CC6.55C7.09AE.14AB


virt17[edit]

  • Location: castle, cab 3-6
  • OS: CentOS 4.4 x86
  • Networking: Priv IP: 10.1.4.67, Pub IP: 69.55.232.162, 2 onboard nics
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 146 GB (2 x 146GB) RAID1 arrays running on an LSI-based, Dell-branded (perc 5/i) RAID card.
  • Remote management: DRAC @ 10.1.4.217
  • Virtuozzo version: 3.0.0
  • VZ license: hwid=2E14.AED9.70B8.C26E.D99F.B0D3.BCD2.229C serial=2A11.DAD0.61DB.E889.8DF4.9AF7.CF82.3C37


virt19[edit]

  • Location: castle, cab 3-6
  • OS: CentOS 5.2 x86
  • Networking: Priv IP: 10.1.4.69, Pub IP: 69.55.236.2, 2 onboard nics
  • Hardware: Dell 2950. 6 SATA/SAS drive bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: one 146 GB (2 x 146GB) RAID1 array, one 300 GB (2 x 300GB) RAID1 array, running on an LSI-based, Dell-branded (perc 5/i) RAID card.
  • Remote management: DRAC @ 10.1.4.219
  • Virtuozzo version: 3.0.0
  • VZ license: hwid=3968.13F7.B2AC.8952.8E19.13A9.6EF5.5822 serial=061D.84CD.CCE5.B213.15B5.C061.D6A7.B034

mail[edit]

Summary[edit]

This machine (mail) is the swiss army knife of the company, playing host to many services and functions.

  • Location: castle, cab 3-7
  • OS: FreeBSD 4.10 x86
  • Networking: Priv IP: 10.1.4.5, Pub IPs: 69.55.230.2, 69.55.225.225 (ns1c jail), 69.55.230.9. 1 onboard and 1 PCI
  • Hardware: Dell 2450. 4 SCSI SCA drive bays (2 columns of 2, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: two 36 GB (2 x 36GB) RAID1 arrays running on an Adaptec-based, Dell-branded (perc) RAID card.

Services Provided[edit]

  • mail
  • web
  • mysql
  • bigbrother server/pager
  • snmp
  • named in a jail (ns1c)

email[edit]

This server hosts mail for johncompanies.com (mail.johncompanies.com). Sendmail 8.13.6/8.13.6 is listening on 69.55.230.2 port 25 for incoming mail. Relaying is allowed per /etc/mail/relay-domains Other addresses (aliases) are defined per /etc/mail/aliases

The following active users have mail hosted on this server:

  • dave
  • linux
  • support
  • payments
  • sales
  • tech1
  • info

Traditionally, mail is checked via shell apps (pine). qpopper (pop3s) is running to allow mail downloading. Checking mail in this way causes an opened INBOX in pine to lock read-only. For this reason, we tee incoming mail to support and linux to tech1.

Procmail rules are setup to filter spam and send text messages. They are enabled for info, support, linux, tech1, dave and can be found in ~/Procmail/, for example:

# more ~support/Procmail/rc.emergency
:0c # use c only if you want to forward a copy and file the original later
* ^Subject:.*\<emergency\>
* ! ^Subject:\<re\>
  {
   :0h
   FROMANDSUBJECT=|formail -XFrom: -XSubject:

   :0fwh
   | /usr/local/bin/formail -I"Subject: " -I"To: pager@johncompanies.com" ; echo $FROMANDSUBJECT ; echo

   :0
  ! -t
  }

control: cd /etc/mail; make stop (stop), cd /etc/mail; make start (start)

The following aliases are also in place:

debian:         linux
jobs:   info
careers:        info
#reboot:         6128102202@txt.att.net
#reboot:         8582298897@vtext.com
reboot:         pager
#pager: 8582298897@vtext.com
pager:  4158718324@txt.att.net
tech1on:  "| /usr/local/sbin/tech1on.sh"
tech1off:  "| /usr/local/sbin/tech1off.sh"

To change them, edit /etc/aliases and then run newaliases

Note on tech1: this address was setup as a read-only address to be mirrored on all email coming into support and linux. We set this up so we could easily check support mail via a pop client- popping email locks out the user in pine so checking support/linux directly via pop was not an option. When checking and responding to email that comes into tech1, care should be taken to make sure it is sent as/under an address other than tech1. This is cause tech1 is not monitored by support staff as closely as email to support/linux. Further, the tech on call may not be checking tech1. Lastly, because of the nature of the copying, you will sometimes notice certain automated email/notices are received 2x in support- this is because of/related to the tech1 mirror.

To enable it (on mail, run):

~support/tech1on.sh

To disable

~support/tech1off.sh

Or via email:

tech1on@johncompanies.com tech1off@johncompanies.com

IP Blocking[edit]

01000 deny ip from 188.92.72.5 to any
01003 deny ip from any to 122.49.31.50
01004 deny ip from 122.49.31.50 to any
01014 deny ip from 74.208.225.225 to any
01015 deny ip from any to 216.243.118.35
01016 deny ip from 216.243.118.35 to any
01017 deny ip from any to 216.243.118.36
01018 deny ip from 216.243.118.36 to any
01020 deny ip from 112.215.0.0/18 to any   2014-08-13 Blocked PT Excelcomindo Pratama (Indonesia) for fradulent credit card attempts 
01020 deny ip from 112.215.64.0/20 to any  2014-08-13 Blocked PT Excelcomindo Pratama (Indonesia) for fradulent credit card attempts 
01022 deny ip from 120.168.0.0/24 to any   2014-08-13 Blocked Indosat 3G Broadband (Indonesia) for fradulent credit card attempts
01022 deny ip from 120.175.213.0/24 to any 2014-08-13 Blocked Indosat 3G Broadband (Indonesia) for fradulent credit card attempts

web[edit]

See Management System / Public Website / Signup

mysql[edit]

mysql 4.1.22 is running on port 3306

  • datadir: /mnt/data1/db/mysql/
  • config: /etc/my.cnf
  • database: jc
  • control: /usr/local/etc/rc.d/mysql-server.sh stop (stop), /usr/local/etc/rc.d/mysql-server.sh start (start)

bigbrother[edit]

There is a client running on mail (which monitors the services running on mail and mail itself), installed under /usr/home/bb/bbc1.9e-btf
And the big brother pager/server (which displays information gathered from all bb-monitored machines, including mail) is installed under /usr/home/bb/bbsrc/bb1.9i-btf

Both are running under the user bb

Refer to BigBrother for more about use.

DNS (ns1c.johncompanies.com)[edit]

ns1c is a jail running on the mail server, who's IP is 69.55.225.225

It's running from /mnt/data1/ns1c-dir

See DNS for more details

Usage and Notes[edit]

  • always mounted to backup1 and backup2 via nfs:
backup2:/mnt/data1 on /backup (nfs)
backup2:/mnt/data2 on /backup2 (nfs)
backup2:/mnt/data3 on /backup3 (nfs)
backup2:/mnt/data4 on /backup4 (nfs)
backup1:/data on /backup1 (nfs)

Cronjobs[edit]

* * * * * /usr/local/www/mgmt/mrtg/mrtg.sh > /dev/null 2>&1

Gathers up data for our mrtg/load graphs

*/5 * * * * /usr/local/bin/rsync -a root@nat2:/mnt/data1/mrtg/data/ /usr/local/www/mgmt/mrtg/data/

Gathers up data from i2b servers for our mrtg/load graphs

40 0 * * * /usr/local/bin/rsync -a root@nat2:"/mnt/data1/mrtg/*.cfg" /usr/local/www/mgmt/mrtg

Gathers up mrtg configuration (port names) from i2b switches for our mrtg/load graphs

41 0 * * * for f in `grep -l "mnt\/data1" /usr/local/www/mgmt/mrtg/switch-p*.cfg`; do cat $f | sed s#\/mnt\/data1#\/usr\/local\/www\/mgmt# > $f.new; mv $f.new $f; done

Gathers up mrtg configuration (port names) from castle switches for our mrtg/load graphs

1 0 1 * * cp /usr/local/www/mgmt/html/top20ip /usr/local/www/mgmt/html/top20ip_last
1 0 1 * * cp /usr/local/www/mgmt/html/top20customers /usr/local/www/mgmt/html/top20customers_last
2 * * * * /usr/local/www/cronjobs/top20ip.pl > /dev/null 2>&1
15 * * * * /usr/local/www/cronjobs/top20customer.pl > /dev/null 2>&1
1 0 1 * * rm /usr/local/www/mgmt/html/bandtrack

Archiving and generation of bandwidth statistics presented in mgmt -> Reference -> Bandwidth

1 0 * * * /usr/local/etc/rsync.backup

Nightly backup script

0 1 * * * /usr/local/www/mgmt/awstats/wwwroot/cgi-bin/awstats.pl -config=jcpub -update

Public web traffic stats

15 0 * * * rm /usr/local/www/mgmt/bwgraphs/*.png
16 0 * * * rm /usr/local/www/am/bwgraphs/*

Cleanup for graph-related temp data generated by customers using the bandwidth reports via the AM

10 0 1 * * /usr/local/www/cronjobs/monthly_bandwidth_report.pl

Monthly bandwidth overage report

*/3 * * * * /usr/local/www/cronjobs/bbcheck.pl

Updates mgmt with bb monitoring issues

5 0 * * * /usr/local/www/cronjobs/shutdownreminder.pl

Emails customers reminding them of upcoming shutdown date

7 0 * * * /usr/local/www/cronjobs/invoice_email.pl

Emails customers who have invoices and are set to auto-email (currently no customer gets these)

8 */4 * * * /usr/local/www/cronjobs/mysqlrepchk.pl

Checking that we are properly replicating (mysql) traffic data from bwdb to backup1

16 0 1 * * /usr/local/www/cronjobs/purge_traffic.pl

Removed old traffic data from the traffic database (running on backup1)

*/5 * * * * chmod 0700 /usr/local/www/ccard_orders/* && mv /usr/local/www/ccard_orders/* /usr/local/www/ccard_orders/done

Secure credit card data: set root-read-only

25 0 * * * /usr/local/www/cronjobs/biller.pl

Enters service charges in customer billing ledgers

10 13 * * * /usr/local/www/cronjobs/pfp_batch_gather.pl

Looks for customers with balance due and active credit card on file, prepares a payflow batch

10 14 * * * /usr/local/www/cronjobs/pfp_batch_process.pl

Tries to collect ccard funds for items in payflow batch - communicates with payflow

15 13 * * * /usr/local/www/cronjobs/pb_batch_gather.pl

Looks for customers with balance due and active paypal billing agreement on file, prepares a paypal batch

15 14 * * * /usr/local/www/cronjobs/pb_batch_process.pl

Tries to collect paypal funds for items in paypal batch - communicates with paypal

0 7 * * 1 /usr/local/www/cronjobs/email_pmt_reminder.pl

Emails customers in arrears, reminding them to pay

0 0 1 * * /usr/bin/mail -s 'archive sent mail in pine' support@johncompanies.com < /dev/null

Reminds us to archive sent mail

0 3 * * * /usr/local/bin/rsync -a isys.e-monitoring.net:/var/mail /backup2/isys; /usr/local/bin/rsync -a isys.e-monitoring.net:/usr/home /backup2/isys

Backup data on isys

Regular maintenance[edit]

Building a new Mail Server[edit]

Installations[edit]

I used FreeBSD 11.2

The order is important especially for the Web Server.

Web Server[edit]

I used FreeBSD 11.2

 perl 5.26 
 OpenSSL 1.0.2o-freebsd
 pcre
 apache22 
 mod_perl2
 PayflowPro
 mariadb 55 server and client

Installation order is important

install perl 5.26.2 from ports

<ore> cd /usr/ports/lang/perl5.26/ make [X] PERL_64BITINT Use 64 bit integers (on i386) [X] USE_PERL Rewrite links in /usr/bin (the rest unchecked make install

install OpenSSL 1.0.2o-freebsd

cd /usr/ports/
make install

install pcre

cd /usr/ports/
make install


install Apache22

cd /usr/ports/distfiles
fetch http://archive.apache.org/dist/httpd/httpd-2.2.32.tar.gz


cd /usr/ports/www/apache22/tmp
fetch --no-verify-peer http://mirror.nexcess.net/apache//httpd/httpd-2.2.34.tar.gz
tar xvzf httpd-2.2.34.tar.gz
./configure --prefix=/usr/local/apache --with-ssl=/usr/local/openssl/ --enable-ssl --enable-so --with-mpm=prefork --enable-threads --enable-mods-shared='mime alias setenvif dir' --enable-modules='mime alias setenvif dir' --with-pcre=/usr/local
make install
apachectl restart

cd /usr/ports/www/apache22
echo "DEFAULT_VERSIONS+=apache=2.2" >> /etc/make.conf
make DISABLE_VULNERABILITIES=yes
make install


install mod_perl2

cd /usr/ports/www/mod_perl2
echo "DEFAULT_VERSIONS+=apache=2.2" >> /etc/make.conf
make DISABLE_VULNERABILITIES=yes
make install


install mariadb

cd /usr/ports/databases/mariadb-103-server
echo "DEFAULT_VERSIONS+=apache=2.2" >> /etc/make.conf
make DISABLE_VULNERABILITIES=yes
make install


Mail Server[edit]

I used Postfix for email

DNS Server (ns1c.johncompanies.com)[edit]

ns2c[edit]

Summary[edit]

  • Location: castle, on lamphost ganeti cloud
  • OS: FreeBSD 11.2 x86_64
  • Networking: Pub IP: 69.55.230.3 Private access: gnt-instance console ns2c.johncompanies.com
  • Hardware: on ganeti cloud gn6.jcihosting.net secondary gn1.jcihosting.net
  • CPU: 1
  • RAM: 1 GB
  • Drives: 10 GB
  • Remote management: gnt-instance console ns2c.johncompanies.com

nat[edit]

Summary[edit]

This is the main machine to which we ssh and runs all our screen sessions. Further, it's ip runs in a special block which is not routed through the firewall and this is somewhat immune to DoS attacks which hobble our firewall. Lastly, it acts as a nat server for certain/random devices on the private network.

  • Location: castle, cab 3-7
  • OS: FreeBSD 9.1 i386
  • Networking: Priv IP: 10.1.4.1, Pub IPs: 69.55.233.195, 69.55.233.196, 69.55.233.197, 69.55.233.198, 69.55.233.199. 1 onboard and 1 PCI
  • Hardware: Custom 1U. single power supply.
  • Drives: one 8 GB IDE drive

Services Provided[edit]

  • nat

nat control[edit]

All rules are contained in and look like:

cat /etc/ipnat.rules
# www (was 69.55.230.12)
# virt19
#bimap fxp0 10.1.4.209/32 -> 69.55.233.198/32
# virt18
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32
# virt13
#bimap fxp0 10.1.4.213/32 -> 69.55.233.196/32
# virt12
#bimap fxp0 10.1.4.212/32 -> 69.55.233.196/32
# virt17
bimap fxp0 10.1.4.217/32 -> 69.55.233.196/32
# virt11
#bimap fxp0 10.1.4.211/32 -> 69.55.233.196/32
# ASA
#bimap fxp0 10.1.4.172/32 -> 69.55.233.196/32
# P1A
bimap fxp0 10.1.4.240/32 -> 69.55.233.197/32
#bimap fxp0 10.1.4.238/32 -> 69.55.233.197/32
# developer (was 69.55.230.17)
# jail2
#bimap fxp0 10.1.4.232/32 -> 69.55.233.198/32
# jail8
#bimap fxp0 10.1.4.238/32 -> 69.55.233.198/32
# jail9
#bimap fxp0 10.1.4.239/32 -> 69.55.233.198/32
# POLL
#BIMAP EM0 10.1.6.134/32 -> 69.55.230.20/32
# 1U SUN
#BIMAP EM0 10.1.4.4/32 -> 69.55.227.46/32
# ??
#BIMAP EM0 10.1.6.3/32 -> 69.55.230.100/32
# random machine
#bimap fxp0 10.1.6.13/32 -> 69.55.233.199/32
#bimap fxp0 10.1.4.232/32 -> 69.55.233.199/32
# OFFICE OUTBOUND TRAFFIC
#map fxp0 10.1.6.0/24 -> 0.0.0.0/32 proxy port ftp ftp/tcp
#map fxp0 10.1.6.0/24 -> 0.0.0.0/32

A simple entry looks like:

bimap fxp0 10.1.4.240/32 -> 69.55.233.197/32

Which essentially means make private IP 10.1.4.240 reachable on 69.55.233.197 and allow 10.1.4.240 to communicate with the public internet via 69.55.233.197

To reload new rule config:

ipnat -C -F -f /etc/ipnat.rules

You may want to setup natting, as above, when you need to reach a DRAC card's web interface, wherin the DRAC card only has a private IP.

nat2[edit]

Summary[edit]

This is the main machine to which we ssh and runs all our screen sessions at i2b, and runs ns3c (this is kind of the what mail is to castle). Further, it's ip runs in IP space provided by i2b: 66.181.18.1 - 66.181.18.30, which is not routed through the firewall and this is somewhat immune to DoS attacks which hobble our firewall. Lastly, it acts as a nat server for certain/random devices on the private network.

  • Location: i2b, cab 6
  • OS: FreeBSD 6.4 x86
  • Networking: Priv IP: 10.1.2.1, Pub IPs: 69.55.229.2, 69.55.229.3, 66.181.18.4, 66.181.18.5, 66.181.18.6, 66.181.18.7, 66.181.18.8, 66.181.18.9, 66.181.18.10, 66.181.18.11, 66.181.18.12, 66.181.18.13, 66.181.18.14 1 onboard and 1 PCI
  • Hardware: Custom 2U. 6 drive bays, non-hot-swappable. single power supply.
  • Drives: one 150 GB (2 x 150GB) RAID1 array running on a 3ware 8006 RAID card.

Services Provided[edit]

  • nat
  • bigbrother
  • ns3c (jail)
  • wiki (jail)
  • ntp

nat config[edit]

Here's what's currently nat'd on nat2:

cat /etc/ipnat.rules
# sample entry
#ATS-9
bimap em0 10.1.2.79/32 -> 66.181.18.14/32
#ATS-8
bimap em0 10.1.2.78/32 -> 66.181.18.13/32
#ATS-7
bimap em0 10.1.2.77/32 -> 66.181.18.12/32
#ATS-6
bimap em0 10.1.2.76/32 -> 66.181.18.6/32
#ATS-5
bimap em0 10.1.2.75/32 -> 66.181.18.7/32
#ATS-4
bimap em0 10.1.2.74/32 -> 66.181.18.8/32
#ATS-3
bimap em0 10.1.2.73/32 -> 66.181.18.9/32
#ATS-2
bimap em0 10.1.2.72/32 -> 66.181.18.10/32
#ATS-1
bimap em0 10.1.2.71/32 -> 66.181.18.11/32
#bwdb2
bimap em0 10.1.2.4/32 -> 66.181.18.5/32

# spare

map em0 10.1.2.0/24 -> 0.0.0.0/32 proxy port ftp ftp/tcp

#bimap fxp0 10.1.6.49/32 -> 10.1.1.2/32
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32

build[edit]

  • partition map:
/ 512m
swap 1G
/var 256m
/tmp 256m
/usr 5g
/mnt/data1 ~
  • edit /etc/make.conf
echo "WITHOUT_X11=yes \
KERNCONF=nat2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf
  • add settings to /boot/loader.conf and /boot.config
echo "-Dh" >> /boot.config

echo 'console="comconsole,vidconsole" \
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf
  • turn off all ttyv's except 0 and 1 in /etc/ttys

also turn on ttyd0, change type to vt100:

vi /etc/ttys

ttyv2   "/usr/libexec/getty Pc"         cons25  off secure
ttyv3   "/usr/libexec/getty Pc"         cons25  off secure
ttyv4   "/usr/libexec/getty Pc"         cons25  off secure
ttyv5   "/usr/libexec/getty Pc"         cons25  off secure
ttyv6   "/usr/libexec/getty Pc"         cons25  off secure
ttyv7   "/usr/libexec/getty Pc"         cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0   "/usr/libexec/getty std.9600"   vt100   on  secure

kill -1 1

on console server:

vi /etc/remote

(rename port to jail8 depending on where and which digi plugged into) test serial console


  • populate hosts
echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.4 bwdb2" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts
  • put key in authorized_keys on backup3
cd
ssh-keygen -t dsa -b 1024

(default location, leave password blank)

cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'

confirm that you can ssh to backup3 and backup 2 without getting a login prompt

ssh backup3 hostname
ssh backup2 hostname
ssh backup1 hostname


  • edit root's path and login script:
vi /root/.cshrc

Change alias entries (add G):

alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm       mb mount
alias mbu       mb umount

and alter the prompt, set the following:

set prompt = "`/bin/hostname -s` %/# "
  • install cvsup
cd /usr/ports/net/cvsup-without-gui 
make install clean; rehash; mail -s 'cvs installed' dave.boodman@vtext.com < /dev/null
  • get latest sources for this release:
cd /usr/src 
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
src-all" > sup

cvsup sup ; mail -s 'cvs sup done' dave.boodman@vtext.com < /dev/null


  • configure new kernel.
cd /usr/src/sys/i386/conf 
scp backup2:/mnt/data4/build/freebsd/nat2-6.4 ./nat2
  • build, install kernel and world
cd /boot

mv kernel kernel.GENERIC
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel

make buildworld ; mail -s 'buildworld done' support@johncompanies.com < /dev/null
make installworld 
mergemaster -i
  • populate /etc/rc.conf with IPs and NFS settings
vi /etc/rc.conf

hostname="nat2.johncompanies.com"
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"

xntpd_enable="YES"
xntpd_flags="-A -p /var/run/ntpd.pid"

nfs_client_enable="YES"
nfs_reserved_port_only="YES"
ifconfig_em0="inet 10.1.6.50 netmask 255.255.255.0"
#ifconfig_em0="inet 69.55.229.2 netmask 255.255.255.0"
#ifconfig_em0_alias0="inet 69.55.229.229 netmask 255.255.255.255"
ifconfig_fxp0="inet 69.55.229.2 netmask 255.255.255.0"
ifconfig_fxp0_alias0="inet 69.55.229.3 netmask 255.255.255.255"
ifconfig_fxp1="inet 10.1.2.1 netmask 255.255.255.0"
defaultrouter="10.1.6.1"
#defaultrouter=" 66.181.14.250"
snmpd_enable="YES"
ipnat_enable="YES"
ipnat_rules="/etc/ipnat.rules"
gateway_enable="YES"

inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.1"
fsck_y_enable="YES"
background_fsck="NO"
sshd_enable="YES"
  • reboot. Confirm new kernel is loaded
uname -a
  • update ports:
cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup

cvsup sup; mail -s 'cvs sup ports done' dave.boodman@vtext.com < /dev/null
  • Install raid mgmt tool
cd /usr/local/sbin
fetch http://3ware.com/download/Escalade9690SA-Series/9.5.3/tw_cli-freebsd-x86-9.5.3.tgz
tar xzf tw_cli-freebsd-x86-9.5.3.tgz
rm tw_cli-freebsd-x86-9.5.3.tgz
chmod 0700 tw_cli

Test:

./tw_cli info c0
  • install rsync from ports
cd /usr/ports/net/rsync
make install clean

choose default options

  • install perl from ports
cd /usr/ports/lang/perl5.8
make install clean
  • install screen from ports
cd /usr/ports/sysutils/screen
make install clean
  • install bb client
adduser
Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]: 
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username   : bb
Password   : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups     : bb
Home       : /home/bb
Shell      : /bin/sh
Locked     : no
OK? (yes/no): yes

cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
tar xvf bb-freebsd.tar

edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:

echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.1 nat2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
vi /home/bb/bbc1.9e-btf/ext/openfiles 
MACHINE="nat2,johncompanies,com"      # HAS TO BE IN A,B,C FORM

cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh 
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..

vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$

./runbb.sh start
more BBOUT 
(look for errors)
exit

echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh

Punch a hole in the firewall to allow it to communicate with bb monitor (probably already exists):

ipfw add 96 allow ip from 66.181.18.0/27 to 69.55.230.2
  • configure bb on mail:
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
64.163.14.48 nat2.johncompanies.com # ssh

su bb
cd
bbsrc/bb/runbb.sh restart ; exit
  • configure ntp
echo "server 69.55.230.2
server 0.pool.ntp.org
server 1.pool.ntp.org
server 2.pool.ntp.org
server 3.pool.ntp.org
server 66.187.233.4
server 217.204.76.170
server 64.112.189.11
server 66.69.112.130
server 80.85.129.25
server 80.237.234.15
server 130.60.7.44
server 134.99.176.3
server 198.144.202.250
server 202.74.170.194
server 204.17.42.199
server 204.87.183.6
server 213.15.3.1
server 213.239.178.33
server 217.114.97.97
server 69.55.230.2" > /etc/ntp.conf
/usr/sbin/ntpd -A -p /var/run/ntpd.pid 
sleep 2; ntpq -p

(confirm it’s able to reach our time server)

echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh
  • fwd and reverse lookups on ns1c
vr johncompanies.com
(edit the PTR too)
  • setup backups, nfs mount
mkdir /backup3
echo 'backup3:/data           /backup3        nfs     rw,bg           0       0' >> /etc/fstab

echo '#\!/bin/sh\
backupdir=/data/nat2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config

on backup3: setup backup dirs:

ssh backup3 mkdir -p /data/nat2/current

on backup3, add the system to

vi /usr/local/sbin/snapshot_archive
scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup 
vi /usr/local/etc/rsync.backup 
backup1 > backup3
crontab -e
1 0 * * * /usr/local/etc/rsync.backup
  • edit sshd_config for security
vi /etc/ssh/sshd_config
ListenAddress 66.181.18.1
ListenAddress 69.55.229.2
ListenAddress 10.1.2.1

kill -1 `cat /var/run/sshd.pid`
  • raid chk
cat > /usr/local/sbin/lsiraidchk
#!/usr/bin/perl

my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;

foreach (@out) {
    if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#print $_;
}
  • netflow stuff

add crontab entries

crontab -e
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl; 
*/5 * * * * /usr/local/sbin/lsiraidchk

#10 0 * * * rm /var/spool/clientmqueue/*
scp /etc/makefwrules.pl user@64.163.14.48:~
scp /etc/makepiperules.pl user@64.163.14.48:~
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
mkdir /etc/oldrules/

other binaries

scp /usr/local/bin/rulemaker user@64.163.14.48:~
mv ~user/rulemaker /usr/local/sbin
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~
  • add nat rules
vi /etc/ipnat.rules
# sample entry
bimap fxp0 10.1.6.70/32 -> 10.1.6.59/32
#bimap fxp0 10.1.4.208/32 -> 69.55.233.196/32

ipnat -C -f /etc/ipnat.rules
  • shell for user
cp /root/.cshrc ~user/
vi ~user/

change # to $

  • mrtg
cd /usr/ports/net-mgmt/mrtg
make install clean

(no FONTCONFIG, v3)

this didn't work cause of libtool incompat

so manually moved files:

scp /usr/local/bin/cfgmaker user@nat2:/usr/local/bin/cfgmaker
scp /usr/local/lib/perl5/site_perl/5.6.1/MRTG_lib.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
scp /usr/local/lib/perl5/site_perl/5.6.1/SNMP_util.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
scp /usr/local/lib/perl5/site_perl/5.6.1/BER.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
scp /usr/local/lib/perl5/site_perl/5.6.1/SNMP_Session.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/
scp /usr/local/bin/mrtg root@nat2:/usr/local/bin/mrtg
scp /usr/local/lib/perl5/site_perl/5.6.1/locales_mrtg.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/locales_mrtg.pm
scp /usr/local/bin/rrdtool root@nat2:/usr/local/bin/rrdtool
scp /usr/local/lib/perl5/site_perl/5.6.1/mach/RRDs.pm root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/mach/RRDs.pm
rsync -av /usr/local/lib/perl5/site_perl/5.6.1/mach/auto/RRDs/ root@nat2:/usr/local/lib/perl5/site_perl/5.8.9/mach/auto/RRDs/
scp /usr/lib/libz.so.2 root@nat2:/usr/lib/libz.so.2
scp /usr/lib/libm.so.2 root@nat2:/usr/lib/libm.so.2
rsync -av /usr/local/lib/librrd* root@nat2:/usr/local/lib/
scp /usr/lib/libc.so.4 root@nat2:/usr/lib/libc.so.4

rsync -av /usr/ports/net/rrdtool root@nat2:/usr/ports/net
cd /usr/ports/net/rrdtool
make install

mkdir -p /mnt/data1/mrtg/data
scp /usr/local/www/mgmt/mrtg/template.pl root@nat2:/mnt/data1/mrtg/
scp /usr/local/www/mgmt/mrtg/host.pl root@nat2:/mnt/data1/mrtg/

cfgmaker --if-template=template.pl --show-op-down --global "options[_]: growright,bits" --global 'WorkDir: /mnt/data1/mrtg/data' --global 'Interval: 1' --global 'LogFormat: rrdtool' --global 'PathAdd: /usr/local/bin' --global 'LibAdd: /usr/local/lib' --host-template=host.pl jc292401@10.1.2.50 --output=switch-p20.cfg

cat > /mnt/data1/mrtg/mrtg.sh
#!/bin/sh
/usr/local/bin/mrtg /mnt/data1/mrtg/switch-p20.cfg

chmod 0700 /mnt/data1/mrtg/mrtg.sh

crontab -e
* * * * * /mnt/data1/mrtg/mrtg.sh 2>&1 > /dev/null
  • snmp firewall block
cat > /usr/local/etc/rc.d/boot.sh
ipfw add 10 allow udp from 69.55.230.2 to any 161
ipfw add 10 allow udp from 10.1.2.1 to any 161
ipfw add 11 deny udp from any to any 161
chmod 0700 /usr/local/etc/rc.d/boot.sh

bwdb[edit]

Summary[edit]

This machine tracks and stores network traffic (netflow) at castle. It is our means to monitor customer bandwidth usage.

  • Location: castle, cab 3-7
  • OS: FreeBSD 4.10 x86
  • Networking: Priv IP: 10.1.4.203 There are 2 onboard nic's, one of which is the "listener"
  • Hardware: Custom 1U. Single power supply.
  • Drives: one 250 GB (2 x 250GB) RAID1 array running on a Promise IDE RAID card.

Services Provided[edit]

  • netflow
  • mysql
  • bigbrother
  • snmp

netflow[edit]

The main function of this server is to run netflow on an eth device in promiscuous mode so as to hear everything happening on the port (wherein all network traffic is mirrored to that port via the cisco swith). Every 15min, it creates a flow file under /usr/home/flows/ (organized by date). The flow file contains all traffic data for a 15min increment of time.

A cronjob moves that flow file (or files if there are multiple due to some delay)

1,16,31,46 * * * * /usr/home/flowbin/queue.pl

into a processing queue: /usr/home/working

Then a separate file processes whatever flow files it finds there, inserting the data into the local mysql database:

2,17,32,47 * * * * /usr/home/flowbin/processflows.pl

mysql[edit]

The database storing all the traffic data is named traffic Tables:

mysql> show tables;
+---------------------------+
| Tables_in_traffic         |
+---------------------------+
| dailyIpTotals_69_55_224   |
| dailyIpTotals_69_55_225   |
| dailyIpTotals_69_55_226   |
| dailyIpTotals_69_55_227   |
| dailyIpTotals_69_55_228   |
| dailyIpTotals_69_55_229   |
| dailyIpTotals_69_55_230   |
| dailyIpTotals_69_55_231   |
| dailyIpTotals_69_55_232   |
| dailyIpTotals_69_55_233   |
| dailyIpTotals_69_55_234   |
| dailyIpTotals_69_55_235   |
| dailyIpTotals_69_55_236   |
| dailyIpTotals_69_55_237   |
| dailyIpTotals_69_55_238   |
| dailyIpTotals_69_55_239   |
| dailyPortTotals_69_55_224 |
| dailyPortTotals_69_55_225 |
| dailyPortTotals_69_55_226 |
| dailyPortTotals_69_55_227 |
| dailyPortTotals_69_55_228 |
| dailyPortTotals_69_55_229 |
| dailyPortTotals_69_55_230 |
| dailyPortTotals_69_55_231 |
| dailyPortTotals_69_55_232 |
| dailyPortTotals_69_55_233 |
| dailyPortTotals_69_55_234 |
| dailyPortTotals_69_55_235 |
| dailyPortTotals_69_55_236 |
| dailyPortTotals_69_55_237 |
| dailyPortTotals_69_55_238 |
| dailyPortTotals_69_55_239 |
| ipTotals_69_55_224        |
| ipTotals_69_55_225        |
| ipTotals_69_55_226        |
| ipTotals_69_55_227        |
| ipTotals_69_55_228        |
| ipTotals_69_55_229        |
| ipTotals_69_55_230        |
| ipTotals_69_55_231        |
| ipTotals_69_55_232        |
| ipTotals_69_55_233        |
| ipTotals_69_55_234        |
| ipTotals_69_55_235        |
| ipTotals_69_55_236        |
| ipTotals_69_55_237        |
| ipTotals_69_55_238        |
| ipTotals_69_55_239        |
| portTotals_69_55_224      |
| portTotals_69_55_225      |
| portTotals_69_55_226      |
| portTotals_69_55_227      |
| portTotals_69_55_228      |
| portTotals_69_55_229      |
| portTotals_69_55_230      |
| portTotals_69_55_231      |
| portTotals_69_55_232      |
| portTotals_69_55_233      |
| portTotals_69_55_234      |
| portTotals_69_55_235      |
| portTotals_69_55_236      |
| portTotals_69_55_237      |
| portTotals_69_55_238      |
| portTotals_69_55_239      |
+---------------------------+

So as you see we store each class-C block in its own table, for efficiency. Further, we store and organize data in 4 ways: "daily" tables and 15-minute granularity tables, and for each of those we track simple IP traffic and port-specific traffic. The daily tables contains 2 entries (one for each direction) for each IP for each day. For the current day, the row data is incremented as the day goes on.

mysql> describe dailyIpTotals_69_55_224;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| id        | varchar(23) |      | PRI |         |       |
| date      | date        | YES  |     | NULL    |       |
| ip        | varchar(15) | YES  | MUL | NULL    |       |
| direction | tinyint(1)  | YES  |     | NULL    |       |
| octets    | bigint(12)  | YES  |     | NULL    |       |
| packets   | int(11)     | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+

mysql> select * from dailyIpTotals_69_55_224 limit 1\G
*************************** 1. row ***************************
       id: 6955224194-20100917-1
     date: 2010-09-17
       ip: 69.55.224.194
direction: 1
   octets: 8821
  packets: 91

The id is a unique identifier (key), direction indicates incoming or outgoing traffic (outbound = 2, inbound = 1), octets are the amount of traffic in kilobytes, and packets is the total number of packets.

The 15-minute table has similar information, but it's organized in 15 minute increments:

mysql> describe ipTotals_69_55_224;
+-----------+------------+------+-----+---------+-------+
| Field     | Type       | Null | Key | Default | Extra |
+-----------+------------+------+-----+---------+-------+
| date      | datetime   | YES  |     | NULL    |       |
| ip        | char(15)   | YES  | MUL | NULL    |       |
| direction | tinyint(1) | YES  |     | NULL    |       |
| octets    | bigint(20) | YES  |     | NULL    |       |
| packets   | int(11)    | YES  |     | NULL    |       |
+-----------+------------+------+-----+---------+-------+

mysql> select * from ipTotals_69_55_224 limit 2\G
*************************** 1. row ***************************
     date: 2010-01-11 19:30:00
       ip: 69.55.224.13
direction: 1
   octets: 288
  packets: 6
*************************** 2. row ***************************
     date: 2010-01-11 19:30:00
       ip: 69.55.224.12
direction: 1
   octets: 216
  packets: 4

So for a given IP, there will be 192 rows in a given day: 4 rows per hour, *2 for 2 directions, *24 for 24hours in a day. Obviously this table is large which is why we broke it down into a daily table for quick, easy, daily-summary access.

That covers the simple traffic tabulation tables. We also track traffic by port:

mysql> describe dailyPortTotals_69_55_224;
+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| id        | varchar(28) |      | PRI |         |       |
| date      | date        | YES  |     | NULL    |       |
| ip        | varchar(15) | YES  | MUL | NULL    |       |
| direction | tinyint(1)  | YES  |     | NULL    |       |
| protocol  | smallint(3) | YES  |     | NULL    |       |
| port      | int(11)     | YES  |     | NULL    |       |
| octets    | bigint(11)  | YES  |     | NULL    |       |
| packets   | int(11)     | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
8 rows in set (0.00 sec)

mysql> select * from dailyPortTotals_69_55_224 limit 1\G
*************************** 1. row ***************************
       id: 695522496-20091218-1-6-23
     date: 2009-12-18
       ip: 69.55.224.96
direction: 1
 protocol: 6
     port: 23
   octets: 1796
  packets: 30

mysql> select * from portTotals_69_55_224 limit 1\G
*************************** 1. row ***************************
     date: 2010-09-07 18:45:00
       ip: 69.55.224.254
direction: 1
 protocol: 6
     port: 99999
   octets: 144
  packets: 3

This is largely the same with 2 more additions: protocol (1=ICMP, 6=TCP, 17=UDP), and port which we set to 99999 if the traffic is return traffic and the port is above 1024. Obviously the potential for number of rows grows quickly when you consider the addition of port and protocol tracking per IP.

Regular maintenance[edit]

archive_daily.pl 2012 09

This will archive data for the given year and month from the daily summary tables. Generally we want to have a year of history in the database.

archive_15min.pl 2012 09

This will archive data for the given year and month from the 15min-increment tables. Generally, we want to have 6 months of history in the database.

  • if space becomes tight, move flow files and exported data to a backup server, both located in /usr/home/flowbin/archive and /usr/home/exported, respectively

Slaving[edit]

If we were going to setup traffic database slaving (we don't do this anymore), perhaps cause the bwdb machine gets busy and it cannot handle traffic requests and netflow, here's how it's done:

On the traffic master:

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'10.1.4.8' IDENTIFIED BY 'qERUG8wf';

in my.cnf:

bin-log
server-id=1
max_binlog_size=500M
expire_logs_days = 3

on slave: in my.cnf:

server-id       = 2
master-host     =   10.1.4.203
master-user     =   repl
master-password =   qERUG8wf
master-connect-retry=60
replicate-wild-do-table=traffic.daily%
max_relay_log_size=500M
expire_logs_days = 3

replicate-wild-do-table=traffic.%

on master:

touch /usr/home/working/.lock

(make sure processflows not running)

FLUSH TABLES WITH READ LOCK;
cd /usr/home/database/traffic
tar -czf mysql-traffic-snapshot.tgz ./daily*
(~1G)
SHOW MASTER STATUS;
+-----------------+-----------+--------------+------------------+
| File            | Position  | Binlog_Do_DB | Binlog_Ignore_DB |
+-----------------+-----------+--------------+------------------+
| bwdb-bin.000039 | 154432615 |              |                  |
+-----------------+-----------+--------------+------------------+

(write down info)
UNLOCK TABLES;
scp mysql-traffic-snapshot.tgz 10.1.4.5:/mnt/data1/db/mysql/traffic/

on slave:

mkdir /mnt/data1/db/mysql/traffic
cd /mnt/data1/db/mysql/traffic/
tar xzvf mysql-traffic-snapshot.tgz
(restart mysql)
CHANGE MASTER TO MASTER_HOST='10.1.4.203',MASTER_USER='repl',MASTER_PASSWORD='qERUG8wf',MASTER_LOG_FILE='bwdb-bin.000059',MASTER_LOG_POS=482502186;
START SLAVE;
cd /usr/home/database/traffic
scp *
optimize table dailyPortTotals_69_55_224;
optimize table dailyPortTotals_69_55_225;
optimize table dailyPortTotals_69_55_226;
optimize table dailyPortTotals_69_55_227;
optimize table dailyPortTotals_69_55_228;
optimize table dailyPortTotals_69_55_229;
optimize table dailyPortTotals_69_55_230;
optimize table dailyPortTotals_69_55_231;
optimize table dailyPortTotals_69_55_232;
optimize table dailyPortTotals_69_55_233;
optimize table dailyPortTotals_69_55_234;
optimize table dailyPortTotals_69_55_235;
optimize table dailyPortTotals_69_55_236;
optimize table dailyPortTotals_69_55_237;
optimize table dailyPortTotals_69_55_238;
optimize table dailyPortTotals_69_55_239;

Build[edit]

BIOS Config[edit]

disable quiet boot

set to last state after power loss

set date/time to GMT

enable serial console output (baud rate 115200)

Install OS[edit]

Install FreeBSD 8.3 amd64

  • partition map:
/ 500m
swap 4096m
/var 256m
/tmp 256m
/usr ~
  • edit /etc/make.conf

Castle:

echo "WITHOUT_X11=yes \
KERNCONF=bwdb \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf

i2b:

echo "WITHOUT_X11=yes \
KERNCONF=bwdb2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf
  • add settings to /boot/loader.conf and /boot.config
echo "-Dh" >> /boot.config

echo 'console="comconsole,vidconsole" \
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf
  • turn off all ttyv's except 0 and 1 in /etc/ttys

also turn on ttyu0, change type to vt100:

vi /etc/ttys

ttyv2   "/usr/libexec/getty Pc"         cons25  off secure
ttyv3   "/usr/libexec/getty Pc"         cons25  off secure
ttyv4   "/usr/libexec/getty Pc"         cons25  off secure
ttyv5   "/usr/libexec/getty Pc"         cons25  off secure
ttyv6   "/usr/libexec/getty Pc"         cons25  off secure
ttyv7   "/usr/libexec/getty Pc"         cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyu0   "/usr/libexec/getty std.9600"   vt100   on secure

kill -1 1

on console server:

vi /etc/remote

(rename port to jail8 depending on where and which digi plugged into) test serial console


  • populate hosts

i2b:

echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts

castle:

echo "10.1.4.3 backup2 backup2.johncompanies.com" >> /etc/hosts
echo "10.1.4.8 backup1 backup1.johncompanies.com" >> /etc/hosts
echo "10.1.4.4 mail mail.johncompanies.com" >> /etc/hosts
  • put key in authorized_keys on backup1 and backup2
cd
ssh-keygen -t dsa -b 1024 

(default location, leave password blank)

castle:

cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 

i2b:

cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys' 

confirm that you can ssh to backup2 and backup1 (and backup3 if at i2b) without getting a login prompt

ssh backup1 hostname
ssh backup2 hostname
  • edit root's path and login script:
vi /root/.cshrc

Change alias entries (add G):

alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG

and alter the prompt, set the following:

set prompt = "`/bin/hostname -s` %/# "
  • install cvsup
cd /usr/ports/net/cvsup-without-gui 
make install clean; rehash; mail -s 'cvs installed' support@johncompanies.com < /dev/null
  • get latest sources for this release:
cd /usr/src 
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_8_3\
*default delete use-rel-suffix\
*default compress\
src-all" > sup

cvsup sup ; mail -s 'cvs sup done' support@johncompanies.com < /dev/null
  • configure new kernel
cd /usr/src/sys/amd64/conf 
scp backup2:/mnt/data4/build/freebsd/kern_config-bwdb-8.3-amd64 ./bwdb

Edit config and change name:

vi bwdb
ident  bwdb
  • build, install kernel and world
cd /boot

mv kernel kernel.GENERIC
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel

make buildworld ; mail -s 'buildworld done' support@johncompanies.com < /dev/null
(2450: 1:56min, supermicro: 59mins, 2950: 38mins)
make installworld 
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i
  • populate /etc/rc.conf with IPs and NFS settings

castle:

vi /etc/rc.conf

hostname="bwdb.johncompanies.com"
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"

xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
ifconfig_fxp0="inet 10.1.4.203 netmask 255.255.255.0"
ifconfig_em0="up promisc"
defaultrouter="10.1.4.1"
snmpd_enable="YES"

inetd_enable="YES"
inetd_flags="-wW -a 10.1.4.203"
fsck_y_enable="YES"
background_fsck="NO"
sshd_enable="YES"
ipfw_load="YES"

i2b:

vi /etc/rc.conf

hostname="bwdb2.johncompanies.com"
kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"

xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
ifconfig_fxp0="inet 10.1.2.4 netmask 255.255.255.0"
ifconfig_em0="up promisc"
defaultrouter="10.1.2.1"
snmpd_enable="YES"

inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.4"
fsck_y_enable="YES"
background_fsck="NO"
sshd_enable="YES"
ipfw_load="YES"
  • reboot. Confirm new kernel is loaded
uname -a
  • update ports:
cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_8_3\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup

cvsup sup; mail -s 'cvs sup ports done' support@johncompanies.com < /dev/null
  • Install raid mgmt tool
cd /usr/local/sbin
scp backup2:/d4/build/3ware/tw_cli-freebsd-x86_64-9.5.0.1.tgz .
tar xzf tw_cli-freebsd-x86_64-9.5.0.1.tgz
rm tw_cli-freebsd-x86_64-9.5.0.1.tgz
chmod 0700 tw_cli

Test:

./tw_cli info c0

Grab raid check script:

scp backup1:/usr/local/sbin/3wraidchk /usr/local/etc

Setup cronjob:

crontab -e
*/5 * * * * /usr/local/etc/3wraidchk
  • install rsync from ports
cd /usr/ports/net/rsync
make install clean

choose default options

  • install perl from ports
cd /usr/ports/lang/perl5.8
make install clean

choose default options

  • install bb client

Compiling from source on AMD64 will not work. So, we use a linux-compiled version and rely on linux compat. Linux compat won't install on 8.x - libtool 2.4 need. So, instead we copy(ed) over linux:

rsync -aSHv --exclude=proc --exclude=sys 10.1.4.108:/usr/compat/linux/ /usr/compat/linux/
adduser

Output/response:

Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]: 
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username   : bb
Password   : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups     : bb
Home       : /home/bb
Shell      : /bin/sh
Locked     : no
OK? (yes/no): yes
cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd_linuxcompat.tgz .
tar xzf bb-freebsd_linuxcompat.tgz

edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:

echo "10.1.4.5 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.4.203 bwdb.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts

Edit for machine name and private IP.

if this machine is at i2b:

echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.4 bwdb2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
vi /home/bb/bbc1.9e-btf/ext/openfiles 

MACHINE="bwdb,johncompanies,com"      # HAS TO BE IN A,B,C FORM

Edit for machine name.

Have bb watch for flow-capture, mysql

cat >> /home/bb/bbc1.9e-btf/etc/bb-proctab
localhost: flow-capture :
localhost: mysqld :


cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh 
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf
./runbb.sh start
more BBOUT 
(look for errors)
exit

Put in script to start bb @ boot:

echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh


If this is at i2b, punch a hole in the firewall to allow it to communicate with bb monitor:

ipfw add 00096 allow tcp from 66.181.18.0/27 to 69.55.230.2


  • configure bb on mail
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
10.1.4.203 bwdb.johncompanies.com # ssh

su bb
cd
bbsrc/bb/runbb.sh restart ; exit
  • configure ntp server

Castle:

echo "server 10.1.4.1" > /etc/ntp.conf

I2b:

echo "server 10.1.2.1" > /etc/ntp.conf
/usr/sbin/ntpd -p /var/run/ntpd.pid
sleep 2; ntpq -p

(confirm it’s able to reach our time server)

echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh
  • fwd and reverse lookups on ns1c

vr johncompanies.com

(edit the PTR too)
  • setup backups
echo '#\!/bin/sh\
backupdir=/data/bwdb/current\
server=backup1\
\
## ENTRY /etc\
## ENTRY /usr/home/flowbin\
## ENTRY /usr/home/database' > /usr/local/etc/backup.config

Castle: setup backup dirs:

ssh backup1 mkdir -p /data/bwdb/current

on backup1, add the system to

vi /usr/local/sbin/snapshot_rotate

I2b: setup backup dirs:

ssh backup3 mkdir -p /data/bwdb/current

on backup3, add the system to

vi /usr/local/sbin/snapshot_archive


Copy over the backup script:

scp backup2:/d4/bin/freebsd8.x/rsync.backup /usr/local/etc/

Edit rsync.backup and change config var to point to correct config file location: /usr/local/etc/backup.config

crontab -e
5 0 * * * /usr/local/etc/rsync.backup
  • make /root/logs
mkdir /root/logs
  • edit sshd_config for security
vi /etc/ssh/sshd_config
ListenAddress 10.1.4.203
PermitRootLogin yes

kill -1 `cat /var/run/sshd.pid`

Edit for private IP.

  • snmp

(Before doing this you may need to take down the firewall and also add to resolv.conf 69.43.143.41)

cd /usr/ports/net-mgmt/net-snmp
make install clean
(defaults)

cat >> /etc/rc.conf
snmpd_enable="YES"
snmpd_flags="-a"
snmpd_conffile="/usr/local/share/snmp/snmpd.conf"
snmptrapd_enable="YES"
snmptrapd_flags="-a -p /var/run/snmptrapd.pid"

cat > /usr/local/share/snmp/snmpd.conf
rocommunity  jcread 10.1.4.5
rocommunity  jcread 10.1.4.202

netflow[edit]

Install flow tools:

cd /usr/ports/net-mgmt/flow-tools
make install clean

Defaults.

mkdir /usr/home/flows

Flow start script:

echo "/usr/local/bin/flow-capture -w /usr/home/flows -S5 -N -2 0/10.1.4.203/4444" > /usr/local/etc/rc.d/flow-capture.sh
chmod 0700 /usr/local/etc/rc.d/flow-capture.sh

Edit for private IP.

Netgraph start script:

cat > /usr/local/etc/rc.d/netgraph.sh

/usr/sbin/ngctl -f- <<-SEQ
mkpeer em0: netflow lower iface0
name em0:lower netflow
connect em0: netflow: upper out0
mkpeer netflow: ksocket export inet/dgram/udp
msg netflow:export connect inet/10.1.4.203:4444
SEQ

#/usr/sbin/ngctl -f- <<-SEQ
#shutdown netflow:
#SEQ

chmod 0700 /usr/local/etc/rc.d/netgraph.sh

Edit for private IP.

Confirm netflow is running after running scripts:

newbwdb /usr/ports/net-mgmt/flow-tools# /usr/sbin/ngctl
Available commands:
  config     get or set configuration of node at <path>
  connect    Connects hook <peerhook> of the node at <relpath> to <hook>
  debug      Get/set debugging verbosity level
  dot        Produce a GraphViz (.dot) of the entire netgraph.
  help       Show command summary or get more help on a specific command
  list       Show information about all nodes
  mkpeer     Create and connect a new node to the node at "path"
  msg        Send a netgraph control message to the node at "path"
  name       Assign name <name> to the node at <path>
  read       Read and execute commands from a file
  rmhook     Disconnect hook "hook" of the node at "path"
  show       Show information about the node at <path>
  shutdown   Shutdown the node at <path>
  status     Get human readable status information from the node at <path>
  types      Show information about all installed node types
  write      Send a data packet down the hook named by "hook".
  quit       Exit program
+ show netflow:
  Name: netflow         Type: netflow         ID: 00000004   Num hooks: 3
  Local hook      Peer name       Peer type    Peer ID         Peer hook
  ----------      ---------       ---------    -------         ---------
  export          <unnamed>       ksocket      00000005        inet/dgram/udp
  out0            em0             ether        00000001        upper
  iface0          em0             ether        00000001        lower
+

We notice that sometimes flow-capture is failing due to swap exhaustion (even after adding more swap). So we crontab flow-capture to restart (it's ok to start if it's already running, it just quits):

crontab -e
#restart flow-capture
*/15 * * * * /usr/local/etc/rc.d/flow-capture.sh

process flow tools[edit]

mkdir /usr/home/flowbin
mkdir /usr/home/working

Install modules:

cd /usr/ports/devel/p5-Date-Calc
make install clean
cd /usr/ports/mail/p5-Mail-Sendmail
make install clean

Queue script:

cat > /usr/home/flowbin/queue.pl
#!/usr/bin/perl

use strict;

BEGIN {
    push @INC, "/usr/home/flowbin";
}

use date;

my $flowbase = "/usr/home/flows";
#my $flowqueue = "/usr/home/queue";
my $flowqueue = "/usr/home/working";

my ($date, $time) = date::CurrentDateTime();

my $flowdir = mkFlowDir($date);
`mv $flowdir/ft-* $flowqueue`;

if (date::DateWindow($date, $time, $date, "00:00:00", 600)) {
    my $newdate = date::AddDays($date, -1);
    my $flowdir = mkFlowDir($newdate);
    `mv $flowdir/ft-* $flowqueue`;
}

sub mkFlowDir {
    my $date = shift;
    $date =~ /([0-9]{4}-[0-9]{2})/;
    my $yearmonth = $1;
    return "$flowbase/$yearmonth/$date";
}

Date.pm module:

cat > /usr/home/flowbin/date.pm
#!/usr/local/bin/perl
#
# $Header: /usr/cvs/newgw/lib/date.pm,v 1.2 2003/11/24 17:06:02 glenn Exp $
#
# Copyright (c) 2001, 2002, 2003
#      e-Monitoring Networks, Inc.  All rights reserved.
#
#
#
# date.pl - Higher level functions written on top of Date::Calc

package date;

use strict;
use Date::Calc qw(:all);

sub DayDiff { #calculate the difference in days from two dates
    my $date1 = shift;
    my $date2 = shift;
    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my $diff = &Delta_Days($year1, $month1, $day1, $year2, $month2, $day2);
    return $diff;
}

sub AddDays { #adds specified number of days to the supplied date
    my $date = shift;
    my $days = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($nyear, $nmonth, $nday) = &Add_Delta_Days($year, $month, $day, $days);
    my $ndate = &ymdToDate($nyear, $nmonth, $nday);
    return $ndate;
}

sub AddHours { #adds specified number of hours to the supplied date and time
    my $date = shift;
    my $time = shift;
    my $addhours = shift;
    my $adddays = 0;
    if (abs($addhours / 24) >= 1) {
        $adddays = int($addhours / 24);
        $addhours -= $adddays * 24;
    }
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($ny, $nm, $nd, $nh, $nmin, $ns) = &Add_Delta_DHMS($year, $month, $day,
                                                          $hour, $minute, $second,
                                                          $adddays, $addhours, 0, 0);
    my $ndate = &ymdToDate($ny, $nm, $nd);
    my $ntime = &hmsToTime($nh, $nmin, $ns);
    return $ndate, $ntime;
}

sub AddMinutes {
    my $date = shift;
    my $time = shift;
    my $minutes = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($ny, $nm, $nd, $nh, $nmin, $ns) = &Add_Delta_DHMS($year, $month, $day,
                                                          $hour, $minute, $second,
                                                          0, 0, $minutes, 0);
    my $ndate = &ymdToDate($ny, $nm, $nd);
    my $ntime = &hmsToTime($nh, $nmin, $ns);
    return $ndate, $ntime;
}

sub CurrentDateTime { #return the current date and time
    my ($y, $m, $d, $h, $min, $s, $z, $z, $z) = &System_Clock;
    my $date = &ymdToDate($y, $m, $d);
    my $time = &hmsToTime($h, $min, $s);
    return $date, $time;
}

sub Currentymd { #return the current year, month and day as separate variables
    my ($y, $m, $d, $h, $min, $s, $z, $z, $z) = &System_Clock;
    return $y, $m, $d;
}

sub DateToymd { #takes a date and returns year, month, day as individual values
    my $date = shift;
    if ($date =~ /([0-9]{4})-([0-9]{2})-([0-9]{2})/) {
        my $day = $3;
        my $month = $2;
        my $year = $1;
        return $year, $month, $day;
    }
    return undef;
}

sub TimeTohms { #takes a time and return hours minutes and seconds as individual values
    my $time = shift;
    if ($time =~ /([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/) {
        my $hour = $1;
        my $minute = $2;
        my $second = $3;
        if ($hour !~ /[0-9]{2}/) { $hour = "0$hour"; }
        if ($minute !~ /[0-9]{2}/) { $minute = "0$minute"; }
        if ($second !~ /[0-9]{2}/) { $second = "0$second"; }
        return $hour, $minute, $second;
    }
    return undef;
}

sub ymdToDate { #takes year, month, day and assembles them into our date format
    my $year = shift;
    my $month = shift;
    my $day = shift;
    if (defined($year) && defined($month) && defined ($day)) {
        $month = sprintf("%02d", $month);
        $day = sprintf("%02d", $day);
        return "$year-$month-$day";
    }
    return undef;
}

sub hmsToTime { #takes hour minute and second and assembles them into our time format
    my $hour = shift;
    my $minute = shift;
    my $second = shift;
    if (defined($hour) && defined($minute) && defined ($second)) {
        if ($hour !~ /[0-9]{2}/) { $hour = "0$hour"; }
        if ($minute !~ /[0-9]{2}/) { $minute = "0$minute"; }
        if ($second !~ /[0-9]{2}/) { $second = "0$second"; }
        return sprintf ("%02d:%02d:%02d", $hour, $minute, $second);
    }
    return undef;
}

sub CompareDates { #compares two date and time pairs
    my $date1 = shift;
    my $time1 = shift;
    my $date2 = shift;
    my $time2 = shift;

    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($hour1, $minute1, $second1) = &TimeTohms($time1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my ($hour2, $minute2, $second2) = &TimeTohms($time2);

#    &debug("$year1, $month1, $day1, $year2, $month2, $day2");
    my $days = &Delta_Days($year1, $month1, $day1, $year2, $month2, $day2);
    if ($days > 0) { return 1;}
    if ($days < 0) { return -1;}
    if ($days == 0) { #same day, compare times
        my $seconds1 = $second1 + (60 * $minute1) + (3600 * $hour1);
        my $seconds2 = $second2 + (60 * $minute2) + (3600 * $hour2);
        if ($seconds1 < $seconds2) { return 1;}
        if ($seconds1 > $seconds2) { return -1;}
        if ($seconds1 == $seconds2) { return 0;}
    }
    return undef;
}

sub DateWindow { #compares two date time pairs to see if they are < X seconds apart
    my $date1 = shift;
    my $time1 = shift;
    my $date2 = shift;
    my $time2 = shift;
    my $window = shift;

    my ($year1, $month1, $day1) = &DateToymd($date1);
    my ($hour1, $minute1, $second1) = &TimeTohms($time1);
    my ($year2, $month2, $day2) = &DateToymd($date2);
    my ($hour2, $minute2, $second2) = &TimeTohms($time2);

    my ($day, $hour, $minute, $second) =
        &Delta_DHMS($year1, $month1, $day1, $hour1, $minute1, $second1,
                    $year2, $month2, $day2, $hour2, $minute2, $second2);
    $minute *= 60;
    $hour *= 3600;
    $day *= 86400;
    my $total = $second + $minute + $hour + $day;
    if (abs($total) < $window) {
        return 1;
    }
    return 0;
}

sub CheckDateOrder { #takes three dates/times, returns true if they are in chronological order
    my $date1 = shift;
    my $time1 = shift;
    my $date2 = shift;
    my $time2 = shift;
    my $date3 = shift;
    my $time3 = shift;
    if (&CompareDates($date1, $time1, $date2, $time2) == -1) {
        return 0;
    }
    if (&CompareDates($date2, $time2, $date3, $time3) == -1) {
        return 0;
    }
    return 1;
}

sub EpochSeconds { #calculates number of seconds since the epoch for the given date/time
    my $date = shift;
    my $time = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my ($hour, $minute, $second) = &TimeTohms($time);
    my ($d, $h, $m, $s) = &Delta_DHMS(1970, 1, 1, 0, 0, 0,
                                      $year, $month, $day, $hour, $minute, $second);
    my $seconds = $s + (60 * $m) + (3600 * $h) + (86400 * $d);
    return $seconds;
}

sub SecondsToDateTime { #converts seconds since epoch to date/time
    my $seconds = shift;
    my $days = int($seconds / 86400);
    $seconds -= $days * 86400;
    my $hours = int($seconds / 3600);
    $seconds -= $hours * 3600;
    my $minutes = int($seconds / 60);
    $seconds -= $minutes * 60;
    my ($year, $month, $day, $hour, $minute, $second) =
        &Add_Delta_DHMS(1970, 1, 1, 0, 0, 0, $days, $hours, $minutes, $seconds);
    $month = sprintf("%02d", $month);
    $day = sprintf("%02d", $day);
    $hour = sprintf("%02d", $hour);
    $minute = sprintf("%02d", $minute);
    $second = sprintf("%02d", $second);
    return "$year-$month-$day", "$hour:$minute:$second";
}

sub DateToDayName {
    my $date = shift;
    my ($year, $month, $day) = &DateToymd($date);
    my $name = &Day_of_Week_to_Text(&Day_of_Week($year, $month, $day));
    $name =~ /^[A-Za-z]{3}/;
    $name = $&;
    return $name;
}

sub ValiDate {
    return @_;



}

sub CheckBusinessDay { # checks to see if date is business day. 1=yes, 0=no
    my $date = shift;
    my ($year, $month, $day) = &DateToymd($date);
    if (Day_of_Week($year,$month,$day) < 6) { return 1; }
    else { return 0; }
}

1; #don't remove this line
chmod 0700 /usr/home/flowbin/queue.pl

Setup cronjob:

crontab -e
#move flow data into the queue
1,16,31,46 * * * * /usr/home/flowbin/queue.pl

flow processing: i2b[edit]

cat > /usr/home/flowbin/processflows-sql.pl
#!/usr/bin/perl

#use strict;
#$debug=1;
#$dry=1;

my $log = '/usr/home/flowbin/discards.log';

use Data::Dumper;

BEGIN {
    push @INC, "/usr/home/flowbin";
}

#my $queuedir = "/usr/home/queue";
my $queuedir = "/usr/home/working";
my $archivedir = "/usr/home/archive";
my $sqldir = "/usr/home/sql";
my $sqldirworking = "/usr/home/sql/tmp";

unless ($dry) {
    if (-e "$queuedir/.lock") {
        open(FILE, "$queuedir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $queuedir/.lock`;
        }
    }
    open(FILE, "> $queuedir/.lock");
    print FILE "$$\n";
    close(FILE);
}

opendir(DIR, $queuedir);
my @files = readdir(DIR);
closedir(DIR);

foreach my $file (sort @files) {
    unless($file =~ /^\./) {
        $file =~ /([0-9]{4}-[0-9]{2}-[0-9]{2})\.([0-9]{2})([0-9]{2})([0-9]{2})/;
        my $date = "$1 $2:$3:$4";
        my $outfile = "$1-$2:$3.sql";
        unless (open (SQL, "+> $sqldirworking/$outfile")) { die "cant open $sqldirworking/$outfile"; }
        my $condensedDate = $1;
        $condensedDate =~ s/-//g;
        my $iptotal = {};
        my $protototal = {};
        my $porttotal = {};

        &debug("started file $file at ");
        &debug(`date`);
        &debug("getting raw flow data (flow-print)");
        `cat $queuedir/$file | /usr/local/bin/flow-print -f 5 > /usr/home/working/tmp-$file`;
        &debug("aggregating data at ");
        &debug(`date`);
        unless (open(DATA, "/usr/home/working/tmp-$file")) { die "can't open: $!"; }
        LOOP: while (my $line = readline DATA) {
            my @d = split /[\s]+/, $line;
            if ($d[0] ne '' && $d[0] ne 'Start') {
                my $addr = 0;
                my $port = 0;

                #Start End Sif SrcIPaddress SrcP DIf DstIPaddress DstP P Fl Pkts Octets
                #0     1   2   3            4    5   6            7    8 9  10   11
                          #|
                          # outbound = 2, inbound = 1

                my (@src_ip) = split '\.', $d[3];
                my (@dst_ip) = split '\.', $d[6];

                if ($src_ip[0] == 69 && $src_ip[1] == 55 && ($src_ip[2] == 229 || $src_ip[2] == 231)) { # for i2b
                   $d[2] = 2;
                   # hack for outbound bulk traffic counted 2x
                   #if ($src_ip[2] == 231) { $d[11] /= 2; $d[10] /= 2; }
                }
                # note- this is where we filter out IPs only found at i2b
                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 && ($dst_ip[2] == 229 || $dst_ip[2] == 231)) { # for i2b
                   $d[2] = 1;
                }
                else { next LOOP; }

                if ($d[2] == 2) {
                    $addr = $d[3];
                    # if the dst-port is low, store that
                    if ($d[7] <= 1024) { $port = $d[7]; }
                    # if the src-port is low, store that
                    elsif ($d[4] <= 1024) { $port = $d[4]; }
                    else { $port = 99999; }
                }
                elsif ($d[2] == 1) {
                    $addr = $d[6];
                    # if the dst-port is high, assume its return traffic, try to store src-port if low
                    if ($d[7] > 1024) {
                        if ($d[4] <= 1024) { $port = $d[4]; }
                        else { $port = 99999; }
                    } else {
                        $port = $d[7];
                    }
                } else {
                    next LOOP;
                }

                my (@ip) = split '\.', $addr;
                unless ($ip[0] == 69) { next LOOP; }
                unless ($ip[1] == 55) { next LOOP; }
                unless ($ip[2] == 229 || $ip[2] == 231) { next LOOP; }

                my $classC = "$ip[0]_$ip[1]_$ip[2]";

#                          IP        dir
#                if ($d[10] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10]; }
#                if ($d[11] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11]; }
#
#                if ($d[10] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10]; }
#                if ($d[11] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11]; }
#
#                if ($d[10] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'pktTotal'} += $d[10]; }
#                if ($d[11] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'octetTotal'} += $d[11]; }
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10];
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11];

                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10];
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11];

                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'pktTotal'} += $d[10];
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'octetTotal'} += $d[11];
            }
        }
        close(DATA);
        `rm /usr/home/working/tmp-$file`;
        &debug("processing ip totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$iptotal})) {
            my @values;
            foreach my $ip (keys(%{$iptotal->{$classC}})) {
                foreach my $dir (keys(%{$iptotal->{$classC}->{$ip}})) {
                    my $octets = $iptotal->{$classC}->{$ip}->{$dir}->{'octetTotal'};
                    my $packets = $iptotal->{$classC}->{$ip}->{$dir}->{'pktTotal'};
#                    $packets = $packets > 2147483647 ? 0 : $packets;
                    if ($octets > 2147483647) {
                        my $ddir = $dir==1 ? 'in' : 'out';
                        #print SQL "$date $ip $ddir $octets\n";
#                        $octets = 0;
                    }
                    # dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                    my $id = "$ip-$condensedDate-$dir";
                    $id =~ s/\.//g;
                    push @values, "('$date', '$ip', $dir, $octets, $packets)";
                    my $sql = "insert into dailyIpTotals_$classC values ('$id', '$date', '$ip', $dir, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                    print "$sql\n" if $dry;
                    print SQL "$sql;\n";
#                    $db->query("insert into ipTotals values ('$date', '$ip', $dir, $octets, $packets)");
                }
            }

            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into ipTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                print SQL "$sql;\n";
            }
        }

#        &debug("processing protocol totals at ");
#        &debug(`date`);
#        foreach my $classC (keys(%{$protototal})) {
#            $db->query("lock tables dailyProtoTotals_$classC write") unless $dry;
#            my @values;
#            foreach my $ip (keys(%{$protototal->{$classC}})) {
#                foreach my $dir (keys(%{$protototal->{$classC}->{$ip}})) {
#                    foreach my $proto (keys(%{$protototal->{$classC}->{$ip}->{$dir}})) {
#                        my $octets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'octetTotal'};
#                        my $packets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'pktTotal'};
# #                        $octets = $octets > 2147483647 ? 0 : $octets;
# #                        $packets = $packets > 2147483647 ? 0 : $packets;
#                        # dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                        my $id = "$ip-$condensedDate-$dir-$proto";
#                        $id =~ s/\.//g;
#                        push @values, "('$date', '$ip', $dir, $proto, $octets, $packets)";
#                        my $sql = "insert into dailyProtoTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
#                        print "$sql\n" if $dry;
#                        $db->query($sql) unless $dry;
# #                        $db->query("insert into protoTotals values ('$date', '$ip', $dir, $proto, $octets, $packets)");
#                    }
#                }
#            }
#            $db->query("unlock tables") unless $dry;
#            my $sql = "insert into protoTotals_$classC values ";
#            $sql .= join ',', @values;
#            $db->query("lock tables protoTotals_$classC write") unless $dry;
#            print "$sql\n" if $dry;
#            $db->query($sql) unless $dry;
#            $db->query("unlock tables") unless $dry;
#        }

        &debug("processing port totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$porttotal})) {
            my @values;
            foreach my $ip (keys(%{$porttotal->{$classC}})) {
                foreach my $dir (keys(%{$porttotal->{$classC}->{$ip}})) {
                    foreach my $proto (keys(%{$porttotal->{$classC}->{$ip}->{$dir}})) {
                        foreach my $port (keys(%{$porttotal->{$classC}->{$ip}->{$dir}->{$proto}})) {
                            my $octets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'octetTotal'};
                            my $packets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'pktTotal'};
    #                        $octets = $octets > 2147483647 ? 0 : $octets;
    #                        $packets = $packets > 2147483647 ? 0 : $packets;

                            # dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-protocol-port
                            my $id = "$ip-$condensedDate-$dir-$proto-$port";
                            $id =~ s/\.//g;
                            push @values, "('$date', '$ip', $dir, $proto, $port, $octets, $packets)";
                            my $sql = "insert into dailyPortTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $port, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                            print "$sql\n" if $dry;
                            print SQL "$sql;\n";

    #                        $db->query("insert into portTotals values ('$date', '$ip', $dir, $port, $octets, $packets)");
                        }
                    }
                }
            }

            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into portTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                print SQL "$sql;\n";
            }
        }

#                       12     1 8      1    1= 23
# dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
#                       12        1  8     1   1       3=26
# dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                       12       1   8    1     1     5=28
# dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-port
        #print "finished at ";
        #print `date`;
        `mv $queuedir/$file $archivedir` unless $dry;
        close(SQL);
        `bzip2 $sqldirworking/$outfile`;
        `mv $sqldirworking/$outfile.bz2 $sqldir/`;
    }
}
`rm $queuedir/.lock` unless $dry;

sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}

# var full during ft-v05.2005-03-28.084500-0800 and
# 2005-02-24 69.55.226

# all port/daily totals before 2005-04-07

This script sends the sql files to the traffic server for processing:

cat > /usr/home/flowbin/sendsql.pl
#!/usr/bin/perl

#use strict;
#$debug=1;
#$dry=1;

my $remote = "69.55.233.199";
my $sqldir = "/usr/home/sql";
my $archive = "/usr/home/archive";
my $sqldirremote = "/data/bwdb2/pending/";
my @err;
unless ($dry) {
    if (-e "$sqldir/.lock") {
        open(FILE, "$sqldir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $sqldir/.lock`;
        }
    }
    open(FILE, "> $sqldir/.lock");
    print FILE "$$\n";
    close(FILE);
}

opendir(DIR, $sqldir);
my @files = readdir(DIR);
closedir(DIR);

foreach my $file (sort @files) {
   next unless $file =~ /bz2$/;

   my $r = `scp -Cq $sqldir/$file $remote:$sqldirremote 2>&1`;
#   print "scp $sqldir/$file $remote:$sqldirremote";
   unless ($?==0) {
      push @err, "scp -Cq $sqldir/$file $remote:$sqldirremote ($r)";
   }
   else {
      `mv $sqldir/$file $archive`;
      `ssh $remote mv $sqldirremote/$file $sqldirremote/${file}.done`;
   }
}

`rm $sqldir/.lock` unless $dry;

if (@err) {
   email_support('bwdb2: sendsql.pl error',join "\n", @err);
}

sub email_support {
    my $subj=shift;
    my $body=shift;
    use Mail::Sendmail;

    # prepare message
    my %mail = (
        To      => 'support@johncompanies.com,dave@johncompanies.com',
        From    => 'support@johncompanies.com',
        Subject => $subj,
        Message => $body,
        smtp    => 'mail.johncompanies.com',
    );
    sendmail(%mail) || warn "Error: $Mail::Sendmail::error";
}

sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}

# var full during ft-v05.2005-03-28.084500-0800 and
# 2005-02-24 69.55.226

# all port/daily totals before 2005-04-07
crontab -e
#process flows
2,17,32,47 * * * * /usr/home/flowbin/processflows-sql.pl
#move sql commands to traffic db
8,23,38,53 * * * * /usr/home/flowbin/sendsql.pl

flow processing: castle[edit]

cat > /usr/home/flowbin/processflows.pl

#!/usr/bin/perl

#use strict;
#$debug=1;
#$dry=1;

my $log = '/usr/home/flowbin/discards.log';

use Data::Dumper;

BEGIN {
    push @INC, "/usr/home/flowbin";
}

use db;

#my $queuedir = "/usr/home/queue";
my $queuedir = "/usr/home/working";
my $archivedir = "/usr/home/archive";

unless ($dry) {
    if (-e "$queuedir/.lock") {
        open(FILE, "$queuedir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $queuedir/.lock`;
        }
    }
    open(FILE, "> $queuedir/.lock");
    print FILE "$$\n";
    close(FILE);
}

my $db = db->new();
$db->connect('traffic', '', 'root', '5over3') || die $db->{'error'};

opendir(DIR, $queuedir);
my @files = readdir(DIR);
closedir(DIR);

foreach my $file (sort @files) {
    unless($file =~ /^\./) {
        $file =~ /([0-9]{4}-[0-9]{2}-[0-9]{2})\.([0-9]{2})([0-9]{2})([0-9]{2})/;
        my $date = "$1 $2:$3:$4";
        my $condensedDate = $1;
        $condensedDate =~ s/-//g;
        my $iptotal = {};
        my $protototal = {};
        my $porttotal = {};

        &debug("started file $file at ");
        &debug(`date`);
        &debug("getting raw flow data (flow-print)");
        `cat $queuedir/$file | /usr/local/bin/flow-print -f 5 > /usr/home/working/tmp-$file`;
        &debug("aggregating data at ");
        &debug(`date`);
        unless (open(DATA, "/usr/home/working/tmp-$file")) { die "can't open: $!"; }
        LOOP: while (my $line = readline DATA) {
            my @d = split /[\s]+/, $line;
            if ($d[0] ne '' && $d[0] ne 'Start') {
                my $addr = 0;
                my $port = 0;

                #Start End Sif SrcIPaddress SrcP DIf DstIPaddress DstP P Fl Pkts Octets
                #0     1   2   3            4    5   6            7    8 9  10   11
                          #|
                          # outbound = 2, inbound = 1

                my (@src_ip) = split '\.', $d[3];
                my (@dst_ip) = split '\.', $d[6];

                if ($src_ip[0] == 69 && $src_ip[1] == 55 &&
                    $src_ip[2] >= 224 && $src_ip[2] <= 239 &&
                    $src_ip[2] != 229 && $src_ip[2] != 231) { # for castle
#                if ($src_ip[0] == 69 && $src_ip[1] == 55 && $src_ip[2] == 229) { # for i2b
                   $d[2] = 2;
                   # hack for outbound bulk traffic counted 2x
                   if ($dst_ip[2] == 234) { $d[11] /= 2; $d[10] /= 2; }
                }
                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 &&
                       $dst_ip[2] >= 224 && $dst_ip[2] <= 239 &&
                       $dst_ip[2] != 229 && $dst_ip[2] != 231) { # for castle
#                elsif ($dst_ip[0] == 69 && $dst_ip[1] == 55 && $dst_ip[2] == 229) { # for i2b
                   $d[2] = 1;
                }
                else { next LOOP; }

                if ($d[2] == 2) {
                    $addr = $d[3];
                    # if the dst-port is low, store that
                    if ($d[7] <= 1024) { $port = $d[7]; }
                    # if the src-port is low, store that
                    elsif ($d[4] <= 1024) { $port = $d[4]; }
                    else { $port = 99999; }
                }
                elsif ($d[2] == 1) {
                    $addr = $d[6];
                    # if the dst-port is high, assume its return traffic, try to store src-port if low
                    if ($d[7] > 1024) {
                        if ($d[4] <= 1024) { $port = $d[4]; }
                        else { $port = 99999; }
                    } else {
                        $port = $d[7];
                    }
                } else {
                    next LOOP;
                }

                my (@ip) = split '\.', $addr;
                unless ($ip[0] == 69) { next LOOP; }
                unless ($ip[1] == 55) { next LOOP; }
                unless ($ip[2] >= 224 && $ip[2] <= 239 && $ip[2] != 229 && $ip[2] != 231) { next LOOP; }
#                unless ($ip[2] == 229) { next LOOP; }

                my $classC = "$ip[0]_$ip[1]_$ip[2]";

#                          IP        dir
#                if ($d[10] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10]; }
#                if ($d[11] < 2147483647) { $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11]; }
#
#                if ($d[10] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10]; }
#                if ($d[11] < 2147483647) { $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11]; }
#
#                if ($d[10] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'pktTotal'} += $d[10]; }
#                if ($d[11] < 2147483647) { $porttotal->{$classC}->{$addr}->{$d[2]}->{$port}->{'octetTotal'} += $d[11]; }
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'pktTotal'} += $d[10];
                $iptotal->{$classC}->{$addr}->{$d[2]}->{'octetTotal'} += $d[11];

                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'pktTotal'} += $d[10];
                $protototal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{'octetTotal'} += $d[11];

                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'pktTotal'} += $d[10];
                $porttotal->{$classC}->{$addr}->{$d[2]}->{$d[8]}->{$port}->{'octetTotal'} += $d[11];
            }
        }
        close(DATA);
        `rm /usr/home/working/tmp-$file`;
        &debug("processing ip totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$iptotal})) {
            $db->query("lock tables dailyIpTotals_$classC write") unless $dry;
            my @values;
            foreach my $ip (keys(%{$iptotal->{$classC}})) {
                foreach my $dir (keys(%{$iptotal->{$classC}->{$ip}})) {
                    my $octets = $iptotal->{$classC}->{$ip}->{$dir}->{'octetTotal'};
                    my $packets = $iptotal->{$classC}->{$ip}->{$dir}->{'pktTotal'};
#                    $packets = $packets > 2147483647 ? 0 : $packets;
                    if ($octets > 2147483647) {
                        my $ddir = $dir==1 ? 'in' : 'out';
                        `echo "$date $ip $ddir $octets\n" >> $log`;
#                        $octets = 0;
                    }
                    # dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
                    my $id = "$ip-$condensedDate-$dir";
                    $id =~ s/\.//g;
                    push @values, "('$date', '$ip', $dir, $octets, $packets)";
                    my $sql = "insert into dailyIpTotals_$classC values ('$id', '$date', '$ip', $dir, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                    print "$sql\n" if $dry;
                    $db->query($sql) unless $dry;
#                    $db->query("insert into ipTotals values ('$date', '$ip', $dir, $octets, $packets)");
                }
            }
            $db->query("unlock tables") unless $dry;

            $db->query("lock tables ipTotals_$classC write") unless $dry;
            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into ipTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                $db->query($sql) unless $dry;
            }
            $db->query("unlock tables") unless $dry;
        }

        sleep 20;
#        &debug("processing protocol totals at ");
#        &debug(`date`);
#        foreach my $classC (keys(%{$protototal})) {
#            $db->query("lock tables dailyProtoTotals_$classC write") unless $dry;
#            my @values;
#            foreach my $ip (keys(%{$protototal->{$classC}})) {
#                foreach my $dir (keys(%{$protototal->{$classC}->{$ip}})) {
#                    foreach my $proto (keys(%{$protototal->{$classC}->{$ip}->{$dir}})) {
#                        my $octets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'octetTotal'};
#                        my $packets = $protototal->{$classC}->{$ip}->{$dir}->{$proto}->{'pktTotal'};
# #                        $octets = $octets > 2147483647 ? 0 : $octets;
# #                        $packets = $packets > 2147483647 ? 0 : $packets;
#                        # dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                        my $id = "$ip-$condensedDate-$dir-$proto";
#                        $id =~ s/\.//g;
#                        push @values, "('$date', '$ip', $dir, $proto, $octets, $packets)";
#                        my $sql = "insert into dailyProtoTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
#                        print "$sql\n" if $dry;
#                        $db->query($sql) unless $dry;
# #                        $db->query("insert into protoTotals values ('$date', '$ip', $dir, $proto, $octets, $packets)");
#                    }
#                }
#            }
#            $db->query("unlock tables") unless $dry;
#            my $sql = "insert into protoTotals_$classC values ";
#            $sql .= join ',', @values;
#            $db->query("lock tables protoTotals_$classC write") unless $dry;
#            print "$sql\n" if $dry;
#            $db->query($sql) unless $dry;
#            $db->query("unlock tables") unless $dry;
#        }

        &debug("processing port totals at ");
        &debug(`date`);
        foreach my $classC (keys(%{$porttotal})) {
            $db->query("lock tables dailyPortTotals_$classC write") unless $dry;
            my @values;
            foreach my $ip (keys(%{$porttotal->{$classC}})) {
                foreach my $dir (keys(%{$porttotal->{$classC}->{$ip}})) {
                    foreach my $proto (keys(%{$porttotal->{$classC}->{$ip}->{$dir}})) {
                        foreach my $port (keys(%{$porttotal->{$classC}->{$ip}->{$dir}->{$proto}})) {
                            my $octets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'octetTotal'};
                            my $packets = $porttotal->{$classC}->{$ip}->{$dir}->{$proto}->{$port}->{'pktTotal'};
    #                        $octets = $octets > 2147483647 ? 0 : $octets;
    #                        $packets = $packets > 2147483647 ? 0 : $packets;

                            # dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-protocol-port
                            my $id = "$ip-$condensedDate-$dir-$proto-$port";
                            $id =~ s/\.//g;
                            push @values, "('$date', '$ip', $dir, $proto, $port, $octets, $packets)";
                            my $sql = "insert into dailyPortTotals_$classC values ('$id', '$date', '$ip', $dir, $proto, $port, $octets, $packets) ON DUPLICATE KEY UPDATE octets=octets+$octets, packets=packets+$packets";
                            print "$sql\n" if $dry;
                            $db->query($sql) unless $dry;
    #                        $db->query("insert into portTotals values ('$date', '$ip', $dir, $port, $octets, $packets)");
                        }
                    }
                }
            }
            $db->query("unlock tables") unless $dry;

            $db->query("lock tables portTotals_$classC write") unless $dry;
            # break inserts into 100 records at a time
            &debug("inserting $#values +1 values");
            while ($#values > 0) {
                my $sql = "insert into portTotals_$classC values ";
                my $max_index = $#values > 100 ? 100 : $#values;
                for (my $i=0; $i<=$max_index; $i++) {
                    $sql .= shift @values;
                    $sql .= ',';
                }
                chop $sql;
                print "$sql\n" if $dry;
                $db->query($sql) unless $dry;
            }
            $db->query("unlock tables") unless $dry;
            sleep 10;
        }

#                       12     1 8      1    1= 23
# dailyIpTotals.id = ip(no .'s)-yyyymmdd-direction
#                       12        1  8     1   1       3=26
# dailyProtoTotals.id = ip(no .'s)-yyyymmdd-direction-proto
#                       12       1   8    1     1     5=28
# dailyPortTotals.id = ip(no .'s)-yyyymmdd-direction-port
        #print "finished at ";
        #print `date`;
        `mv $queuedir/$file $archivedir` unless $dry;
    }
}
`rm $queuedir/.lock` unless $dry;

sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}

# var full during ft-v05.2005-03-28.084500-0800 and
# 2005-02-24 69.55.226

# all port/daily totals before 2005-04-07
cat > /usr/home/flowbin/db.pm

#!/usr/bin/perl
#
# $Header: /usr/cvs/newgw/lib/db.pm,v 1.4 2003/06/05 18:20:01 glenn Exp $
#
# Copyright (c) 2003
#      e-Monitoring Networks, Inc.  All rights reserved.
#
#
package db;

use strict;
use DBI;

sub new {
    my $class = shift;
    my $self = {};

    $self->{'debug'} = 0;
    bless $self, $class;

    return $self;
}

sub connect {
    my $self = shift;
    my $dbname = shift;
    my $dbhost = shift;
    my $dbuser = shift;
    my $dbpass = shift;

    my $host = '';
    if (defined($dbhost)) {
        $host = ";host=$dbhost";
    }

    eval {
        $self->debug("connecting to: DBI:mysql:database=$dbname;$host", 1);
        $self->{'dbh'} = DBI->connect("DBI:mysql:database=$dbname;$host", $dbuser, $dbpass);
    };
    if ($self->{'dbh'}) {
        return 1;
    }
    $self->{'error'} = "Error connecting to database $@";
    $self->debug("Error connecting to database $@");
    return 0;
}

sub query {
    my $self = shift;
    my $query = shift;

    $self->debug($query, 1);
    my $sth;
    eval {
        $sth = $self->{'dbh'}->prepare($query);
    };
    unless ($sth) {
        $self->{'error'} = "error preparing query $@";
        $self->debug("error preparing query $@");
        return undef;
    }
    my $qty;
    eval {
        $qty = $sth->execute;
    };
    unless ($qty) {
        $self->{'error'} = "error executing query $@";
        warn "error executing query $@ $query";
        return undef;
    }
    $self->debug("returning $qty, $sth from query", 6);
    return ($qty, $sth);
}

sub disconnect {
    my $self = shift;

    $self->{'dbh'}->disconnect;
    return 0;
}

sub debug {
    my $self = shift;
    my $msg = shift;
    my $level = shift || 0;

    if ($level < $self->{'debug'}) {
        print "$msg\n";
    }
    return 0;
}
1;
mkdir /usr/home/archive
mkdir -p /usr/home/sql/tmp
crontab -e
#process flows
2,17,32,47 * * * * /usr/home/flowbin/processflows.pl

setup traffic db[edit]

  • Install mysql:
cd /usr/ports/databases/mysql50-server
make install clean
cat >> /etc/rc.conf
mysql_enable="YES" 

Move db data dir:

/usr/local/etc/rc.d/mysql-server stop
mkdir /usr/home/database/
mv /var/db/mysql/* /usr/home/database/
chown -R mysql:mysql /usr/home/database

Edit database location in startup script:

vi /usr/local/etc/rc.d/mysql-server
# : ${mysql_dbdir="/var/db/mysql"}
: ${mysql_dbdir="/usr/home/database"}
/usr/local/etc/rc.d/mysql-server start


  • Install mysql perl database modules:
cd /usr/ports/databases/p5-DBI
make install clean
cd /usr/ports/databases/p5-DBD-mysql50
make install clean
(no to SSL support)
  • Setting up database
rehash
/usr/local/etc/rc.d/mysql-server start
mysql -u root
create database traffic;
grant all on *.* to root@localhost identified by '5over3';
grant all on traffic.* to jc@10.1.4.5 identified by '2gMKY3Wt';

If this was a new server we'd setup new tables. See mysql for how those tables would be setup.

We are assuming here we are moving data from an existing db, here's how that's done (from the current traffic db):

rsync -av --progress /usr/home/database/traffic/ 10.1.4.203:/usr/home/database/traffic/

When you're ready to do the cutover, shut down mysql on both hosts and do one last sync.


process flows from bwdb2[edit]

On traffic database server (bwdb):

crontab -e
#import sql from bwdb2
10,25,40,55 * * * * /usr/home/flowbin/processsql.pl

Add access to mysql:

mysql -u root -p 
grant all on traffic.* to bwdb2@localhost identified by 's1lver4d';
cat > /usr/home/flowbin/processsql.pl

#!/usr/bin/perl

#use strict;
#$debug=1;
#$dry=1;

my $sqldir = "/usr/home/bwdb2/pending";
my $mysql = '/usr/local/bin/mysql';
my @err;
unless ($dry) {
    if (-e "$sqldir/.lock") {
        open(FILE, "$sqldir/.lock");
        my $pid = <FILE>;
        chomp($pid);
        close(FILE);
        if (kill(0, $pid)) {
            #another process is using the queue, bail out
            exit(0);
        }
        else {
            #dead lock file, remove it
            `rm $sqldir/.lock`;
        }
    }
    open(FILE, "> $sqldir/.lock");
    print FILE "$$\n";
    close(FILE);
}

opendir(DIR, $sqldir);
my @files = readdir(DIR);
closedir(DIR);

foreach my $file (sort @files) {
   next unless $file =~ /done$/;
   my $r = `bzcat $sqldir/$file | $mysql -u bwdb2 -ps1lver4d traffic`;
   unless ($?==0) {
      push @err, "bzcat $sqldir/$file | $mysql -u bwdb2 -pxxxxx traffic ($r)";
   }
   else {
      `rm $sqldir/$file`;
   }
}

`rm $sqldir/.lock` unless $dry;

if (@err) {
   email_support('bwdb: processsql.pl error',join "\n", @err);
}

sub email_support {
    my $subj=shift;
    my $body=shift;
    use Mail::Sendmail;

    # prepare message
    my %mail = (
        To      => 'dave@johncompanies.com',
        From    => 'support@johncompanies.com',
        Subject => $subj,
        Message => $body,
        smtp    => 'mail.johncompanies.com',
    );
    sendmail(%mail) || warn "Error: $Mail::Sendmail::error";
}

sub debug {
    my $message = shift;
    if ($debug) {
        print "$message\n";
    }
}
chmod 0700 /usr/home/flowbin/processsql.pl

Make sure bwdb is reachable from the outside only to bwdb2:

On nat, add to /etc/ipnat.rules

# bwdb
bimap fxp0 10.1.4.203/32 -> 69.55.233.199/32

Reload:

ipnat -C -F -f /etc/ipnat.rules

Setup firewall rule on firewall:

ipfw add 00094 allow ip from 66.181.18.5 to 69.55.233.199 22
ipfw add 00094 deny ip from any to 69.55.233.199

Setup firewall on bwdb to restrict access now that it's nat'd:

cat >> /usr/local/etc/rc.d/boot.sh
ipfw add 1 allow tcp from any to any established
ipfw add 2 allow ip from 10.1.4.0/24,66.181.18.5,69.55.233.195 to me 22
ipfw add 3 allow ip from 10.1.4.5 to me 3306
ipfw add 4 allow ip from 69.55.225.225 53 to me 
ipfw add 5 allow ip from 69.55.230.2 25 to me 
ipfw add 6 allow ip from me to me 4444
ipfw add 7 allow icmp from any to me
ipfw add 8 allow udp from 10.1.4.203 to 10.1.4.203 dst-port 4444
ipfw add 9 allow udp from 10.1.4.5 to me 161
ipfw add 100 deny ip from any to me
chmod 0700 /usr/local/etc/rc.d/boot.sh

From bwdb2, add ssh key:

cat /root/.ssh/id_dsa.pub | ssh 69.55.233.199 'cat - >> /root/.ssh/authorized_keys' 

Confirm no password access:

ssh 69.55.233.199 hostname

bwdb2[edit]

Summary[edit]

This machine tracks and stores network traffic (netflow) at i2b. It is our means to monitor customer bandwidth usage.

  • Location: i2b, cab6
  • OS: FreeBSD 6.4 x86
  • Networking: Priv IP: 10.1.2.4 There are 2 onboard nic's, one of which is the "listener"
  • Hardware: Custom 2U. Single power supply.
  • Drives: two 150 GB (2 x 150GB) RAID1 arrays running on a 3ware 7006 RAID card.

Services Provided[edit]

  • netflow
  • bigbrother

netflow[edit]

The main function of this server is to run netflow on an eth device in promiscuous mode so as to hear everything happening on the port (wherein all network traffic is mirrored to that port via the cisco swith). Every 15min, it creates a flow file under /usr/home/flows/ (organized by date). The flow file contains all traffic data for a 15min increment of time.

A cronjob moves that flow file (or files if there are multiple due to some delay)

1,16,31,46 * * * * /usr/home/flowbin/queue.pl

into a processing queue: /usr/home/working

Then a separate file processes whatever flow files it finds there, and builds sql files ready for insertion into the traffic database:

2,17,32,47 * * * * /usr/home/flowbin/processflows-sql.pl

Then yet another process copies the sql files to the traffic database server for processing and insertion into the mysql database:

8,23,38,53 * * * * /usr/home/flowbin/sendsql.pl

Regular maintenance[edit]

  • if space becomes tight, move sql files and flow files to backup server, both located in /usr/home/flowbin/archive

firewall (newgateway)[edit]

Summary[edit]

This machine is the primary (only) firewall for the entire network at castle.

  • Location: castle, cab 3-8
  • OS: FreeBSD 4.11 x86
  • Networking: Priv IP: 10.1.4.223, Pub IPs: 69.55.233.164 (external), 69.55.233.156 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks. If you're looking at the back of the server, the internal-network-facing nic is on the right (em1), and the external-facing-network (3750) is on the left (em0).
  • Hardware: 6 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: 36 GB (2 x 36GB) RAID1 array running on an Adaptec 2120S PCI RAID card.

Services Provided[edit]

  • firewall (ipfw)
  • snmp
  • bigbrother

Firewall Rule Configuration[edit]

See Firewall Rule Configuration for more discussion on how to actually manipulate firewall rules.

Disaster Recovery[edit]

If there is ever an outage with the firewall, the old firewall "gate" is located just below and is running with the proper network configuration, but with no firewall rules in place (to facilitate good throughput). Have castle move the cable on the left on the current firewall to the left port in the old firewall and the right cable to the right port.

Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)

hostname="newgateway.johncompanies.com"
firewall_script="/etc/firewall.sh"
firewall_enable="NO"
sendmail_enable="NONE"
sshd_enable="YES"
inetd_enable="NO"
xntpd_enable="YES"
snmpd_enable="YES"
#snmpd_flags="-as -p /var/run/snmpd.pid"
#ipnat_enable="YES"
#ipnat_rules="/etc/ipnat.rules"
gateway_enable="YES"

defaultrouter="69.55.233.161"

ifconfig_xl0="inet 10.1.4.223 netmask 255.255.255.0"
ifconfig_em0="inet 69.55.233.164 netmask 255.255.255.248"

#
# Original JohnCompanies 69.55.224.0/20
#
ifconfig_em1="inet 69.55.233.156 netmask 255.255.255.248"

static_routes="route1 route2 route3 route4 route5 route6 route7 route8 route9 route10 route11 route1
2 route13 route14 route15 route16 route17 route18"

route_route1="-net 69.55.224.0 69.55.233.153"
route_route2="-net 69.55.225.0 69.55.233.153"
route_route3="-net 69.55.226.0 69.55.233.153"
route_route4="-net 69.55.227.0 69.55.233.153"
route_route5="-net 69.55.228.0 69.55.233.153"
route_route6="-net 69.55.229.0 69.55.233.153"
route_route7="-net 69.55.230.0 69.55.233.153"
route_route8="-net 69.55.231.0 69.55.233.153"
route_route9="-net 69.55.232.0 69.55.233.153"
route_route10="-net 69.55.233.0 69.55.233.153"
route_route11="-net 69.55.234.0 69.55.233.153"
route_route12="-net 69.55.235.0 69.55.233.153"
route_route13="-net 69.55.236.0 69.55.233.153"
route_route14="-net 69.55.237.0 69.55.233.153"
route_route15="-net 69.55.238.0 69.55.233.153"
route_route16="-net 69.55.239.0 69.55.233.153"
route_route17="-net 10.1.5.0 10.1.4.2"
route_route18="-net 10.1.6.0 10.1.4.2"


#In case of 3750 failure:
#defaultrouter="69.43.128.81"
#ifconfig_em0="inet 69.43.129.84 netmask 255.255.255.248"

#bind .1's here:
#ifconfig_em1="inet 69.55.224.1 netmask 255.255.255.0"
#ifconfig_em1_alias0="inet 69.55.225.1 netmask 255.255.255.0"
#ifconfig_em1_alias1="inet 69.55.226.1 netmask 255.255.255.0"
#ifconfig_em1_alias2="inet 69.55.227.1 netmask 255.255.255.0"
#ifconfig_em1_alias3="inet 69.55.228.1 netmask 255.255.255.0"
#ifconfig_em1_alias4="inet 69.55.229.1 netmask 255.255.255.0"
#ifconfig_em1_alias5="inet 69.55.230.1 netmask 255.255.255.0"
#ifconfig_em1_alias6="inet 69.55.231.1 netmask 255.255.255.0"
#ifconfig_em1_alias7="inet 69.55.232.1 netmask 255.255.255.0"
#ifconfig_em1_alias8="inet 69.55.233.1 netmask 255.255.255.0"
#ifconfig_em1_alias9="inet 69.55.234.1 netmask 255.255.255.0"
#ifconfig_em1_alias10="inet 69.55.235.1 netmask 255.255.255.0"
#ifconfig_em1_alias11="inet 69.55.236.1 netmask 255.255.255.0"
#ifconfig_em1_alias12="inet 69.55.237.1 netmask 255.255.255.0"
#ifconfig_em1_alias13="inet 69.55.238.1 netmask 255.255.255.0"
#ifconfig_em1_alias14="inet 69.55.239.1 netmask 255.255.255.0"

#bulk:
# reassign 69.55.231.1 to the int iface on the firewall
# set the DG on the firewall to 69.43.138.9
# set the ext firewall IP to 69.43.138.12, NM: 255.255.255.248

Cronjobs[edit]

1 0 * * * /usr/local/etc/rsync.backup

Backup to backup1

0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3  4 5 17331

Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).

Inside /etc/daily.local you will see a call to /etc/makepiperules.pl This script will create /etc/firewall.sh which contains all the firewall and pipe rules in place at the time the script was run.

DOS attacks[edit]

See Handling a DoS attack regarding how to handle a DOS attack.

Theres a background process (running from user shell) that monitors the firewall for incoming UDP DoS attacks. When it notices packets above a certain level it will

  1. enter a rule that allows all UDP to go through
  2. send an emergency email to support and indicating an attack is in progress
  3. send an email to castle (nocstaff@castleaccess.com and jcsupport@castleaccess.com) telling them to investigate and put up a null if warranted
  4. wait for a couple minutes to see if the attack subsides- if so it will remove the pass-all UDP rule, if not it will repeat the process from #1

This file lives under /usr/home/user/doswatch.pl To run:

cd /usr/home/user
./doswatch.pl &

To kill;

fg
^C

It writes its findings to /usr/home/user/doswatch.log

backup1[edit]

Summary[edit]

This machine acts as the primary backup location for all VPS-based customers. No customer directly accesses this server to perform their backups. We also store cancelled customers on this server.

  • Location: castle, cab 3-8
  • OS: Ubuntu 8.04.1 server x86
  • Networking: Priv IP: 10.1.4.8, Pub IP: 69.55.230.11 (firewalled from all but JC infrastructure @ i2b)
  • Hardware: 6 SATA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Single power supply.
  • Drives: 4.5 TB (6 x 1TB) RAID5 array running on a 3ware 9650SE-8LPML (8-port) card

Services provided[edit]

  • backup via rsync
  • mysql - traffic data
  • nfs server - for backups
  • snmp client - for big brother
  • bigbrother client

Usage and Notes[edit]

  • all data is stored under /data
  • virtually all jc infrastructure, and all VPS machines are setup to mount to backup1 via nfs (mountpoint: /backup1), and they all have their ssh keys setup to allow passwordless rsync's
  • each virt or jail backs up each evening to backup1. Each server has it's own directory (named for the server). Under those directories are 7 daily snapshots (0-6)
  • at the time of writing, the mysql server running here is replicating from (slave to) the mysql instance on bwdb. Requests for bandwidth data usage for customers (coming from management, account manager, and accounting scripts running on mail) all direct towards the database "traffic" running on this server.
  • cancelled customer systems are compressed and stored under /data/deprecated
  • archived bwdb2 flow files are stored under /data/bwdb2
  • critical files from backup2 are stored under /data/backup2

Cronjobs[edit]

00 5 * * * /usr/local/sbin/backupwatch.pl 2>&1 > /dev/null
35 5 * * * /usr/local/sbin/usage_check; /usr/local/sbin/snapshot_archive; /usr/local/sbin/snapshot_rotate  /data/backuplog.log

this runs daily the scripts to report on how much disk space each customer system occupies and how long their backups took. Then it rotates backups for each system, removing the oldest backup. It will email support@johncompanies.com at it’s conclusion. This email can be deleted, however note when it begins to take significantly longer to complete, ie runs past 2200 pm – this usually indicates a problem on the backup server.

10,25,40,55 * * * * /usr/local/sbin/processsql.pl

this processes prepared sql command files sent from/by bwdb2 (@ i2b) and imports them into the traffic database.

0 0 * * * /usr/local/sbin/3wraidchk

checks the health of the RAID array

Regular maintenance[edit]

build[edit]

Setup raid5 with a boot vol of 12G 5.45tb 
12G boot
4664 GB 

Install ubuntu 8.04

Swap 4G

Don’t format data drive

http://www.unixgods.org/~tilo/linux_larger_2TB.html

parted /dev/sdb
print
mklabel gpt
print

#Disk /dev/sdb: 4987GB
#Sector size (logical/physical): 512B/512B
#Partition Table: gpt

#Number  Start  End  Size  File system  Name  Flags

mkpart primary ext3 0 4987GB
print

#Disk /dev/sdb: 5987GB
#Sector size (logical/physical): 512B/512B
#Partition Table: gpt

#Number  Start   End     Size    File system  Name     Flags
# 1      17.4kB  4987GB  4987GB               primary

quit

mkfs.ext3 /dev/sdb1
#mke2fs 1.40.8 (13-Mar-2008)
#Filesystem label=
#OS type: Linux
#Block size=4096 (log=2)
#Fragment size=4096 (log=2)
#304390144 inodes, 1217544183 blocks
#60877209 blocks (5.00%) reserved for the super user
#First data block=0
#Maximum filesystem blocks=0
#37157 block groups
#32768 blocks per group, 32768 fragments per group
#8192 inodes per group
#Superblock backups stored on blocks:
#        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
#        4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
#        102400000, 214990848, 512000000, 550731776, 644972544
#
#Writing inode tables:   967/37157

mkdir /data

#root@backup1:~# df -h
#Filesystem            Size  Used Avail Use% Mounted on
#/dev/sda2             8.3G  540M  7.3G   7% /
#varrun               1013M   40K 1013M   1% /var/run
#varlock              1013M     0 1013M   0% /var/lock
#udev                 1013M   56K 1013M   1% /dev
#devshm               1013M     0 1013M   0% /dev/shm
#/dev/sdb1             4.5T  192M  4.3T   1% /data


apt-get update
apt-get upgrade
apt-get install snmp snmpd ntp nfs-kernel-server

echo "\"\e[5~\": history-search-backward" >> ~/.inputrc
echo "\"\e[6~\": history-search-forward" >> ~/.inputrc

vi /etc/ntp.conf
server 10.1.4.5

scp root@10.1.4.3:/root/.ssh/authorized_keys /root/.ssh/
cd /root/
ssh-keygen -t dsa
echo "10.1.4.3        backup2" >> /etc/hosts

cat .ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 

ssh backup2

vi /root/.bashrc
export PS1="[\u@\h \w]# "
alias h='history'
alias vi='vim'
alias j='jobs'
export PS1="[\u@\h \w]# "
alias dr='screen -dr'
export EDITOR=vim
export GREP_OPTIONS='--color=auto'
export HISTFILESIZE=1000

source /root/.bashrc

echo "# ttyS0 - getty 
# 
# This service maintains a getty on ttyS0 from the point the system is
# started until it is shut down again.

start on runlevel 2
start on runlevel 3
start on runlevel 4
start on runlevel 5

stop on runlevel 0
stop on runlevel 1
stop on runlevel 6

respawn
exec /sbin/getty 38400 ttyS0" > /etc/event.d/ttyS0 


vi /boot/grub/menu.lst

serial --unit=0 --speed=38400 --word=8 --parity=no --stop=1
terminal --timeout=15 serial console

append to kernel lines: 
console=tty0 console=ttyS0,38400n8

show menu:
#hiddenmenu

echo 'rocommunity  jcread 10.1.4.5
rocommunity  jcread 10.1.4.3
agentaddress 10.1.4.8:161' > /etc/snmp/snmpd.conf

# to see which iface it is, on backup2:

snmpwalk -v 1 -c jcread 10.1.4.8 interface


echo "bb:x:1984:1984:Big Brother:/home/bb:/bin/bash" >> /etc/passwd

echo "bb:x:1984:" >> /etc/group

pwconv

mkdir /home/bb
chown bb.bb /home/bb

cd ~bb
scp backup2:/mnt/data4/build/bb/bb-linux.tar .

tar xf bb-linux.tar

cd /home/bb/bbc1.9e-btf/etc

echo "10.1.4.5 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
echo "10.1.4.8 backup1.johncompanies.com # ssh" >> /home/bb/bbc1.9e-btf/etc/bb-hosts

echo "/:90:95
/var:90:95
/data:85:99" > /home/bb/bbc1.9e-btf/etc/bb-dftab


vi /home/bb/bbc1.9e-btf/bin/bb-disk.sh
(remove all | SORT xxxx)

chmod +r /var/log/messages

./bbchkcfg.sh 
#(y to questions)
./bbchkhosts.sh
#(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src

#make; make install
cd ..
./runbb.sh start
more BBOUT 
(look for errors)
exit

vi /etc/rc.local
su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"


echo '/data 10.1.4.0/24(rw, no_root_squash,async,no_subtree_check)' >> /etc/exports

/etc/init.d/nfs-kernel-server restart


echo 'chmod o+r /var/log/messages' >> /etc/cron.weekly/sysklogd


echo '10.1.4.8                backup1' >> /etc/hosts
echo '/dev/sdb1	/data  ext3  rw,noatime  0  0' >> /etc/fstab


to install digi drivers:

wget http://ftp1.digi.com/support/driver/40002086_n.tgz
apt-get install linux-image-2.6.24-19-server
apt-get install linux-source-2.6.24 (not needed?)
apt-get install linux-headers-2.6.24-19-server 
apt-get install make
apt-get install gcc
apt-get install g++	
apt-get install libncurses5-dev
apt-get install expect
apt-get install libdbi-perl libdate-calc-perl libdbd-mysql-perl

cd /usr/src; ln -s linux-headers-2.6.24-19-server linux
./configure
make all
make install
make postinstall

/usr/bin/dgrp_cfg_node -v -v init el 65.116.11.2 8

apt-get install mysql

mkdir /data/mysql
chown mysql:mysql /data/mysql
/etc/init.d/mysql stop
mv /var/lib/mysql/* /data/mysql/
mv /data/mysql/ib_* /var/lib/mysql/
vi /etc/mysql/my.cnf
(change datadir to /data/mysql)
vi /etc/apparmor.d/usr.sbin.mysqld
add:
  /data/mysql/ r,
  /data/mysql/** rwk,
Comment out:
#  /var/lib/mysql/ r,
#  /var/lib/mysql/** rwk,

/etc/init.d/apparmor restart
/etc/init.d/mysql start

tw_cli /c0/u0 set ignoreECC=on
tw_cli /c0/u0 set storsave=balance
tw_cli /c0/u0 set cache=on


0 0 * * * /usr/local/sbin/3wraidchk

backup2[edit]

Summary[edit]

THIS SERVER IS OUT OF SERVICE AND REPLACED BY BACKUP4

This machine is used for archiving data and is a backup server for colo customers. It was the former primary backup location for all VPS-based customers before backup1 was installed. Only dedicated customers directly accesses this server to perform their backups. NOTE: power button is broken, so the reset button (paper clip) was rewired to be the power button.

  • Location: castle, cab 3-7
  • OS: FreeBSD 6.1 x86
  • Networking: Priv IP: 10.1.4.3, Pub IP: 69.55.230.10 (firewalled from all but JC infrastructure @ i2b)
  • Hardware: 16 IDE drive bays (4 columns of 4, drive 0-0 top left, drive 0-1 just to the right TODO) all hot-swap. Triple power supply.
  • Drives:
    • 3ware 7500-8:
      • 200 GB JBOD (1 x 200G) labeled 0-0
      • 500 GB RAID5 (3 x 250G) 0-1 thru 0-3
      • 700 GB RAID5 (4 x 250G) 0-4 thru 0-7
    • 3ware 7500-8:
      • 700 GB RAID5 (4 x 250G) 1-0 thru 1-3
      • 700 GB RAID5 (4 x 250G) 1-4 thru 1-7

All drives MUST be western digital IDE drives. Other brands will not fit.

In case of an outage, nfs will hang on all connected servers until the nfs service returns. If you can't get backup2 back online, you can get nfs running elsewhere and fake backup2's MAC's: priv: 00:0e:0c:59:c1:a6, pub: 00:07:e9:5b:c6:45

To configure:

ifconfig fxp0 link 00:90:27:f9:0a:d9

Services provided[edit]

  • backup via rsync and nfs
  • samba
  • nfs
  • snmp
  • bigbrother

Usage[edit]

  • all data is stored under 4 mount points, corresponding to the 4 large RAID5 arrays: /mnt/data1 /mnt/data2 /mnt/data3 /mnt/data4
  • iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under /mnt/data2/iso
  • this used to be our primary backup server so you will see old backups from virt and jails around- missing customer data though, just the machine's data
  • this server serves as an archive for exported db data from bwdb and old flow files.
  • isys backs up here
  • customers are nfs-moutned under /mnt/data3/customers as file-backed md devices
  • in /mnt/data4 there are lots of useful things used for building our vps servers, customer servers, and management scripts:
    • /bin: the master repository of scripts and custom binaries we use on jails and virts. Each night every virt and jail rsync's what's in here to update the local files. So any global updates to scripts would need to be made here (or will be overwritten with what's in here)
    • /build: files we use for setting up big brother, 3ware cli and scripts for colo's, vzcp customized setup files and so on
    • /vzrpms: contains the OS templates for many-to-most of the OS's we offer on vz systems

Cronjobs[edit]

  • backs itself up nightly to nfs-mounted backup1 (mountpoint: /backup2)

Regular maintenance[edit]

backup3[edit]

Summary[edit]

This machine is used for archiving data, is a backup server for colo customers, runs a samba server to make available iso's to the IPKVMs, and allows us to connect to the digi serial multiplexer at i2b. Only dedicated customers directly accesses this server to perform their backups.

  • Location: i2b, cab 6
  • OS: Ubuntu 10.04.1 server amd64
  • Networking: Priv IP: 10.1.2.3, Pub IPs: 69.55.229.4 AND 69.55.231.2
  • Hardware: 16 drive SATA bays (4 columns of 4, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: 5 TB (6 x 1TB) RAID5 array running on an Areca Technology Corp. ARC-1160 16-Port

Services provided[edit]

  • backup via rsync and nfs
  • samba
  • nfs
  • digi realport
  • snmp
  • bigbrother

Usage[edit]

  • all data is stored under /data
  • iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under /data/iso
  • this server serves as an archive for exported db data from bwdb and old flow files.
  • inftrastructure machines at i2b back up here
  • customers are nfs-moutned under /data/customers as file-backed loopback devices

management scripts[edit]

  • mkbackups

mkbackup <cid> GB <ip>

Cronjobs[edit]

0 0 * * * /usr/local/sbin/arecaraidchk

RAID checks

35 4 * * * /usr/local/sbin/snapshot_archive

Rotate daily snapshots for infrastructure machine backups

Regular maintenance[edit]

Build[edit]

BIOS Config[edit]

disable quiet boot

set to last state after power loss

set date/time to GMT

enable serial console output (baud rate 115200)

Install OS[edit]

Ubuntu 10.04.1 amd64 (couldn't get 12.04 to load cause the H/W was incompat)
10G / ext3
2G swap
~ /data ext4

Install packages:
openssh
samba

DNS and private IP[edit]

echo "nameserver 69.55.225.225" >> /etc/resolv.conf

Add a 2nd IP to eth0 and setup priv net

vi /etc/network/interfaces

auto eth0
iface eth0 inet static
        address 69.55.229.4
        netmask 255.255.255.0
        network 69.55.229.0
        broadcast 69.55.229.255
        gateway 69.55.229.1
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 69.55.229.3 66.181.0.2
        dns-search johncompanies.com

auto eth0:1
iface eth0:1 inet static
        address 69.55.231.2
        netmask 255.255.255.0
        network 69.55.231.0
        broadcast 69.55.231.255

auto eth1
iface eth1 inet static
        address 10.1.2.3
        netmask 255.255.255.0
        network 10.1.2.0
        broadcast 10.1.2.255

Install packages[edit]

apt-get update
apt-get upgrade
apt-get install gcc
apt-get install libssl-dev
apt-get install libncurses5-dev
apt-get install cu
apt-get install unzip
apt-get install snmp snmpd ntp nfs-kernel-server

tweak grub, enable serial[edit]

vi /etc/default/grub
#GRUB_HIDDEN_TIMEOUT=0
GRUB_CMDLINE_LINUX_DEFAULT="max_loop=64"
GRUB_CMDLINE_LINUX="console=tty0 console=ttyS0"
update-grub
echo "start on stopped rc RUNLEVEL=[2345]
stop on runlevel [!2345]
respawn
exec /sbin/getty -L ttyS0 38400 vt102" > /etc/init/ttyS0.conf

install realport (digi) driver[edit]

give the digi an ip with DgIpServ.exe

cd /usr/src/
wget ftp://ftp1.digi.com/support/beta/linux/dgrp/dgrp-1.9.tgz
tar xzf dgrp-1.9.tgz 
cd dgrp-1.9/
./configure
make
make install
make postinstall
update-rc.d dgrp_daemon defaults

configure ports:

dgrp_cfg_node init el 10.1.2.10 16

try connecting with:

cu -l /dev/ttyel00 -s 38400

shell, ntp, ssh key, hosts[edit]

Shell autocompletion search:

echo "\"\e[5~\": history-search-backward" >> ~/.inputrc
echo "\"\e[6~\": history-search-forward" >> ~/.inputrc

Setup ntp:

vi /etc/ntp.conf
server 10.1.2.1
server ntp.ubuntu.com

Generate ssh keys:

cd /root/
ssh-keygen -t dsa

Defaults, no password

Setup hosts:

echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.4 bwdb2" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts

Copy keys to servers where we need passwordless login:

cat .ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 
cat .ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys'

Setup shell:

vi /root/.bashrc
(add to bottom)
alias h='history'
alias vi='vim'
alias j='jobs'
export PS1="[\u@\h \w]# "
alias dr='screen -dr'
export EDITOR=vim
export GREP_OPTIONS='--color=auto'
export HISTFILESIZE=1000

alias tip-switch-p20='cu -l ttyel00 -s 9600'
alias tip-switch-p21='cu -l ttyel15 -s 9600'
alias tip-switch-p22='cu -l ttyel14 -s 9600'
alias tip-switch-p23='cu -l ttyel05 -s 9600'
alias tip-switch-p24='cu -l ttyel06 -s 9600'
alias tip-switch-p25='cu -l ttyel09 -s 9600'
alias tip-switch-p26='cu -l ttyel07 -s 9600'
alias tip-switch-p27='cu -l ttyel08 -s 9600'
alias tip-firewall2='cu -l ttyel01 -s 115200'
alias tip-nat2='cu -l /dev/ttyel02 -s 115200'
alias tip-backup3='cu -l ttyel04 -s 38400'
alias tip-bwdb2='cu -l ttyel03 -s 115200'
alias tip-backup4='cu -l ttyel13 -s 115200'
alias tip-jail3='cu -l ttyel11 -s 115200'

Load new shell:
 source /root/.bashrc

Setup snmpd (this is only valid for a server at castle):
echo 'rocommunity  jcread 10.1.4.5
rocommunity  jcread 10.1.4.3
agentaddress 10.1.4.8:161' > /etc/snmp/snmpd.conf

to see which iface it is, on backup2:

snmpwalk -v 1 -c jcread 10.1.4.8 interface

=== nfs ===

Allow mounts from private net:
 echo '/data 10.1.2.0/24(rw,no_root_squash,async,no_subtree_check)' >> /etc/exports

Restart nfsd:
 /etc/init.d/nfs-kernel-server restart

=== bb ===

Add user, group:
 echo "bb:x:1984:1984:Big Brother:/home/bb:/bin/bash" >> /etc/passwd
 echo "bb:x:1984:" >> /etc/group
 pwconv

Create home:
 mkdir /home/bb
 chown bb.bb /home/bb
 cd ~bb

Copy over and install files:
<pre>scp backup2:/mnt/data4/build/bb/bb-linux.tar .
tar xf bb-linux.tar
cd /home/bb/bbc1.9e-btf/etc

Configure main bb server:

echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts
echo "10.1.2.3 backup3.johncompanies.com # ssh" >> /home/bb/bbc1.9e-btf/etc/bb-hosts

Configure low disk alerts:

echo "/:90:95
/var:90:95
/data:85:99" > /home/bb/bbc1.9e-btf/etc/bb-dftab
vi /home/bb/bbc1.9e-btf/bin/bb-disk.sh

(remove all | SORT xxxx since SORT is broken)

chmod +r /var/log/messages
./bbchkcfg.sh 

(y to questions)

./bbchkhosts.sh

(ignore ssh errors)

cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..
./runbb.sh start
more BBOUT

(look for errors)

exit
vi /etc/rc.local
su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"

(before the exit 0)

echo 'chmod o+r /var/log/messages' >> /etc/cron.weekly/sysklogd

Add f/w rule:

ipfw add 00096 allow ip from { 69.55.229.4 or 69.55.229.3 } to 69.55.230.2 1984
vi ~bb/bbc1.9e-btf/etc/bbdef-client.sh
DFWARN=199
DFPANIC=199


raid check[edit]

3ware[edit]

scp backup1:/usr/local/sbin/tw_cli /usr/local/sbin/tw_cli
scp backup1:/usr/local/sbin/checkraid.sh /usr/local/sbin/checkraid.sh
scp backup1:/usr/local/sbin/3wraidchk /usr/local/sbin/3wraidchk
vi /usr/local/sbin/checkraid.sh
:%s/c0/c2/g

crontab -e
0 0 * * * /usr/local/sbin/3wraidchk

areca[edit]

cd /tmp
wget http://www.areca.us/support/s_linux/cli/linuxcli_V1.10.0_120815.zip
unzip linuxcli_V1.10.0_120815.zip
cp linuxcli_V1.10.0_120815/x86_64/cli64 /usr/local/sbin/
chmod 0700 /usr/local/sbin/cli64
cli64 rsf info
scp backup2:/data4/bin/arecaraidchk /usr/local/sbin
scp backup1:/usr/local/sbin/Sendmail.pm /usr/local/sbin

crontab -e
0 0 * * * /usr/local/sbin/arecaraidchk
cat > /root/verify.sh
cli64 vsf info
cli64 rsf info
cli64 disk info
cli64 event info
echo press enter when ready to run verify ; read x

cli64 vsf check vol=1

misc binaries[edit]

scp backup1:/usr/local/sbin/snapshot_archive /usr/local/sbin/snapshot_archive
vi /usr/local/sbin/snapshot_archive

(remove entries)

crontab -e
35 4 * * * /usr/local/sbin/snapshot_archive
scp backup1:/usr/local/sbin/pagedave /usr/local/sbin/pagedave
scp backup1:/usr/local/sbin/taskdone /usr/local/sbin/taskdone

Since installing /bin/mail requires all sorts of packages (lame) we write a simple one here...which can only email johncompanies.com addr's unless you add relaying for this host:

cat > /bin/mail
#!/usr/bin/perl
use strict;
use warnings;

use lib '/usr/local/sbin';
use Sendmail qw(sendmail);

my $sub = $ARGV[1];
my $to = $ARGV[2];


my %mail = (
   To      => $to,
   From    => $to,
   Subject => $sub,
   Message => '',
   smtp    => 'mail.johncompanies.com'
);
sendmail(%mail) || print "Error: $Sendmail::error";

chmod 0700 /bin/mail

mkbackup[edit]

mkdir /data/customers
cat > /usr/local/sbin/mkbackup
#!/bin/sh

if test $1; then
  cid=$1
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi

if test $2; then
  gb=$2
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi

if test $3; then
  ip=$3
else
  echo "ERROR: Usage: mkbackup cid GB ip  Terminating."
  exit
fi


if test -e /data/customers/${cid}-file; then
  echo "ERROR: /data/customers/${cid}-file exists"
  exit
else
  echo "touch /data/customers/${cid}-file"
  touch /data/customers/${cid}-file
  count=`echo $gb|awk '{print $1*1000}'`
  echo "dd if=/dev/zero of=/data/customers/${cid}-file bs=1024K count=$count"
  dd if=/dev/zero of=/data/customers/${cid}-file bs=1024K count=$count
  echo "/sbin/mkfs -t ext3 -F -j -q /data/customers/${cid}-file"
  /sbin/mkfs -t ext3 -F -j -q /data/customers/${cid}-file
fi

if test -e /data/customers/$cid; then
  echo "ERROR: /data/customers/$cid exists"
  exit
else
  echo "mkdir /data/customers/${cid}"
  mkdir /data/customers/${cid}
  echo "mount -o loop /data/customers/${cid}-file /data/customers/$cid"
  mount -o loop /data/customers/${cid}-file /data/customers/$cid
  df -h /data/customers/$cid

  echo "fsck -y /data/customers/${cid}-file" >> /etc/nfs_backup_mounts.sh
  echo "mount -o loop /data/customers/${cid}-file /data/customers/$cid" >> /etc/nfs_backup_mounts.sh
  echo "" >> /etc/nfs_backup_mounts.sh

  echo "/data/customers/$cid $ip/32(rw,no_root_squash,async,no_subtree_check)" >> /etc/exports
  /etc/init.d/nfs-kernel-server restart
  tail /var/log/messages
fi
chmod 0700 /usr/local/sbin/mkbackup
vi /etc/rc.local

add:

/etc/nfs_backup_mounts.sh

samba[edit]

apt-get install samba
vi /etc/samba/smb.conf
comment out any mounts, add
[data]
   read only = yes
   locking = no
   path = /data/iso
   guest ok = yes
/etc/init.d/smbd restart
mkdir /data/iso

Bring over some stuff from backup2

cd /data/iso
scp backup2:/d2/iso/3wfirmware.iso .
scp backup2:/d2/iso/MD5SUMS .
scp backup2:/d2/iso/bootimg.iso .
scp backup2:/d2/iso/systemrescuecd-x86-0.2.19.iso .
scp backup2:/d2/iso/win98bootcd.iso .
scp backup2:/d2/iso/acronis_bootdisk.iso .
scp backup2:/d2/iso/memtest86-3.2.iso .

Moving from one server to another[edit]

Here are the steps you would take to move settings and data from one server to a new backup server:

  • rsync over all /data/customers (we do this cause if we didn't use *-file it would copy over the files AND the data in the mountpoint)
rsync -av --progress --ignore-times *-file root@10.1.2.33:/data/customers/

after umounting all the customers, copy over the (empty) directories separately:

for f in `find .  -type d`; do rsync -av $f root@69.55.229.25:/data/customers; done
  • copy mount script
[root@backup3 /data/customers]# scp /etc/nfs_backup_mounts.sh root@69.55.229.25:/etc/nfs_backup_mounts.sh
  • copy rc.local
[root@backup3 /data/customers]# scp /etc/rc.local root@69.55.229.25:/etc/rc.local
  • copy /etc/exports
[root@backup3 /data/customers]# scp /etc/exports root@69.55.229.25:/etc/exports
  • edit /etc/hostname on both machines (set current to oldbackup3)
  • edit /etc/network/interfaces (swap IPs).
  • stop mounts from mounting on old and new servers so it doesnt start with reboot right away:
chmod 000 /etc/nfs_backup_mounts.sh
  • reboot both servers @ same time
  • check everything out
  • run /etc/nfs_backup_mounts.sh on new server
  • if switch port changed update mrtg to reflect correct port pub nic is on (on p20):
vi /usr/local/www/mgmt/mrtg/mrtg1.cfg

backup4[edit]

Summary[edit]

This machine is used for archiving data, is a backup server for colo customers, runs a samba server to make available iso's to the IPKVMs. Only FreeBSD virt customers directly accesses this server to perform their backups.

  • Location: castle, cab 3-7
  • OS: FreeNAS 9.3 (FreeBSD 9.3)
  • Networking: Priv IP: 10.1.2.9/24 AND 10.1.7.9/24, Pub IPs: 69.55.230.6/24
  • Hardware: JC-08014
           Intel S5000VSA Motherboard
           1 x Intel Xeon E5410  @ 2.33GHz CPU
           3ware 9690SA-8I RAID Card w BBU
           16GB RAM
           Dual power supply.
  • Drives: 7 TB (6 x 2TB) ZFS RAIDZ2 array running on JBOD
      1 128 GB SSD system drive and 6 drive SATA bays (3 columns of 2, drive 0 top left, drive 1 just below) all hot-swap.

Services provided[edit]

  • backup via rsync and nfs
  • samba
  • nfs
  • snmp?
  • bigbrother?

Usage[edit]

  • all data is stored under /data
  • iso images provided for customers wanting to mount an ISO as a CDROM via the IPKVM are provided via samba on this server. Images live under /data/iso  ??
  • this server serves as an archive for exported db data from bwdb and old flow files. ??
  • customers are nfs-moutned under /data/users (/mnt/zfs/users) as zfs ?

management scripts[edit]

  • mkbackups?

mkbackup <cid> GB <ip>

Cronjobs[edit]

0 0 * * * /usr/local/sbin/arecaraidchk  

RAID checks ?

35 4 * * * /usr/local/sbin/snapshot_archive

Rotate daily snapshots for infrastructure machine backups

00 15 * * * /usr/local/sbin/snapshot_rotate

Rotate daily snapshots for customer machine backups

Regular maintenance[edit]

Build[edit]

console[edit]

Summary[edit]

This box's only purpose is to serve as a means to connect to the digi serial multiplexer boxes at castle. Connect to it using the blue (cisco) ribbon cable with the beige RJ-45 to serial connector, 9600 8N1.

OBSOLETE

  • Location: castle, cab 3-8
  • OS: SunOS 5.8 (solaris)
  • Networking: Priv IP: 10.1.4.4
  • Hardware: Sun Netra


To connect to consoles, ssh in as user 'console' and use the tip command to connect to devices listed in /etc/remote

SSH WORK ~2021 ssh user@console.johncompanies.com

PW: 674*****

i.e.

tip switch-p1
tip jail1

Configuring digi/ports[edit]

/etc/remote[edit]

This is where the configuration/mapping for ports and custom names which we use along with the tip command to connect to various ports on the digi switches.

We have 2 digi's at castle we connect to:

#3-7 10.1.4.10
virt15:dv=/dev/dty/CO001s:br#38400:el=^C^S^Q^U^D:ie=%$:oe=^D:
virt13:dv=/dev/dty/CO002s:br#115200:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:

and

#3-6 10.1.4.11
jail4:dv=/dev/dty/CP001s:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:
jail16:dv=/dev/dty/CP002s:br#9600:el=^C^S^Q^U^D:ie=%$:oe=^D:hf:

The only things you need to edit are the first part (i.e. jail4) and the speed (i.e. 9600). You can decipher which port on the digi each line corresponds to by the CP001s or CO001s (port 1 on digi1 and digi2), CP002s or CO002s (port 2 on digi1 and digi2)

drpadmin[edit]

The tool you use to configure a device to a digi box is drpadmin:

bash-2.03$ su
Password:
# drpadmin

Please select an option (a)dd (d)elete (s)how (r)eset (q)uit : s
0       10.1.4.10       32      CO      771     never   1027
1       10.1.4.11       32      CP      771     never   1027
2       65.116.11.2     8       el      771     never   1027

Please select an option (a)dd (d)elete (s)how (r)eset (q)uit :

Use those commands above to modify the devices available.

Switching IP/hostname[edit]

Edit:

/etc/defaultrouter
/etc/hosts
/etc/hostname.hme0
/etc/nodename
Maybe needed to run: # ifconfig hme0 10.1.4.4 up

devweb[edit]

We do web development on devweb.johncompanies.com

Currently this is a jail running on jail17 / 69.55.230.8

If the jail is restarted, you will need to manually restart the web service with:

httpsdctl restart

All website development work should be done here first. It works exactly like and is setup like our main site.


firewall2[edit]

Summary[edit]

This machine is the primary firewall for the entire network at i2b. firewall3 is a hot standby replacement for firewall2. Both firewall2 and firewall3 should not be connected at the same time since they use the same internal and external IP addresses.

  • Location: i2b, cab 6
  • OS: FreeBSD 6.4 x86
  • Networking: Priv IP: 10.1.2.2, Pub IPs: 66.181.18.3 (external), 69.55.229.1 & 69.55.231.1 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks. TODO: describe NIC location/orientation
  • Hardware: 2 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: 73 GB (2 x 73GB) RAID1 array running on an LSI MegaRAID SCSI 320 PCI RAID card.

Services Provided[edit]

  • firewall (ipfw)
  • bigbrother for customer machines

Firewall Rule Configuration[edit]

See Firewall Rule Configuration for more discussion on how to actually manipulate firewall rules.

Disaster Recovery[edit]

TODO: need backup f/w and instructions on how to move cables.

Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)

TODO

Here's the config on the live firewall:

kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"

xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.2"

fsck_y_enable="YES"
background_fsck="NO"

defaultrouter="66.181.18.2"
hostname="firewall2.johncompanies.com"
ifconfig_bge0="inet 66.181.18.3  netmask 255.255.255.224"
ifconfig_bge1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_bge1_alias0="inet 69.55.231.1 netmask 255.255.255.0"
ifconfig_bge1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
ifconfig_bge1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
ifconfig_bge1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
ifconfig_bge1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
ifconfig_bge1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
ifconfig_bge1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
ifconfig_bge1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
ifconfig_bge1_alias8="inet 65.50.235.1  netmask 255.255.255.0"
ifconfig_fxp0="inet 10.1.2.2 netmask 255.255.255.0"
sshd_enable="YES"
usbd_enable="YES"


Cronjobs[edit]

30 3 * * * /usr/local/etc/rsync.backup Backup to backup3

0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5

Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).

59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count

Capture counts periodically

0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;

This script will create /etc/firewall.sh which contains all the firewall and pipe rules in place at the time the script was run.

*/5 * * * * /usr/local/sbin/lsiraidchk

Checking the health of the RAID array


DOS attacks[edit]

See Handling a DoS attack regarding how to handle a DOS attack.


build[edit]

partition map:
/ 58g
swap 4g
/var 512m
/tmp 512m
/usr 5.5g

4. edit /etc/make.conf 
echo "WITHOUT_X11=yes \
KERNCONF=firewall2 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf

5. add settings to /boot/loader.conf and /boot.config

echo "-Dh" >> /boot.config

echo 'console="comconsole,vidconsole" \
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf


6. turn off all ttyv's except 0 and 1 in /etc/ttys
also turn on ttyd0, change type to vt100:
vi /etc/ttys

ttyv2   "/usr/libexec/getty Pc"         cons25  off secure
ttyv3   "/usr/libexec/getty Pc"         cons25  off secure
ttyv4   "/usr/libexec/getty Pc"         cons25  off secure
ttyv5   "/usr/libexec/getty Pc"         cons25  off secure
ttyv6   "/usr/libexec/getty Pc"         cons25  off secure
ttyv7   "/usr/libexec/getty Pc"         cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0   "/usr/libexec/getty std.9600"   vt100   on  secure

kill -1 1

on console server:
vi /etc/remote
(rename port to jail8 depending on where and which digi plugged into)
test serial console


7. populate hosts
echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts

8. put key in authorized_keys on backup3
cd
ssh-keygen -t dsa -b 1024 
(default location, leave password blank)

Punch a hole in firewall1 to allow traffic to backup servers @ castle:

ipfw add 99 allow ip from 66.181.18.0/27 to 69.55.230.10 22
ipfw add 95 allow ip from 66.181.18.0/27 to 69.55.230.11 22

cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys' 

confirm that you can ssh to backup3 and backup 2 without getting a login prompt

ssh backup3 hostname

ssh backup2 hostname

ssh backup1 hostname


10. edit root's path and login script:
vi /root/.cshrc

Change alias entries (add G):
alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm       mb mount
alias mbu       mb umount

and alter the prompt, set the following:
set prompt = "`/bin/hostname -s` %/# "

11. install cvsup
cd /usr/ports/net/cvsup-without-gui 
make install clean; rehash; mail -s 'cvs installed' dave.boodman@vtext.com < /dev/null

12. get latest sources for this release:
cd /usr/src 
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
src-all" > sup

cvsup sup ; mail -s 'cvs sup done' dave.boodman@vtext.com < /dev/null

13. configure new kernel. 

cd /usr/src/sys/i386/conf 
scp backup2:/mnt/data4/build/freebsd/firewall2-6.4 ./firewall2

15. build, install kernel and world

cd /boot

mv kernel kernel.GENERIC
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel

make buildworld ; mail -s 'buildworld done' dave.boodman@vtext.com < /dev/null
(2450: 1:56min, supermicro: 59mins, 2950: 38mins)
make installworld 
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i

17. populate /etc/rc.conf with IPs and NFS settings
vi /etc/rc.conf

kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"

xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.2"

ifconfig_bce1="inet 10.1.2.2 netmask 255.255.255.0"
fsck_y_enable="YES"
background_fsck="NO"

defaultrouter="66.181.18.2"
hostname="firewall2.johncompanies.com"
ifconfig_bge0="inet 66.181.18.3  netmask 255.255.255.224"
ifconfig_bge1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_fxp0="inet 10.1.2.2 netmask 255.255.255.0"
sshd_enable="YES"
usbd_enable="YES"

20. reboot. Confirm new kernel is loaded

uname -a

21. update ports:
cd /usr/ports
echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_6_4\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup

cvsup sup; mail -s 'cvs sup ports done' dave.boodman@vtext.com < /dev/null

22. Install raid mgmt tool

# linux base
cd /usr/ports/devel/libtool22
make install base

cd /usr/ports/emulators/linux_base-fc4
make install clean

#linux-megamgr-5.20
cd /usr/ports/sysutils/linux-megamgr
make install clean

# megarc-1.51
cd /usr/ports/sysutils/megarc
make install clean

Test:
rehash; megarc -ldInfo -a0 -l0

23. install rsync from ports
cd /usr/ports/net/rsync
make install clean

choose default options

25. install bb client
adduser
Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]: 
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username   : bb
Password   : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups     : bb
Home       : /home/bb
Shell      : /bin/sh
Locked     : no
OK? (yes/no): yes

cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
tar xvf bb-freebsd.tar

edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.1 firewall2.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts

vi /home/bb/bbc1.9e-btf/ext/openfiles 
MACHINE="firewall2,johncompanies,com"      # HAS TO BE IN A,B,C FORM

cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh 
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..

vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$

./runbb.sh start
more BBOUT 
(look for errors)
exit

echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh

Punch a hole in the firewall to allow it to communicate with bb monitor:

ipfw add 00096 allow ip from 66.181.18.0/27 to 69.55.230.2


27. configure bb on mail:
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
66.181.18.3 firewall2.johncompanies.com # ssh

su bb
cd
bbsrc/bb/runbb.sh restart ; exit

29. configure ntp
echo "server 10.1.2.1" > /etc/ntp.conf

/usr/sbin/ntpd -p /var/run/ntpd.pid
sleep 2; ntpq -p
(confirm it’s able to reach our time server)

echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh

30. fwd and reverse lookups on ns1c
vr johncompanies.com
 (edit the PTR too)


33. setup backups
echo '#\!/bin/sh\
backupdir=/data/firewall2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config

on backup3:
setup backup dirs:
ssh backup3 mkdir -p /data/firewall2/current

on backup3, add the system to 
vi /usr/local/sbin/snapshot_archive

scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup 
vi /usr/local/etc/rsync.backup 
backup1 > backup3

crontab -e
1 0 * * * /usr/local/etc/rsync.backup


34. mkdir /root/logs

35. edit sshd_config for security
vi /etc/ssh/sshd_config
ListenAddress 66.181.18.3
ListenAddress 10.1.2.1

kill -1 `cat /var/run/sshd.pid`

35. raid chk

cat > /usr/local/sbin/lsiraidchk
#!/usr/bin/perl

my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;

foreach (@out) {
    if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#print $_;
}

36. add crontab entries
crontab -e
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl; 
*/5 * * * * /usr/local/sbin/lsiraidchk

#10 0 * * * rm /var/spool/clientmqueue/*

scp /etc/makefwrules.pl user@64.163.14.48:~
scp /etc/makepiperules.pl user@64.163.14.48:~
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
mkdir /etc/oldrules/

other binaries
	
scp /usr/local/bin/rulemaker user@64.163.14.48:~
mv ~user/rulemaker /usr/local/sbin
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~

Setup basic ruleset

ipfw add 00009 count udp from any to any
ipfw add 00010 allow tcp from any to any established
ipfw add 00012 deny tcp from any to any tcpflags syn tcpoptions !mss
ipfw add 00012 deny icmp from any to any icmptypes 4,5,9,10,12,13,14,15,16,17,18
ipfw add 00012 deny tcp from any to any tcpflags syn,fin
ipfw add 00012 deny tcp from any to any tcpflags fin,psh,rst,urg
ipfw add 00012 allow icmp from any to any
ipfw add 00014 deny tcp from any to any dst-port 135
ipfw add 00150 skipto 65535 ip from any to any via em1 in

IPKVM3:
00098 allow ip from { 69.55.230.6 or 69.55.230.7 } to 69.55.230.10 dst-port 139
00098 deny ip from any to 69.55.230.10 dst-port 139


firewall3[edit]

Summary[edit]

This machine is the backup firewall for the network at i2b.

  • Location: i2b, cab ?
  • OS: FreeBSD 9.1 amd64
  • Networking: Priv IP: 10.1.2.5, Pub IPs: 66.181.18.3 (external), 69.55.229.1 & 69.55.231.1 (internal). It has 3 network connections (2 onboard, 1 PCI) connecting to the external, internal and private networks.

The internal network NIC is the left one on the motherboard (69.55.229.1/24, ...).
The external network NIC is the right one on the motherboard (66.181.18.3/28).
The PCI ethernet card is connected to our private network (10.1.2.5/24).

  • Hardware: 2 SCSI SCA drive bays (2 columns of 3, drive 0 top left, drive 1 just below) all hot-swap. Dual power supply.
  • Drives: 160 GB (2 x 160GB) RAID1 array running on an LSI MegaRAID SCSI 320 PCI RAID card.

Services Provided[edit]

  • firewall (ipfw)
  • bigbrother

Firewall Rule Configuration[edit]

See Firewall Rule Configuration for more discussion on how to actually manipulate firewall rules.

Disaster Recovery[edit]

To put the backup firewall3 into service:

Move the internal cable (to our networks) from firewall2 to em1 which is the left most ethernet port (69.55.229.1).
Move the external cable (to outside world) from firewall2 to em0 which is the port to the right on the motherboard (66.181.18.3).
The PCI ethernet port (fxp0) should already be connected to private network (10.1.2.5).

Here's what you need to put in /etc/rc.conf to get a firewall going (as far as routes and IPs)

kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"

xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"
inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.5"

fsck_y_enable="YES"
background_fsck="NO"

defaultrouter="66.181.18.2"
hostname="firewall3.johncompanies.com"
ifconfig_em0="inet 66.181.18.3  netmask 255.255.255.224"

ifconfig_em1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_em1_alias0="inet 69.55.231.1 netmask 255.255.255.0"

# ifconfig_em1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
# ifconfig_em1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
# ifconfig_em1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
# ifconfig_em1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
# ifconfig_em1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
# ifconfig_em1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
# ifconfig_em1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
# ifconfig_em1_alias8="inet 65.50.235.1  netmask 255.255.255.0"

ifconfig_fxp0="inet 10.1.2.5 netmask 255.255.255.0"

sshd_enable="YES"
usbd_enable="YES"

Cronjobs[edit]

30 3 * * * /usr/local/etc/rsync.backup Backup to backup3

0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5

Reset counters and remove pipe rules on the 1st of the month. Pay attention when setting up a rule as 3 4 5 (that's not a temporary traffic cap).

59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count

Capture counts periodically

0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl;

This script will create /etc/firewall.sh which contains all the firewall and pipe rules in place at the time the script was run.

*/5 * * * * /usr/local/sbin/lsiraidchk

Checking the health of the RAID array


DOS attacks[edit]

See Handling a DoS attack regarding how to handle a DOS attack.


build[edit]

partition map:
/ 58g
swap 4g
/var 512m
/tmp 512m
/usr 5.5g

4. edit /etc/make.conf 
echo "WITHOUT_X11=yes \
KERNCONF=firewall3 \
BOOT_COMCONSOLE_SPEED=115200" >> /etc/make.conf

5. add settings to /boot/loader.conf and /boot.config

echo "-Dh" >> /boot.config

echo 'console="comconsole,vidconsole" \
boot_multicons="YES" \
boot_serial="YES" \
comconsole_speed="115200"' >> /boot/loader.conf


6. turn off all ttyv's except 0 and 1 in /etc/ttys
also turn on ttyd0, change type to vt100:
vi /etc/ttys

ttyv2   "/usr/libexec/getty Pc"         cons25  off secure
ttyv3   "/usr/libexec/getty Pc"         cons25  off secure
ttyv4   "/usr/libexec/getty Pc"         cons25  off secure
ttyv5   "/usr/libexec/getty Pc"         cons25  off secure
ttyv6   "/usr/libexec/getty Pc"         cons25  off secure
ttyv7   "/usr/libexec/getty Pc"         cons25  off secure
# Serial terminals
# The 'dialup' keyword identifies dialin lines to login, fingerd etc.
ttyd0   "/usr/libexec/getty std.9600"   vt100   on  secure

kill -1 1

on console server:
vi /etc/remote
(rename port to jail8 depending on where and which digi plugged into)
test serial console


7. populate hosts
echo "69.55.230.10 backup2" >> /etc/hosts
echo "69.55.230.11 backup1" >> /etc/hosts
echo "10.1.2.3 backup3" >> /etc/hosts

8. put key in authorized_keys on backup3
cd
ssh-keygen -t dsa -b 1024 
(default location, leave password blank)

Punch a hole in firewall1 to allow traffic to backup servers @ castle:

ipfw add 99 allow ip from 66.181.18.0/27 to 69.55.230.10 22
ipfw add 95 allow ip from 66.181.18.0/27 to 69.55.230.11 22

cat /root/.ssh/id_dsa.pub | ssh backup3 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup2 'cat - >> /root/.ssh/authorized_keys' 
cat /root/.ssh/id_dsa.pub | ssh backup1 'cat - >> /root/.ssh/authorized_keys' 

confirm that you can ssh to backup3 and backup 2 without getting a login prompt

ssh backup3 hostname

ssh backup2 hostname

ssh backup1 hostname


10. edit root's path and login script:
vi /root/.cshrc

Change alias entries (add G):
alias la        ls -aG
alias lf        ls -FAG
alias ll        ls -lAG
alias ls        ls -AG
alias mbm       mb mount
alias mbu       mb umount

and alter the prompt, set the following:
set prompt = "`/bin/hostname -s` %/# "

11. install cvsup
cd /usr/ports/net/cvsup-without-gui 
make install clean; rehash; mail -s 'cvs installed' 8583619553@vtext.com < /dev/null

12. get latest sources for this release:
cd /usr/src 
echo "*default host=cvsup4.freebsd.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_9_1\
*default delete use-rel-suffix\
*default compress\
src-all" > sup

cvsup sup ; mail -s 'cvs sup done' 8583619553@vtext.com < /dev/null

13. configure new kernel. 

cd /usr/src/sys/amd64/conf 
scp backup2:/mnt/data4/build/freebsd/firewall3-9.1 ./firewall3

15. build, install kernel and world

cd /boot

mv kernel kernel.GENERIC
cd kernel.GENERIC
cd /usr/src
make buildkernel installkernel

make buildworld ; mail -s 'buildworld done' 8583619553@vtext.com < /dev/null
(supermicro: 2:15 mins, 2950: 38? mins)
make installworld 
(2450: 3min, supermicro: 1min, 2950: :34)
mergemaster -i

17. populate /etc/rc.conf with IPs and NFS settings
vi /etc/rc.conf

kern_securelevel_enable="NO"
portmap_enable="NO"
sendmail_enable="NO"
usbd_enable="YES"
gateway_enable="YES"

xntpd_enable="YES"
nfs_client_enable="YES"
nfs_reserved_port_only="YES"

fsck_y_enable="YES"
background_fsck="NO"

hostname="firewall3.johncompanies.com"
#  external network
ifconfig_em0="inet 66.181.18.3  netmask 255.255.255.224"

#  internal network
ifconfig_em1="inet 69.55.229.1 netmask 255.255.255.0"
ifconfig_em1_alias0="inet 69.55.231.1  netmask 255.255.255.0"

ifconfig_em1_alias1="inet 65.50.228.1  netmask 255.255.255.0"
ifconfig_em1_alias2="inet 65.50.229.1  netmask 255.255.255.0"
ifconfig_em1_alias3="inet 65.50.230.1  netmask 255.255.255.0"
ifconfig_em1_alias4="inet 65.50.231.1  netmask 255.255.255.0"
ifconfig_em1_alias5="inet 65.50.232.1  netmask 255.255.255.0"
ifconfig_em1_alias6="inet 65.50.233.1  netmask 255.255.255.0"
ifconfig_em1_alias7="inet 65.50.234.1  netmask 255.255.255.0"
ifconfig_em1_alias8="inet 65.50.235.1  netmask 255.255.255.0"

defaultrouter="66.181.18.2"

#  private network
ifconfig_fxp0="inet 10.1.2.5 netmask 255.255.255.0"

inetd_enable="YES"
inetd_flags="-wW -a 10.1.2.5"

sshd_enable="YES"
usbd_enable="YES"
ntpd_enable="YES"
# powerd_enable="YES"


20. reboot. Confirm new kernel is loaded

uname -a

21. update ports:
cd /usr/ports

echo "*default host=cvsup4.FreeBSD.org\
*default base=/usr\
*default prefix=/usr\
*default release=cvs tag=RELENG_9_1\
*default delete use-rel-suffix\
*default compress\
ports-all tag=." > sup

cvsup sup; mail -s 'cvs sup ports done' 8583619553@vtext.com < /dev/null

22. Install raid mgmt tool

# linux base
cd /usr/ports/devel/libtool22
make install base

cd /usr/ports/emulators/linux_base-fc4
make install clean

scp backup2:/d4/build/3ware/tw_cli-freebsd-x86_64-9.5.0.1.tgz /usr/local/sbin
cd /usr/local/sbin 
tar xzvf tw_cli-freebsd-x86_64-9.5.0.1.tgz
rm tw_cli-freebsd-x86_64-9.5.0.1.tgz

23. install rsync from ports
cd /usr/ports/net/rsync
make install clean

choose default options

25. install bb client
adduser
Username: bb
Full name: bb
Uid (Leave empty for default): 1984
Login group [bb]:
Login group is bb. Invite bb into other groups? []:
Login class [default]:
Shell (sh csh tcsh nologin) [sh]: 
Home directory [/home/bb]:
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username   : bb
Password   : <random>
Full Name  : bb
Uid        : 1984
Class      :
Groups     : bb
Home       : /home/bb
Shell      : /bin/sh
Locked     : no
OK? (yes/no): yes

cd /usr/home/bb
scp backup2:/mnt/data4/build/bb/bb-freebsd.tar .
tar xvf bb-freebsd.tar

edit /home/bb/bbc1.9e-btf/etc/bb-hosts with something like:
echo "69.55.230.2 mail.johncompanies.com # BBPAGER BBNET BBDISPLAY smtp ssh \
10.1.2.5 firewall3.johncompanies.com # ssh" > /home/bb/bbc1.9e-btf/etc/bb-hosts

vi /home/bb/bbc1.9e-btf/ext/openfiles 
MACHINE="firewall3,johncompanies,com"      # HAS TO BE IN A,B,C FORM

cd /usr/home/bb/bbc1.9e-btf/etc
./bbchkcfg.sh 
(y to questions)
./bbchkhosts.sh
(ignore ssh errors)
cd ../..
chown -R bb .
su bb
cd
cd bbc1.9e-btf/src
make; make install
cd ..

vi /usr/home/bb/bbc1.9e-btf/bin/bb-cpu.sh
        $1 $TOPARGS > $BBTMP/TOP.$$
#        /usr/local/jail/bin/jtop > $BBTMP/TOP.$$

./runbb.sh start
more BBOUT 
(look for errors)
exit

echo 'su - bb -c "cd /home/bb/bbc1.9e-btf; ./runbb.sh start"' > /usr/local/etc/rc.d/bb.sh
chmod +x /usr/local/etc/rc.d/bb.sh

Punch a hole in the firewall to allow it to communicate with bb monitor:

ipfw add 00096 allow ip from 66.181.18.0/27 to 69.55.230.2


27. configure bb on mail:
vi /usr/home/bb/bbsrc/bb1.9e-btf/etc/bb-hosts
66.181.18.3 firewall3.johncompanies.com # ssh

su bb
cd
bbsrc/bb/runbb.sh restart ; exit

29. configure ntp
echo "server 10.1.2.1" > /etc/ntp.conf

/usr/sbin/ntpd -p /var/run/ntpd.pid
sleep 2; ntpq -p
(confirm it’s able to reach our time server)

echo '/usr/sbin/ntpd -c /etc/ntp.conf -p /var/run/ntpd.pid -f /var/db/ntpd.drift' > /usr/local/etc/rc.d/ntp.sh
chmod 0700 /usr/local/etc/rc.d/ntp.sh

30. fwd and reverse lookups on ns1c
vr johncompanies.com
 (edit the PTR too)


33. setup backups
echo '#\!/bin/sh\
backupdir=/data/firewall2/current\
\
## ENTRY /etc ' > /usr/local/etc/backup.config

on backup3:
setup backup dirs:
ssh backup3 mkdir -p /data/firewall2/current

on backup3, add the system to 
vi /usr/local/sbin/snapshot_archive

scp 69.55.230.2:/usr/local/etc/rsync.backup /usr/local/etc/rsync.backup 
vi /usr/local/etc/rsync.backup 
backup1 > backup3

crontab -e
1 0 * * * /usr/local/etc/rsync.backup


34. mkdir /root/logs

35. edit sshd_config for security
vi /etc/ssh/sshd_config
ListenAddress 66.181.18.3
ListenAddress 10.1.2.5

kill -1 `cat /var/run/sshd.pid`

35. raid chk

cat > /usr/local/sbin/lsiraidchk
#!/usr/bin/perl

my @out = split "\n", `megarc -ldInfo -a0 -Lall|grep Status:`;

foreach (@out) {
    if ($_ =~ /DEGRADED/) { $date = `date`; chomp $date; `echo "$date: RAID ARRAY DEGRADED" >> /var/log/messages`; }
#print $_;
}

36. add crontab entries
crontab -e
30 3 * * * /usr/local/etc/rsync.backup
0 0 1 * * /sbin/ipfw zero
0 0 1 * * /sbin/ipfw del 3 4 5
59 23 30 * * /sbin/ipfw show > /tmp/ipfw_count
3 0 30 * * /sbin/ipfw show > /tmp/ipfw_count
0 3 * * * /etc/makefwrules.pl; /etc/makepiperules.pl; 
*/5 * * * * /usr/local/sbin/lsiraidchk

#10 0 * * * rm /var/spool/clientmqueue/*

scp /etc/makefwrules.pl user@64.163.14.48:~
scp /etc/makepiperules.pl user@64.163.14.48:~
mv /home/user/makefwrules.pl /etc
mv /home/user/makepiperules.pl /etc
touch /etc/firewall.sh
mkdir /etc/oldrules/

other binaries
	
scp /usr/local/bin/rulemaker user@64.163.14.48:~
mv ~user/rulemaker /usr/local/sbin
scp ~user/Sendmail.pm user@64.163.14.48:~
scp ~user/doswatch.pl user@64.163.14.48:~

Setup basic ruleset

ipfw add 00009 count udp from any to any
ipfw add 00010 allow tcp from any to any established
ipfw add 00012 deny tcp from any to any tcpflags syn tcpoptions !mss
ipfw add 00012 deny icmp from any to any icmptypes 4,5,9,10,12,13,14,15,16,17,18
ipfw add 00012 deny tcp from any to any tcpflags syn,fin
ipfw add 00012 deny tcp from any to any tcpflags fin,psh,rst,urg
ipfw add 00012 allow icmp from any to any
ipfw add 00014 deny tcp from any to any dst-port 135
ipfw add 00150 skipto 65535 ip from any to any via em1 in

IPKVM3:
00098 allow ip from { 69.55.230.6 or 69.55.230.7 } to 69.55.230.10 dst-port 139
00098 deny ip from any to 69.55.230.10 dst-port 139

wiki[edit]

The wiki (mediawiki) runs on nat2 in a jail running off 69.55.229.8

The backup wiki lives on virt13 in CT 5 / 69.55.230.18

Setup jail[edit]

mkdir /mnt/data1/wiki-dir
cd /usr/src
make installworld DESTDIR=/mnt/data1/wiki-dir
cd etc
make distribution DESTDIR=/mnt/data1/wiki-dir

mount -t devfs devfs /mnt/data1/wiki-dir/dev
devfs -m /mnt/data1/wiki-dir/dev rule -s 3 applyset 

cd /mnt/data1/wiki-dir

ln -sf dev/null kernel

scp jail9:/usr/local/sbin/jkill /mnt/data1/wiki-dir/sbin

jail /mnt/data1/wiki-dir wiki.johncompanies.com 69.55.229.8 /bin/sh
csh

touch /etc/fstab
echo 'network_interfaces=""\
hostname="wiki.johncompanies.com"\
kern_securelevel_enable="NO"\
sendmail_enable="YES"\
sshd_enable="YES"' > /etc/rc.conf

echo "nameserver 69.55.229.3\
nameserver 69.55.225.225" >> /etc/resolv.conf 

vi /etc/crontab
 
(remove the adjkerntz lines )
 
vi /etc/periodic/security/100.chksetuid
 
replace: MP=`mount -t ufs | grep -v " nosuid" | awk '{ print $3 }' | sort`
 with: MP='/' (use single quotes) 

mkdir -p /usr/compat/linux/dev
 
adduser

Username: user
Full name: user
Uid (Leave empty for default):
Login group [user]:
Login group is user. Invite user into other groups? []: wheel
Login class [default]:
Shell (sh csh tcsh nologin) [sh]:
Home directory [/home/user]:
Home directory permissions (Leave empty for default):
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: y
Lock out the account after creation? [no]:
Username   : user
Password   : <random>
Full Name  : user
Uid        : 1001
Class      :
Groups     : user
Home       : /home/user
Home Mode  :
Shell      : /bin/sh
Locked     : no
OK? (yes/no): y
adduser: INFO: Successfully added (user) to the user database.
adduser: INFO: Password for (user) is: 901gmYjO
Add another user? (yes/no): n
Goodbye! 

vi /usr/home/user/.profile 
TERM=vt100;     export TERM
 
tzsetup
 
newaliases 
 
rm /sbin/halt /sbin/reboot
ln /sbin/jkill /sbin/halt
ln /sbin/jkill /sbin/reboot
 
vi /etc/syslog.conf
#*.err;kern.warning;auth.notice;mail.crit               /dev/console
*.err;kern.warning;auth.notice;mail.crit                /var/log/messages 

exit
exit
 
cd libexec
chflags noschg ld-elf32.so.1
chflags noschg ld-elf.so.1
mv ld-elf32.so.1 ld-elf32.so.1-orig
ln ld-elf.so.1 ld-elf32.so.1
chflags schg ld-elf.so.1
chflags schg ld-elf32.so.1
 
cp -r /usr/ports /mnt/data1/wiki-dir/usr 

cat > /usr/local/etc/rc.d/wiki.sh
mount -t devfs devfs /mnt/data1/wiki-dir/dev/
devfs -m /mnt/data1/wiki-dir/dev rule -s 3 applyset
jail /mnt/data1/wiki-dir wiki.johncompanies.com 69.55.229.8 /bin/sh /etc/rc

chmod 0700 /usr/local/etc/rc.d/wiki.sh

mediawiki setup[edit]


cd /usr/ports/net/rsync
make install clean

cd /usr/ports/distfiles/
fetch http://downloads.mysql.com/archives/mysql-5.5/mysql-5.5.4-m3.tar.gz
cd /usr/ports/databases/mysql55-server
make install clean

cd /usr/ports/distfiles/
fetch http://downloads.php.net/johannes/php-5.3.2.tar.bz2
cd /usr/ports/lang/php52
make install clean
(build apache module)

cd /usr/ports/lang/php5-extensions
make install clean

cd /usr/ports/www/apache22
make install clean

cd /usr/local/www/
fetch http://download.wikimedia.org/mediawiki/1.19/mediawiki-1.19.2.tar.gz
tar xzf mediawiki-1.19.2.tar.gz
mv mediawiki-1.19.2 wiki

vi /usr/local/etc/apache22/httpd.conf
DocumentRoot "/usr/local/www/"

Include etc/apache22/extra/vhost-wiki.conf
Listen 443

<IfModule mod_php5.c>
    <FilesMatch "\.ph(p3?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>
    <FilesMatch "\.phps$">
        SetHandler application/x-httpd-php-source
    </FilesMatch>
    # To re-enable php in user directories comment the following lines
    # (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
    # prevents .htaccess files from disabling it.
    <IfModule mod_userdir.c>
        <Directory /home/*/public_html>
            php_admin_value engine Off
        </Directory>
    </IfModule>
</IfModule>


cat > /usr/local/etc/apache22/extra/vhost-wiki.conf 
<VirtualHost *:443>
        ServerAdmin support@johncompanies.com

        DocumentRoot /usr/local/www/wiki
#        <Directory />
#                Options FollowSymLinks
#                AllowOverride None
#                Order deny,allow
#        </Directory>
        <Directory /usr/local/www/wiki>
                Options Indexes FollowSymLinks MultiViews
                Deny from all
                AllowOverride AuthConfig
                Order allow,deny
                DirectoryIndex index.php
                #Allow from 69.55.233.195
                #Allow from boody.dyndns.org
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog /var/log/httpd-error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/httpd-access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

    SSLEngine on
    SSLCertificateFile /usr/local/etc/apache22/ssl/server.crt
    SSLCertificateKeyFile /usr/local/etc/apache22/ssl/server.key

</VirtualHost>

mkdir ssl
cd ssl

openssl req -days 1999 -new -x509 -nodes -out server.crt -keyout server.key
US
CA
San Diego
johncompanies.com
johncompanies.com
wiki.johncompanies.com
support@johncompanies.com

cat > /usr/local/www/wiki/.htaccess
AuthType Basic
AuthUserFile /usr/local/etc/apache22/wiki.passwd
AuthName wiki
require valid-user
satisfy any

cd /usr/local/etc/apache22
htpasswd -c wiki.passwd admin

https://69.55.229.8/index.php

use mysql (innodb)
wiki name: JCWiki
Support / (mail pass) / support@johncompanies.com

cat > /usr/local/www/wiki/LocalSettings.php

<?php
# This file was automatically generated by the MediaWiki 1.19.2
# installer. If you make manual changes, please keep track in case you
# need to recreate them later.
#
# See includes/DefaultSettings.php for all configurable settings
# and their default values, but don't forget to make changes in _this_
# file, not there.
#
# Further documentation for configuration settings may be found at:
# http://www.mediawiki.org/wiki/Manual:Configuration_settings

# Protect against web entry
if ( !defined( 'MEDIAWIKI' ) ) {
	exit;
}

## Uncomment this to disable output compression
# $wgDisableOutputCompression = true;

$wgSitename      = "JCWiki";

## The URL base path to the directory containing the wiki;
## defaults for all runtime URL paths are based off of this.
## For more information on customizing the URLs please see:
## http://www.mediawiki.org/wiki/Manual:Short_URL
$wgScriptPath       = "";
$wgScriptExtension  = ".php";

## The protocol and server name to use in fully-qualified URLs
$wgServer           = "https://69.55.229.8";

## The relative URL path to the skins directory
$wgStylePath        = "$wgScriptPath/skins";

## The relative URL path to the logo.  Make sure you change this from the default,
## or else you'll overwrite your logo when you upgrade!
#$wgLogo             = "$wgStylePath/common/images/wiki.png";
$wgLogo             = "$wgStylePath/common/images/jclogo.gif";

## UPO means: this is also a user preference option

$wgEnableEmail      = true;
$wgEnableUserEmail  = true; # UPO

$wgEmergencyContact = "apache@69.55.229.8";
$wgPasswordSender   = "apache@69.55.229.8";

$wgEnotifUserTalk      = false; # UPO
$wgEnotifWatchlist     = false; # UPO
$wgEmailAuthentication = true;

## Database settings
$wgDBtype           = "mysql";
$wgDBserver         = "localhost";
$wgDBname           = "my_wiki";
$wgDBuser           = "root";
$wgDBpassword       = "";

# MySQL specific settings
$wgDBprefix         = "";

# MySQL table options to use during installation or update
$wgDBTableOptions   = "ENGINE=InnoDB, DEFAULT CHARSET=binary";

# Experimental charset support for MySQL 5.0.
$wgDBmysql5 = false;

## Shared memory settings
$wgMainCacheType    = CACHE_NONE;
$wgMemCachedServers = array();

## To enable image uploads, make sure the 'images' directory
## is writable, then set this to true:
$wgEnableUploads  = false;
#$wgUseImageMagick = true;
#$wgImageMagickConvertCommand = "/usr/bin/convert";

# InstantCommons allows wiki to use images from http://commons.wikimedia.org
$wgUseInstantCommons  = false;

## If you use ImageMagick (or any other shell command) on a
## Linux server, this will need to be set to the name of an
## available UTF-8 locale
$wgShellLocale = "en_US.utf8";

## If you want to use image uploads under safe mode,
## create the directories images/archive, images/thumb and
## images/temp, and make them all writable. Then uncomment
## this, if it's not already uncommented:
#$wgHashedUploadDirectory = false;

## Set $wgCacheDirectory to a writable directory on the web server
## to make your wiki go slightly faster. The directory should not
## be publically accessible from the web.
#$wgCacheDirectory = "$IP/cache";

# Site language code, should be one of the list in ./languages/Names.php
$wgLanguageCode = "en";

$wgSecretKey = "abc699ef26890b49b4055430f8ebbd25e84cce21a7e53aeaec4d4313af4c9739";

# Site upgrade key. Must be set to a string (default provided) to turn on the
# web installer while LocalSettings.php is in place
$wgUpgradeKey = "3196710f4a7d7332";

## Default skin: you can change the default skin. Use the internal symbolic
## names, ie 'standard', 'nostalgia', 'cologneblue', 'monobook', 'vector':
$wgDefaultSkin = "vector";

## For attaching licensing metadata to pages, and displaying an
## appropriate copyright notice / icon. GNU Free Documentation
## License and Creative Commons licenses are supported so far.
$wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
$wgRightsUrl  = "";
$wgRightsText = "";
$wgRightsIcon = "";

# Path to the GNU diff3 utility. Used for conflict resolution.
$wgDiff3 = "/usr/bin/diff3";

# Query string length limit for ResourceLoader. You should only set this if
# your web server has a query string length limit (then set it to that limit),
# or if you have suhosin.get.max_value_length set in php.ini (then set it to
# that value)
$wgResourceLoaderMaxQueryLength = -1;



# End of automatically generated settings.
# Add more configuration options below.


copy/backup wiki[edit]

on main/primary wiki:

/usr/local/etc/rc.d/mysql-server stop
ssh 69.55.230.18 "/etc/init.d/mysql stop"
rsync -av /var/db/mysql/my_wiki/ 69.55.230.18:/var/lib/mysql/my_wiki/
rsync -av /var/db/mysql/ib* 69.55.230.18:/var/lib/mysql/
/usr/local/etc/rc.d/mysql-server start
ssh 69.55.230.18 "/etc/init.d/mysql start"