Monday, August 17, 2015

Objective C Using Class (Note)

An Objective-C class is comprised of an interface and an implementation.

The interface declares the class properties and methods.

The implementation defines class instance variables, properties and methods.

Scope of instance variables:

  • @private The instance variable is only accessible within class that declares it and other instances of this class type.
  • @protected The instance variable is accessible within the class that declares it and the instance methods of any of its subclasses. This is default scope.
  • @public The instance variable is accessible from everywhere.
  • @package The instance variable is accessible from any other class instances or functions, but outside the package, it is treated as private. This scope can be useful for libraries or framework classes. 
Properties, in many programming language, methods can access an object internal state -- often referred to as getter/setter methods -- must be manual code. Objective C provides declared properties to both automate and simplify this task. A property differs from an instance variable in that it doesn’t directly access an object’s internal state, but rather provides a convenient mechanism (i.e., getter/ setter methods) for accessing this data, and thus may include other logic. Objective-C declared properties enable the compiler to generate these methods automatically according to your provided specification. This reduces the amount of code you have to write and maintain, and increases program consistency and reliability.

  • nonatomic Accessors are not atomic and, consequently, could provide different results when accessed concurrently by multiple threads. If not specified, accessors are atomic; that is, their values are always fully set/retrieved.
  • assign The setter method performs a simple assignment of properties value without using copy or retain. This is default setting.
  • retain On assignment, the input value will be sent retain message and the previous value will be sent a release message.
  • copy A copy of new message will be set on assignment and the previous value will be sent a release message.
  • strong This attribute (used when ARC memory management is applied on a property) is equivalent to the retain attribute.
  • weak This attribute (used when ARC memory management is applied on a property) is similar to the assign attribute except that if the affect property is released, its value is set to nil.
  • read/write The property can be read or written to. Both getter and setter methods must be implemented. This is the default setting.
  • read-only The property can be read but not written to. The getter method must be implemented.
  • getter=getterName Renames the getter to the specified getterName.
  • setter=setterName Renames the setter to the specified setterName.
Through use of the @synthesize keyword, the compiler can auto generate property definitions. A properties is synthesized in the corresponding class implementation section.


The method type identifier specifies whether the method is a class or an instance method. A class method is declared with a + (plus) sign and indicates that the method has class scope, meaning that it operates at the class level and does not have access to the instance variables of the class (unless they are passed as parameters to the method). An instance method is declared with a – (minus) sign and indicates that the method has object scope. It operates at the instance level and has direct access to the instance variables of the object and its parent objects (subject to the access controls on the instance variables).

A protocol declares methods and properties that can be implemented by any class. A class interface is directly associated with a specific class and, hence, a class hierarchy. On the other hand, a protocol is not associated with any particular class, thus it can be used to capture similarities among classes that are not hierarchically related. Protocols provide Objective-C with the capability to support the concept of multiple inheritance of specification (i.e., of method declarations). A protocol can also be used to define the messages that an object can send (by specifying properties that conform to a protocol).

A category enables the addition of new functionality to an existing class without subclassing it. Typically, categories are used 1) to extend classes defined by others (even if you don’t have access to the source code); 2) as an alternative to a subclass; or 3) to distribute the implementation of a new class into multiple source files. An extension can be considered an anonymous category; however, its declarations must be implemented in the main implementation block of the class. Extensions can also declare instance variables and properties.

An interface may employ inheritance to obtain the properties and methods of subclasses in a class hierarchy.

By convention, a class interface is stored (on disk) in a header file (suffixed with .h) and its implementation is stored in a file suffixed with .m.

Xcode provides templates for creating Objective-C classes, protocols, categories, and extensions, thereby making it easy to get started developing your own classes.
This has been a detailed primer on developing classes using Objective-C and Xcode, so this is
a good time to take a break and review what you’ve gone over. In the next chapter, you’ll pick up where you left off by exploring the details of object messaging using Objective-C.

Monday, July 27, 2015

grep command

grep can be used to match literal string in text file
  • #grep "string" full_file_name
print string but except '#' char at first line and remove blank lines
  • #grep -v "^$\|^\s*[#]" full_file_name
find string in file
  • find . -name '*.*' -exec grep -i 'string to search for' {} \; -print
and then compress files
  • find /path/ -name "pattern" -type f -exec tar -rvf {} +
  • find /path/ -name "pattern" -type f -print0 | xargs tar cvf compress.tar 

Friday, July 24, 2015

Top 20 Nginx WebServer Best Security Practices


by VIVEK GITE on MARCH 6, 2010

Nginx is a lightweight, high performance web server/reverse proxy and e-mail (IMAP/POP3) proxy. It runs on UNIX, GNU/Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows. According to Netcraft, 6% of all domains on the Internet use nginx webserver. Nginx is one of a handful of servers written to address the C10K problem. Unlike traditional servers, Nginx doesn't rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. Nginx powers several high traffic web sites, such as WordPress, Hulu, Github, and SourceForge. This page collects hints how to improve the security of nginx web servers running on Linux or UNIX like operating systems.

Default Config Files and Nginx Port

/usr/local/nginx/conf/ - The nginx server configuration directory and /usr/local/nginx/conf/nginx.conf is main configuration file.
/usr/local/nginx/html/ - The default document location.
/usr/local/nginx/logs/ - The default log file location.
Nginx HTTP default port : TCP 80
Nginx HTTPS default port : TCP 443
You can test nginx configuration changes as follows:
# /usr/local/nginx/sbin/nginx -t

Sample outputs:

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful
To load config changes, type:
# /usr/local/nginx/sbin/nginx -s reload

To stop server, type:
# /usr/local/nginx/sbin/nginx -s stop

#1: Turn On SELinux

Security-Enhanced Linux (SELinux) is a Linux kernel feature that provides a mechanism for supporting access control security policies which provides great protection. It can stop many attacks before your system rooted. See how to turn on SELinux for CentOS / RHEL based systems.

Do Boolean Lockdown
Run the getsebool -a command and lockdown system:

getsebool -a | less
getsebool -a | grep off
getsebool -a | grep o
To secure the machine, look at settings which are set to 'on' and change to 'off' if they do not apply to your setup with the help of setsebool command. Set correct SE Linux booleans to maintain functionality and protection. Please note that SELinux adds 2-8% overheads to typical RHEL or CentOS installation.

#2: Allow Minimal Privileges Via Mount Options

Server all your webpages / html / php files via separate partitions. For example, create a partition called /dev/sda5 and mount at the /nginx. Make sure /nginx is mounted with noexec, nodev and nosetuid permissions. Here is my /etc/fstab entry for mounting /nginx:

LABEL=/nginx     /nginx          ext3   defaults,nosuid,noexec,nodev 1 2
Note you need to create a new partition using fdisk and mkfs.ext3 commands.

#3: Linux /etc/sysctl.conf Hardening

You can control and configure Linux kernel and networking settings via /etc/sysctl.conf.


# Avoid a smurf attack
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Turn on protection for bad icmp error messages
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Turn on syncookies for SYN flood attack protection
net.ipv4.tcp_syncookies = 1

# Turn on and log spoofed, source routed, and redirect packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# No source routed packets here
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Turn on reverse path filtering
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Make sure no one can alter the routing tables
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0

# Don't act as a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0


# Turn on execshild
kernel.exec-shield = 1
kernel.randomize_va_space = 1

# Tuen IPv6
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

# Optimization for port usefor LBs
# Increase system file descriptor limit
fs.file-max = 65535

# Allow for more PIDs (to reduce rollover problems); may break some programs 32768
kernel.pid_max = 65536

# Increase system IP port limits
net.ipv4.ip_local_port_range = 2000 65000

# Increase TCP max buffer size setable using setsockopt()
net.ipv4.tcp_rmem = 4096 87380 8388608
net.ipv4.tcp_wmem = 4096 87380 8388608

# Increase Linux auto tuning TCP buffer limits
# min, default, and max number of bytes to use
# set max to at least 4MB, or higher if you use very high BDP paths
# Tcp Windows etc
net.core.rmem_max = 8388608
net.core.wmem_max = 8388608
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_window_scaling = 1

See also:

Linux Tuning The VM (memory) Subsystem
Linux Tune Network Stack (Buffers Size) To Increase Networking Performance
#4: Remove All Unwanted Nginx Modules

You need to minimizes the number of modules that are compiled directly into the nginx binary. This minimizes risk by limiting the capabilities allowed by the webserver. You can configure and install nginx using only required modules. For example, disable SSI and autoindex module you can type:
# ./configure --without-http_autoindex_module --without-http_ssi_module
# make
# make install

Type the following command to see which modules can be turn on or off while compiling nginx server:
# ./configure --help | less

Disable nginx modules that you don't need.

(Optional) Change Nginx Version Header
Edit src/http/ngx_http_header_filter_module.c, enter:
# vi +48 src/http/ngx_http_header_filter_module.c

Find line


static char ngx_http_server_string[] = "Server: nginx" CRLF;
static char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;

Change them as follows:


static char ngx_http_server_string[] = "Server: Ninja Web Server" CRLF;
static char ngx_http_server_full_string[] = "Server: Ninja Web Server" CRLF;

Save and close the file. Now, you can compile the server. Add the following in nginx.conf to turn off nginx version number displayed on all auto generated error pages:

server_tokens off
#5: Use mod_security (only for backend Apache servers)

mod_security provides an application level firewall for Apache. Install mod_security for all backend Apache web servers. This will stop many injection attacks.

#6: Install SELinux Policy To Harden The Nginx Webserver

By default SELinux will not protect the nginx web server. However, you can install and compile protection as follows. First, install required SELinux compile time support:
# yum -y install selinux-policy-targeted selinux-policy-devel

Download targeted SELinux policies to harden the nginx webserver on Linux servers from the project home page:
# cd /opt
# wget 'http://downloads.sourceforge.net/project/selinuxnginx/se-ngix_1_0_10.tar.gz?use_mirror=nchc'

Untar the same:
# tar -zxvf se-ngix_1_0_10.tar.gz

Compile the same
# cd se-ngix_1_0_10/nginx
# make

Sample outputs:

Compiling targeted nginx module
/usr/bin/checkmodule:  loading policy configuration from tmp/nginx.tmp
/usr/bin/checkmodule:  policy configuration loaded
/usr/bin/checkmodule:  writing binary representation (version 6) to tmp/nginx.mod
Creating targeted nginx.pp policy package
rm tmp/nginx.mod.fc tmp/nginx.mod
Install the resulting nginx.pp SELinux module:
# /usr/sbin/semodule -i nginx.pp

#7: Restrictive Iptables Based Firewall

The following firewall script blocks everything and only allows:

Incoming HTTP (TCP port 80) requests
Incoming ICMP ping requests
Outgoing ntp (port 123) requests
Outgoing smtp (TCP port 25) requests
#!/bin/bash
IPT="/sbin/iptables"

#### IPS ######
# Get server public ip
SERVER_IP=$(ifconfig eth0 | grep 'inet addr:' | awk -F'inet addr:' '{ print $2}' | awk '{ print $1}')
LB1_IP="204.54.1.1"
LB2_IP="204.54.1.2"

# Do some smart logic so that we can use damm script on LB2 too
OTHER_LB=""
SERVER_IP=""
[[ "$SERVER_IP" == "$LB1_IP" ]] && OTHER_LB="$LB2_IP" || OTHER_LB="$LB1_IP"
[[ "$OTHER_LB" == "$LB2_IP" ]] && OPP_LB="$LB1_IP" || OPP_LB="$LB2_IP"

### IPs ###
PUB_SSH_ONLY="122.xx.yy.zz/29"

#### FILES #####
BLOCKED_IP_TDB=/root/.fw/blocked.ip.txt
SPOOFIP="127.0.0.0/8 192.168.0.0/16 172.16.0.0/12 10.0.0.0/8 169.254.0.0/16 0.0.0.0/8 240.0.0.0/4 255.255.255.255/32 168.254.0.0/16 224.0.0.0/4 240.0.0.0/5 248.0.0.0/5 192.0.2.0/24"
BADIPS=$( [[ -f ${BLOCKED_IP_TDB} ]] && egrep -v "^#|^$" ${BLOCKED_IP_TDB})

### Interfaces ###
PUB_IF="eth0"   # public interface
LO_IF="lo"      # loopback
VPN_IF="eth1"   # vpn / private net

### start firewall ###
echo "Setting LB1 $(hostname) Firewall..."

# DROP and close everything
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP

# Unlimited lo access
$IPT -A INPUT -i ${LO_IF} -j ACCEPT
$IPT -A OUTPUT -o ${LO_IF} -j ACCEPT

# Unlimited vpn / pnet access
$IPT -A INPUT -i ${VPN_IF} -j ACCEPT
$IPT -A OUTPUT -o ${VPN_IF} -j ACCEPT

# Drop sync
$IPT -A INPUT -i ${PUB_IF} -p tcp ! --syn -m state --state NEW -j DROP

# Drop Fragments
$IPT -A INPUT -i ${PUB_IF} -f -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL ALL -j DROP

# Drop NULL packets
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL NONE -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix " NULL Packets "
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL NONE -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags SYN,RST SYN,RST -j DROP

# Drop XMAS
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags SYN,FIN SYN,FIN -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix " XMAS Packets "
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP

# Drop FIN packet scans
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags FIN,ACK FIN -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix " Fin Packets Scan "
$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags FIN,ACK FIN -j DROP

$IPT  -A INPUT -i ${PUB_IF} -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

# Log and get rid of broadcast / multicast and invalid
$IPT  -A INPUT -i ${PUB_IF} -m pkttype --pkt-type broadcast -j LOG --log-prefix " Broadcast "
$IPT  -A INPUT -i ${PUB_IF} -m pkttype --pkt-type broadcast -j DROP

$IPT  -A INPUT -i ${PUB_IF} -m pkttype --pkt-type multicast -j LOG --log-prefix " Multicast "
$IPT  -A INPUT -i ${PUB_IF} -m pkttype --pkt-type multicast -j DROP

$IPT  -A INPUT -i ${PUB_IF} -m state --state INVALID -j LOG --log-prefix " Invalid "
$IPT  -A INPUT -i ${PUB_IF} -m state --state INVALID -j DROP

# Log and block spoofed ips
$IPT -N spooflist
for ipblock in $SPOOFIP
do
         $IPT -A spooflist -i ${PUB_IF} -s $ipblock -j LOG --log-prefix " SPOOF List Block "
         $IPT -A spooflist -i ${PUB_IF} -s $ipblock -j DROP
done
$IPT -I INPUT -j spooflist
$IPT -I OUTPUT -j spooflist
$IPT -I FORWARD -j spooflist

# Allow ssh only from selected public ips
for ip in ${PUB_SSH_ONLY}
do
        $IPT -A INPUT -i ${PUB_IF} -s ${ip} -p tcp -d ${SERVER_IP} --destination-port 22 -j ACCEPT
        $IPT -A OUTPUT -o ${PUB_IF} -d ${ip} -p tcp -s ${SERVER_IP} --sport 22 -j ACCEPT
done

# allow incoming ICMP ping pong stuff
$IPT -A INPUT -i ${PUB_IF} -p icmp --icmp-type 8 -s 0/0 -m state --state NEW,ESTABLISHED,RELATED -m limit --limit 30/sec  -j ACCEPT
$IPT -A OUTPUT -o ${PUB_IF} -p icmp --icmp-type 0 -d 0/0 -m state --state ESTABLISHED,RELATED -j ACCEPT

# allow incoming HTTP port 80
$IPT -A INPUT -i ${PUB_IF} -p tcp -s 0/0 --sport 1024:65535 --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o ${PUB_IF} -p tcp --sport 80 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT


# allow outgoing ntp
$IPT -A OUTPUT -o ${PUB_IF} -p udp --dport 123 -m state --state NEW,ESTABLISHED -j ACCEPT
$IPT -A INPUT -i ${PUB_IF} -p udp --sport 123 -m state --state ESTABLISHED -j ACCEPT

# allow outgoing smtp
$IPT -A OUTPUT -o ${PUB_IF} -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
$IPT -A INPUT -i ${PUB_IF} -p tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT

### add your other rules here ####

#######################
# drop and log everything else
$IPT -A INPUT -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix " DEFAULT DROP "
$IPT -A INPUT -j DROP

exit 0
#8: Controlling Buffer Overflow Attacks

Edit nginx.conf and set the buffer size limitations for all clients.
# vi /usr/local/nginx/conf/nginx.conf

Edit and set the buffer size limitations for all clients as follows:


 ## Start: Size Limits & Buffer Overflows ##
  client_body_buffer_size  1K;
  client_header_buffer_size 1k;
  client_max_body_size 1k;
  large_client_header_buffers 2 1k;
 ## END: Size Limits & Buffer Overflows ##

Where,

client_body_buffer_size 1k - (default is 8k or 16k) The directive specifies the client request body buffer size.
client_header_buffer_size 1k - Directive sets the headerbuffer size for the request header from client. For the overwhelming majority of requests a buffer size of 1K is sufficient. Increase this if you have a custom header or a large cookie sent from the client (e.g., wap client).
client_max_body_size 1k- Directive assigns the maximum accepted body size of client request, indicated by the line Content-Length in the header of request. If size is greater the given one, then the client gets the error "Request Entity Too Large" (413). Increase this when you are getting file uploads via the POST method.
large_client_header_buffers 2 1k - Directive assigns the maximum number and size of buffers for large headers to read from client request. By default the size of one buffer is equal to the size of page, depending on platform this either 4K or 8K, if at the end of working request connection converts to state keep-alive, then these buffers are freed. 2x1k will accept 2kB data URI. This will also help combat bad bots and DoS attacks.
You also need to control timeouts to improve server performance and cut clients. Edit it as follows:


 ## Start: Timeouts ##
  client_body_timeout   10;
  client_header_timeout 10;
  keepalive_timeout     5 5;
  send_timeout          10;
## End: Timeouts ##

client_body_timeout 10; - Directive sets the read timeout for the request body from client. The timeout is set only if a body is not get in one readstep. If after this time the client send nothing, nginx returns error "Request time out" (408). The default is 60.
client_header_timeout 10; - Directive assigns timeout with reading of the title of the request of client. The timeout is set only if a header is not get in one readstep. If after this time the client send nothing, nginx returns error "Request time out" (408).
keepalive_timeout 5 5; - The first parameter assigns the timeout for keep-alive connections with the client. The server will close connections after this time. The optional second parameter assigns the time value in the header Keep-Alive: timeout=time of the response. This header can convince some browsers to close the connection, so that the server does not have to. Without this parameter, nginx does not send a Keep-Alive header (though this is not what makes a connection "keep-alive").
send_timeout 10; - Directive assigns response timeout to client. Timeout is established not on entire transfer of answer, but only between two operations of reading, if after this time client will take nothing, then nginx is shutting down the connection.
#9: Control Simultaneous Connections

You can use NginxHttpLimitZone module to limit the number of simultaneous connections for the assigned session or as a special case, from one IP address. Edit nginx.conf:


