Useful GNU/Linux search commands

These will work on any GNU/Linux system.

Find the email address someone@example.com within the path /etc recursively

grep -H -r "someone@example.com" /etc

-H, –with-filename
Print the file name for each match.
-R, -r, –recursive
Read all files under each directory, recursively

Find every file under the directory /home owned by the user john

find /home -user john

Find every file under the directory /usr ending in ”log”

find /usr -name *log

Find every file under the directory /etc that was modified more than 60 days ago

find /etc -mtime +60

Runs `file’ on every file in or below the current directory

find . -type f -exec file '{}' \;

Search for files in your home directory which have been modified in the last twenty-four hours. This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime

find $HOME -mtime 0

Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched

find . -perm 664

Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit)

find . -perm -664

Search for files which are writable by somebody (their owner, or their group, or anybody else)

find . -perm /222

All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. These commands all search for files which are writable by either their owner or their group. The files don’t have to be writable by both the owner and group to be matched; either will do

find . -perm /220
find . -perm /u+w,g+w
find . -perm /u=w,g=w

Both these commands do the same thing; search for files which are writable by both their owner and their group

find . -perm -220
find . -perm -g+w,u+w

These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least on write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 and ! -perm /a+x respectively)

find . -perm -444 -perm /222 ! -perm /111
find . -perm -a+r -perm /a+w ! -perm /a+x

// CrashMAG

Change the default SSH port and alter SELinux context to match

Security through obscurity is not something one would generally recommend. But to thwart the effort of automated scanners changing the default OpenSSH port will yield you less pain in every day life. This will not fend off directed attacks or nullify vulnerabilities or bad security design.

Should you see an error message such as

shd[14221]: error: Bind to port 9898 on 192.168.0.50 failed: Permission denied

it indicates that the system prevented the daemon to bind that port. Most likely SELinux.

The instructions provided will be valid on Fedora 14/15, CentOS 6, RHEL 6, Scientific Linux 6 and newer versions.

To change the default SSH port you need to do the following.

  • Stop the SSH daemon
  • Alter the /etc/ssh/sshd_config with your new port
  • Alter the SELinux context with semanage
  • Start the SSH daemon

Stop the SSH daemon

# service sshd stop

Alter the /etc/ssh/sshd_config with your new port

Alter the configuration file with your favorite editor, in my case “nano”.

# nano /etc/ssh/sshd_config

Alter the port configuration parameter change the following line

Port 22

to

Port 9898

Alter the SELinux context with semanage

# semanage port -a -t ssh_port_t -p tcp 9898

Initially you would think the following would work. But it will not. For it to work you would have to alter the policy in the selinux-policy package, rebuild and install it. So skip it, but now you know why.

# semanage port -d -t ssh_port_t -p tcp 22

Start the SSH daemon

# service sshd start

// CrashMAG

Set a SQL Server 2005/2008 database offline and disconnect users

These 2 snippets of T-SQL code will disconnect the users (application) and set the database offline. The usefulness of disconnecting the users is so that you’re actually able to set the database as offline.

Note: YOUR_DATABASE will have to be replaced by the name of the database you wish to set as offline.

-- set database offline
alter database YOUR_DATABASE set single_user
with ROLLBACK IMMEDIATE; -- all connections are disconnected
go
alter database YOUR_DATABASE set offline;
go
-- set the database online
alter database YOUR_DATABASE set online; -- database in single-user mode
go
alter database YOUR_DATABASE set multi_user; -- allow multi-user access
go

// CrashMAG

Change the default MySQL data directory with SELinux enabled

This is a short article that explains how you change the default MySQL data directory and adjust SELinux to account for the changes. The article assumes that you’re running either RHEL, CentOS, Scientific Linux or Fedora with SELinux enabled. This works with the most recent EL (6.2) version.

We’ll be doing this in the following order.

  • Stopping the MySQL server
  • Create a new data directory and move the content from the old data directory
  • Correct the MySQL configuration file
  • Adjust SELinux parameters to accept our new change
  • Starting the MySQL server

Stopping the MySQL server

# service mysqld stop

Create a new data diretory and move the content from the old one

Creating a new data directory

# mkdir /srv/mysql/
# chown mysql:mysql /srv/mysql

Moving the original data files

 # mv /var/lib/mysql/* /srv/mysql/

Correct the MySQL configuration file

Edit the my.cnf file for your distribution. In my example it’s located in the /etc/mysql/ directory. RHEL/CentOS/Scientific Linux put the my.cnf file directly in /etc by default.

# nano /etc/mysql/my.cnf

Change

datadir=/var/lib/mysql

to

datadir=/srv/mysql

and

socket=/var/lib/mysql/mysql.sock

to

socket=/srv/mysql/mysql.sock

and save the file.

Adjust SELinux parameters to accept our new change

Should the following command output “Permissive” or “Disabled” then you may skip the details for SELinux.

# getenforce

Run the semanage command to add a context mapping for /srv/mysql.

# semanage fcontext -a -t mysqld_db_t "/srv/mysql(/.*)?"

Now use the restorecon command to apply this context mapping to the running system.

# restorecon -Rv /srv/mysql

Starting the MySQL server

# service mysqld start

Verifying access and connectivity

$ mysql -u root -p
mysql> show databases;

If this is working, you’re up and running. Should you get a message that says

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’

then add the following to your /etc/my.cnf

[client]
socket = /srv/mysql/mysql.sock

Optionally you can just use

$ mysql -u root -p --protocol tcp

to avoid connecting via the socket.

// CrashMAG

Useful SystemD commands

List all running services

# systemctl

Start/stop or enable/disable services

Activates a service immediately:

# systemctl start foo.service

Deactivates a service immediately:

# systemctl stop foo.service

Restarts a service:

# systemctl restart foo.service

Shows status of a service including whether it is running or not:

# systemctl status foo.service

Enables a service to be started on bootup:

# systemctl enable foo.service

Disables a service to not start during bootup:

# systemctl disable foo.service

Check whether a service is already enabled or not:

# systemctl is-enabled foo.service; echo $?

0 indicates that it is enabled. 1 indicates that it is disabled

How do I change the runlevel?

systemd has the concept of targets which is a more flexible replacement for runlevels in sysvinit.

Run level 3 is emulated by multi-user.target. Run level 5 is emulated by graphical.target. runlevel3.target is a symbolic link to multi-user.target and runlevel5.target is a symbolic link to graphical.target.

You can switch to ‘runlevel 3’ by running

# systemctl isolate multi-user.target (or) systemctl isolate runlevel3.target

You can switch to ‘runlevel 5’ by running

# systemctl isolate graphical.target (or) systemctl isolate runlevel5.target

How do I change the default runlevel?

systemd uses symlinks to point to the default runlevel. You have to delete the existing symlink first before creating a new one

# rm /etc/systemd/system/default.target

Switch to runlevel 3 by default

# ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target

Switch to runlevel 5 by default

# ln -sf /lib/systemd/system/graphical.target /etc/systemd/system/default.target

systemd does not use /etc/inittab file.

List the current run level

runlevel command still works with systemd. You can continue using that however runlevels is a legacy concept in systemd and is emulated via ‘targets’ and multiple targets can be active at the same time. So the equivalent in systemd terms is

# systemctl list-units --type=target

Powering off the machine

You can use

# poweroff

Some more possibilities are: halt -p, init 0, shutdown -P now

Note that halt used to work the same as poweroff in previous Fedora releases, but systemd distinguishes between the two, so halt without parameters now does exactly what it says – it merely stops the system without turning it off.

 

Service vs. systemd

# service NetworkManager stop

(or)

# systemctl stop NetworkManager.service

Chkconfig vs. systemd

# chkconfig NetworkManager off

(or)

# systemctl disable NetworkManager.service

Readahead

systemd has a built-in readahead implementation is not enabled on upgrades. It should improve bootup speed but your mileage may vary depending on your hardware. To enable it:

# systemctl enable systemd-readahead-collect.service
# systemctl enable systemd-readahead-replay.service

SystemD cheatsheet

service foobar start systemctl start foobar.service Used to start a service (not reboot persistent)
service foobar stop systemctl stop foobar.service Used to stop a service (not reboot persistent)
service foobar restart systemctl restart foobar.service Used to stop and then start a service
service foobar reload systemctl reload foobar.service When supported, reloads the config file without interrupting pending operations.
service foobar condrestart systemctl condrestart foobar.service Restarts if the service is already running.
service foobar status systemctl status foobar.service Tells whether a service is currently running.
ls /etc/rc.d/init.d/ ls /lib/systemd/system/*.service /etc/systemd/system/*.service Used to list the services that can be started or stopped
chkconfig foobar on systemctl enable foobar.service Turn the service on, for start at next boot, or other trigger.
chkconfig foobar off systemctl disable foobar.service Turn the service off for the next reboot, or any other trigger.
chkconfig foobar systemctl is-enabled foobar.service Used to check whether a service is configured to start or not in the current environment.
chkconfig foobar –list ls /etc/systemd/system/*.wants/foobar.service Used to list what levels this service is configured on or off
chkconfig foobar –add Not needed, no equivalent.

References

fedoraproject.org/wiki/Systemd
fedoraproject.org/wiki/SysVinit_to_Systemd_Cheatsheet

Distribution Documentation

Gentoo
Arch
Ubuntu
Debian

// CrashMAG

List of useful MySQL commands

Logging in

$ mysql -h hostname -u root -p

If you omit the password value following the –password or -p option on the command line, mysql prompts for one.

Example of password typed in clear text on the commandline

$ mysql -h hostname -u root -psecret

Create a MySQL database

mysql> create database [database_name];

List all databases on the MySQL server

mysql> show databases;

Use a database

mysql> use [db_name];

The USE db_name statement tells MySQL to use the db_name database as
the default (current) database for subsequent statements. The database
remains the default until the end of the session or another USE
statement is issued.

See all the tables in a database

mysql> show tables;

See database field formats

mysql> describe [table name];

DESCRIBE provides information about the columns in a table. It is a
shortcut for SHOW COLUMNS FROM. These statements also display
information for views.

Deleting a database

mysql> drop database [database name];

DROP DATABASE drops all tables in the database and deletes the
database.

Deleting a table

mysql> drop table [table_name];

DROP TABLE removes one or more tables. You must have the DROP privilege for each table. All table data and the table definition are removed.

Use a regular expression to find records. Use “REGEXP BINARY” to force case-sensitivity. This finds any record beginning with a

mysql> SELECT * FROM [table name] WHERE [column] RLIKE "^a";

RLIKE is a synonym for REGEXP, provided for mSQL compatibility.

Change a users password

$ mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;

Delete a user

mysql> DROP USER 'jeffrey'@'localhost';

The statement removes privilege rows for the account from all grant tables.

View privileges/grants/rights for a user

show grants for 'user'@'localhost';

Set a root password if there is on root password

# mysqladmin -u root password newpassword

Update database permissions/privileges.

mysql> flush privileges;

Delete a column

mysql> alter table [table name] drop column [column name];

Add a new column to db

mysql> alter table [table name] add column [new column name] varchar (20);

Change column name

mysql> alter table [table name] change column old_col_name new_col_name;

// CrashMAG

Self-signed certificate for Apache

These instructions are distribution agnostic. However I used CentOS during my tests, so file paths will match that of CentOS, RHEL, Scientific Linux and Fedora. For any other distribution you’ll have to look that up yourself.

The tools required are OpenSSL, Apache and mod_ssl for Apache. To accomplish this I had to run

# yum install mod_ssl

on my CentOS 5.6 box. Which already had Apache up and running.

Setting up a self-signed certificate using certificate and key

Generate your key and certificate

Most of these parameters explain themselves, see beneath for those who do not.

openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout website.key -out website.crt

-nodes
don’t encrypt the output key
-x509
output a x509 structure instead of a cert. req.

Copy the key and certificate

# cp website.key website.crt /etc/httpd/conf/

Set permissions and ownership on your key and certificate

This way nobody except root has read access.

chmod 440 /etc/httpd/conf/website.key /etc/httpd/conf/website.crt
chown root:root /etc/httpd/conf/website.key /etc/httpd/conf/website.crt

Alter the apache configuration file, also known as httpd.conf

Edit /etc/httpd/conf/httpd.conf with your favorite text editor, in my case, nano. Add the following text at the bottom of the file.

      <VirtualHost *:443>
        SSLEngine on
        # Change the next two lines according to where you've actually
        # stored the certificate and key files.
        SSLCertificateFile /etc/httpd/conf/website.crt
	SSLCertificateKeyFile /etc/httpd/conf/apache2/website.key

        ServerName domain.tld
        SSLOptions StrictRequire
        SSLProtocol all -SSLv2

        DocumentRoot /path/to/ssl/enabled/site
        <Directory /path/to/ssl/enabled/site/>
          SSLRequireSSL
          Order Deny,Allow
          Allow from All
        </Directory>
      </VirtualHost>

StrictRequire
This forces forbidden access when SSLRequireSSL or SSLRequire successfully decided that access should be forbidden. Usually the default is that in the case where a “Satisfy any” directive is used, and other access restrictions are passed, denial of access due to SSLRequireSSL or SSLRequire is overridden (because that’s how the Apache Satisfy mechanism should work.) But for strict access restriction you can use SSLRequireSSL and/or SSLRequire in combination with an “SSLOptions +StrictRequire”. Then an additional “Satisfy Any” has no chance once mod_ssl has decided to deny access.

Enable SSLv3 and TLSv1, but not SSLv2
SSLProtocol all -SSLv2

Setting up a self-signed certificate with the certificate and key in one file

Generate your key and certificate

Most of these parameters explain themselves, see beneath for those who do not.

openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout website.pem -out website.pem

-nodes
don’t encrypt the output key
-x509
output a x509 structure instead of a cert. req.

Copy the key and certificate

# cp website.pem  /etc/httpd/conf/

Set permissions and ownership on your key and certificate

This way nobody except root has read access.

chmod 440 /etc/httpd/conf/website.pem
chown root:root /etc/httpd/conf/website.pem

Alter the apache configuration file, also known as httpd.conf

Edit /etc/httpd/conf/httpd.conf with your favorite text editor, in my case, nano. Add the following text at the bottom of the file.

      <VirtualHost *:443>
        SSLEngine on
        # Change the next line according to where you've actually
        # stored the certificate and key file.
        SSLCertificateFile /etc/httpd/conf/website.pem

        ServerName domain.tld
        SSLOptions StrictRequire
        SSLProtocol all -SSLv2

        DocumentRoot /path/to/ssl/enabled/site
        <Directory /path/to/ssl/enabled/site/>
          SSLRequireSSL
          Order Deny,Allow
          Allow from All
        </Directory>
      </VirtualHost>

StrictRequire
This forces forbidden access when SSLRequireSSL or SSLRequire successfully decided that access should be forbidden. Usually the default is that in the case where a “Satisfy any” directive is used, and other access restrictions are passed, denial of access due to SSLRequireSSL or SSLRequire is overridden (because that’s how the Apache Satisfy mechanism should work.) But for strict access restriction you can use SSLRequireSSL and/or SSLRequire in combination with an “SSLOptions +StrictRequire”. Then an additional “Satisfy Any” has no chance once mod_ssl has decided to deny access.

Enable SSLv3 and TLSv1, but not SSLv2
SSLProtocol all -SSLv2

// CrashMAG

How to check for active trace flags on Microsoft SQL Server

You check for active trace flags by running the following query. They may be global or they may be session based.

Checking for active trace flags

DBCC TRACESTATUS

The output could be something like the following.

TraceFlag Status Global Session
--------- ------ ------ -------
4199      1      1      0
4616      1      1      0

(2 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

If there are no active trace flags you will only see

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Enable session based trace flags

To enable trace flags only in your session use the following two commands.

DBCC TRACEON (trace#)
DBCC TRACEOFF (trace#)

trace#
Is the number of the trace flag to turn on.

Enable trace flags globally

DBCC TRACEON (trace#,-1)
DBCC TRACEOFF (trace#,-1)

-1
Switches on the specified trace flags globally.

To enable a trace flag to persist through a restart. Alter the “Startup Parameters” in the Advanced tab for the SQL Server service in SQL Server Configuration Manager.

One example would be.

Before modification

-dC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG;-lC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\mastlog.ldf

After modification

-dC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log\ERRORLOG;-lC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\mastlog.ldf;-T4199

sqlservr [-sinstance_name] [-c] [-dmaster_path] [-f]
[-eerror_log_path] [-lmaster_log_path] [-m]
[-n] [-Ttrace#] [-v] [-x] [-gnumber] [-h]

References

DBCC TRACEON (Transact-SQL)
DBCC TRACEOFF (Transact-SQL)
DBCC TRACESTATUS (Transact-SQL)
Trace Flags (Transact-SQL)

// CrashMAG

View information about your BIOS from Linux using dmidecode

To get at this information we will use a utility called “dmidecode”. dmidecode is a tool for dumping a computer’s DMI (some say SMBIOS) table contents in a human-readable format.

On CentOS/RHEL/Fedora you may run the following to install it.

# yum install dmidecode

On Arch Linux you may run

# pacman -S dmidecode

The following examples will allow you to see a few important parts of information such as;

  • The manufacturer of your motherboard
  • What type of motherboard you have
  • The version of the BIOS running on your motherboard

To view the manufacturer and what type of motherboard you have, run the following

dmidecode --type system

Example

# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0001, DMI type 1, 27 bytes
System Information
        Manufacturer: Gigabyte Technology Co., Ltd.
        Product Name: GA-MA78G-DS3H
        Version:
        Serial Number:
        UUID: 4E2F4100-0000-0000-0000-0000FFFFFFFF
        Wake-up Type: Power Switch
        SKU Number:
        Family:

Handle 0x0034, DMI type 32, 11 bytes
System Boot Information
        Status: No errors detected

To view the version of your BIOS you may run the following

#dmidecode --type bios

Example

# dmidecode 2.11
SMBIOS 2.4 present.

Handle 0x0000, DMI type 0, 24 bytes
BIOS Information
        Vendor: Award Software International, Inc.
        Version: FA
        Release Date: 09/19/2008
        Address: 0xE0000
        Runtime Size: 128 kB
        ROM Size: 1024 kB
        Characteristics:
                ISA is supported
                PCI is supported
                PNP is supported
                APM is supported
                BIOS is upgradeable
                BIOS shadowing is allowed
                Boot from CD is supported
                Selectable boot is supported
                BIOS ROM is socketed
                EDD is supported
                5.25"/360 kB floppy services are supported (int 13h)
                5.25"/1.2 MB floppy services are supported (int 13h)
                3.5"/720 kB floppy services are supported (int 13h)
                3.5"/2.88 MB floppy services are supported (int 13h)
                Print screen service is supported (int 5h)
                8042 keyboard services are supported (int 9h)
                Serial services are supported (int 14h)
                Printer services are supported (int 17h)
                CGA/mono video services are supported (int 10h)
                ACPI is supported
                USB legacy is supported
                AGP is supported
                LS-120 boot is supported
                ATAPI Zip drive boot is supported
                BIOS boot specification is supported
                Targeted content distribution is supported

Handle 0x0029, DMI type 13, 22 bytes
BIOS Language Information
        Language Description Format: Long
        Installable Languages: 3
                n|US|iso8859-1
                n|US|iso8859-1
                r|CA|iso8859-1
        Currently Installed Language: n|US|iso8859-1

There’s also additional options to use with dmidecode. You probably also want to try the following to get an idea of what type of information you can get your hands on.

#dmidecode --type keyword
Valid type keywords are:
  bios
  system
  baseboard
  chassis
  processor
  memory
  cache
  connector
  slot

// CrashMAG

How you tell Firefox 4 to open links in a new tab instead of a new window

There’s so little useful information on the matter so I’ve decided to post about it. And the default option under Preferences -> Tabs called “Open new windows in a new tab instead” does not work. I have no idea why, and I’m embarrassed on behalf of Mozilla that it doesn’t. However here’s how you fix it.

This is what you have to do to have Firefox 4 open your links in a new tab instead of a new window.

1. In your URL bar enter “about:config”.
2. Accept the prompt.
3. Search up the line

browser.link.open_newwindow.restriction

4. Change the default value “2” to “0”.

Once you’ve set it to “0” it will immediately work.

Further refrence can be found here http://kb.mozillazine.org/About:config_entries

// CrashMAG

Linux | Open Source | Technology | Databases | Web