'ITWeb/서버관리'에 해당되는 글 125건

  1. 2018.06.12 [MySQL] mysql.user 테이블에 계정 추가하기.
  2. 2015.02.06 install locate on centos 6
  3. 2013.11.22 httpd mod_proxy 와 tomcat lb 설정에 따른 load balancer 구현
  4. 2013.11.21 yum package download 하기.
  5. 2013.11.12 기본 iptables 설정.
  6. 2013.07.11 [VirtualBox] VM CentOS 설치 시 Disk 최소사이즈.
  7. 2013.07.11 [VirtualBox] VM CentOS 네트워크 설정 - Mac
  8. 2013.07.10 [VirtualBox] VM 생성 시 이미지 선택.
  9. 2013.04.30 [MySQL] Mac OSX 에서 MySQL 설치하기.
  10. 2013.04.26 [CentOS] iptables service disable command.

[MySQL] mysql.user 테이블에 계정 추가하기.

ITWeb/서버관리 2018. 6. 12. 13:21


[MySQL 5.7 에서 User 등록]

INSERT INTO `user` (`Host`, `User`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `Event_priv`, `Trigger_priv`, `Create_tablespace_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`, `plugin`, `authentication_string`, `password_expired`, `password_last_changed`, `password_lifetime`, `account_locked`)

VALUES

('%','root','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','',0,0,0,0,'mysql_native_password',password('1234'),'N',NOW(),NULL,'N')


- 아래는 아마도 MySQL 5.6 이하 버전에서 동작 했던 것 같습니다.


SQL 문으로 계정 추가하기 위한 쿼리 입니다.

로컬 개발서버 기준으로 작성 된 것이기 때문에 보안에 문제가 될 수도 있으니 주의 하시기 바랍니다.

grant all 입니다.


mysql> INSERT INTO user