### Directive describes the zone, in which the session states are stored i.e. store in slimits. ###
### 1m can handle 32000 sessions with 32 bytes/session, set to 5m x 32000 session ###
       limit_zone slimits $binary_remote_addr 5m;

### Control maximum number of simultaneous connections for one session i.e. ###
### restricts the amount of connections from a single ip address ###
        limit_conn slimits 5;

The above will limits remote clients to no more than 5 concurrently "open" connections per remote ip address.

#10: Allow Access To Our Domain Only

If bot is just making random server scan for all domains, just deny it. You must only allow configured virtual domain or reverse proxy requests. You don't want to display request using an IP address:

## Only requests to our Host are allowed i.e. nixcraft.in, images.nixcraft.in and www.nixcraft.in
      if ($host !~ ^(nixcraft.in|www.nixcraft.in|images.nixcraft.in)$ ) {
         return 444;
      }
##
#11: Limit Available Methods

GET and POST are the most common methods on the Internet. Web server methods are defined in RFC 2616. If a web server does not require the implementation of all available methods, they should be disabled. The following will filter and only allow GET, HEAD and POST methods:

## Only allow these request methods ##
     if ($request_method !~ ^(GET|HEAD|POST)$ ) {
         return 444;
     }
## Do not accept DELETE, SEARCH and other methods ##
More About HTTP Methods
The GET method is used to request document such as http://www.cyberciti.biz/index.php.
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
The POST method may involve anything, like storing or updating data, or ordering a product, or sending E-mail by submitting the form. This is usually processed using the server side scripting such as PHP, PERL, Python and so on. You must use this if you want to upload files and process forms on server.
#12: How Do I Deny Certain User-Agents?

You can easily block user-agents i.e. scanners, bots, and spammers who may be abusing your server.

## Block download agents ##
     if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
            return 403;
     }
##
Block robots called msnbot and scrapbot:

## Block some robots ##
     if ($http_user_agent ~* msnbot|scrapbot) {
            return 403;
     }
#12: How Do I Block Referral Spam?

Referer spam is dengerouns. It can harm your SEO ranking via web-logs (if published) as referer field refer to their spammy site. You can block access to referer spammers with these lines.

## Deny certain Referers ###
     if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) )
     {
         # return 404;
         return 403;
     }
##
#13: How Do I Stop Image Hotlinking?

Image or HTML hotlinking means someone makes a link to your site to one of your images, but displays it on their own site. The end result you will end up paying for bandwidth bills and make the content look like part of the hijacker's site. This is usually done on forums and blogs. I strongly suggest you block and stop image hotlinking at your server level itself.

# Stop deep linking or hot linking
location /images/ {
  valid_referers none blocked www.example.com example.com;
   if ($invalid_referer) {
     return   403;
   }
}
Example: Rewrite And Display Image
Another example with link to banned image:

valid_referers blocked www.example.com example.com;
 if ($invalid_referer) {
  rewrite ^/images/uploads.*\.(gif|jpg|jpeg|png)$ http://www.examples.com/banned.jpg last
 }
See also:

HowTo: Use nginx map to block image hotlinking. This is useful if you want to block tons of domains.
#14: Directory Restrictions

You can set access control for a specified directory. All web directories should be configured on a case-by-case basis, allowing access only where needed.

Limiting Access By Ip Address
You can limit access to directory by ip address to /docs/ directory:

location /docs/ {
  ## block one workstation
  deny    192.168.1.1;
  ## allow anyone in 192.168.1.0/24
  allow   192.168.1.0/24;
  ## drop rest of the world
  deny    all;
}
Password Protect The Directory
First create the password file and add a user called vivek:
# mkdir /usr/local/nginx/conf/.htpasswd/
# htpasswd -c /usr/local/nginx/conf/.htpasswd/passwd vivek

Edit nginx.conf and protect the required directories as follows:

### Password Protect /personal-images/ and /delta/ directories ###
location ~ /(personal-images/.*|delta/.*) {
  auth_basic  "Restricted";
  auth_basic_user_file   /usr/local/nginx/conf/.htpasswd/passwd;
}
Once a password file has been generated, subsequent users can be added with the following command:
# htpasswd -s /usr/local/nginx/conf/.htpasswd/passwd userName

#15: Nginx SSL Configuration

HTTP is a plain text protocol and it is open to passive monitoring. You should use SSL to to encrypt your content for users.

Create an SSL Certificate
Type the following commands:
# cd /usr/local/nginx/conf
# openssl genrsa -des3 -out server.key 1024
# openssl req -new -key server.key -out server.csr
# cp server.key server.key.org
# openssl rsa -in server.key.org -out server.key
# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Edit nginx.conf and update it as follows:

server {
    server_name example.com;
    listen 443;
    ssl on;
    ssl_certificate /usr/local/nginx/conf/server.crt;
    ssl_certificate_key /usr/local/nginx/conf/server.key;
    access_log /usr/local/nginx/logs/ssl.access.log;
    error_log /usr/local/nginx/logs/ssl.error.log;
}
Restart the nginx:
# /usr/local/nginx/sbin/nginx -s reload

See also:

For more information, read the Nginx SSL documentation.
#16: Nginx And PHP Security Tips

PHP is one of the popular server side scripting language. Edit /etc/php.ini as follows:


# Disallow dangerous functions
disable_functions = phpinfo, system, mail, exec

## Try to limit resources  ##

# Maximum execution time of each script, in seconds
max_execution_time = 30

# Maximum amount of time each script may spend parsing request data
max_input_time = 60

# Maximum amount of memory a script may consume (8MB)
memory_limit = 8M

# Maximum size of POST data that PHP will accept.
post_max_size = 8M

# Whether to allow HTTP file uploads.
file_uploads = Off

# Maximum allowed size for uploaded files.
upload_max_filesize = 2M

# Do not expose PHP error messages to external users
display_errors = Off

# Turn on safe mode
safe_mode = On

# Only allow access to executables in isolated directory
safe_mode_exec_dir = php-required-executables-path

# Limit external access to PHP environment
safe_mode_allowed_env_vars = PHP_

# Restrict PHP information leakage
expose_php = Off

# Log all errors
log_errors = On

# Do not register globals for input data
register_globals = Off

# Minimize allowable PHP post size
post_max_size = 1K

# Ensure PHP redirects appropriately
cgi.force_redirect = 0

# Disallow uploading unless necessary
file_uploads = Off

# Enable SQL safe mode
sql.safe_mode = On

