Saturday, March 5, 2011

Linux/Unix Common Commands 2

Hey
I have had a post about linux commands. as I had promised, here I am going to progress it.
First of all I have forgotten a very useful command.
23. locate sth: to search something
      Example: [root@testserver opt]# locate test
      Result:

/usr/share/tcl8.4/tcltest2.2/testresults.tcl
/usr/share/vim/vim70/syntax/colortest.vim
/usr/share/vim/vim70/syntax/hitest.vim
/var/lib/mysql/test
...
 switches:
  1. -b: match only the base name of path names
  2. -c: only print number of found entries
  3. -i: ignore case distinctions when matching patterns
  4. ... . use --help to see all of switches.
      Example: [root@testserver opt]# locate test -c
      Result:3310

also you can use "| grep sth" to limit it more:

      Example: [root@testserver opt]# locate test | grep tomcat
      Result:
/opt/apache-tomcat-6.0.18/webapps/ROOT/html/testing/myportlet/menu.jsp
/opt/apache-tomcat-6.0.18/webapps/ROOT/html/testing/myportlet/view.jsp
/opt/apache-tomcat-6.0.18/webapps/ROOT/html/testing/myportlet/images/menu-btm.pn

... 

Set a variable for all user

Sometimes we need to set a variable for all users. for example:
CATALINA_HOME=/opts/tomcat
or
JAVA_OPTS=-Xms256m -Xmx512m -XX:MaxPermSize=128m

To do it, you need to setup global config in /etc/profile OR /etc/bash.bashrc file for all users:
  1. vi /etc/profile
  2. write your export command at the end of the opened file
  3. ...
    for i in /etc/profile.d/*.sh ; do
        if [ -r "$i" ]; then
            if [ "$PS1" ]; then
                . $i
            else
                . $i >/dev/null 2>&1
            fi
        fi
    done
    export JAVA_OPTS="-Xms256m -Xmx512m -XX:MaxPermSize=128m"
  4. then save and quit it. :wq! + Enter
  5. this variable will be created whenever anyone log in. you can see it via echo command.

Yum automated software installation and update
Yum is the easiest way to keep all programs up to date. It downloads and installs the latest version of a program. A single command can update all software installed, including third-party software, security updates and operating system. It can do the updating automatically in the night. here we install yum and make it do all the above.

Yum is similar to, but better than apt, apt4rpm, windows update, up2date, yast and many other package managers I have ever seen.

Yum works in a safe, standardized way. It uses rpm (Red Hat package manager) for installing programs. Authenticity of packages is checked with strong gpg encryption. Package repositories are just folders on a web server.

We will install yum, then choose trusted packagers and start installing programs. We will also see some yum tips.

Install yum

Red Hat has rpm package manager installed by default. We use rpm to install yum.

First download yum then go to the folder where you downloaded yum. If you can see the file with ls, you are on the right place. you can also use locate command to find its path. Then write this command:

rpm -Uvh yum*.noarch.rpm

In the command above, rpm -Uvh means installing just like rpm -i you may have used allready. -Uvh just displays some extra info and erases old version of program if necessary. You can rpm -q yum to see if yum is installed. It should tell you the version number of yum.

Exampe: [root@testserver opt]# rpm -q yum
Result: yum-2.0.3-0.fdr.1.rh90

Add trusted packagers to your keyring

In yum, it really does not matter if enemy takes over the internet and fakes to be some website offering software. All software is cryptographically checked before installation (if you have set gpgcheck=1 in yum.conf. this is the configuration file of yum. you can locate to find this file). To install some software, we must tell yum who we trust.
rpm --import /usr/share/doc/yum-*/Fedora-GPG-KEY
rpm --import /usr/share/doc/yum-*/RPM-GPG-KEY
We installed the key of Red Hat Inc, as we obviously trust the company that compiled our operating system. We installed Fedora's key, as we have allready installed yum packaged by Fedora. These two keys are probably the most usefull ones.

Start installing software
yum install lynx

