본문 바로가기
Linux/for Hosting

[VSFTPD] FTP 설치, 기본 설정, 포트변경, FTPS설정

by aegypius 2020. 6. 8.
728x90
반응형

1. 설치와 구동

  설치는 아래와 같이 간단하다. yum install vsftpd

[root@localhost /]# yum install vsftpd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
 * epel: ftp.iij.ad.jp
 * extras: mirror.kakao.com
 * remi-php72: ftp.riken.jp
 * remi-safe: ftp.riken.jp
 * updates: mirror.kakao.com
Resolving Dependencies
--> Running transaction check
---> Package vsftpd.x86_64 0:3.0.2-27.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=====================================================================================================================================
 Package                       Arch                          Version                               Repository                   Size
=====================================================================================================================================
Installing:
 vsftpd                        x86_64                        3.0.2-27.el7                          base                        172 k

Transaction Summary
=====================================================================================================================================
Install  1 Package

Total download size: 172 k
Installed size: 353 k
Is this ok [y/d/N]: y
Downloading packages:
vsftpd-3.0.2-27.el7.x86_64.rpm                                                                                | 172 kB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : vsftpd-3.0.2-27.el7.x86_64                                                                                        1/1
  Verifying  : vsftpd-3.0.2-27.el7.x86_64                                                                                        1/1

Installed:
  vsftpd.x86_64 0:3.0.2-27.el7

Complete!
[root@localhost /]#

  설치가 끝났다면 바로 구동시켜보자. 

# systemctl start vsftpd

2. 방화벽 설정

  방화벽에서 ftp 포트를 허용하자.

#firewall-cmd --permanent --zone=public --add-service=ftp
#firewall-cmd --permanent --zone=public --add-port=21/tcp

  둘 중에 편한 것을 선택하자. (CentOS 7 미만은 iptables ) add-service를 사용하자.

  서버에 있는 일반계정으로 접속을 시도했을 때 기본 홈디렉토리로 접속 되겠지만, 서버의 모든 디렉토리로의 이동이 가능할 것이다. vsftpd.conf를 편집해서 이 문제를 해결하자. (방화벽 설정 후에도 접속이 안된다면 SELINUX를 끄자.  anonymous 로그인도 테스트 해보자.)