# Avoid Opening remote files
allow_url_fopen = Off

See also:

PHP Security: Limit Resources Used By Script
PHP.INI settings: Disable exec, shell_exec, system, popen and Other Functions To Improve Security
#17: Run Nginx In A Chroot Jail (Containers) If Possible

Putting nginx in a chroot jail minimizes the damage done by a potential break-in by isolating the web server to a small section of the filesystem. You can use traditional chroot kind of setup with nginx. If possible use FreeBSD jails, XEN, or OpenVZ virtualization which uses the concept of containers.

#18: Limits Connections Per IP At The Firewall Level

A webserver must keep an eye on connections and limit connections per second. This is serving 101. Both pf and iptables can throttle end users before accessing your nginx server.

Linux Iptables: Throttle Nginx Connections Per Second
The following example will drop incoming connections if IP make more than 15 connection attempts to port 80 within 60 seconds:


/sbin/iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
/sbin/iptables -A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 60  --hitcount 15 -j DROP
service iptables save

BSD PF: Throttle Nginx Connections Per Second
Edit your /etc/pf.conf and update it as follows. The following will limits the maximum number of connections per source to 100. 15/5 specifies the number of connections per second or span of seconds i.e. rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.

webserver_ip="202.54.1.1"
table <abusive_ips> persist
block in quick from <abusive_ips>
pass in on $ext_if proto tcp to $webserver_ip port www flags S/SA keep state (max-src-conn 100, max-src-conn-rate 15/5, overload <abusive_ips> flush)
Please adjust all values as per your requirements and traffic (browsers may open multiple connections to your site). See also:

Sample PF firewall script.
Sample Iptables firewall script.
#19: Configure Operating System to Protect Web Server

Turn on SELinux as described above. Set correct permissions on /nginx document root. The nginx runs as a user named nginx. However, the files in the DocumentRoot (/nginx or /usr/local/nginx/html) should not be owned or writable by that user. To find files with wrong permissions, use:
# find /nginx -user nginx
# find /usr/local/nginx/html -user nginx

Make sure you change file ownership to root or other user. A typical set of permission /usr/local/nginx/html/
# ls -l /usr/local/nginx/html/

Sample outputs:

-rw-r--r-- 1 root root 925 Jan  3 00:50 error4xx.html
-rw-r--r-- 1 root root  52 Jan  3 10:00 error5xx.html
-rw-r--r-- 1 root root 134 Jan  3 00:52 index.html
You must delete unwated backup files created by vi or other text editor:
# find /nginx -name '.?*' -not -name .ht* -or -name '*~' -or -name '*.bak*' -or -name '*.old*'
# find /usr/local/nginx/html/ -name '.?*' -not -name .ht* -or -name '*~' -or -name '*.bak*' -or -name '*.old*'

Pass -delete option to find command and it will get rid of those files too.

#20: Restrict Outgoing Nginx Connections

The crackers will download file locally on your server using tools such as wget. Use iptables to block outgoing connections from nginx user. The ipt_owner module attempts to match various characteristics of the packet creator, for locally generated packets. It is only valid in the OUTPUT chain. In this example, allow vivek user to connect outside using port 80 (useful for RHN access or to grab CentOS updates via repos):

/sbin/iptables -A OUTPUT -o eth0 -m owner --uid-owner vivek -p tcp --dport 80 -m state --state NEW,ESTABLISHED  -j ACCEPT
Add above rule to your iptables based shell script. Do not allow nginx web server user to connect outside.

Bounce Tip: Watching Your Logs & Auditing

Check the Log files. They will give you some understanding of what attacks is thrown against the server and allow you to check if the necessary level of security is present or not.
# grep "/login.php??" /usr/local/nginx/logs/access_log
# grep "...etc/passwd" /usr/local/nginx/logs/access_log
# egrep -i "denied|error|warn" /usr/local/nginx/logs/error_log

The auditd service is provided for system auditing. Turn it on to audit service SELinux events, authetication events, file modifications, account modification and so on. As usual disable all services and follow our "Linux Server Hardening" security tips.

Conclusion

Your nginx server is now properly harden and ready to server webpages. However, you should be consulted further resources for your web applications security needs. For example, wordpress or any other third party apps has its own security requirements.

Sunday, July 12, 2015

PGS.TS.NGND Nguyễn Võ Kỳ Anh: “Đừng bỏ lỡ giai đoạn vàng” để phát triển trí thông minh ở trẻ


Theo Phó Giáo sư, Tiến sĩ, Nhà giáo nhân dân Nguyễn Võ Kỳ Anh, Viện trưởng Viện nghiên cứu giáo dục, phát triển tiềm năng con người Việt Nam( IPD), điểm mấu chốt trong việc nuôi dạy trẻ thông minh là bắt đầu giáo dục sớm cho trẻ ngay từ những năm đầu đời và chú trọng phát triển toàn diện 4 khía cạnh then chốt: trí não, tầm vóc, hệ tiêu hóa, hệ miễn dịch.

Vừa qua, PGS. TS. Nguyễn Võ Kỳ Anh đã thực hiện 2 buổi giao lưu trực tuyến về chủ đề phát triển trí thông minh đa diện cho trẻ em và đã thu hút được sự quan tâm, hưởng ứng của đông đảo các bậc phụ huynh. Theo ông, một tín hiệu đáng mừng là nhiều cha mẹ đã bắt đầu có biểu hiện chú trọng hơn trong việc nuôi dạy con cái theo phương pháp hiện đại. Tuy nhiên, vẫn còn một số người chưa hiểu rõ về tầm quan trọng của việc giáo dục sớm, nhất là ở giai đoạn vàng để phát triển trí thông minh của trẻ.

Đừng bỏ lỡ giai đoạn vàng để phát triển trí thông minh ở trẻ.
Đừng bỏ lỡ giai đoạn vàng để phát triển trí thông minh ở trẻ.

Cụ thể của việc giáo dục sớm và giai đoạn vàng này là như thế nào. Mục đích để làm gì thưa PGS. TS?

Giáo dục sớm để phát triển trí thông minh ở trẻ phải bắt đầu từ khi còn là thai nhi, sơ sinh đến 6 tuổi. Đó là giai đoạn vàng của một đời người vì trẻ đang phát triển với tốc độ nhanh về thể lực và trí lực. 