Because it is your first run, it first downloads headers that contain information about what is available. This can take as long as 20 minutes, but it only needs to be done once. Yum prints the names of headers it downloads
Gathering header information file(s) from server(s)
Server: Fedora Linux / stable for Red Hat Linux 9 (i386)
Server: Fedora Linux / testing for Red Hat Linux 9 (i386)
Server: Red Hat Linux 9 (i386)
Server: Red Hat Linux 9 (i386) updates
Finding updated packages
Downloading needed headers
getting /var/cache/yum/fedora-stable/headers/leafnode-0-1.9.43-0.fdr.1.rh90.i386.hdr
getting /var/cache/yum/fedora-stable/headers/libzvt-devel-0-2.0.1-0.fdr.5.rh90.i386.hdr
getting /var/cache/yum/fedora-stable/headers/mhash-devel-0-0.8.18-0.fdr.1.rh90.i386.hdr
   [..]
Resolving dependencies
Dependencies resolved
I will do the following:
[install: lynx 0-2.8.5-7.1.i386]
Is this ok [y/N]: y
Accept with y and press enter. Yum downloads requested packages and installs them.

If any additional programs, dependencies, are needed, yum will ask if you want to install those too. For example, lynx needs perl-CGI, so if we don't have that installed yet, yum installs it.
Calculating available disk space - this could take a bit
lynx 100 % done 1/1
Installed:  lynx 0-2.8.5-7.1.i386
Transaction(s) Complete
Now all users can use lynx right away. No reboots, no changing cdroms, no nuisance. If you are still root (have a # on your command prompt), exit.

Now try lynx. If you can run lynx (the text mode web browser), you have succeeded. Congratulations, you have now installed the state of the art package manager yum.

Yum tips

Here there are other useful switches with yum:

  • yum list "*ssh*": To list packages that have "ssh" in the name
  • chkconfig yum on: To make yum update all programs every night
  • yum remove up2date: To remove a program, dependencies handled
  • yum -y install curl: -y answers "yes" to all questions
Now you can try to install mysql yourselves.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

Wednesday, March 2, 2011

Spring Security

Hey...
Most of projects need security to check logged in user and its roles to access to different parts of an application. In Spring MVC(Simple CRUD) and Spring MVC-View  post we could create a simple CRUD usecase. Here I am going to make a simple security with customary Roles.
Spring has a powerfull security framework that can commiunicate usual security systems like CAS, LDAP and so on. Here I will create a simple security system including authentication and authorization.
the usecase senario is:
  1. An anonymous user first visit the home page. it can log in to the system
  2. In log in page user should enter its username and password.
  3. After login user can see a list of system user and it can change the list depending on its roles:
    1. administrator: it can add, edit, delete the records. and also make a user expired or disabled and so on.
    2. poweruser: it can add and view users. but it can not make user expired or disabled and so on.
    3. user: it can just view users.
  4. It can log out.
  5. The log out page will be displayed.
  6. It can go back to home page(refer 1).
The first step of spring security is to make an spring application context and make a listener to load a ContextLoaderListener. So in web.xml:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
then we should create a security filter to pass any request from this filter:
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Now everything is ready for spring security configuration. in applicationContext.xml I import spring-servlet.xml. it is the main spring configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-servlet.xml"/>

</beans>
in spring-servlet.xml file first I import security-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--security config-->
    <import resource="classpath:security-config.xml"/>

    ...
</beans>
other configuration description has been taken in Spring MVC(Simple CRUD). this is the spring security configuration file:
<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <global-method-security pre-post-annotations="enabled">
    </global-method-security>

    <http use-expressions="true" auto-config="true">
        <intercept-url pattern="/user/**" access="isAuthenticated()"/>
        <intercept-url pattern="/**" access="permitAll"/>
        <form-login authentication-success-handler-ref="loginSuccess"/>
        <logout logout-success-url="/home/logout.html"/>
        <remember-me/>
        <session-management>
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/>
        </session-management>
    </http>
    <beans:bean id="loginSuccess" class="com.security.LoginSuccessHandler"/>
    <beans:bean id="userDetailsService" class="com.security.UserSecurityService"/>
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder hash="md5"/>
        </authentication-provider>
    </authentication-manager>
</beans:beans>
  1. global-method-security: we can use spring security annotation(@PreAuthorize and @PostAuthorize) by this tag.
  2. intercept-url: we can check security in any url patterns by this tag.
  3. form-login: we can make a custom login form or use default spring security login form. in this sample we use the default spring security form. But you can get authentication success handler class to set general attribute when a user successfully logs in. For example setting current user theme. Here we create "com.security.LoginSuccessHandler" class to get the loggin success handler.
  4. logout: you can set logout url and logout from via this tag.
  5. authentication-provider: we can determine which authentication-providers should authenticate the user. we can use different providers like: CAS, LDAP and so on. Here we use implicit provider: "com.security.UserSecurityService". This class should implements "UserDetailsService".
  6. password-encoder: we can determine password encoder policy via this tag. we can use hash encoder like: MD4, MD5, SHA, ... and also Base64.
In this sample we have 2 major entity beans:
  • Role: implements GrantedAuthority (needed for spring security)
  • User: implements UserDetails (needed for spring security)
the class diagram is available here:
UserSecurityService class should implements loadUserByUsername method. so in this method i use userService calls to fetch a user from database by its user name:
public class UserSecurityService implements UserDetailsService {

    @Autowired
    UserService userService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        return userService.findByUsername(username);
    }
}
Scince the returned user should be an standard user(implements "org.springframework.security.core.userdetails.UserDetails"), so when I return a user via this method, spring security will compare the input user and password and this returned user's username and password and also its lock and other states.
this was the authentication step.
the authorization step will be check in different levels: 
1. action url
in security-config.xml file we can use "intercept-url" to make and access for each url. for example:
<intercept-url pattern="/user/**" access="hasRole('administrator')"/>

