Stunnel 加密隧道搭建

Stunnel (http://www.stunnel.org/)是一款可以加密网络数据的TCP连接,并可工作在UnixWindows平台上,它采用Client/Server模式,将Client端的网络数据采用SSL(Secure Sockets Layer)加密后,安全的传输到指定的Server端再进行解密还原,然后再发送到访问的服务器。在加密传输过程中,可充分确保数据的安全性,我们只要把Server端程序安装在局域网外面的一台服务器上,即可保证传输的数据在局域网内是安全的,如图所示。




Stunnel的配置:

Client和Server端都包含stunnel.conf配置文件,格式如下表所示: 

Client端stunnel.conf文件内容

Server端stunnel.conf文件内容

# Use it for client mode
client = yes

#Client-level configuration

[ 应用服务名称 ]

accept =本地IP : 目标端口

connect =Server端IP : 指定的端口

# Use it for server mode

client = no

#Server-level configuration

[ 应用服务名称 ]

accept   = 指定的端口

connect =目标服务器IP : 目标端口

1.加密邮件传输:

加密邮件,需要将发送和接收的过程都要进行保护,那么我们就要对POP3SMTP传送方式进行加密。如果我们有一个xxx@colasoft.com.cn信箱,服务器的IP202.108.44.153,配置文件stunnel.conf如下: 

Client端SMTP和POP3文件内容

Server端SMTP和POP3文件内容

[smtp.colasoft.com.cn]

accept = 127.0.0.1:25

connect = 202.151.90.28:125

 

[pop3.colasoft.com.cn]

accept = 127.0.0.1:110

connect = 202.151.90.28:1110

[smtp.colasoft.com.cn]

accept = 125

connect = 202.108.44.170:25

 

[pop3.colasoft.com.cn]

accept = 1110

connect = 202.108.44.153:110

如果有多个邮件传输需要加密,则增加相应的POP3SMTP设置即可。设置好了配置文件,我们还需要将邮件客户端(常见的为FoxmailOutlook)与其对应,设置如下:
发送的邮件地址改为:127.0.0.1        端口改为:125
接收的邮件地址改为:127.0.0.1        端口改为:1110

2.加密FTP传输:

FTP是比较早的文件传输协议,内容都是以明文方式传输,我们利用Stunnel后,也可以让FTP的传输非常安全,现在我们只需要在前面的stunnel.conf内容里面增加以下配置信息: 

Client端FTP的配置

Server端FTP的配置

[ftp.net130.com]

accept = 127.0.0.1:21

connect = 202.151.90.28:121

[ftp.net130.com]

accept = 121

connect = 218.7.9.73:21

FTP软件(如CuteFTP)也要做相应更改:

登录的远程地址改为:127.0.0.1        端口改为121

3.加密HTTP网站访问传输:

我们不能对所有的网站访问都进行加密,因为太多,但对于很重要的网站,我们也可以用Stunnel来保护访问的内容不受到监听。例如我们要访问www.colasoft.com.cn,网站IP地址是202.108.36.172HTTP的配置如下: 

Client端HTTP的配置

Server端HTTP的配置

[www.colasoft.com.cn]

accept = 127.0.0.1:80

connect = 202.151.90.28:8080

[www.colasoft.com.cn]

accept = 8080

connect = 202.108.36.172:80

 

通过结合使用科来网络分析系统与Stunnel,既可以做到对网络的安全检测,并找出网络内的潜在安全隐患,又能从防护的角度出发,保护公司内部网络的重要信息。此方案成本低,不改变当前网络内的结构,容易实施,是一个简单有效的安全管理方案。

 

Stunnle加密rsyslog

服务端:

1.      Stunnel软件包安装系统的时候就有了,没有的话,敲打一下

#yum –y install stunnel

为了确保日志在网络传输过程中不会被截取信息,我这里建立了一下stunnel隧道,所以配置stunnel加密隧道,对上传的日志进行加密

2.      Server先自我签名

#openssl req -new -x509 -days 3650 -nodes-out stunnel.pem -keyout stunnel.pem

-days 3650

使这个证书的有效期是10年,之后它将不能再用

-new

创建一个新的证书

-x509

创建一个 X509 证书(自己签名的)

-nodes

这个证书没有密码

-out stunnel.pem

把 SSL 证书写到哪里

-keyout stunnel.pem

把 SSL 证书放到这个文件中

3.      把证书拷贝到对应目录

#cp stunnel.pem /etc/stunnel/

4.      修改服务端的配置:

#vim rsyslog-server.conf

#certficate/key is needed in server mode

client = no

cert = /etc/stunnel/stunnel.pem

 

debug = 7

foreground = yes

#output = stunnel.log

 

[syslog]

accept = 61514

connect = 60514

 

5.      修改服务端的/etc/rsyslog.conf

将514端口改为60514

 

6.      重启rsyslog

7.      stunnel /etc/stunnel/rsyslog-server.conf


8.   netstat –anp|grep 514


客户端:

1.      安装stunnel

#yum –y install stunnel

2.      修改/etc/rsyslog.conf

#将之前的目标ip换成对本地的端口

*.*;mail.none;authpriv.none;cron.none                  @@127.0.0.1:60514

authpriv.*                                             @@127.0.0.1:60514

*.emerg                                                 @@127.0.0.1:60514

3.      重启rsyslog

#service rsyslog restart

 

4.      配置/etc/stunnel/syslog-client.conf

client = yes

debug = 7

foreground = yes

#output = stunnel.log

 

[syslog]

accept = 127.0.0.1:60514

connect = 192.168.12.98:61514

 

5.      开启stunnel,

#stunnel syslog-client.conf


客户端验证:


服务端验证:


如果服务端出现了:

getsockopt: Connection refused (111)

那就是配置错了,端口连接不上

 

这样就算配置成功了,可以在message中查看到日志了


附录:

Stunnel-4.10 Man Page



NAME

stunnel - universal SSL tunnel


SYNOPSIS

Unix:

stunnel [<filename>] |-fd n | -help | -version | -sockets

WIN32:

stunnel [ [-install |-uninstall] [-quiet] [<filename>] ] | -help | -version | -sockets


DESCRIPTION

The stunnel program is designed to work as SSL encryption wrapper between remoteclients and local (inetd-startable)or remote servers. The concept is that having non-SSL aware daemons running onyour system you can easily set them up to communicate with clients over secureSSL channels.

stunnel canbe used to add SSL functionality to commonly used Inetd daemons like POP-2, POP-3, and IMAP servers,to standalone daemons like NNTP, SMTP and HTTP, and in tunneling PPP overnetwork sockets without changes to the source code.

This product includescryptographic software written by Eric Young (eay@cryptsoft.com)


OPTIONS

<filename>

Use specified configuration file

-fd n (Unix only)

Read the config file from specified file descriptor

-help

Print stunnel help menu

-version

Print stunnel version and compile time defaults

-sockets

Print default socket options

-install (NT/2000/XP only)

Install NT Service

-uninstall (NT/2000/XP only)

Uninstall NT Service

-quiet (NT/2000/XP only)

Don't display a message box when successfully installed oruninstalled NT service


CONFIGURATIONFILE

Each line of the configurationfile can be either:

  • an empty line (ignored)
  • a comment starting with ';' (ignored)
  • an 'option_name = option_value' pair
  • '[service_name]' indicating a start of a service definition

GLOBALOPTIONS

CApath =directory

Certificate Authority directory

This isthe directory in which stunnel will look for certificates when usingthe verify. Note that the certificates in thisdirectory should be named XXXXXXXX.0 where XXXXXXXX is the hash value of thecert.

CApath pathis relative to chroot directory if specified.

CAfile =certfile

Certificate Authority file

Thisfile contains multiple CA certificates, used with the verify.

cert =pemfile

certificate chain PEM file name

A PEMis always needed in server mode. Specifying this flag in client mode will usethis certificate chain as a client side certificate chain. Using client sidecerts is optional. The certificates must be in PEM format and must be sortedstarting with the certificate to the highest level (root CA).

chroot = directory (Unix only)

directory to chroot stunnel process

chroot keeps stunnel in chrooted jail. CApathCRLpathpid and exec are located inside the jail and thepatches have to be relative to the directory specified with chroot.

To havelibwrap (TCP Wrappers) control effective in a chrooted environment you alsohave to copy its configuration files (/etc/hosts.allow and /etc/hosts.deny)there.

ciphers =cipherlist

Select permitted SSL ciphers

A colondelimited list of the ciphers to allow in the SSL connection. For example DES-CBC3-SHA:IDEA-CBC-MD5

client =yes | no

client mode (remote service uses SSL)

default:no (server mode)

compression = zlib | rle

select data compression algorithm

default:no compression

CRLpath =directory

Certificate Revocation Lists directory

This isthe directory in which stunnel will look for CRLs when using the verify.Note that the CRLs in this directory should be named XXXXXXXX.0 where XXXXXXXXis the hash value of the CRL.

CRLpath pathis relative to chroot directory if specified.

CRLfile =certfile

Certificate Revocation Lists file

Thisfile contains multiple CRLs, used with the verify.

debug = [facility.]level

debugging level

Levelis a one of the syslog level names or numbers emerg (0), alert (1), crit (2),err (3), warning (4), notice (5), info (6), or debug (7). All logs for thespecified level and all levels numerically less than it will be shown. Use debug= debug or debug= 7 for greatestdebugging output. The default is notice (5).

Thesyslog facility 'daemon' will be used unless a facility name is supplied.(Facilities are not supported on Win32.)

Case isignored for both facilities and levels.

EGD = egd path (Unix only)

path to Entropy Gathering Daemon socket

EntropyGathering Daemon socket to use to feed OpenSSL random number generator.(Available only if compiled with OpenSSL 0.9.5a or higher)

engine = auto | <engine id>

select hardware engine

default:software-only cryptography

foreground = yes | no (Unix only)

foreground mode

Stay inforeground (don't fork) and log to stderr instead of via syslog (unless output is specified).

default:background in daemon mode

key =keyfile

private key for certificate specified with cert option

Privatekey is needed to authenticate certificate owner. Since this file should be keptsecret it should only be readable to its owner. On Unix systems you can use thefollowing command:

    chmod 600 keyfile

default:value of cert option

options =SSL_options

OpenSSL library options

Theparameter is the OpenSSL option name as described in the SSL_CTX_set_options(3ssl) manual, but without SSL_OP_ prefix. Several options can be used to specify multipleoptions.

Forexample for compatibility with erroneous Eudora SSL implementation thefollowing option can be used:

    options = DONT_INSERT_EMPTY_FRAGMENTS

output =file

append log messages to a file instead of using syslog

/dev/stdoutdevice can be used to redirect log messages to the standard output (for exampleto log them with daemontools splogger).

pid = file (Unix only)

pid file location

If theargument is empty, then no pid file will be created.

pid pathis relative to chroot directory if specified.

RNDbytes =bytes

bytes to read from random seed files

Numberof bytes of data read from random seed files. With SSL versions less than0.9.5a, also determines how many bytes of data are considered sufficient toseed the PRNG. More recent OpenSSL versions have a builtin function todetermine when sufficient randomness is available.

RNDfile =file

path to file with random seed data

The SSLlibrary will use data from this file first to seed the random number generator.

RNDoverwrite =yes | no

overwrite the random seed files with new random data

default:yes

service =servicename

use specified string as the service name

OnUnix: inetd modeservice name for TCP Wrapper library.

OnNT/2000/XP: NTservice name in the Control Panel.

default:stunnel

session =timeout

session cache timeout

setgid = groupname (Unix only)

setgid() to groupname in daemon mode and clears all other groups

setuid = username (Unix only)

setuid() to username in daemon mode

socket = a|l|r:option=value[:value]

Set an option on accept/local/remote socket

Thevalues for linger option are l_onof:l_linger. The values for time aretv_sec:tv_usec.

Examples:

    socket = l:SO_LINGER=1:60
        set one minute timeout for closing local socket
    socket = r:TCP_NODELAY=1
        turn off the Nagle algorithm for remote sockets
    socket = r:SO_OOBINLINE=1
        place out-of-band data directly into the
        receive data stream for remote sockets
    socket = a:SO_REUSEADDR=0
        disable address reuse (enabled by default)
    socket = a:SO_BINDTODEVICE=lo
        only accept connections on loopback interface

taskbar = yes | no (WIN32 only)

enable the taskbar icon

default:yes

verify =level

verify peer certificate

    level 1 - verify peer certificate if present
    level 2 - verify peer certificate
    level 3 - verify peer with locally installed certificate
    default - no verify

SERVICE-LEVELOPTIONS

Each configuration sectionbegins with service name in square brackets. The service name is used forlibwrap (TCP Wrappers) access control and lets you distinguish stunnel services in your log files.

Note that if you wish to run stunnel in inetd mode (where it is provided a networksocket by a server such asinetdxinetd,or tcpserver) then you should read the sectionentitled INETD MODE below.

accept = [host:]port

accept connections on specified host:port

If nohost specified, defaults to all IP addresses for the local host.

connect = [host:]port

connect to remote host:port

If nohost specified, defaults to localhost.

delay =yes | no

delay DNS lookup for 'connect' option

exec =executable_path (Unix only)

execute local inetd-type program

exec pathis relative to chroot directory if specified.

execargs = $0 $1 $2 ... (Unix only)

arguments for exec including program name ($0)

Quotingis currently not supported. Arguments are separated with arbitrary number ofwhitespaces.

ident =username

use IDENT (RFC 1413) username checking

local =host

IP of the outgoing interface is used as source for remoteconnections. Use this option to bind a static local IP address, instead.

protocol =proto

Negotiate SSL with specified protocol

currentlysupported: cifs, nntp, pop3, smtp

pty = yes | no (Unix only)

allocate pseudo terminal for 'exec' option

TIMEOUTbusy =seconds

time to wait for expected data

TIMEOUTclose =seconds

time to wait for close_notify (set to 0 for buggy MSIE)

TIMEOUTconnect =seconds

time to wait to connect a remote host

TIMEOUTidle =seconds

time to keep an idle connection

transparent = yes | no (Unix only)

transparent proxy mode

Re-writeaddress to appear as if wrapped daemon is connecting from the SSL clientmachine instead of the machine running stunnel. This optionis only available in local mode (exec option) by LD_PRELOADing env.so sharedlibrary or in remote mode (connect option) on Linux 2.2 kernel compiledwith transparent proxy option and then only in server mode.Note that this option will not combine with proxy mode (connect) unless theclient's default route to the target machine lies through the host running stunnel,which cannot be localhost.


RETURN VALUE

stunnel returnszero on success, non-zero on error.


EXAMPLES

In order to provide SSLencapsulation to your local imapd service, use

    [imapd]
    accept = 993
    exec = /usr/sbin/imapd
    execargs = imapd

If you want to providetunneling to your pppd daemon on port 2020, use somethinglike

    [vpn]
    accept = 2020
    exec = /usr/sbin/pppd
    execargs = pppd local
    pty = yes

If you want to use stunnel in inetd mode to launch your imapd process,you'd use this stunnel.conf. Note theremust be no [service_name] section.

    exec = /usr/sbin/imapd
    execargs = imapd

FILES

stunnel.conf

stunnel configuration file

stunnel.pem

stunnel certificate and privatekey


BUGS

Option execargs does not support quoting.


RESTRICTIONS

stunnel cannotbe used for the FTP daemon because of the nature of the FTP protocol whichutilizes multiple ports for data transfers. There are available SSL enabledversions of FTP and telnet daemons, however.


NOTES

INETD MODE

The most common use of stunnel is to listen on a network port andestablish communication with either a new port via the connect option, or a newprogram via the exec option. However there is a specialcase when you wish to have some other program accept incoming connections andlaunch stunnel, for examplewith inetd,xinetd,or tcpserver.

For example, if you have thefollowing line in inetd.conf:

    imaps stream tcp nowait root /usr/sbin/stunnel stunnel /etc/stunnel/imaps.conf

In these cases, the inetd-styleprogram is responsible for binding a network socket (imaps above) and handing it to stunnel when a connection is received. Thusyou do not want stunnel to have any accept option. All theService Level Options should be placed in the global optionssection, and no [service_name] section will be present. See the EXAMPLES section for example configurations.

CERTIFICATES

Each SSL enabled daemon needsto present a valid X.509 certificate to the peer. It also needs a private keyto decrypt the incoming data. The easiest way to obtain a certificate and a keyis to generate them with the free OpenSSL package. You can find more informationon certificates generation on pages listed below.

Two things are important whengenerating certificate-key pairs for stunnel. The privatekey cannot be encrypted, because the server has no way to obtain the passwordfrom the user. To produce an unencrypted key add the -nodes option when running the req command from the OpenSSL kit.

The order of contents of the .pem file is also important. It shouldcontain the unencrypted private key first, then a signed certificate (notcertificate request). There should be also empty lines after certificate andprivate key. Plaintext certificate information appended on the top of generatedcertificate should be discarded. So the file should look like this:

    -----BEGIN RSA PRIVATE KEY-----
    [encoded key]
    -----END RSA PRIVATE KEY-----
    [empty line]
    -----BEGIN CERTIFICATE-----
    [encoded certificate]
    -----END CERTIFICATE-----
    [empty line]

RANDOMNESS

stunnel needsto seed the PRNG (pseudo random number generator) in order for SSL to use good randomness.The following sources are loaded in order until sufficient random data has beengathered:

  • The file specified with the RNDfile flag.
  • The file specified by the RANDFILE environment variable, if set.
  • The file .rnd in your home directory, if RANDFILE not set.
  • The file specified with '--with-random' at compile time.
  • The contents of the screen if running on Windows.
  • The egd socket specified with the EGD flag.
  • The egd socket specified with '--with-egd-sock' at compile time.
  • The /dev/urandom device.

With recent (>=OpenSSL0.9.5a) version of SSL it will stop loading random data automatically whensufficient entropy has been gathered. With previous versions it will continueto gather from all the above sources since no SSL function exists to tell whenenough data is available.

Note that on Windows machinesthat do not have console user interaction (mouse movements, creating windows,etc) the screen contents are not variable enough to be sufficient, and youshould provide a random file for use with the RNDfile flag.

Note that the file specifiedwith the RNDfile flag should contain random data --that means it should contain different information each time stunnel is run. This is handled automaticallyunless the RNDoverwrite flag is used. If you wish to updatethis file manually, the openssl rand command in recent versions of OpenSSL,would be useful.

One important note -- if/dev/urandom is available, OpenSSL has a habit of seeding the PRNG with it evenwhen checking the random state, so on systems with /dev/urandom you're likelyto use it even though it's listed at the very bottom of the list above. Thisisn't stunnel's behaviour, it's OpenSSLs.


SEE ALSO

tcpd(8)

access control facility for internet services

inetd(8)

internet 'super-server'

http://stunnel.mirt.net/http://stunnel.mirt.net/

stunnel homepage

http://www.stunnel.org/http://www.stunnel.org/

stunnel Frequently AskedQuestions

http://www.openssl.org/http://www.openssl.org/

OpenSSL project website


AUTHOR

Michal Trojnara

<Michal.Trojnara@mirt.net>

The UbiquitousMiscellaneous Section

Those things that don't have aproper home yet may end up here. Or they may stay here. I've heard that manyanswers prefer to be in the miscellaneous sections. Maybe they're just shy.


What are the offical SSL ports?

These are the officially'registered' ports for various SSL-ified protocols. note that listing them heredoesn't mean that they can be used with stunnel.

    nsiiops      261/tcp   # IIOP Name Service over TLS/SSL
    https        443/tcp   # http protocol over TLS/SSL
    smtps        465/tcp   # smtp protocol over TLS/SSL (was ssmtp)
    nntps        563/tcp   # nntp protocol over TLS/SSL (was snntp)
    imap4-ssl    585/tcp   # IMAP4+SSL (use 993 instead)
    sshell       614/tcp   # SSLshell
    ldaps        636/tcp   # ldap protocol over TLS/SSL (was sldap)
    ftps-data    989/tcp   # ftp protocol, data, over TLS/SSL
    ftps         990/tcp   # ftp protocol, control, over TLS/SSL
    telnets      992/tcp   # telnet protocol over TLS/SSL
    imaps        993/tcp   # imap4 protocol over TLS/SSL
    ircs         994/tcp   # irc protocol over TLS/SSL
    pop3s        995/tcp   # pop3 protocol over TLS/SSL (was spop3)
    msft-gc-ssl  3269/tcp  # Microsoft Global Catalog with LDAP/SSL

How do I know which encryption ciphers areavailable?

The ciphers that are availabreto stunnel (and usable by the '-C' flag) are determined by your OpenSSLlibrary. To list the available ciphers, run the following:

    openssl ciphers -v

How can I delay DNS lookups until connecttime?

If you're using Stunnel-4.0 orlater, add the following to your Stunnel configuration file:

  delay = yes

If you are using olderversions, there are several different patches available for this in the patches directoryon this site you may try.

Another option is to launch redir (aTCP redirector) dynamically instead of using the "-r host:port"option, like this:

   -l /usr/bin/redir -- redir --inetd --caddr host --cport port

How can I convert a certificate from derformat (.cer) to PEM format?

Some institutions that supplycertificates will send them to you in der format instead of PEM format. You canuse the openssl command line tool to convert from one to the other:

  openssl x509 -in file.cer -inform d -out file.pem

 

转载请注明文章转自:良玉的博客 [http://blog.uouo123.com]




  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向良玉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值