Mục đích của việc giáo dục sớm là giúp phát triển não bộ, chủ yếu ở giai đoạn này là não phải, làm cho trẻ phát triển hài hòa, hoàn thiện cả 2 bán cầu đại não và khai mở tiềm năng các loại hình trí thông minh mà trẻ có khả năng nổi trội. Nếu bỏ qua giai đoạn này sẽ khiến trẻ lãng phí mất thời gian quý giá để có thể phát triển nổi trội các loại hình thông minh mà trẻ sẵn có ngay từ khi còn nhỏ.

PGS. TS. Có nhắc đến loại hình trí thông minh trẻ sở hữu, phải chăng trí thông minh có nhiều loại và có hình thái riêng?

Đúng vậy. Theo thuyết trí thông minh đa diện, con người không chỉ có một mà có thể có đến 8 loại hình thông minh, với nhiều sự kết hợp khác nhau, đó là: thông minh logic/toán học, thông minh ngôn ngữ, thông minh không gian/thị giác, thông minh âm nhạc/nhịp điệu/tiết tấu, thông minh vận động cơ thể, thông minh tương tác/xã hội, thông minh nhận thức bản thân, thông minh tự nhiên. Thuyết trí Thông minh đa diện này do giáo sư đại học Harvard Howard Garner trình bày vào năm 1983 và được phát triển và phổ biến rộng rãi bởi tiến sĩ Thomas Armstrong, Giám đốc Viện Nghiên cứu và Phát triển Tiềm năng Con người Hoa Kỳ.Học thyết này đã được công nhận và áp dụng trên 128 nước trên thế giới.

Trí thông minh đa diện cần được phát hiện sớm để có thể hỗ trợ và bồi dưỡng cho trẻ, giúp bé phát triển đúng hướng.

Thưa PGS. TS., vậy làm thế nào để nhận diện loại hình trí thông minh trẻ sở hữu?


Khi sinh ra, trẻ nào cũng sẽ có 8 loại hình thông minh. Có điều, mỗi đứa trẻ sẽ nổi trội ở những loại hình thông minh khác nhau. Cha mẹ có thể bước đầu nhận biết những loại hình trí thông minh trẻ nổi trội thông qua việc quan sát, tương tác cùng con hàng ngày. Chỉ có hiểu rõ thiên hướng của con thì cha mẹ mới có thể đưa ra những phương pháp hỗ trợ con phát triển. Đồng thời, cha mẹ cần trang bị cho mình kiến thức và kỹ năng cơ bản về thuyết Trí thông minh đa diện. Để tìm hiểu kỹ hơn, có thể tham khảo ứng dụng http://bit.ly/be-thuoc-loai-thong-minh-naovà chờ đón bộ sách mới về thuyết Trí thông minh đa diện và cách nuôi dạy con do Viện Nghiên cứu giáo dục phát triển tiềm năng con người-IPD thực hiện.

Có một số ý kiến cho rằng, dù phát hiện sớm con mình có những biểu hiện của một loại hình thông minh nhất định nhưng bé cũng cần phải giỏi toán, văn trong nhà trường sau này. PGS.TS nghĩ sao về điều này?


Việc cha mẹ phát hiện ra con có biểu hiện thông minh nổi trội ở một loại hình thông minh nào đó là rất tốt. Tuy nhiên, tại sao cha mẹ lại nghĩ nếu con phát triển có năng khiếu nghệ thuật thì sẽ không học văn hóa giỏi? Trên thực tế, phát triển loại hình thông minh nổi trội ở trẻ sẽ kéo theo những loại hình thông minh còn hạn chế một cách tự nhiên.Trước tiên, trong giai đoạn vàng, nên cho trẻ tự do phát triển những gì trẻ hứng thú, say mê. Sau đó sẽ dùng những biện pháp thích hợp để tác động giúp bé phát triển những loại hình thông minh còn lại như logic/toán học và ngôn ngữ… Tuy nhiên, Cha mẹ cũng không nên tạo áp lực không cần thiết hay gò ép quá mức đối với trẻ.

Vậy, với một số ông bố bà mẹ lại muốn con mình biết đàn, biết múa, trong khi cháu chỉ thích bơi lội hay chơi cờ thì PGS.TS có lời khuyên nào dành cho họ không?


Cha mẹ có ý thức muốn phát triển đa diện cho trẻ như vậy là rất đáng quý. Trong trường hợp bạn ví dụ, học múa sẽ giúp kích thích phát triển trí thông minh vận động ở trẻ. Điều này cũng hoàn toàn có thể làm được nếu họ cho trẻ bơi lội. Còn việc tập đàn hay chơi cờ, cha mẹ nên chú ý quan sát tính tình cũng như sở thích của cháu. Nếu cho tập đàn thử một vài buổi mà cháu không tỏ ra có hứng thú thì cũng nên xem xét lại xem mình “đầu tư” như vậy đã đúng hướng chưa. 

Có người còn cho rằng, thông minh là tố chất bẩm sinh, di truyền, vậy làm sao có thể tác động để phát triển thưa PGS. TS.?


Thật ra, có 3 yếu tố ảnh hưởng đến sự phát triển trí thông minh của trẻ là di truyền, dinh dưỡng và phương pháp giáo dục. Trong khi di truyền là yếu tố khó can thiệp được thì cha mẹ cần quan tâm áp dụng chế độ dinh dưỡng đúng đắn và phương pháp giáo dục thích hợp ngay từ những năm đầu đời để giúp kích thích sự phát triển trí thông minh của con. Cần nói thêm là trong 6 năm đầu đời, trẻ cần phát triển cả 4 khía cạnh then chốt: trí não, hệ tiêu hóa, tầm vóc, hệ miễn dịch.

Xin cảm ơn PGS. TS. Nguyễn Võ Kỳ Anh.

Tuesday, June 2, 2015

Học người Pháp 7 cách để con không bao giờ kén ăn

Học người Pháp 7 cách để con không bao giờ kén ăn

Người Pháp cho rằng đói là loại gia vị tốt nhất, giúp trẻ sẽ ăn nhiều hơn vào bữa chính thay vì làm đầy bụng bằng các loại đồ ăn vặt.
Vài năm trước, Karen Le Billon (người Canada) chuyển tới Pháp sống, tại một thị trấn nhỏ quê chồng. Điều Karen không hề ngờ tới là cô và hai con gái (vốn rất kén ăn) thay đổi hoàn toàn cách ăn uống sau một thời gian ở Pháp.
Le Billon đã viết một cuốn sách chia sẻ những nguyên tắc cô học được từ người Pháp về cách nuôi dạy con có thói quen ăn uống lành mạnh, vui vẻ. Mời bạn tham khảo một số điều trong cuốn sách này: 
Trẻ ăn những gì người lớn ăn
Khi các con gái nhỏ của Le Billon đi học ở Pháp, thực đơn tại trường khiến lũ trẻ rất ngạc nhiên: Củ cải, thịt bò áp chảo, cá tuyết Alaska, phô mai xanh... Các bé ở Pháp được tiếp xúc với các hương vị mạnh từ sớm. Trẻ ăn ba bữa một ngày, thêm một bữa phụ lúc 16h. Phụ huynh sẽ chọn thực đơn và không có sự thay đổi.
Ăn cùng bữa với gia đình và làm cho trẻ cảm thấy đặc biệt
Le Billon giải thích rằng, trẻ ở Pháp thực sự hưởng ứng "nghi lễ" của bữa ăn hàng ngày. "Người Pháp hiếm khi ăn mà không trải khăn lên bàn. Họ thậm chí gọi việc dọn bàn ăn bằng một cụm từ đặc biệt là 'trang trí bàn ăn'. Điều này có một ảnh hưởng đáng ngạc nhiên với trẻ. Ánh nến, những chiếc đĩa đẹp, khăn ăn lịch sự... ngay lập tức khiến trẻ muốn thể hiện những hành vi tốt nhất khi ăn uống", Le Billon viết. Đó là một hành động nhỏ nhưng thực sự thú vị và hiệu quả.
Untitled-1-Phap-9276-1433294303.jpg
Người Pháp luôn cố gắng tạo cho mỗi bữa ăn đều trở nên đặc biệt và trẻ thường thích thú với điều đó. Ảnh: Infotatabanya.
Thức ăn không phải là phần thưởng, hình phạt hay đồ mua chuộc
Nguyên tắc này có thể áp dụng với rất nhiều bà mẹ. Hẳn nhiều người sẵn sàng cho con một gói bim bim khi bé ngoan ngoãn đi tắm hay nghe lời mẹ chào khách tới chơi. Cũng có bà mẹ dùng thức ăn như một cách để chiều chuộng, dỗ dành con. Có khi nào bạn nói với con "Thôi, về nhà mẹ sẽ cho cái bánh kem" khi thấy bé buồn thiu lúc phải rời khu vui chơi?
Các bà mẹ rất hay dùng thức ăn như một phần thưởng hay đồ dụ dỗ trẻ. Làm như vậy có thể dẫn tới việc sau này trẻ sẽ ăn uống theo cảm xúc. Chúng ta muốn con cái mình biết quý trọng thực phẩm và không muốn các con hễ khi nào buồn chán, mệt mỏi là ăn. Vì vậy, đừng mang thức ăn đến cho trẻ để vỗ về hay xoa dịu cảm xúc nào đó. Có nhiều cách bạn có thể sử dụng để thưởng, phạt con thay vì dùng thức ăn, đúng không?
Ăn rau trước
Trong bữa ăn, người Pháp thường mang rau ra trước, khi trẻ đói nhất. Họ thường trộn rau theo nhiều cách khác nhau mỗi ngày để tạo sự hấp dẫn cho trẻ: salad cà rốt nạo, dưa chuột thái lát trộn dầu giấm, củ cải đường rưới cam, salad rau diếp với phó mát và bánh mì nướng... Bạn hãy thử cách này xem. 
"Con không cần thích món đó nhưng con phải nếm thử"
Bàn ăn không nên là chiến trận. Các bố mẹ Pháp không quan trọng hóa bữa ăn hay bỏ lửng kệ con thích ăn thế nào cũng được. Nếu trẻ không muốn ăn, bố mẹ đơn giản là cất thức ăn đi mà không bàn luận quá nhiều. Một bác sĩ nhi khoa cũng từng chia sẻ: "Hãy kiềm chế, đừng nài nỉ hay yêu cầu con ăn, đừng khen ngợi để chúng ăn. Hãy duy trì cuộc hội thoại tích cực và đừng tập trung vào thức ăn, để trẻ muốn ngồi vào bàn ăn vì chính chúng muốn ăn chứ không phải bởi lý do nào khác". Chắc hẳn, nhiều bà mẹ từng thường xuyên khuyến khích con ăn và khen ngợi khi bé ăn hết phần. Lời khuyên của các bà mẹ Pháp là hãy trò chuyện với con về những thứ khác trong bữa ăn và đừng biến thức ăn trở thành một vấn đề. 
Cũng theo người Pháp, ngay cả khi con bạn không muốn ăn thứ gì đó, chúng ít nhất cũng phải nếm thử. Theo các chuyên gia dinh dưỡng, hầu hết trẻ phải nếm thức ăn mới 7-15 lần trước khi chúng sẵn sàng ăn món đó. Vì vậy, nếu ban đầu trẻ không thích một loại thực phẩm nào đó, điều này không có nghĩa là trẻ sẽ không bao giờ ăn nó. 
tre-an-1377-1433240403.jpg
Bạn hãy bắt đầu bữa ăn của trẻ với các món rau. Ảnh minh họa: Smallstepsonline.
Không ăn vặt
Chẳng có vấn đề gì khi để trẻ đói giữa các bữa ăn. Sợ con đói và cho con ăn vặt là sai lầm nhiều bà mẹ mắc phải. Chắc chắn, không ít bà mẹ khi cho con bú, thường lo lắng không biết con đã đủ no chưa và luôn cố gắng cho con lượng sữa càng nhiều càng tốt để đảm bảo con không đói. Sau này trẻ lớn lên, bạn cũng vẫn mang nỗi lo đó.
Người Pháp cho rằng "đói là loại gia vị tốt nhất" và điều đó thực sự đúng: Mùi vị thức ăn sẽ trở nên ngon hơn khi bạn đói và rõ ràng trẻ sẽ ăn nhiều thực phẩm lành mạnh vào bữa chính hơn khi chúng đói, thay vì làm đầy bụng bằng các loại đồ ăn vặt. Tác giả Le Billon giải thích, sẽ rất tốt cho trẻ khi bé học được cách kiểm soát cảm giác đói, nếu không, khi lớn, trẻ có thể trở thành người luôn cảm thấy cần ăn ngay khi hơi đói thay vì đợi đến bữa tiếp theo.
Ăn chậm rãi
Chính phủ Pháp quy định rằng, trẻ phải dành ít nhất 30 phút tại bữa trưa ở trường - ngay cả khi chúng đã ở tuổi teen. Bữa ăn không phải chỉ để ăn mà còn là sự giao lưu với bạn bè, người thân. Dạy trẻ kiên nhẫn ngồi suốt bữa ăn và tận hưởng cuộc trò chuyện với những người bé yêu mến là một kỹ năng quan trọng trong cuộc sống.
http://doisong.vnexpress.net/tin-tuc/gia-dinh/nuoi-day-con/hoc-nguoi-phap-7-cach-de-con-khong-bao-gio-ken-an-3227967.html