3. 기본설정

      1 # Example config file /etc/vsftpd/vsftpd.conf
      2 #
      3 # The default compiled in settings are fairly paranoid. This sample file
      4 # loosens things up a bit, to make the ftp daemon more usable.
      5 # Please see vsftpd.conf.5 for all compiled in defaults.
      6 #
      7 # READ THIS: This example file is NOT an exhaustive list of vsftpd options.
      8 # Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
      9 # capabilities.
     10 #
     11 # Allow anonymous FTP? (Beware - allowed by default if you comment this out).
     12 anonymous_enable=YES
     13 #
     14 # Uncomment this to allow local users to log in.
     15 # When SELinux is enforcing check for SE bool ftp_home_dir
     16 local_enable=YES
     17 #
     18 # Uncomment this to enable any form of FTP write command.
     19 write_enable=YES
     20 #
     21 # Default umask for local users is 077. You may wish to change this to 022,
     22 # if your users expect that (022 is used by most other ftpd's)
     23 local_umask=022
     24 #
     25 # Uncomment this to allow the anonymous FTP user to upload files. This only
     26 # has an effect if the above global write enable is activated. Also, you will
     27 # obviously need to create a directory writable by the FTP user.
     28 # When SELinux is enforcing check for SE bool allow_ftpd_anon_write, allow_ftpd_full_access
     29 #anon_upload_enable=YES
     30 #
     31 # Uncomment this if you want the anonymous FTP user to be able to create
     32 # new directories.
     33 #anon_mkdir_write_enable=YES
     34 #
     35 # Activate directory messages - messages given to remote users when they
     36 # go into a certain directory.
     37 dirmessage_enable=YES
     38 #
     39 # Activate logging of uploads/downloads.
     40 xferlog_enable=YES
     41 #
     42 # Make sure PORT transfer connections originate from port 20 (ftp-data).
     43 connect_from_port_20=YES
     44 #
     45 # If you want, you can arrange for uploaded anonymous files to be owned by
     46 # a different user. Note! Using "root" for uploaded files is not
     47 # recommended!
     48 #chown_uploads=YES
     49 #chown_username=whoever
     50 #
     51 # You may override where the log file goes if you like. The default is shown
     52 # below.
     53 #xferlog_file=/var/log/xferlog
     54 #
     55 # If you want, you can have your log file in standard ftpd xferlog format.
     56 # Note that the default log file location is /var/log/xferlog in this case.
     57 xferlog_std_format=YES
     58 #
     59 # You may change the default value for timing out an idle session.
     60 #idle_session_timeout=600
     61 #
     62 # You may change the default value for timing out a data connection.
     63 #data_connection_timeout=120
     64 #
     65 # It is recommended that you define on your system a unique user which the
     66 # ftp server can use as a totally isolated and unprivileged user.
     67 #nopriv_user=ftpsecure
     68 #
     69 # Enable this and the server will recognise asynchronous ABOR requests. Not
     70 # recommended for security (the code is non-trivial). Not enabling it,
     71 # however, may confuse older FTP clients.
     72 #async_abor_enable=YES
     73 #
     74 # By default the server will pretend to allow ASCII mode but in fact ignore
     75 # the request. Turn on the below options to have the server actually do ASCII
     76 # mangling on files when in ASCII mode. The vsftpd.conf(5) man page explains
     77 # the behaviour when these options are disabled.
     78 # Beware that on some FTP servers, ASCII support allows a denial of service
     79 # attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
     80 # predicted this attack and has always been safe, reporting the size of the
     81 # raw file.
     82 # ASCII mangling is a horrible feature of the protocol.
     83 #ascii_upload_enable=YES
     84 #ascii_download_enable=YES
     85 #
     86 # You may fully customise the login banner string:
     87 #ftpd_banner=Welcome to blah FTP service.
     88 #
     89 # You may specify a file of disallowed anonymous e-mail addresses. Apparently
     90 # useful for combatting certain DoS attacks.
     91 #deny_email_enable=YES
     92 # (default follows)
     93 #banned_email_file=/etc/vsftpd/banned_emails
     94 #
     95 # You may specify an explicit list of local users to chroot() to their home
     96 # directory. If chroot_local_user is YES, then this list becomes a list of
     97 # users to NOT chroot().
     98 # (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
     99 # the user does not have write access to the top level directory within the
    100 # chroot)
    101 #chroot_local_user=YES
    102 #chroot_list_enable=YES
    103 # (default follows)
    104 #chroot_list_file=/etc/vsftpd/chroot_list
    105 #
    106 # You may activate the "-R" option to the builtin ls. This is disabled by
    107 # default to avoid remote users being able to cause excessive I/O on large
    108 # sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
    109 # the presence of the "-R" option, so there is a strong case for enabling it.
    110 #ls_recurse_enable=YES
    111 #
    112 # When "listen" directive is enabled, vsftpd runs in standalone mode and
    113 # listens on IPv4 sockets. This directive cannot be used in conjunction
    114 # with the listen_ipv6 directive.
    115 listen=NO
    116 #
    117 # This directive enables listening on IPv6 sockets. By default, listening
    118 # on the IPv6 "any" address (::) will accept connections from both IPv6
    119 # and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
    120 # sockets. If you want that (perhaps because you want to listen on specific
    121 # addresses) then you must run two copies of vsftpd with two configuration
    122 # files.
    123 # Make sure, that one of the listen options is commented !!
    124 listen_ipv6=YES
    125
    126 pam_service_name=vsftpd
    127 userlist_enable=YES
    128 tcp_wrappers=YES

