Articles

Friday, April 5, 2013

Run ZNC IRC Bouncer as a Service

Below is a simple init script that will run your ZNC server as a service. Create a new file in /etc/init.d/ called znc and paste the following code in it. 


#!/bin/bash
### BEGIN INIT INFO
# Provides:          znc
# Required-Start:    $local_fs $syslog $network
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start ZNC at boot time
# Description:       Enable ZNC provided by /etc/init.d/znc.
### END INIT INFO

PID=`pidof znc`

case "$1" in
    start)
        if [[ $PID != "" ]]; then
            echo "ZNC is already running"
            exit 1
         else
            echo "Starting ZNC"
            sudo -u ubuntu znc > /dev/null 2>&1
        fi
        ;;
    stop)
        if [[ $PID != "" ]]; then
            echo "Stopping ZNC"
            kill -9 $PID > /dev/null 2>&1
        else
            echo "ZNC is not running"
            exit 1
        fi
        ;;
    restart|reload)
        if [[ $PID != '' ]]; then
            echo "Stopping ZNC"
            kill -9 $PID > /dev/null 2>&1
            echo "Starting ZNC"
            sudo -u ubuntu znc > /dev/null 2>&1
        else
            echo "ZNC is not running"
            exit 1
        fi
        ;;
    status)
        if [[ $PID != "" ]]; then
            echo "ZNC is running"
        else
            echo "ZNC is not running"
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status}"
        exit 2
        ;;
esac



After you've created the file you need to make it executable:

chmod +x /etc/init.d/znc

Then to add it to your runlevels run:

sudo update-rc.d znc defaults

Edit:

Apparently I should have read the docs. In the ZNC wiki are instructions for doing this. Ah well...

http://wiki.znc.in/Running_ZNC_as_a_system_daemon

Wednesday, February 13, 2013

Setting up Zarafa on Debian

This is just my personal documentation on the process I use. I had this in a text file and didn't want to lose it so I figured I'd post it here. If it helps someone out, great.


1 - Install OS - Choose SSH and Web Server during tasksel package selection
                 Make sure to enable the extra repos

2 - Configure networking
nano /etc/network/interfaces
nano /etc/resolv.conf

3 - Install MySQL
apt-get install mysql-server

4 - Create MySQL user
mysql -u root -p
CREATE USER 'zarafa'@'localhost' IDENTIFIED BY 'password';


4 - Test PHP/Apache
echo '<?php echo phpinfo(); ?>' >>/var/www/index.php
* Be sure to delete this file after successfully testing that PHP is working :: rm /var/www/index.php

5 - Install Zarafa Common Package
dpkg -i zarafa-common_7.1.2-39121_amd64.deb

6 - Install Dependencies
apt-get install libboost-system1.42.0 libboost-filesystem1.42.0 libicu44

7 - Install Zarafa Server
./install.sh

8 - Test Zarafa WebAccess
http://<ip address>/webaccess/

9 - Grant priveleges (documentation was wrong)
mysql -u root -p
GRANT alter, alter routine, create, create routine, delete, drop, index, insert, lock tables, select, update ON zarafa.* TO 'zarafa'@'localhost' IDENTIFIED BY 'password';

10 - Restart Zarafa Server
/etc/init.d/zarafa-server restart

13 - Create Public Store
zarafa-admin -s
* If you the message 'The server is not running, or not accessable through file:///var/run/zarafa.' try restarting the Zarafa Server

14 - Verify Public Store was created successfully
zarafa-admin -s
* Should tell you: 'Unable to create store, public already exists'

15 - Create OU in AD for Zarafa users

16 - Install ADS plugin on DC
* Make sure the user is part of the Schema Admins group
* Right click, Run as Administrator
* View the Properties of a user and verify the Zarafa tab is available in AD Users and Computer snap-in

17 - Change user store in server.cfg to use LDAP (Need to work on using LDAPS for LDAP over SSL)
nano /etc/zarafa/server.cfg
user_plugin             = ldap

18 - Verify the user plugin path is set correctly for x86_64 systems
plugin_path             = /usr/lib64/zarafa

19 - Create AD user that Zarafa will use to bind to the LDAP database (need to figure out the least priveleged permissions for this to work)
     Create the user in the same OU or Container that the rest of the Zarafa users will be in