Monday, April 13, 2015

When to Use MongoDB Rather than MySQL (or Other RDBMS): The Billing Example

http://java.dzone.com/articles/when-use-mongodb-rather-mysql

NoSQL is a hot buzz in the air for a pretty long time (well, it's not only a buzz anymore).
However, when should we really use it?
Best Practices for MongoDB
NoSQL products (and among them MongoDB) should be used to meet challenges. If you have one of the following challenges, you should consider MongoDB:
You Expect a High Write Load
MongoDB by default prefers high insert rate over transaction safety. If you need to load tons of data lines with a low business value for each one, MongoDB should fit. Don't do that with $1M transactions recording or at least in these cases do it with an extra safety.
You need High Availability in an Unreliable Environment (Cloud and Real Life)
Setting replicaSet (set of servers that act as Master-Slaves) is easy and fast. Moreover, recovery from a node (or a data center) failure is instant, safe and automatic
You need to Grow Big (and Shard Your Data)
Databases scaling is hard (a single MySQL table performance will degrade when crossing the 5-10GB per table). If you need to partition and shard your database, MongoDB has a built in easy solution for that.
Your Data is Location Based
MongoDB has built in spacial functions, so finding relevant data from specific locations is fast and accurate.
Your Data Set is Going to be Big (starting from 1GB) and Schema is Not Stable
Adding new columns to RDBMS can lock the entire database in some database, or create a major load and performance degradation in other. Usually it happens when table size is larger than 1GB (and can be major pain for a system like BillRun that is described bellow and has several TB in a single table). As MongoDB is schema-less, adding a new field, does not effect old rows (or documents) and will be instant. Other plus is that you do not need a DBA to modify your schema when application changes.

You Don't have a DBA
If you don't have a DBA, and you don't want to normalize your data and do joins, you should consider MongoDB. MongoDB is great for class persistence, as classes can be serialized to JSON and stored AS IS in MongoDB. Note: If you are expecting to go big, please notice that you will need to follow some best practices to avoid pitfalls.
Real World Case Study: Billing
In the last ILMUG, Ofer Cohen presented BillRun, a next generation Open Source billing solution that utilizes MongoDB as its data store. This billing system runs in production in the fastest growing cellular operator in Israel, where it processes over 500M CDRs (call data records) each month. In his presentation Ofer presented how this system utilizes MongoDB advantages:
  1. Schema-less design enables rapid introduction of new CDR types to the system. It let BillRun keep the data store generic.
  2. Scale BillRun production site already manages several TB in a single table, w/o being limited by adding new fields or being limited by growth
  3. Rapid replicaSet enables meeting regulation with easy to setup multi data center DRP and HA solution.
  4. Sharding enables linear and scale out growth w/o running out of budget.
  5. With over 2,000/s CDR inserts, MongoDB architecture is great for a system that must support high insert load. Yet you can guarantee transactions with findAndModify (which is slower) and two-phase commit (application wise).
  6. Developer oriented queries, enable developers write a elegant queries.
  7. Location based is being utilized to analyze users usage and determining where to invest in cellular infrastructure.
Bottom Line
MongoDB is great tool, that should be used in the right scenarios to gain unfair advantage in your market. BillRun is a fine example for that.
Keep Performing,
Moshe Kaplan

Friday, April 3, 2015

Lọc nước nhiễm asen (http://khoahoc.tv/doisong/ung-dung/8974_loc-nuoc-nhiem-asen.aspx)

ới định hướng tìm kiếm loại vật liệu từ khoáng chất tự nhiên để xử lý asen (thạch tín) làm ô nhiễm nước, GS.TS Trần Hồng Côn và cộng sự tại khoa hóa Trường ĐH Khoa học tự nhiên (ĐH Quốc gia Hà Nội) tìm ra nguyên liệu đất sét, đá ong, đá son (limônit) đã được biến tính để chế tạo thành công thiết bị xử lý asen trong nước sinh hoạt.
TS Trần Hồng Côn với thiết bị lọc nước nhiễm asen cỡ nhỏ - (Ảnh: T.Hà)
Bình lọc có cấu tạo như các bình lọc thông thường nhưng bộ cột lọc có tính năng oxy hóa và hấp thụ để giữ lại asen.  Thiết bị lọc này có cấu tạo rất đơn giản, gồm một chiếc thùng có hai ngăn bằng inox. Ngăn thứ nhất (đầu vào) chứa một cột lọc với kích cỡ 75m3 hoặc 300m3 nước. Khi nước chảy qua cột lọc, asen trong nước bị oxy hóa, các hạt đất sét, đá ong và đá son biến tính trong đó sẽ giữ lại asen và mangan. Nước sạch sẽ chảy vào thùng thứ hai, có thể sử dụng.
Với thiết bị nói trên, asen thu hồi triệt để có thể sử dụng vào mục đích khác hoặc đem chôn lấp an toàn. Thiết bị này cũng đã được thử nghiệm để lọc nước giếng khoan tại khu tập thể 51 Cảm Hội, phường Đống Mác, quận Hai Bà Trưng, Hà Nội trong mười ngày liên tục. Kết quả cho thấy trước khi lọc nồng độ asen trong nước tại khu vực trên dao động từ 0,186-0,198mg/l vào mùa khô, sau khi xử lý còn nhỏ hơn 0,01mg/l, dưới giới hạn cho phép của Tổ chức Y tế thế giới (WHO) và tiêu chuẩn VN về asen.
Theo tính toán, thiết bị xử lý asen qui mô hộ gia đình bằng inox có dung tích 20 lít, phục vụ nhu cầu nước ăn uống, giá thành không cao, từ 300.000-400.000 đồng/bình. Trung bình một năm phải thay cột hấp thụ một lần với chi phí khoảng 20.000 đồng.
Có thể liên hệ tiến sĩ Trần Hồng Côn, khoa hóa Trường ĐH Khoa học tự nhiên Hà Nội, 19 Lê Thánh Tông, Hà Nội, ĐT: 04.8245527 - 0989092396.