- anonymous 로그인의 거부
     : line 12의 anonymous_enable=YESNO로 설정.
  vsftpd의 기본값이 익명로그인을 허용하고 있기 때문에 12번째 줄을 주석처리하면 기본값(anonymous 로그인이 허용으로 설정된다. 익명로그인을 막으려면 반드시 NO로 설정해야 한다.

- chroot 사용여부 (홈 디렉토리의 제한 설정)
     : line 101의 # chroot_local_user=YES의 주석 해제.
  chroot를 사용함으로써 ftp로 접속하는 모든 계정의 최상위 디렉토리를 해당 계정의 홈디렉토리로 제한할 수 있다.

- chroot의 예외계정
    : line 102, 104는 chroot의 예외설정이다.

chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/chroot_list

  위와 같이 설정했다면 chroot_list에 등록한 계정들은 상위 디렉토리로의 이동이 가능하게 되며, 그 이외의 계정들은 자신의 홈디렉토리가 최상위 디렉토리로 제한되는 것이다.

  반대로 chroot_local_user=NO로 설정했다면 chroot_list에 등록된 계정들은 상위 디렉토리로의 이동이 제한된다. 

     chroot_list_enable은 chroot_list를 사용할지의 여부를 결정한다. 이것을 사용한다는 것은 현재 설정되어 있는 chroot_local_user 규칙의 예외를 설정하는 것으로.....

  이 예외 규칙은 chroot_local_user=YES로 설정되어 있다면 (ftp로)접속하는 모든 계정들은 상위 디렉토리로의 이동이 제한될 것이며, 이때의 chroot_list에 포함된 계정(들)은 설정된 규칙(전 계정의 상위 디렉토리로의 이동 제한)의 예외가 되므로 모든 디렉토리로의 이동이 자유롭게 된다.

  반대로 chroot_local_user=NO로 설정되어 있을 때는 모든 계정들이 상위 디렉토리로의 이동이 자유로울 것이다. 이때의 chroot_list에 지정된 계정(들)은 이 규칙의 예외로서 상위 디렉토리로의 이동이 제한된다.

  시스템의 모든 디렉토리를 ftp로 접근 가능한 계정이 필요할지는 의문이다. 기본 설정값인 chroot_list는 별도로 만들어야 하며 다른 이름으로 변경할 수 있다. 그리고 ftp접속을 허용하지 않는 계정은 ftpusers에 등록해서 접속을 거부할 수도 있다.


4. chroot 사용에 대해서...

  chroot를 사용하기로 설정 했다면, 각각의 계정들이 ftp로 접속했을 때에 각 계정의 홈디렉토리가 최상위 디렉토리로 제한된다. 여기서 발생하는 문제는....리눅스 시스템은 각 계정별 홈디렉토리의 소유권은 기본적으로 그 계정에게 주어지는데, chroot는 그것이 각 계정의 홈디렉토리라고 할지라도 root가 소유해야 한다. 이러한-계정별 홈디렉토리의 소유권과 chroot 소유권의 불일치- 문제로 로그인이 안되는 오류가 발생한다. 이를 해결할 수 있는 방법으로는

  첫 째로 vsftpd.conf에 allow_writeable_chroot=YES를 한 줄 추가하는 것이다. vsftpd.conf의 가장 마지막 줄이나 기타 원하는 곳 어디에 위치해도 상관없다. 간단한 방법이지만, 개인적으로 그다지 권장하고 싶은 옵션은 아니다. 둘 째로 각 계정의 홈디렉토리의 소유권을 root 계정이 갖게 하는 것이다.(퍼미션은 755) 그리고 그 하위에 디렉토리를 추가로 만들고 새로 만든 디렉토리의 소유권을 해당 계정에게 넘겨주면 문제가 해결된다. 예를 들어 pius라는 계정이 있다면 /home/pius의 디렉토리 소유권은 시스템의 root 에게 주고, 대신 그 하위에 추가한 디렉토리의 (예를 들어 /home/pius/ftproot) 소유권을 pius에게 주는 것이다.


5. 기본 포트의 변경

  ftp는 작동방식(active mode/passive mode)에 따라서 사용하는 포트가 조금 다를 수 있는데, 기본적으로 제어명령을 위한 port 21, 데이터의 전송을 위한 port 20을 사용한다. 

  ftp의 기본 포트를 아래와 같이 바꿔보자. vsftpd.conf에 아래의 3줄을 추가 후 재시작 해야 한다.

  변경전 변경후
ftp port 21 62,000
ftp data port 20 62,001 ~ 62,010

  ▶ line추가 : listen_port=62000
  ▶ line추가 : pasv_min_port=62001
  ▶ line추가 : pasv_max_port=62010

  이제 클라이언트에서 접속할 때에 ftp 포트는 62000으로 지정해야 한다. 물론 vsftp 데몬은 다시 시작해야 하며, 새로 설정한 포트(62000, 62001~62010)는 방화벽에서 열어 두어야 한다. 이는 passive mode 설정이며, 실제 데이터가 전송되는 포트는 62001~62010 범위의 포트가 랜덤하게 사용된다. 이 예에서 처럼 ftp 포트와 ftp-data 포트는 꼭 인접해야 하는 것은 아니다. 사용할 포트의 수량(범위)은 계정의 수량, ftp 사용빈도, 전송하는 데이터의 양을 고려해서 정하자.

  방화벽은 아래와 같이 범위를 지정하여 열어 둘 수 있다.

# firewall-cmd --permanent --zone=public --add-port=62001-62010/tcp
success
# firewall-cmd --reload
success
#

6. FTPS의 설정

  FTP에 SSL/TLS을 적용하여 FTPS로 운영해보자. 운영에 필요한 인증서는 openssl로 생성하면 된다.

[root@localhost /]# openssl req -x509 -days 720 -newkey rsa:2048 -nodes -keyout /etc/vsftpd/vsftpd.pem -out /etc/vsftpd/vsftpd.pem
Generating a 2048 bit RSA private key
.........................+++
......................................................................................+++
writing new private key to '/etc/vsftpd/vsftpd.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:kr
State or Province Name (full name) []:
Locality Name (eg, city) [Default City]:
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:123.123.123.123
Email Address []:account@domain
[root@localhost /]#

  인증서의 저장 위치는 vsftpd.conf와 같은 곳으로 했지만 어디라도 상관없다. 인증서의 유효기간은 720일(2년)로 설정했다. 인증서의 생성과정에서 모든 옵션은 생략가능 하다. - Common Name의 서버의 호스트 네임이나 ip주소 또한 생략해도 무방하다. - vsftpd.conf에 아래의 내용을 추가하자.

ssl_enable=YES
rsa_cert_file=/etc/vsftpd/vsftpd.pem
force_local_logins_ssl=YES
force_local_data_ssl=YES
ssl_tlsv1=YES
#allow_anon_ssl=NO

  이제 PC에서 FTP클라이언트 프로그램(파일질라, 알드라이브 등)을 통해서 FTP서버에 접속할 수 있다. 접속 방식은 explicit FTP over TLS(TLS를 통한 명시적 FTP)를 선택하자. 접속 포트는 위에서 설정한 62000을 사용해야 할 것이다. 위에서 FTPS를 위해 추가한 옵션에 대해서 간단하게 정리하자면....

ssl_enable=YES : SSL(TLS)를 통한 보안 연결설정을 허용한다.
rsa_cert_file=인증서파일의 경로를 지정한다.
force_local_logins_ssl=YES : 모든 로그인은 보안 ssl 연결을 사용하게 된다. (anonymous는 별도 설정)
force_local_data_ssl=YES : 송수된 되는 모든 데이터는 보안 ssl 연결을 사용하게 된다.
ssl_tlsv1=YES : TLS v1연결을 허용하는 것이다. ssl_sslv2 / ssl_sslv3으로 대체가능하다.

#allow_anon_ssl=NO : anonymous의 보안SSL 연결을 거부한다. 기본값이 NO이므로 생략(주석처리)해도 결과는 같다.

  일반적으로 FTP 클라이언트 프로그램으로 특정 서버에 접속 할 때에 FTP / SFTP / FTPS 중에서 하나를 선택한다. 이는 FTP 서버의 설정 방식에 맞춰서 선택해야 한다.

  기본 FTP(FTP plain)는 가장 고전적인 방식으로 내부 동작모드에 따라서 active modepassive mode로 나뉜다. 구동방식의 차이점을 잘 정리한 사이트나 블로그가 정말로 많다. 그래서 더이상의 설명은 패스한다 -_-; 그리고 FTP에 SSL/TLS를 이용하여 데이터를 암화화하여 전송하는 FTPS가 있다. 기존 FTP의 보안문제를 해결한 방식이며 내부의 작동 방식에 따라서 implicit FTP over TLS -명시적 ftp-와 explicit FTP over TLS -암시적 ftp-방식으로 구분한다. 단어 자체가 난해하다. 검색을 생활화 하자. -_-;

  단지 ftp의 active mode를 보완한 것이 passive mode이며, ftp의 보안문제를 해결한 것이 ftps이고, ftps의  최초 방식인 implicit FTPS를 보완한 것이 explicit FTP이며, explicit FTP가 현재 FTPS의 표준이라고 이해하자. 참고로 vsftpd.conf에 다음의 한 줄을 넣으면 FTPS는 implicit FTP over TLS 방식으로 작동한다. 즉, 기본설정이 explicit FTP over TLS 라는 것이다.

implicit_ssl=YES

  SFTP는 FTP와 같이 데이터를 전송하지만 ssh를 이용한 파일전송 프로토콜이며, FTP와는 그 태생부터 다르다. 용도는 FTP(S)과 같겠지만 내부 구동방식은 서로 별개의 프로그램이기에 (필요가 있다면)두 가지 모두 동시에 운영이 가능하다. SFTP의 설정은 별도로 정리해야겠다.


  아래의 이미지는 지금 구축한 FTP 서버에 접속하여 파일을 전송할 때 netstat로 사용되는 포트를 확인한 것이다. 서버의 ip와 클라이언트(내pc)의 ip는 왜 가렸을까....-_- 오늘 포토샵의 모자이크와 노이즈 필터를 배웠다;


SFTP와 SSH의 설정은 최근의 글에 정리해 두었다.

2020/11/10 - [Linux/for Hosting] - [CentOS] ssh와 sftp 설정

 

[CentOS] ssh와 sftp 설정

[CentOS] 하나의 계정으로 SSH와 SFTP 모두 ACCESS를 허용하는 방법 직접 서버를 운영하고 있다면 ssh(secure shell)는 필수일 것이며, 파일전송을 위한 ftp(s)나 sftp 또한 필요할 것이다. ftp(s)의 설정에 대해.

aegypius.tistory.com

 

728x90
반응형

댓글