2. code
we can use @PreAuthorize or @PostAuthorize annotation on top of a method or we can check a role manually by use of SecurityContextHolder class.
here is annotation sample:
    @PreAuthorize("hasRole('administrator') or hasRole('power_user')")
    public void saveOrUpdate(User user, List<Long> roleIds) {

    ...
    }
and here is manual sample:
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
for(Role role : user.getRoleList()){
if(role.getAuthority().equals("administrator") || role.getAuthority().equals("power_user"))
return true;
}
return false;
3. jsp
there are some tag libraries to in "http://www.springframework.org/security/tags". we can use them to check authentication and authorization and also display current user and current user access list:
  • security:authorize: A tag which outputs the body of the tag if the configured access expression
                evaluates to true for the currently authenticated principal.
  • authentication: Allows access to the current Authentication object.
  • accesscontrollist: Allows inclusion of a tag body if the current Authentication
                has one of the specified permissions to the presented
                domain object instance.
for example:
<security:authorize access="hasRole('administrator')">
                        <input type="submit" value="edit"
                               onclick="setUserId(${user.id}); setFormAction('<spring:url value="/user/edit.html"/>');"/>

</security:authorize>
and:
    <security:authorize access="isAuthenticated()">
        <a href="/j_spring_security_logout">logout</a> welcome <security:authentication property="name"/>
    </security:authorize>
well...
now its the time to download the sample source code and take a tour in it yourself. in this sample I imported spring security jar files. But other needed Spring jar files are available in sample of  Spring MVC(Simple CRUD) post. after running the sample, the first page you can see is: http://localhost:8080/home/view.html
To create the needed databse schema, there is a mysql script in [sample root]/db/security.sql file. you can restore it in you mysql server. The datasource properties are available in [sample root]/src/database.properties file. after you restore the script, a single user with role of administrator will be created. its specification is:
username:administrator
password:123456
you can run the sample and log in by this user then create more users with different roles.
Enjoy yourselves.


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog