Calculate Free Space Using Python
- February 23rd, 2010
- Write comment
Here is an easy way of finding the total amount of free disk space using Python:
import os
diskSpace = os.statvfs(‘/’)
(diskSpace.f_bavail * diskSpace.f_frsize) / (1024 * 1024)
Here is an easy way of finding the total amount of free disk space using Python:
import os
diskSpace = os.statvfs(‘/’)
(diskSpace.f_bavail * diskSpace.f_frsize) / (1024 * 1024)
There are times where SELinux just does not want to play nice. For instance, after installing ClamAV I began running into problems where if I did not turn off SELinux while ClamAV was running, then SMTP traffic would fail. To fix this issue we must first look at the messages file under /var/log. Within this file we will see error messages like:
setroubleshoot: SELinux is preventing cleanup (postfix_cleanup_t) "search" to ./clamav (clamd_var_lib_t).
Which tells you to run the command:
sealert -l a1bc9b39-80a2-4f2e-963f-12daf766a8d4
Usually the report is very good and diagnosing and telling you which booleans to activate, however in this instance we have to create our own module.
First: Download and install selinux-policy-devel
Second: Parse through the raw audit messages. We are looking for two things; message type and comm name.
Third: Run the ausearch command and pipe it to audit2allow
For instance: ausearch -m AVC --comm cleanup | audit2allow -M ClamAV
Once the files have been generated then run: semodule -i ClamAV.pp and see if the problem has been resolved. If not, tail the messages log again to see if there is any additional SEAlerts that you should be aware of.
In running my periodic Nessus scans, it picked up a few medium severity vulnerabilities against Dovecot. One was “SSL Anonymous Cipher Suites Supported” and the other, “SSL Weak Cipher Suites Supported.”
Look in the Dovecot config file located in /etc/dovecot.conf under “SSL ciphers to use” and you will see:
ssl_cipher_list = ALL:!LOW:!MEDIUM
To disable these weak ciphers change this to:
ssl_cipher_list = ALL:!LOW:!MEDIUM:!MD5:!SSL2:!EXP-ADH-DES-CBC-SHA:!EXP-EDH-RSA-DES-CBC-SHA:!EXP-DES-CBC-SHA:!EXP-EDH-RSA-DES-CBC-SHA:!EXP-ADH-DES-CBC-SHA:!EXP-DES-CBC-SHA:!ADH-AES256-SHA:!ADH-AES128-SHA:!ADH-DES-CBC3-SHA:!EXP-ADH-DES-CBC-SHA:!EXP-ADH-DES-CBC-SHA:!ADH-DES-CBC3-SHA
Run the Nessus scan again and those two vulnerabilities go away
As a part of the sys admin’s job, it is important to take a few extra minutes to go through and properly secure a newly installed Linux server. These steps include enabling SELinux on the machine, configuring the firewall, and setting user permissions. There are however additional steps one should take in order to secure their server. One would be to tune and secure kernel parameters, set limits on kernel dumps, prevent IPv6 from loading if you company is not using it, and turning off unnecessary services.
Networking
First, lets take a look at configuring kernel parameters to prevent network based attacks. These include disallowing intruders to alter routing tables and source routed packets, preventing an intruder from configuring the server to become a router, and turning on reverse path filtering. To change these settings edit the /etc/sysctl.conf file and enter:
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_messages = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
If you are currently running IPv6 at your company, here are a few kernel parameters to prevent network based attacks:
net.ipv6.conf.default.router_solicitations = 0
net.ipv6.conf.default.accept_ra_rtr_pref = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.default.dad_transmits = 0
net.ipv6.conf.default.max_addresses = 1
To make these settings effective without rebooting the server type sysctl -p
We can go a step further by disabling unused network functions such as IPv6 and prevent self assigned addressing.
To detect whether or not IPv6 is running on a server type: ifconfig | grep inet6 which will return:
inet6 addr: fe80::240:5ff:fe32:ef19/64 Scope:Link
inet6 addr: ::1/128 Scope:Host
inet6 addr: fe80::200:ff:fe00:0/64 Scope:Link
To prevent IPv6 from loading, run the following command:
echo "install ipv6 /bin/true" > /etc/modprobe.d/ipv6
Then add the following lines to /etc/sysconfig/network:
NETWORKING_IPV6=no
IPV6INIT=no
This will deactivate the IPv6 protocol from running on the server.
To prevent self assigned addressing on network cards, open the /etc/sysconfig/network file and add:
NOZEROCONF=yes
Server security
Turning off the ability to create core dumps is important as intruders can use this to gather information about running services and configurations in order to exploit them. To do so, edit the /etc/security/limits.conf file and insert:
* hard core 0
We should also prevent setuid programs from creating these as well:
sysctl -w fs.suid_dumpable=0
There are also built in kernel features which can help protect against buffer overflow attacks. These features are turned on by default, however these kernel parameters should be enabled in case they have been turned off:
sysctl -w kernel.exec-shield=1
sysctl -w kernel.randomize_va_space=1
These settings ensure randomization of the stack and memory regions, which are refereed to as the ExecShield.
There are many services which are running on a default installation which include cups, sendmail, isdn, bluetooth, and many others. If these services are not being used on the server then they should be turned off and configured not to start up on a reboot. To do so we can run the following bash script:
for i in acpid autofs avahi-daemon luetooth cups firstboot gpm hidd ip6tables sendmail exim xfs xinetd yum-updatesd rhnsd pcscd readahead_early readahead_later apmd hplip isdn ip6tables mcstrans
do
service $i stop
chkconfig $i off
done
Your services will vary depending on the installation. We should also ensure that X does not run on reboot, placing the server in run level three. To do so, edit the /etc/inittab file and change id:5:initdefault: to id:3:initdefault:
For further reading I highly encourage you to download the NSA RHEL 5 hardening documents at RHEL 5 Pamphlet
Hardening RHEL 5 Guide
You will need to install the Extra Packages for Enterprise Linux (EPEL) rpm which can be found at:
'rpm -ivh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm' for i386
or: 'rpm -ivh http://download.fedora.redhat.com/pub/epel/5/x86_64/repoview/epel-release.html' for 64bit.
Once the EPEL rpm has been installed, you will then be able to install mod_security by typing 'yum install mod_security' and restart the Apache service.
Make sure that the mod_security engine is turned on by going to
/etc/httpd/modsecurity.d/modsecurity_crs_10_config.conf and look for 'SecRuleEngine On'
One of the coolest features is masking the server signature of Apache. This can be done by editing the httpd.conf and making sure that 'ServerTokens' is set to 'Full'. Then change 'SecServerSignature' in 'modsecurity_crs_10_config.conf' to whatever you want.
First we need to create our certificates. To create a certificate authority download the openssl-perl package through Yum:
———————————————————–
yum install openssl-perl
———————————————————–
Then issue the following command to create the CA certificate.
———————————————————–
./CA.pl -newca
———————————————————–
After this process is done we need to create the certificate request and key. Once the certificate request has been generated you then need to have the pem file signed by the CA.
———————————————————–
openssl req -new -days 365 -newkey rsa:2048 -keyout newkey.key -out newreq.pem
openssl ca -out post_signed_cert.pem -infiles newreq.pem
———————————————————–
Create a directory on the Postfix server under the /etc/pki directory called postfix, place these files there, and change the permissions on the files.
———————————————————–
chmod 0400 *
———————————————————–
Add the following lines at the bottom of the main.cf file for Postfix
———————————————————–
#SASL
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination
#TLS
smtpd_tls_key_file = /etc/pki/postfix/private/postkey.key
smtpd_tls_cert_file = /etc/pki/postfix/certs/post_signed_cert.pem
smtpd_tls_loglevel = 1
smtpd_tls_session_cache_timeout = 3600s
smtpd_tls_session_cache_database = btree:/var/spool/postfix/smtpd_tls_cache
tls_random_source = dev:/dev/urandom
smtpd_tls_auth_only = yes
smtpd_tls_security_level = may
#HELO Restrictions
smtpd_delay_reject = yes
smtpd_helo_required = yes
smtpd_helo_restrictions =
permit_mynetworks,
reject_non_fqdn_helo_hostname,
reject_invalid_helo_hostname,
permit
———————————————————–
Next uncomment the submission line in the master.cf file.
———————————————————–
smtp inet n - n - - smtpd
submission inet n - n - - smtpd
———————————————————–
We now need to tie it into Dovecot. Go to the auth default section of the configuration file and add/edit the following lines.
———————————————————–
auth default {
mechanisms = plain login
passdb pam {
}
userdb passwd {
}
user = root
socket listen {
client {
path = /var/spool/postfix/private/auth
mode = 0660
user = postfix
group = postfix
}
}
}
———————————————————–
Restart the Postfix and Dovecot services.
———————————————————–
service postfix restart
service dovecot restart
———————————————————–
In order to test to make sure SSL/TLS is working we will need to telnet to the port and run a few commands.
———————————————————–
$ telnet localhost 25
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
220 smtp.example.com ESMTP Postfix
ehlo smtp.example.com
250-smtp.example.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
———————————————————–
What you are looking for is STARTTLS, this will tell you that SSL/TLS is activated. To make sure that the certificates are working correctly type: STARTTLS which should say 220 2.0.0 Ready to start TLS. If it says anything else then there is something wrong and you will need to go back and fix it.
Postfix Install
To create a functional SMTP server, first you need to install Postfix by running
———————————————————–
yum install postfix
———————————————————–
Check to make sure that your hostname also has your fully qualified domain name.
———————————————————–
echo $HOSTNAME
———————————————————–
If it does not have your domain, then you must add it to the configuration file.
———————————————————–
myhostname = smtp.example.com
———————————————————–
You must also make your SMTP server listen on an interface besides the localhost. Uncomment:
———————————————————–
inter_interfaces = localhost
-----------------------------------------------------------
To:
-----------------------------------------------------------
inet_interfaces = all
-----------------------------------------------------------
Now edit the configuration to allow trusted networks to relay emails. In most situations uncommenting:
-----------------------------------------------------------
mynetworks_style = subnet
-----------------------------------------------------------
should be sufficient, however if you are allowing a larger network or deal with multiple networks then manually add the networks that will be trusted.
-----------------------------------------------------------
mynetworks = 127.0.0.0/8, 192.168.1.0/24
-----------------------------------------------------------
ClamAV
Download and install clamav, clamav-db, clamd, clamav-milter from http://packages.sw.be/clamav/
Edit the init scripts to allow Postfix to read the clamav-milter socket. Add the following lines in the start, stop, and restart case statements.
-----------------------------------------------------------
chmod 0775 /var/clamav/clmilter.socket
chown clamav.postfix /var/clamav/clmilter.socket
-----------------------------------------------------------
If these settings are not set, Postfix will not be able to correctly communicate with the ClamAV milter and will receive a
warning: connect to Milter service unix:/var/clama/clmilter.socket: Permission denied
in the mail log
Now add:
-----------------------------------------------------------
smtpd_milters = unix:/var/clamav/clmilter.socket
non_smtpd_milters = unix:/var/clamav/clmilter.socket
-----------------------------------------------------------
to the bottom of main.cf and restart the Postfix service.
Now add freshclam to the cron to get automatic updates and everything should be all set.
Here is an easy way of encrypting USB thumb drives with Luks. Examples below assume your thumb drive is/dev/sdb
First, check the device for bad blocks:
~]# badblocks -c 10240 -s -w -t random -v /dev/sdb
Next create the partition on the drive itself.
~]# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0x99faf680.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)
Command (m for help): p
Disk /dev/sdb: 4066 MB, 4066377728 bytes
126 heads, 62 sectors/track, 1016 cylinders
Units = cylinders of 7812 * 512 = 3999744 bytes
Disk identifier: 0x99faf680
Device Boot Start End Blocks Id System
Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-1016, default 1):
Using default value 1
Last cylinder, +cylinders or +size{K,M,G} (1-1016, default 1016):
Using default value 1016
Command (m for help): p
Disk /dev/sdb: 4066 MB, 4066377728 bytes
126 heads, 62 sectors/track, 1016 cylinders
Units = cylinders of 7812 * 512 = 3999744 bytes
Disk identifier: 0x99faf680
Device Boot Start End Blocks Id System
/dev/sdb1 1 1016 3968465 83 Linux
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
Now create the password and encrypt the device. This will encrypt the device with AES256.
~]# cryptsetup luksFormat -v -y -s 256 -c aes /dev/sdb1
WARNING!
========
This will overwrite data on /dev/sdb1 irrevocably.
Are you sure? (Type uppercase yes): YES
Enter LUKS passphrase:
Verify passphrase:
Command successful.
To open the encrypted drive type:
cryptsetup luksOpen /dev/sdb1 usbdrive
It will then prompt for the password.
***WARNING*** Do not lose your password, there is no way to recover it!
Now format the drive. This example shows how to format the drive with ext4 however ext3 will also work if you are running an older distro.
~] # mkfs.ext4 /dev/mapper/usbdrive
mke2fs 1.41.4 (27-Jan-2009)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
248000 inodes, 991859 blocks
49592 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=1019215872
31 block groups
32768 blocks per group, 32768 fragments per group
8000 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736
Writing inode tables: done
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 31 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
Mount the drive:
~]# mount /dev/mapper/usbdrive /media/thumbdrive/
Now your drive is encrypted
Gnome should automatically ask the next time you insert your usb drive for the password. However if you are using the cli, here are the steps to mount/unmount the drive.
Mount the device
~]# cryptsetup luksOpen /dev/sdb1 usbdrive
~]# mount /dev/mapper/usbdrive /media/usbdrive
Unmount the device
~]# umount /media/usbdrive
~]# cryptsetup luksClose usbdrive
GnuPG is used to encrypt and sign email messages and files. First you need to create the GPG key:
Generating Keys
———————————————————–
$ gpg --gen-key
———————————————————–
Select option 5 for RSA and then type the encryption level.
———————————————————–
Please select what kind of key you want:
(1) DSA and Elgamal (default)
(2) DSA (sign only)
(5) RSA (sign only)
Your selection? 5
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048) 4096
Requested keysize is 4096 bits
Please specify how long the key should be valid.
0 = key does not expire
= key expires in n days
w = key expires in n weeks
m = key expires in n months
y = key expires in n years
Key is valid for? (0)
Key does not expire at all
Is this correct? (y/N) y
———————————————————–
Now enter your personal information
———————————————————–
Real name: Jason Brown
Email address: jasonbrown@example.com
Comment: Example
You selected this USER-ID:
"Jason Brown (Example) "
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o
You need a Passphrase to protect your secret key.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
............................+++++
...........+++++
gpg: key 7C11053D marked as ultimately trusted
public and secret key created and signed.
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 4 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 4u
pub 4096R/7C11053D 2009-10-12
Key fingerprint = EE6B C53F A665 593C 3607 FEE1 F984 2AF9 7C11 053D
uid Jason Brown (Example)
———————————————————–
As stated in the option menu, this key is only generated to sign email or files and cannot be used to encrypt. You now have to edit the key that was just generated to use it for encryption.
———————————————————–
$ gpg --edit-key jasonbrown@exmaple.com
pub 4096R/7C11053D created: 2009-10-12 expires: never usage: SC
trust: ultimate validity: ultimate
[ultimate] (1). Jason Brown (Example)
Command> addkey
You need a passphrase to unlock the secret key for
user: "Jason Brown (Example) "
4096-bit RSA key, ID 7C11053D, created 2009-10-12
———————————————————–
Enter in your passphrase and then select option 6 for ‘RSA (encrypt only)’. It will then ask for a key size and key expiration, use the same settings as in the first section. Once complete you will have a new key for encryption.
———————————————————–
pub 4096R/7C11053D created: 2009-10-12 expires: never usage: SC
trust: ultimate validity: ultimate
sub 4096R/55D59203 created: 2009-10-12 expires: never usage: E
[ultimate] (1). Jason Brown (Example)
———————————————————–
Now type save to exit:
———————————————————–
Command> save
———————————————————–
Your new key is now ready to be uploaded to the key repository servers.
———————————————————–
$ gpg --keyserver pgp.mit.edu --send-key jasonbrown@example.com
———————————————————–
GPG Key Backup
Once your keys have been generated, you will need to export both the public and private keys and store them for safe keeping. To export your public key:
———————————————————-
$ gpg --export -a jasonbrown@example.com > example-pub.key
———————————————————-
And the private key:
———————————————————-
$ gpg --export-secret-key -a jasonbrown@example.com > example-priv.key
———————————————————-
You can then create a tar backup of these two keys and encrypt them with a passphrase.
———————————————————-
$ tar -cvf gpgkeys.tar example-priv.key example-pub.key
$ gpg -c --cipher-algo aes256 gpgkeys.tar
———————————————————-
Then enter in a strong password. This will allow you to retrieve your keys if you do not have your public/private key pair installed on a machine. Once this is done you will need to securely delete your keys leaving just the tarball. This is important as someone can compromise your keys.
———————————————————-
$ for i in gpgkeys.tar example-priv.key example-pub.key
>do
>shred -n 100 -z -u -v $i
>done
———————————————————-
Retrieving Public Keys
To search for a persons key type:
———————————————————-
$ gpg --search-keys jasonbrown@example.com
———————————————————-
As this is an example and a fake email address, this will not return any results. Had this been a real address you will see a list of email addresses with numbers along the side. To request the public key of that person, type the number and hit ‘enter’ and it will retreive the public.
Encrypting Files to Other Users
To encrypt a file to a different user you must first have that users public key. To check type:
———————————————————-
$ gpg --list-keys
pub 4096R/7C11053D 2009-10-12
uid Jason Brown (Example)
sub 4096R/55D59203 2009-10-12
———————————————————-
I will encrypt a file to myself. The ‘-e’ option is to tell it to encrypt and the ‘-r’ is the recipient or public key of the person you want to give the file to.
———————————————————-
$ gpg -e -r jasonbrown@example.com ssn.txt
———————————————————-
To decrypt the file, the receipient must have their public key installed on the machine. Then type:
———————————————————-
$ gpg --output ssn.txt --decrypt ssn.txt.gpg
———————————————————-
Where ‘–output’ is the name of the decrypted file and ‘–decrypt’ is the file being decrypted.
You may also want to digitally sign the file you are encrypting, to do so type:
———————————————————-
$ gpg --detach-sig ssn.txt.gpg
———————————————————-
And to verify the signature file:
———————————————————-
$ gpg --verify ssn.txt.gpg
gpg: Signature made Mon 12 Oct 2009 02:21:26 PM EDT using DSA key ID 7C11053D
gpg: Good signature from "Jason Brown (Example) "
———————————————————-
,’%',’^',’&’,'*’,'(‘,’)',’-',’_',’=',’+',’<’,'>’,’[',']‘,’{‘,’}',’:',’;',’?',’|');