20 - Configure Zarafa to use ADS for user store
nano /etc/zarafa/ldap.active-directory.cfg

21 - Configure AD user for LDAP bind (Must be in LDAP DN format)
nano /etc/zarafa/ldap.active-directory.cfg
ldap_bind_user = cn=Zarafa,ou=ZarafaUsers,dc=domain,dc=local
* Make sure none of the CN's in the DN contain spaces
ldap_bind_passwd = password

22 - Set the LDAP search base
ldap_search_base = ou=ZarafaUsers,dc=domain,dc=local

23 - Rename the LDAP config.
mv /etc/zarafa/ldap.active-directory.cfg /etc/zarafa/ldap.cfg

24 - Restart Zarafa Server
/etc/init.d/zarafa-server restart

25 - Test that you can authenticate to Zarafa webaccess with an AD account

26 - Install Postfix
apt-get install postfix postfix-ldap
* Choose Internet Site during setup

27 - Add MX record to DNS server

28 - Postfix main.cf config
http://doc.zarafa.com/7.1/Administrator_Manual/en-US/html-single/#_MTAIntegration

nano /etc/postfix/main.cf

echo 'virtual_mailbox_domains = domain.local' >> /etc/postfix/main.cf
echo 'virtual_mailbox_maps = ldap:/etc/postfix/ldap-users.cf' >> /etc/postfix/main.cf
echo 'virtual_alias_maps = ldap:/etc/postfix/ldap-aliases.cf, ldap:/etc/postfix/ldap-groups.cf' >> /etc/postfix/main.cf
echo 'virtual_transport = lmtp:127.0.0.1:2003' >> /etc/postfix/main.cf

29 - Configure Postfix for LDAP authentication
touch /etc/postfix/ldap-users.cf
nano ldap-users.cf

server_host = 192.168.0.100
search_base = ou=Users,dc=example,dc=local
version = 3
bind = yes
bind_dn = cn=zarafa,ou=Users,dc=example,dc=local
bind_pw = secret
scope = sub
query_filter = (&(objectClass=user)(mail=%s))
result_attribute = mail
 
 
touch /etc/postfix/ldap-groups.cf

server_host = 192.168.0.100
search_base = ou=groups,dc=example,dc=local
version = 3
bind = yes
bind_dn = cn=zarafa,ou=Users,dc=example,dc=local
bind_pw = secret
query_filter = (&(objectclass=group)(mail=%s))
leaf_result_attribute = mail
special_result_attribute = member


touch /etc/postfix/ldap-aliases.cf

server_host = 192.168.0.100
search_base = ou=Users,dc=example,dc=local
version = 3
bind = yes
bind_dn = cn=zarafa,ou=Users,dc=example,dc=local
bind_pw = secret
scope = sub
query_filter = (&(objectClass=user)(otherMailbox=%s))
result_attribute = mail

30 - Restart services for changes to take effect
/etc/init.d/postfix restart
/etc/init.d/zarafa-dagent restart

31 - Configure the Dagent to start at boot time
update-rc.d zarafa-dagent defaults



## Hardening Zarafa ##



32 - Configure Zarafa to run as non-root

addgroup --system zarafa
adduser --system --home /dev/null --no-create-home \
     --ingroup zarafa \
     --disabled-password --gecos 'Zarafa services' \
     --shell /bin/false zarafa
chown -R zarafa:zarafa /var/log/zarafa
chmod -R 710 /var/log/zarafa/
 
33 - Setup Certificate CA for SSL

mkdir /etc/zarafa/ssl
chmod -R 700 /etc/zarafa/ssl
cd /etc/zarafa/ssl
sh /usr/share/doc/zarafa/ssl-certificates.sh server
 * Organizational Unit names must be different
 * No public key is needed
nano /etc/zarafa/server.cfg
 * Configure SSL settings
cp /etc/zarafa/ssl/demoCA/cacert.pem /etc/zarafa/ssl
chown -R zarafa:zarafa /etc/zarafa/ssl/
 
34 - Restart Zarafa
/etc/init.d/zarafa-server restart

Tuesday, December 11, 2012

How to determine if Windows was shutdown or rebooted


An user on FreeNode recently asked a question regarding how he can run a backup script only if the system is shutting down. At the face of it, it sounds simple, use a shutdown script like people have for years, but the keyword here is only. He needed to be able to run a script if the system was sent a shutdown event, but not run the script if the system was rebooted. This throws a wrench into using a shutdown script because a shutdown script runs regardless of whether the system is rebooted or shutdown. When an application or user initiates a shutdown Windows will write an event to the Event Viewer System log. The event originates from the USER32 event source with an Event ID of 1074. A typical 1074 event looks like this:

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="USER32" /> 
  <EventID Qualifiers="32768">1074</EventID> 
  <Level>4</Level> 
  <Task>0</Task> 
  <Keywords>0x80000000000000</Keywords> 
  <TimeCreated SystemTime="2012-12-05T01:34:03.000000000Z" /> 
  <EventRecordID>6649</EventRecordID> 
  <Channel>System</Channel> 
  <Computer>computer.domain.local</Computer> 
  <Security UserID="S-1-5-21-2671312382-3219971570-2213343823-1105" /> 
  </System>
- <EventData>
  <Data>C:\Windows\system32\shutdown.exe (COMPUTERNAME)</Data> 
  <Data>COMPUTERNAME</Data> 
  <Data>No title for this reason could be found</Data> 
  <Data>0x800000ff</Data> 
  <Data>restart</Data> 
  <Data /> 
  <Data>DOMAIN\username</Data> 
  <Binary>FF000080000000000000000000000000000000000000000000000000000000000000000000000000</Binary> 
  </EventData>
  </Event>

This is the XML view of the event data generated by a reboot request. The part we are interested in is under the EventData node, where it says restart. If it was a shutdown event that was initiated it would say shutdown rather than restart. This is perfect as we now have a way to determine whether or not the system was sent a shutdown or restart request. So how can we get this data programatically via our shutdown script? Simple, we can use the wevtutil utility that ships with Windows Vista and up. The help context for the utility is quite lengthy so I won't post it all here, but you can open a Command Prompt and run wevtutil /? to see all the options. The wevtutil can make use of XPath queries for querying the XML output of an event. We can use an XPath query to query only for the data we need to check whether or not the system was sent a shutdown or restart. The following command will grab all the 1074 events from the USER32 source in the System event log:


C:\>wevtutil qe system /f:text /q:"*[System/EventID=1074]"
Event[0]:
  Log Name: System
  Source: USER32
  Date: 2012-10-05T01:10:59.000
  Event ID: 1074
  Task: N/A
  Level: Information
  Opcode: N/A
  Keyword: Classic
  User: S-1-5-18
  User Name: NT AUTHORITY\SYSTEM
  Computer: computername
  Description:
The process C:\Windows\system32\winlogon.exe (COMPUTERNAME) has initiated the restart of computer COMPUTERNAME on be
half of user NT AUTHORITY\SYSTEM for the following reason: Operating System: Upgrade (Planned)
 Reason Code: 0x80020003
 Shutdown Type: restart
 Comment:

Event[1]:
  Log Name: System
  Source: USER32
  Date: 2012-10-04T18:55:14.000
  Event ID: 1074
  Task: N/A
  Level: Information
  Opcode: N/A
  Keyword: Classic
  User: S-1-5-18
  User Name: NT AUTHORITY\SYSTEM
  Computer: computername
  Description:
The process C:\Windows\System32\shutdown.exe (COMPUTERNAME) has initiated the restart of computer COMPUTERNAME on behalf of u
ser NT AUTHORITY\SYSTEM for the following reason: No title for this reason could be found
 Reason Code: 0x800000ff
 Shutdown Type: restart
 Comment:

...

We use the /f switch here to specify that the output should be in plain text as it defaults to XML. So now we can query for the events we need, but we need a way to sort them and to only grab the last event. We can use the /c and /rd switches to do this. The /c switch takes an unsigned integer as a parameter that tells wevtutil how many events to return. The /rd switch takes a boolean and tells wevtutil do sort them in reverse direction. Now our command looks like this:

C:\>wevtutil qe system /c:1 /rd:true /f:text /q:"*[System/EventID=1074]"
Event[0]:
  Log Name: System
  Source: USER32
  Date: 2012-12-04T19:34:03.000
  Event ID: 1074
  Task: N/A
  Level: Information
  Opcode: N/A
  Keyword: Classic
  User: S-1-5-21-2671312382-3219971570-2213343823-1105
  User Name: DOMAIN\username
  Computer: computer.domain.local
  Description:
The process C:\Windows\system32\shutdown.exe (WIN7) has initiated the restart of computer WIN7 on behalf of user DOMAIN\username for the following reason: No title for this reason could be found
 Reason Code: 0x800000ff
 Shutdown Type: restart
 Comment:

Now all we have to do is parse out the Shutdown Type which is made simple with the for command:


C:\>for /f "tokens=3 delims= " %i in ('wevtutil qe system /c:1 /rd:true /f:text /q:"*[System/EventID=1074]" ^| findstr /c:"Shutdown Type"') do @echo %i
restart

C:\>

Now that we have parsed out the shutdown type we can set it to a variable and then run conditional code based on the value of the variable.

@echo off
for /f "tokens=3 delims= " %%i in ('wevtutil qe system /c:1 /rd:true /f:text /q:"*[System/EventID=1074]" ^| findstr /c:"Shutdown Type"') do (
    set shutdownType=%%i
)
if ["%shutdownType%"]==["shutdown"] (
    :: your shutdown code here
) else (
    :: if not a shutdown, do something else
)

Just to be safe we can make sure the event we are grabbing is the event that was just initiated by using the XPath timediff() function. This will make sure the event was initiated within the last 60 seconds, specified in milliseconds:

@echo off
for /f "tokens=3 delims= " %%i in ('wevtutil qe system /c:1 /rd:true /f:text /q:"*[System/EventID=1074] and TimeCreated[timediff(@SystemTime) >= 60000]" ^| findstr /c:"Shutdown Type"') do (
    set shutdownType=%%i
)
if ["%shutdownType%"]==["shutdown"] (
    :: your shutdown code here
) else (
    :: if not a shutdown, do something else
)

Saturday, December 1, 2012

Joining Windows Server 2012 Core to a domain

You can use the netdom utility to join a Windows Server 2012 Core of Full server to a domain.

>netdom join %computername% /domain:yourdomain.local /userd:<DomainAdmin> /passwordd: /reboot:0

If you're using the PowerShell console substitute %computername% with $env:computername.

Changing the hostname on Windows Server 2012

Use the following commands to change the hostname on a Windows Server 2012 Core or Full server from the command line. This can be done with either the Command Prompt or PowerShell console:

Change the hostname from the Command Prompt

> netdom renamecomputer %computername% /newname:<NewName> /reboot:0

Change the hostname from the PowerShell console

> netdom renamecomputer $env:computername /newname:<NewName> /reboot:0


You will be warned that certain services such as Active Directory Certificate Services may not function correctly after changing the hostname. If you do not want to reboot the system immediately omit the /reboot switch. To reboot the server a later time use shutdown -r -t 0.

Adding and removing the GUI from Windows Server 2012

Microsoft introduced the ability to add and remove the GUI from Windows Server 2012 in case you find yourself lost with only a Command Prompt for administration and configuration of your servers. If you do a Core installation of Windows Server 2012 and want to add the full GUI back to your server you can use the Install-WindowsFeature cmdlet to install it.

To install the full GUI

> Install-WindowsFeature Server-Gui-Mgmt-Infra, Server-Gui-Shell -Restart

To uninstall the GUI from a full installation of Windows Server 2012

> Uninstall-WindowsFeature Server-Gui-Mgmt-Infra, Server-Gui-Shell -Restart

You may be wondering why you would ever want to uninstall the GUI? A good scenario is that you want to configure your server initially using the graphical tools, and after it's full configured, you want to reduce the footprint and attack surface of your server.


Friday, November 30, 2012

Windows Server 2012 - Renaming Network Interfaces from the Command Line

Every since I started using Linux as my primary desktop OS I've gotten used to configuring network settings from the command line. Linux names network interfaces according to what type of interface they are, ethernet, wireless, tunnel, etc, using the naming convention ethX, wlanX, tunX, where X is an incremental integer.

By default in Windows Server 2012 ethernet adapters have the name Ethernet, which to me is too much to type when configuring network settings on a Windows server from the command line with netsh. You can rename your interfaces using the following commands in Windows:

Get a list of current interfaces on the system:

>netsh int show interface

Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Connected      Dedicated        Ethernet


Rename the interface using the Linux naming convention:

>netsh int set interface name="Ethernet" newname=eth0