VALUES ('localhost', 'cloumon', password('cloumon'), 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', '', '', '', '', 0, 0, 0, 0, '', '', 'N');


mysql> FLUSH PRIVILEGES;


:

install locate on centos 6

ITWeb/서버관리 2015. 2. 6. 13:14

[yum 설치]

$ yum install mlocate


[db update]

$ sudo updatedb


[usage]

$ locate gangliaEnv.sh | xargs ls -al


끝.

:

httpd mod_proxy 와 tomcat lb 설정에 따른 load balancer 구현

ITWeb/서버관리 2013. 11. 22. 15:55

[추가 - httpd + tomcat]
- 그냥 tomcat 을 l4 에 바로 연결 하면 되는데 요구사항에 따라 아래와 같이 할 수도 있습니다.

<VirtualHost www.xxxx.com:80>
    ServerAdmin admin@xxxx.com
    DocumentRoot "/home/shop/app/httpd/htdocs"
    ServerName www.xxxx.com
    ServerAlias www.xxxx.com
    ErrorLog "/home/shop/app/httpd/logs/error.log"
    CustomLog "/home/shop/app/httpd/logs/access.log" common

ProxyRequests On
ProxyPass /admin balancer://shopAdmin
ProxyPass /admin/resources balancer://shopAdminStatic

<Proxy balancer://shopAdmin>
BalancerMember ajp://192.168.1.1:8009/admin loadfactor=1 route=shopAdmin1
BalancerMember ajp://192.168.1.2:8009/admin loadfactor=1 route=shopAdmin2
ProxySet lbmethod=byrequests
</Proxy>

<Proxy balancer://shopAdminStatic>
BalancerMember http://192.168.1.1:8080/admin/resources loadfactor=1 route=shopAdminStatic1
BalancerMember http://192.168.1.1:8080/admin/resources loadfactor=1 route=shopAdminStatic2
ProxySet lbmethod=byrequests
</Proxy>

<Directory "/home/shop/app/httpd/htdocs">
Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from All
</Directory>
</VirtualHost>



[httpd 의 mod_proxy 를 이용한 load balancing 구현]

<VirtualHost dev.session-cluster.com:80>

    ServerAdmin howook.jeong@nhn.com

    DocumentRoot "D:\Application\httpd\htdocs\session_cluster\web"

    ServerName dev.session-cluster.com

    ServerAlias dev.session-cluster.com

    ErrorLog "D:/Application/httpd/logs/dev.session-cluster.com-error.log"

    CustomLog "D:/Application/httpd/logs/dev.session-cluster.com-access.log" common

DirectoryIndex index.html index.jsp

ProxyPass /cluster balancer://mycluster

ProxyPassReverse /cluster ajp://10.67.8.113:8009/

ProxyPassReverse /cluster ajp://10.67.8.113:8109/

<Proxy balancer://mycluster>

BalancerMember ajp://10.67.8.113:8009/ loadfactor=1 route=tomcat1

BalancerMember ajp://10.67.8.113:8109/ loadfactor=1 route=tomcat2

ProxySet lbmethod=byrequests

</Proxy>


<Directory "D:\Application\httpd\htdocs\session_cluster\web">

Options FollowSymLinks

AllowOverride None

Order allow,deny

Allow from All

</Directory>

</VirtualHost>


※ ProxyRequests Off 를 설정 하게 되면 ProxySet lbmethod=byrequests 가 동작 하지 않습니다.
※ 위와 같이 적용했을 경우 mod_jk.so 를 통한 연결은 필요가 없습니다. 이유는 mod_proxy_ajp.so 를 이용해서 연결을 하기 때문 입니다.

[참고자료]
http://httpd.apache.org/docs/2.2/mod/mod_proxy.html 

ParameterDefaultDescription
lbmethod byrequests Balancer load-balance method. Select the load-balancing scheduler method to use. Either byrequests, to perform weighted request counting, bytraffic, to perform weighted traffic byte count balancing, or bybusyness (Apache HTTP Server 2.2.10 and later), to perform pending request balancing. Default is byrequests.
maxattempts One less than the number of workers, or 1 with a single worker. Maximum number of failover attempts before giving up.
nofailover Off If set to On the session will break if the worker is in error state or disabled. Set this value to On if backend servers do not support session replication.
stickysession - Balancer sticky session name. The value is usually set to something like JSESSIONID or PHPSESSIONID, and it depends on the backend application server that support sessions. If the backend application server uses different name for cookies and url encoded id (like servlet containers) use | to to separate them. The first part is for the cookie the second for the path.
scolonpathdelim Off If set to On the semi-colon character ';' will be used as an additional sticky session path deliminator/separator. This is mainly used to emulate mod_jk's behavior when dealing with paths such as JSESSIONID=6736bcf34;foo=aabfa
timeout 0 Balancer timeout in seconds. If set this will be the maximum time to wait for a free worker. Default is not to wait.
failonstatus - A single or comma-separated list of HTTP status codes. If set this will force the worker into error state when the backend returns any status code in the list. Worker recovery behaves the same as other worker errors. Available with Apache HTTP Server 2.2.17 and later.


※ 이전 글 Tomcat Sessoin Clustering 과 연관 해서 load balance 를 적용해 보시는 것도 성능에 도움이 될 수 있습니다.


:

yum package download 하기.

ITWeb/서버관리 2013. 11. 21. 17:00

centos 에서 yum package 다운로드 하는 방법 입니다.

검색해 보시면 많이 나와 있습니다.

간혹 네트워크 이슈로 yum 패키지 다운로드가 안되서 설치가 어려울 경우 별도로 다운로드 받아서 해당 서버로 밀어 넣은 다음 rpm 설치 하시면 되겠습니다.


1. sudo yum -y install yum-downloadonly or yum-plugin-downloadonly

2. sudo yum reinstall gcc -y --downloadonly --downloaddir=/home/henry/temp


이렇게 하시면 /home/henry/temp 아래로 make-3.81-20.el6.x86_64.rpm 파일이 다운로드 되어 있는걸 보실 수 있습니다.

rpm 설치 방법도 검색해 보시면 많이 나와 있습니다.


1. rpm -ivh make-3.81-20.el6.x86_64.rpm

이 방법은 패키지를 처음 설치 할때 사용하시면 됩니다.

2. rpm -Uvh make-3.81-20.el6.x86_64.rpm

이 방법은 패키지가 기본 설치 및 업그레이드 방식으로 설치 하는 것입니다.

설치 시 강제 또는 종속성을 무시하고 설치 하고 싶으실 경우는 아래 옵션을 추가해서 설치 하시면 됩니다.

--force --nodeps


근데 갑자기 삭제가 하고 싶으세요.

1. rpm -e make

이렇게 하시면 되구요.


패키지 설치 여부를 확인하고 싶으시다면,

1. rpm -q make


더 궁금한건 help 를 보세요.

사용법: rpm [옵션...]

  --quiet


Query/Verify package selection options:

  -a, --all                     모든 패키지에 대해 질의/검증합니다

  -f, --file                    파일이 들어있는 패키지에 대해 질의/검증 합니다

  -g, --group                   그룹 안의 패키지를 질의/검증 합니다

  -p, --package                 query/verify a package file

  -W, --ftswalk                 query/verify package(s) from TOP file tree walk

  --pkgid                       패키지 식별자(identifier)를 사용하여 패키지를 질의/검증 합니다

  --hdrid                       헤더 식별자(identifier)를 사용하여 패키지를 질의/검증 합니다

  --fileid                      파일 식별자(identifier)를 사용하여 패키지를 질의/검증 합니다

  --specfile                    spec 파일에 대해 질의합니다

  --triggeredby                 패키지로 인해 생성되는(triggered) 패키지에 대해 질의합니다

  --whatrequires                의존성을 필요로 하는 패키지에 대해 질의/검증 합니다

  --whatprovides                의존성을 제공하는 패키지에 대해 질의/검증 합니다

  --nomanifest                  do not process non-package files as manifests


질의 옵션 (-q 또는 --query 옵션과 함께 사용):

  -c, --configfiles             모든 설정 파일을 나열합니다

  -d, --docfiles                모든 문서 파일을 나열합니다

  --dump                        기본 파일 정보를 보여줍니다

  -l, --list                    패키지 안의 파일을 나열합니다

  --queryformat=QUERYFORMAT     다음의 질의 형식을 사용하십시요

  -s, --state                   나열된 파일의 상태(state)를 보여줍니다


검증 옵션 (-V 또는 --verify 옵션과 함께 사용):

  --nofiledigest                don't verify digest of files

  --nomd5                       don't verify digest of files

  --nofiles                     패키지 안의 파일을 검사하지 않습니다

  --nodeps                      패키지의 의존성을 검사하지 않습니다

  --noscript                    don't execute verify script(s)


File tree walk options (with --ftswalk):

  --comfollow                   follow command line symlinks

  --logical                     logical walk

  --nochdir                     don't change directories

  --nostat                      don't get stat info

  --physical                    physical walk

  --seedot                      return dot and dot-dot

  --xdev                        don't cross devices

  --whiteout                    return whiteout information


서명 옵션:

  --addsign                     sign package(s) (identical to --resign)

  -K, --checksig                verify package signature(s)

  --delsign                     delete package signatures

  --import                      import an armored public key

  --resign                      sign package(s) (identical to --addsign)

  --nodigest                    don't verify package digest(s)

  --nosignature                 don't verify package signature(s)


데이터베이스 옵션:

  --initdb                      데이터베이스를 초기화 합니다

  --rebuilddb                   설치된 패키지 헤더에서 상반된 목록(inverted lists)의 데이터베이스를

                                재구축 합니다


설치/업그레이드/삭제 옵션:

  --aid                         add suggested packages to transaction

  --allfiles                    특정 파일을 생략하기 위한 설정이 적용된 경우에도, 패키지 안의 모든

                                파일을 설치합니다

  --allmatches                  <패키지> 이름과 일치하는 패키지는 모두 제거합니다 (<패키지>에

                                여러개의 패키지를 동시에 지정할 경우에는 오류가 발생합니다)

  --badreloc                    relocate files in non-relocatable package

  -e, --erase=<패키지>+            패키지를 (제거) 삭제합니다

  --excludedocs                 패키지에 포함된 문서 파일을 설치하지 않습니다

  --excludepath=<경로>            <경로>로 시작되는 파일은 설치하지 않습니다

  --fileconflicts               detect file conflicts between packages

  --force                       --replacepkgs 와 --replacefiles 옵션을 동시에 사용합니다

  -F, --freshen=<패키지파일>+        기존에 설치된 패키지를 업그레이드 합니다

  -h, --hash                    패키지 설치를 해시마크(#)로 표시합니다 (-v 옵션과 함께 사용하는 것이

                                좋습니다)

  --ignorearch                  패키지의 아키텍쳐를 검사하지 않습니다

  --ignoreos                    패키지의 운영체제를 검사하지 않습니다

  --ignoresize                  패키지를 설치하기 전에 디스크 공간을 검사하지 않습니다

  -i, --install                 install package(s)

  --justdb                      파일시스템을 변경하지 않고, 데이터베이스를 갱신합니다

  --nodeps                      패키지의 의존성을 검사하지 않습니다

  --nofiledigest                don't verify digest of files

  --nomd5                       don't verify digest of files (obsolete)

  --nocontexts                  don't install file security contexts

  --noorder                     의존성이 있는 패키지를 설치하도록 재요구하지 않습니다

  --nosuggest                   do not suggest missing dependency resolution(s)

  --noscripts                   패키지 스크립틀릿(scriptlet)을 실행하지 않습니다

  --notriggers                  이 패키지에 의해 생성되는(triggered) 어떠한 스크립틀릿(scriptlet)도

                                실행하지 않습니다

  --oldpackage                  이전 버전의 패키지로 다운그레이드 합니다 (--force 옵션을 사용시에는 이

                                옵션이 자동으로 적용됩니다)

  --percent                     패키지 설치를 퍼센트(%)로 표시합니다

  --prefix=<디렉토리>               재배치 기능이 있는 패키지의 경우, 지정한 <디렉토리>로 재배치하여

                                설치합니다

  --relocate=<이전경로>=<새로운경로>     <이전경로>에서 <새로운경로>로 파일을 재배치 합니다

  --replacefiles                ignore file conflicts between packages

  --replacepkgs                 패키지가 이미 설치되어 있는 경우에도 설치합니다

  --test                        패키지를 설치하지 않고, 제대로 설치되는지만 확인합니다

  -U, --upgrade=<패키지파일>+        패키지를 업그레이드 합니다


Common options for all rpm modes and executables:

  -D, --define='MACRO EXPR'     define MACRO with value EXPR

  -E, --eval='EXPR'             print macro expansion of EXPR

  --macros=<FILE:...>           read <FILE:...> instead of default file(s)

  --nodigest                    don't verify package digest(s)

  --nosignature                 don't verify package signature(s)

  --rcfile=<FILE:...>           read <FILE:...> instead of default file(s)

  -r, --root=ROOT               use ROOT as top level directory (default: "/")

  --querytags                   질의 태그를 보여줍니다

  --showrc                      현재 설정되어 있는 rpmrc의 내용과 매크로를 보여줍니다

  --quiet                       자세한 출력을 제공합니다

  -v, --verbose                 아주 상세한 출력을 제공합니다

  --version                     현재 사용되고 있는 rpm 버전을 표시합니다


Options implemented via popt alias/exec:

  --scripts                     list install/erase scriptlets from package(s)

  --setperms                    set permissions of files in a package

  --setugids                    set user/group ownership of files in a package

  --conflicts                   list capabilities this package conflicts with

  --obsoletes                   list other packages removed by installing this package

  --provides                    list capabilities that this package provides

  --requires                    list capabilities required by package(s)

  --info                        list descriptive information from package(s)

  --changelog                   list change logs for this package

  --xml                         list metadata in xml

  --triggers                    list trigger scriptlets from package(s)

  --last                        list package(s) by install time, most recent first

  --dupes                       list duplicated packages

  --filesbypkg                  list all files from each package

  --fileclass                   list file names with classes

  --filecolor                   list file names with colors

  --fscontext                   list file names with security context from file system

  --fileprovide                 list file names with provides

  --filerequire                 list file names with requires

  --filecaps                    list file names with POSIX1.e capabilities


Help options:

  -?, --help                    Show this help message

  --usage                       Display brief usage message



:

기본 iptables 설정.

ITWeb/서버관리 2013. 11. 12. 11:21

# 기본 방화벽 정책

iptables -F

iptables -P INPUT ACCEPT

iptables -P FORWARD ACCEPT

iptables -P OUTPUT ACCEPT

iptables -A INPUT -j ACCEPT -i lo

iptables -A INPUT -j ACCEPT -m state --state ESTABLISHED,RELATED

iptables -A INPUT -j ACCEPT -m state --state NEW -p tcp --dport 22


# 서버간 방화벽 정책

iptables -A INPUT -p tcp -s  192.168.0.0/16 --dport 1:65535 -j ACCEPT

iptables -A INPUT -p tcp ! -s 192.168.0.0/16 --dport 1:65535 -j DROP


service iptables save

service iptables start

- CIDR 참고 : http://jjeong.tistory.com/396


제일 쉬운 설정이 아닌가 싶구요.

보안에 취약 할 수도 있지만 기본적으로 사설 IP 및 네트워크 구간에서 뚤린거면.. 그냥 포기 하는게.. 빠르지 않나 싶기도.. ㅎㅎ


보통 포털에서는 인프라 및 보안 전문가들이 이런거 관리를 해주기 때문에 일반 개발자들은 크게 신경쓰지 않고 개발을 많이 하는데 뭐 기본은 알고 있으면 좋을것 같내요.


- 참고 URL

http://wiki.centos.org/HowTos/Network/IPTables


IPTables

1. Introduction

CentOS has an extremely powerful firewall built in, commonly referred to as iptables, but more accurately is iptables/netfilter. Iptables is the userspace module, the bit that you, the user, interact with at the command line to enter firewall rules into predefined tables. Netfilter is a kernel module, built into the kernel, that actually does the filtering. There are many GUI front ends for iptables that allow users to add or define rules based on a point and click user interface, but these often lack the flexibility of using the command line interface and limit the users understanding of what's really happening. We're going to learn the command line interface of iptables.

Before we can really get to grips with iptables, we need to have at least a basic understanding of the way it works. Iptables uses the concept of IP addresses, protocols (tcp, udp, icmp) and ports. We don't need to be experts in these to get started (as we can look up any of the information we need), but it helps to have a general understanding.

Iptables places rules into predefined chains (INPUT, OUTPUT and FORWARD) that are checked against any network traffic (IP packets) relevant to those chains and a decision is made about what to do with each packet based upon the outcome of those rules, i.e. accepting or dropping the packet. These actions are referred to as targets, of which the two most common predefined targets are DROP to drop a packet or ACCEPT to accept a packet.

Chains

These are 3 predefined chains in the filter table to which we can add rules for processing IP packets passing through those chains. These chains are:

  • INPUT - All packets destined for the host computer.
  • OUTPUT - All packets originating from the host computer.
  • FORWARD - All packets neither destined for nor originating from the host computer, but passing through (routed by) the host computer. This chain is used if you are using your computer as a router.

For the most part, we are going to be dealing with the INPUT chain to filter packets entering our machine - that is, keeping the bad guys out.

Rules are added in a list to each chain. A packet is checked against each rule in turn, starting at the top, and if it matches that rule, then an action is taken such as accepting (ACCEPT) or dropping (DROP) the packet. Once a rule has been matched and an action taken, then the packet is processed according to the outcome of that rule and isn't processed by further rules in the chain. If a packet passes down through all the rules in the chain and reaches the bottom without being matched against any rule, then the default action for that chain is taken. This is referred to as the default policy and may be set to either ACCEPT or DROP the packet.

The concept of default policies within chains raises two fundamental possibilities that we must first consider before we decide how we are going to organize our firewall.

1. We can set a default policy to DROP all packets and then add rules to specifically allow (ACCEPT) packets that may be from trusted IP addresses, or for certain ports on which we have services running such as bittorrent, FTP server, Web Server, Samba file server etc.

or alternatively,

2. We can set a default policy to ACCEPT all packets and then add rules to specifically block (DROP) packets that may be from specific nuisance IP addresses or ranges, or for certain ports on which we have private services or no services running.

Generally, option 1 above is used for the INPUT chain where we want to control what is allowed to access our machine and option 2 would be used for the OUTPUT chain where we generally trust the traffic that is leaving (originating from) our machine.

2. Getting Started

Working with iptables from the command line requires root privileges, so you will need to become root for most things we will be doing.

IMPORTANT: We will be turning off iptables and resetting your firewall rules, so if you are reliant on your Linux firewall as your primary line of defense you should be aware of this.

Iptables should be installed by default on all CentOS 5.x and 6.x installations. You can check to see if iptables is installed on your system by:

$ rpm -q iptables
iptables-1.4.7-5.1.el6_2.x86_64

And to see if iptables is actually running, we can check that the iptables modules are loaded and use the -L switch to inspect the currently loaded rules:

# lsmod | grep ip_tables
ip_tables              29288  1 iptable_filter
x_tables               29192  6 ip6t_REJECT,ip6_tables,ipt_REJECT,xt_state,xt_tcpudp,ip_tables

# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED 
ACCEPT     icmp --  anywhere             anywhere            
ACCEPT     all  --  anywhere             anywhere            
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh 
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited 

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited 

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Above we see the default set of rules on a CentOS 6 system. Note that SSH service is permitted by default.

If iptables is not running, you can enable it by running:

# system-config-securitylevel

3. Writing a Simple Rule Set

IMPORTANT: At this point we are going to clear the default rule set. If you are connecting remotely to a server via SSH for this tutorial then there is a very real possibility that you could lock yourself out of your machine. You must set the default input policy to accept before flushing the current rules, and then add a rule at the start to explicitly allow yourself access to prevent against locking yourself out.

We will use an example based approach to examine the various iptables commands. In this first example, we will create a very simple set of rules to set up a Stateful Packet Inspection (SPI) firewall that will allow all outgoing connections but block all unwanted incoming connections:

# iptables -P INPUT ACCEPT
# iptables -F
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
# iptables -L -v

which should give the following output:

Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere
    0     0 ACCEPT     all  --  any    any     anywhere             anywhere            state RELATED,ESTABLISHED
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:ssh
Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Now lets look at each of the 8 commands above in turn and understand exactly what we've just done:

  1. iptables -P INPUT ACCEPT If connecting remotely we must first temporarily set the default policy on the INPUT chain to ACCEPT otherwise once we flush the current rules we will be locked out of our server.

  2. iptables -F We used the -F switch to flush all existing rules so we start with a clean state from which to add new rules.

  3. iptables -A INPUT -i lo -j ACCEPT Now it's time to start adding some rules. We use the -A switch to append (or add) a rule to a specific chain, the INPUT chain in this instance. Then we use the -i switch (for interface) to specify packets matching or destined for the lo (localhost, 127.0.0.1) interface and finally -j (jump) to the target action for packets matching the rule - in this case ACCEPT. So this rule will allow all incoming packets destined for the localhost interface to be accepted. This is generally required as many software applications expect to be able to communicate with the localhost adaptor.

  4. iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT This is the rule that does most of the work, and again we are adding (-A) it to the INPUT chain. Here we're using the -m switch to load a module (state). The state module is able to examine the state of a packet and determine if it is NEW, ESTABLISHED or RELATED. NEW refers to incoming packets that are new incoming connections that weren't initiated by the host system. ESTABLISHED and RELATED refers to incoming packets that are part of an already established connection or related to and already established connection.

  5. iptables -A INPUT -p tcp --dport 22 -j ACCEPT Here we add a rule allowing SSH connections over tcp port 22. This is to prevent accidental lockouts when working on remote systems over an SSH connection. We will explain this rule in more detail later.

  6. iptables -P INPUT DROP The -P switch sets the default policy on the specified chain. So now we can set the default policy on the INPUT chain to DROP. This means that if an incoming packet does not match one of the following rules it will be dropped. If we were connecting remotely via SSH and had not added the rule above, we would have just locked ourself out of the system at this point.

  7. iptables -P FORWARD DROP Similarly, here we've set the default policy on the FORWARD chain to DROP as we're not using our computer as a router so there should not be any packets passing through our computer.

  8. iptables -P OUTPUT ACCEPT and finally, we've set the default policy on the OUTPUT chain to ACCEPT as we want to allow all outgoing traffic (as we trust our users).

  9. iptables -L -v Finally, we can list (-L) the rules we've just added to check they've been loaded correctly.

Finally, the last thing we need to do is save our rules so that next time we reboot our computer our rules are automatically reloaded:

# /sbin/service iptables save

This executes the iptables init script, which runs /sbin/iptables-save and writes the current iptables configuration to /etc/sysconfig/iptables. Upon reboot, the iptables init script reapplies the rules saved in /etc/sysconfig/iptables by using the /sbin/iptables-restore command.

Obviously typing all these commands at the shell can become tedious, so by far the easiest way to work with iptables is to create a simple script to do it all for you. The above commands may be entered into your favourite text editor and saved as myfirewall, for example:

#!/bin/bash
#
# iptables example configuration script
#
# Flush all current rules from iptables
#
 iptables -F
#
# Allow SSH connections on tcp port 22
# This is essential when working on remote servers via SSH to prevent locking yourself out of the system
#
 iptables -A INPUT -p tcp --dport 22 -j ACCEPT
#
# Set default policies for INPUT, FORWARD and OUTPUT chains
#
 iptables -P INPUT DROP
 iptables -P FORWARD DROP
 iptables -P OUTPUT ACCEPT
#
# Set access for localhost
#
 iptables -A INPUT -i lo -j ACCEPT
#
# Accept packets belonging to established and related connections
#
 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#
# Save settings
#
 /sbin/service iptables save
#
# List rules
#
 iptables -L -v

Note: We can also comment our script to remind us what were doing.

now make the script executable:

# chmod +x myfirewall

We can now simply edit our script and run it from the shell with the following command:

# ./myfirewall

4. Interfaces

In our previous example, we saw how we could accept all packets incoming on a particular interface, in this case the localhost interface:

iptables -A INPUT -i lo -j ACCEPT

Suppose we have 2 separate interfaces, eth0 which is our internal LAN connection and ppp0 dialup modem (or maybe eth1 for a nic) which is our external internet connection. We may want to allow all incoming packets on our internal LAN but still filter incoming packets on our external internet connection. We could do this as follows:

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -i eth0 -j ACCEPT

But be very careful - if we were to allow all packets for our external internet interface (for example, ppp0 dialup modem):

iptables -A INPUT -i ppp0 -j ACCEPT

we would have effectively just disabled our firewall!

5. IP Addresses

Opening up a whole interface to incoming packets may not be restrictive enough and you may want more control as to what to allow and what to reject. Lets suppose we have a small network of computers that use the 192.168.0.x private subnet. We can open up our firewall to incoming packets from a single trusted IP address (for example, 192.168.0.4):

# Accept packets from trusted IP addresses
 iptables -A INPUT -s 192.168.0.4 -j ACCEPT # change the IP address as appropriate

Breaking this command down, we first append (-A) a rule to the INPUT chain for the source (-s) IP address 192.168.0.4 to ACCEPT all packets (also note how we can use the # symbol to add comments inline to document our script with anything after the # being ignored and treated as a comment).

Obviously if we want to allow incoming packets from a range of IP addresses, we could simply add a rule for each trusted IP address and that would work fine. But if we have a lot of them, it may be easier to add a range of IP addresses in one go. To do this, we can use a netmask or standard slash notation to specify a range of IP address. For example, if we wanted to open our firewall to all incoming packets from the complete 192.168.0.x (where x=1 to 254) range, we could use either of the following methods:

# Accept packets from trusted IP addresses
 iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT  # using standard slash notation
 iptables -A INPUT -s 192.168.0.0/255.255.255.0 -j ACCEPT # using a subnet mask

Finally, as well as filtering against a single IP address, we can also match against the MAC address for the given device. To do this, we need to load a module (the mac module) that allows filtering against mac addresses. Earlier we saw another example of using modules to extend the functionality of iptables when we used the state module to match for ESTABLISHED and RELATED packets. Here we use the mac module to check the mac address of the source of the packet in addition to it's IP address:

# Accept packets from trusted IP addresses
 iptables -A INPUT -s 192.168.0.4 -m mac --mac-source 00:50:8D:FD:E6:32 -j ACCEPT

First we use -m mac to load the mac module and then we use --mac-source to specify the mac address of the source IP address (192.168.0.4). You will need to find out the mac address of each ethernet device you wish to filter against. Runningifconfig (or iwconfig for wireless devices) as root will provide you with the mac address.

This may be useful for preventing spoofing of the source IP address as it will allow any packets that genuinely originate from 192.168.0.4 (having the mac address 00:50:8D:FD:E6:32) but will block any packets that are spoofed to have come from that address. Note, mac address filtering won't work across the internet but it certainly works fine on a LAN.

6. Ports and Protocols

Above we have seen how we can add rules to our firewall to filter against packets matching a particular interface or a source IP address. This allows full access through our firewall to certain trusted sources (host PCs). Now we'll look at how we can filter against protocols and ports to further refine what incoming packets we allow and what we block.

Before we can begin, we need to know what protocol and port number a given service uses. For a simple example, lets look at bittorrent. Bittorrent uses the tcp protocol on port 6881, so we would need to allow all tcp packets on destination port (the port on which they arrive at our machine) 6881:

# Accept tcp packets on destination port 6881 (bittorrent)
 iptables -A INPUT -p tcp --dport 6881 -j ACCEPT

Here we append (-A) a rule to the INPUT chain for packets matching the tcp protocol (-p tcp) and entering our machine on destination port 6881 (--dport 6881).

Note: In order to use matches such as destination or source ports (--dport or --sport), you must first specify the protocol (tcp, udp, icmp, all).

We can also extend the above to include a port range, for example, allowing all tcp packets on the range 6881 to 6890:

# Accept tcp packets on destination ports 6881-6890
 iptables -A INPUT -p tcp --dport 6881:6890 -j ACCEPT

7. Putting It All Together

Now we've seen the basics, we can start combining these rules.

A popular UNIX/Linux service is the secure shell (SSH) service allowing remote logins. By default SSH uses port 22 and again uses the tcp protocol. So if we want to allow remote logins, we would need to allow tcp connections on port 22:

# Accept tcp packets on destination port 22 (SSH)
 iptables -A INPUT -p tcp --dport 22 -j ACCEPT

This will open up port 22 (SSH) to all incoming tcp connections which poses a potential security threat as hackers could try brute force cracking on accounts with weak passwords. However, if we know the IP addresses of trusted remote machines that will be used to log on using SSH, we can limit access to only these source IP addresses. For example, if we just wanted to open up SSH access on our private lan (192.168.0.x), we can limit access to just this source IP address range:

# Accept tcp packets on destination port 22 (SSH) from private LAN
 iptables -A INPUT -p tcp -s 192.168.0.0/24 --dport 22 -j ACCEPT

Using source IP filtering allows us to securely open up SSH access on port 22 to only trusted IP addresses. For example, we could use this method to allow remote logins between work and home machines. To all other IP addresses, the port (and service) would appear closed as if the service were disabled so hackers using port scanning methods are likely to pass us by.

8. Summary

We've barely scratched the surface of what can be achieved with iptables, but hopefully this HOWTO has provided a good grounding in the basics from which one may build more complicated rule sets.

9. Links

http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-fw.html

http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-iptables.html

:

[VirtualBox] VM CentOS 설치 시 Disk 최소사이즈.

ITWeb/서버관리 2013. 7. 11. 13:58

- 2GB : fail

- 3GB 이상 : success

- centos 설치 시 기본 1.5GB 를 사용 함.

:

[VirtualBox] VM CentOS 네트워크 설정 - Mac

ITWeb/서버관리 2013. 7. 11. 10:42

1. VirtualBox 환경설정

- 네트워크

- 어댑터

IPv4 : 192.168.56.1

IPv4 서브넷 마스크 : 255.255.255.0

- DHCP 서버

서버 사용함 Checked

서버주소 : 192.168.56.100

서버마스크 : 255.255.255.0

최저주소한계 :192.168.56.101

최고주소한계 :162.168.56.254


2. VM 환경설정

- 네트워크

- 어댑터 1

연결됨 : NAT

- 어댑터 2

연결됨 : 브리지 어댑터

이름 : en0: Wi-Fi (AirPort)

- 어댑터 3

연결됨 : 호스트 전용 어댑터

이름 : vboxnet0


3. VM 실행 후 Console

root$ cd /etc/sysconfig/network-scripts

root$ vi ifcfg-eth0

# 아래 코드 수정

ONBOOT=no 를 ONBOOT=yes


재시작

root$ cd /etc/sysconfig/network-scripts

root$ vi ifcfg-eth2

DEVICE=eth2

BOOTPROTO=none

ONBOOT=yes

HWADDR=08:00:27:D1:10:93 # 네트워크 설정에서 어댑터 3 에 나와 있는 Mac주소 등록

TYPE=Ethernet

USERCTL=no

IPV6INIT=yes

PEERDNS=yes

NETMASK=255.255.255.0

IPADDR=192.168.56.102

root$ ifup eth2

root$ ifconfig


:

[VirtualBox] VM 생성 시 이미지 선택.

ITWeb/서버관리 2013. 7. 10. 10:09

VirtualBox 를 이용해서 CentOS 구성 시 이미지 파일을 마운트 시킬때 주의 해야 하는 사항이 있내요.

꼭 세컨더리 마스터와 세컨더리 슬레이브로 마운트해서 시작 하시기 바랍니다.

프라이머리로 선택해서 실행을 하시면 맥북 확 다운되어 버립니다.


:

[MySQL] Mac OSX 에서 MySQL 설치하기.

ITWeb/서버관리 2013. 4. 30. 11:01

맥에서 mysql 설치는 쉽게 되어 있더군요.

저는 아래 처럼 설치 했습니다.


- 다운로드(MAC) : http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.11-osx10.7-x86_64.tar.gz/from/http://cdn.mysql.com/

- 설치 위치 : ~/server/app/mysql

- cd ~/server/app/

- tar -xvzf mysql-5.6.11-osx10.7-x86_64.tar.gz

- ln -s mysql-5.6.11-osx10.7-x86_64 mysql

- cd mysql

- vi INSTALL-BINARY 참고

- scripts/mysql_install_db --user=실행계정명

- sudo cp support-files/my-default.cnf /etc/my.cnf

- bin/mysqld_safe --user=실행계정명 &


:

[CentOS] iptables service disable command.

ITWeb/서버관리 2013. 4. 26. 10:29

[VM 재부팅 시 또는 서비스 시작 시 방화벽 disable 하기]

- root 권한으로 실행


[IPV4]

# service iptables save

# service iptables stop

# chkconfig iptables off


[IPV6]

# service ip6tables save

# service ip6tables stop

# chkconfig ip6tables off



[iptables enable 하기]

- root 권한으로 실행


[IPV4]

# service iptables start

# chkconfig iptables on


[IPV6]

# service ip6tables start

# chkconfig ip6tables on



[iptables 상태보기]

- root 권한으로 실행


# service iptables status

# service ip6tables status


: