Posts tagged linux

Advanced Bash Scripting – Part 2

3

Shell ScriptThe problem statement is as follows :

The Playfair Cipher encrypts text by substitution of digrams (2-letter groupings). It is traditional to use a 5 x 5 letter scrambled-alphabet key square for the encryption and decryption.

Each letter of the alphabet appears once, except “I” also represents “J”. The arbitrarily chosen key word, “CODES” comes first, then all the rest of the alphabet, in order from left to right, skipping letters already used.

To encrypt, separate the plaintext message into digrams (2-letter groups). If a group has two identical letters, delete the second, and form a new group. If there is a single letter left over at the end, insert a “null” character, typically an “X.”

To read more about the question, check http://tldp.org/LDP/abs/html/writingscripts.html

The solution for this question is pretty long (over 100 lines in shell script). You can check the final solution at http://sp2hari.com/bash/playfair-cipher.html

Explanation of function/code used in the solution.

locateInKeySquare: Searches for the character passed as the parameter in the keySquare and returns the position of the character.
addToKeySquare: Adds a character c passed as the parameter to the keySquare. This checks if the character is already present, if it is J and changes it to uppercase (if needed)
printKeySquare: Prints the keySquare from 1D to 2D format.

The rest of the code adds the keyWord to keySquare. The the remaining words are added to the keySquare. After that, we extract the dialects from the plaintext and based on the 3 rules, we encrypt the text.

Hope this is helpful..

Security settings for a LAMP Server : Iptables

0

Security is the major concern for anyone hosting a website on the internet. These are the preliminary security settings to be performed to protect your server.

iptables
Our server stack is LAMP. Hence iptables as the firewall is the most natural choice. The requirements are like

1. Block everything except Ping, SSH, Apache, and SSL.
2. Enabled SSH only from the selected IP addresses.

The following script takes care of all iptables settings. (Idea copied from here)

Note: Please enter the command one by one. Make sure you replace IP1.IP2.IP3.IP4 with your own IP address.

# Establish a clean slate
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F # Flush all rules
iptables -X # Delete all chains
# Disable routing. Drop packets if they reach the end of the chain.
iptables -P FORWARD DROP
# Drop all packets with a bad state
iptables -A INPUT -m state --state INVALID -j DROP
# Accept any packets that have something to do with ones we've sent on outbound
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# Accept any packets coming or going on localhost (this can be very important)
iptables -A INPUT -i lo -j ACCEPT
# Accept ICMP
iptables -A INPUT -p icmp -j ACCEPT
# Allow ssh
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow httpd
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Allow mysql
iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
# Allow SSL
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Block all other traffic
iptables -A INPUT -j DROP

I guess the above script should take care of the basic security issues. Hope it helps.

Advanced Bash Scripting – Part 1

6

Shell Script

Hello everyone, I’m planning to solve the problems in the Advanced Bash-Scripting Guide, say like one problem per week. Why am I doing this?

1. The problems there are very interesting.
2. Working in windows all the time, I feel I’m losing my shell scripting abilities. This will keep me updated.

The problem we are going to solve this week is “Testing Passwords”. The problem statement is as follows.

Write a script to check and validate passwords. The object is to flag “weak” or easily guessed password candidates.
A trial password will be input to the script as a command-line parameter. To be considered acceptable, a password must meet the following minimum qualifications:

1. Minimum length of 8 characters
2. Must contain at least one numeric character
3. Must contain at least one of the following non-alphabetic characters: @, #, $, %, &, *, +, -, =

Optional:
Do a dictionary check on every sequence of at least four consecutive alphabetic characters in the password under test. This will eliminate passwords containing embedded “words” found in a standard dictionary.
Enable the script to check all the passwords on your system. These probably do not reside in /etc/passwd.

The command I’m planning to use for this is grep, with a few for loop constructs and string operations.

Let’s check the constraints one by one.

#Minimum length of 8 characters
if [ ${#password} -lt 8 ]
then
  echo "$password: $weakString"
  return
fi

#Must contain at least one numeric character
if [ `echo $password | grep -c -E "[0-9]+"` -eq 0 ]
then
  echo "$password: $weakString"
  return
fi

#Must contain at least one of the following non-alphabetic characters: @, #, $, %, &, *, +, -, =
if [ `echo $password | grep -c -E "[@#$%&*=+-]+"` -eq 0 ]
then
  echo "$password: $weakString"
  return
fi

#Do a dictionary check on every sequence of at least four consecutive alphabetic characters in the password under test. This will eliminate passwords containing embedded "words" found in a standard dictionary.
for((i=4;i<=${#password};i++))
do
  for((j=0;j<=${#password}-$i;j++))
  do
    if [ `grep -c -E "^${password:$j:$i}$" dict.txt` -gt 0 ]
    then
      echo "$password: $weakString"
      return
    fi
  done
done

That's about it, we have checked all the constraints. Now, we will combine all the checks in one function and then we will pass all the command line parameters to this function one by one.

You can take a look at the final script here.

Can you make it any better or reduce the code size? Feel free to add it in the comments section.

Meet GNU/Linux 07

0

After 2 successful editions of Meet GNU/Linux, which is conducted by
GLUG-T every year for beginners, the third edition of MGL is starting
on 27th July, at NITT.

A few updates about MGL’07 :

1. Guys are planning to release a beginner handbook, which would be
given out to them. The content is being edited in a wiki :
http://glugt-mgl.pbwiki.com/ Go ahead and edit when you are free.

2. This is GNU/Linux for dummies. So, if you have any of your
friend/relative interested in learning about it(in trichy), you can
ask them to contact suren who is co-ordinating
the event.

3. The co-ords are planning to release podcasts of the events, which
will be helpful.

Ideas, suggestion about how to organise the classes are welcome!

Coding Style …

2
I have never thought much about coding style before i did my NOSIP in Novell. But once i started coding for ldtprecord, according to the coding style suggested to me by nags, i was surprised to see how nice and neat the final code looks.

Some tips/tricks for nice coding skills are,

1. Do spend some time to think about the variable names and the function names. This sometimes might be bit boring, especially when you want to concentrate much on the program logic and performance. But this is Rule 0 for coding conventions. A variable name “k” can imply anything like “kappa, kozhukattai, katthu, kaadhal, kerala, kozhuppu…” to someone who might have to read your code later. This is again mentioned here clearly. Many thanks to emacs, you can always use the auto complete, if your variable name is too long. :-) .

2. The actual coding convention depends much on the language and the standards your team is using already. The following style won’t work for someone, whose team is already using a totally different style.

A few examples for C is posted here .

Sample Code 1 :

if (a == 5) {

    b = 10;

}
else {
    b = 20;
}

Things to be noticed in the above snippet are.

1. A space between if and “(” .
2. Space in both the sides of the comparison operator.
3. Space between “)” and “{“
4. Space between both the sides of assignment operator (line 2 & 5) . This is true for almost all the operators.
5. Proper indentation of lines 2 & 5. If you are using emacs or vi, check here for your .emacs or .vimrc file .

Well, your code will compile and run even if you don’t give these spaces, but a program coded with a bad coding style is equivalent to an inefficient code.

Sample Code 2

Let us have a function which takes two integers and returns their sum .
The code should be like

int add_numbers (int num1, int num2) {

    return (num1 + num2);
}

The function call will be something like,

int sum;
sum = add_numbers (10, 20);

Things to be noticed in the above snippet is

In the first line in the function declaration,

1. The function name should be as clear as possible.
2. A space between the end of function name and “(” .
3. Spaces are given after every “,” in the function argument list.
4. A space is given between “)” and “{“.

In the second line in the function declaration,

1. A space before “(“. [ This rule is almost global. Apply it everywhere whenever you use "(" ] .

2. There is a space on both the sides of the addition operator. This is again almost global. A space between both the sides of operator makes the code look real neat.

3. The indentation about which was mentioned earlier.

But yes, if your girl friend is a geek or a nerd or a psycho or a fundoo, then you better go for this. ;-)

#define MAGIC “eilouvy43605321″
#define _(p,o,q) (t o#p[0])?(q)
#define __(p,o,q) _(p,o,t-q)
int main(){int t, i; for(i=8;i>0;i–)printf(“%c”, MAGIC[(((t=(MAGIC+7)[i-1])==’_')?62:_(.,==,63):_(@,==,64):__(a,>=,’a'+36):__(A,>=,’A'+10):(t-’0′))]);}

Note :: I wont say the coding style i use is the perfect one. It always depends upon what your team was using till now and how easy it is to read, debug and maintain the code.

Useful Links :

The guide coding standards in GNOME is really a nice one.
Even better was this one i found recently. Though i didn’t read it completely, it was quite interesting.
This article was short and sweet.

Seg Fault

1

Wikipedia says,
A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).”

I have seen hundreds and hundreds of seg faults ;-) while coding for record module of LDTP and Spider SMS. But the one i saw yesterday was new, strange and fascinating. I am not sure whether i will be able to reproduce it again. The screenshot says why it is strange and fascinating :-) .

-bash-3.1$ man su
says

AUTHOR
Written by David MacKenzie.

REPORTING BUGS
Report bugs to <bug-coreutils@gnu.org>.

Maybe i should consider reporting this :P .

Go to Top