之前发过一篇debian下debian+apache+fcgid+php+mod_suexec+mysql一键安装脚本,虽说现在个人VPS用LAMP组合的人已经很少了,但是不可否认apache的市场占有率,特别是一些虚拟主机提供商的环境,一般都是apache的,在研究了Cpanel的环境后,我模仿着写了一个CentOS一键安装apache+mod_fcgid+suexec+php+mysql并防跨目录访问的脚本,旨在学习一下Cpanel环境里的安全设置问题。
脚本和之前我发的几个类似的用法,使用的是yum安装,我不怎么喜欢用源码编译的方式安装软件,一个是我用的VPS一般都是比较低端的,性能有限,编译的话得等上半天才行,另外源码编译的软件在升级的方便性上是无法与yum安装相比较的。
此脚本默认安装好apache+mod_fcgid+suexec+php+mysql,网站用户和apache为不同用户,每个用户的目录用openbasedir加以限制,并且禁用了一些危险的函数,每个用户有独立的php-cgi进程,且有独立的php.ini配置文件,目录结构相对比较合理,每个用户可以建多个网站,网站目录、日志、临时文件、配置文件等都在用户的家目录里。默认网站目录在/var/www目录且不能修改,因为suexec默认已经将目录限制在/var/www目录下,我查找资料后没发现有什么办法可以自定义这个目录,除了源码编译suexec外。

脚本在chicagovps的Centos6.5上测试通过
不废话了,脚本如下 centos-lamp.sh

用法

1
2
3
bash centos-lamp.sh system #初始化VPS,删除无用软件,添加软件源,升级系统
bash centos-lamp.sh lamp   #安装并设置LNMP
bash centos-lamp.sh vhost  #根据提示添加虚拟主机
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#!/bin/bash
function check_sanity {
    # Do some sanity checking.
    if [ $(/usr/bin/id -u) != "0" ]
    then
        die 'Must be run by root user'
    fi

    if [ ! -f /etc/redhat-release ]
    then
        die "Distribution is not supported"
    fi
}

function die {
    echo "ERROR: $1" > /dev/null 1>&2
    exit 1
}

get_char()
{
	SAVEDSTTY=`stty -g`
	stty -echo
	stty cbreak
	dd if=/dev/tty bs=1 count=1 2> /dev/null
	stty -raw
	stty echo
	stty $SAVEDSTTY
}


function get_password() {
    # Check whether our local salt is present.
    SALT=/var/lib/random-seed
    if [ ! -f "$SALT" ]
    then
        head -c 512 /dev/urandom > "$SALT"
        chmod 400 "$SALT"
    fi
    password=`(cat "$SALT"; echo $1) | md5sum | base64`
    echo ${password:0:13}
}

function install_lamp() {
	echo "Press any key to start install lamp..."
	char=`get_char`
	yum -y install  mysql-server  httpd mod_fcgid php-cli php-curl php-gd php-sqlite php-mysql
	service mysqld stop
	service httpd stop
	
	echo "setup apache ......"
	mkdir /etc/httpd/sites
	chmod 700 -R /etc/httpd/sites
	cat >>/etc/httpd/conf/httpd.conf<<ENDL
Include sites/*.conf
ENDL
    cat >>/etc/httpd/conf.d/fcgid.conf<<ENDL
<IfModule mod_fcgid.c>
AddHandler fcgid-script .php .py .pl .fcgi
FcgidConnectTimeout 60
FcgidIdleTimeout 60
FcgidProcessLifeTime 600
FcgidMaxRequestsPerProcess 4000
FcgidMaxProcesses 10
FcgidMinProcessesPerClass 2
FcgidMaxProcessesPerClass 5
FcgidIOTimeout 600
FcgidBusyTimeout 600
FcgidFixPathinfo 1
</IfModule>
ENDL

	echo "setup mysql ......"    
	cat > /etc/my.cnf <<END
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
bind-address=127.0.0.1
symbolic-links=0
key_buffer = 8M
query_cache_size = 0
skip-innodb

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

END
	service mysqld start
#	sleep 2s
    # Generating a new password for the root user.
	passwd=`get_password root@mysql`
	mysqladmin -uroot  password "$passwd"
rm -rf ~/.my.cnf
    cat > ~/.my.cnf <<END
[client]
user = root
password = $passwd
END
	cat > ~/temp.sql <<END
delete from user where user='' or password='';
flush privileges;
END
	mysql -uroot -p"$passwd" mysql<temp.sql
	rm -rf ~/temp.sql
	chmod 600 ~/.my.cnf

# setup complete
	service mysqld restart
	service httpd start
	chkconfig mysqld on
	chkconfig httpd on
	echo "========================"
	echo "LAMP setup complete!"
	echo "Please use {`basename $0` vhost} to add a site"
	echo "Enjoy!"
	echo "========================"
}

function install_vhost {
	domain="www.kwxiaozhu.com"
	echo "Please input domain:"
	read -p "(Default domain: www.kwxiaozhu.com):" domain
	if [ "$domain" = "" ]; then
		domain="www.kwxiaozhu.com"
	fi
	grep "$domain" /etc/httpd/sites/* >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
	echo "==========================="
	echo "$domain is exist!"
	echo "===========================" 
	exit 0
	else
	echo "==========================="
	echo "domain=$domain"
	echo "==========================="	
	fi

	echo -n "Please input website username:"
	read -p "(Default username: nobody):" username
	if [ -f "/etc/httpd/sites/$username.conf" ]; then
	user_exist='y'
	echo "==========================="
	echo "$username is exist!"
	echo "==========================="
	echo "Do you want to add a website use this username? (Y/n)"
	read add_a_site
		if [ "$add_a_site" == 'n' ]; then
			exit 0	
		fi
	else
	echo "==========================="
	echo "username=$username"
	echo "===========================" 
	fi

	echo ""
	echo "Press any key to start create virtul host..."
	char=`get_char`

	echo "Create Virtul Host directory......"
	mkdir -p /var/www/sites/$username/{$domain,sessions,tmp,conf,logs}
	
	echo "Create Virtual Host User......"
	if [ "$user_exist" != 'y' ]; then 
		useradd -s /bin/false -d /var/www/sites/$username $username
	fi 
	
	echo "set permissions of Virtual Host directory......"
	if [ "$user_exist" != 'y' ]; then 
		chown -R $username:$username /var/www/sites/$username
	fi 
	chown $username:apache /var/www/sites/$username/$domain
	chmod 711 /var/www/sites
	chmod 710 /var/www/sites/$username/$domain
	chmod 700 /var/www/sites/$username/logs
	wget -q -P "/var/www/sites/$username/$domain" https://github.com/kwxiaozhu/shell/raw/master/tz.php
	
	echo "Create Apache Virtual Host Config File ......"
	if [ ! -f "/etc/httpd/sites/$username.conf" ]; then 
	cat >/etc/httpd/sites/$username.conf<<eof
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName      $domain
    DocumentRoot /var/www/sites/$username/$domain
    SuexecUserGroup $username $username
    FcgidWrapper /var/www/sites/$username/conf/php-cgi .php
#   FcgidInitialEnv "/var/www/sites/$username/conf"
    <Directory />
            DirectoryIndex index.php index.html
            Options +ExecCGI 
            AllowOverride all
            Order allow,deny
	    Allow from all
    </Directory>
    ErrorLog /var/www/sites/$username/logs/error-$domain.log
    LogLevel warn
    CustomLog /var/www/sites/$username/logs/access-$domain.log combined
    ServerSignature Off
</VirtualHost>    
eof
	else
	cat >>/etc/httpd/sites/$username.conf<<eof
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName      $domain
    DocumentRoot /var/www/sites/$username/$domain
    SuexecUserGroup $username $username
    FcgidWrapper /var/www/sites/$username/conf/php-cgi .php
#   FcgidInitialEnv "/var/www/sites/$username/conf"
    <Directory />
            DirectoryIndex index.php index.html
            Options +ExecCGI 
            AllowOverride all
            Order allow,deny
	    Allow from all
    </Directory>
    ErrorLog /var/www/sites/$username/logs/error-$domain.log
    LogLevel warn
    CustomLog /var/www/sites/$username/logs/access-$domain.log combined
    ServerSignature Off
</VirtualHost>  
eof
	fi
	echo "Create PHP-CGI Config File ......"
	if [ ! -f "/var/www/sites/$username/conf/php-cgi" ]; then
	cat >/var/www/sites/$username/conf/php-cgi<<end
#!/bin/sh
export PHPRC="/var/www/sites/$username/conf/"
#export PHP_FCGI_MAX_REQUESTS=1000
#export PHP_FCGI_CHILDREN=5
#exec /usr/lib/cgi-bin/php
exec /usr/bin/php-cgi
end
	fi
	if [ ! -f "/var/www/sites/$username/conf/php.ini" ]; then
	cat >/var/www/sites/$username/conf/php.ini<<start
[PHP]
short_open_tag=On
register_globals=Off
magic_quotes_gpc=On
post_max_size = 20M
upload_max_filesize = 20M
allow_url_fopen = On
memory_limit=64M
max_execution_time=30
default_socket_timeout=60
display_errors = off
register_argc_argv = on

open_basedir = /var/www/sites/$username/:/proc
upload_tmp_dir = /var/www/sites/$username/tmp
soap.wsdl_cache_dir = /var/www/sites/$username/tmp
session.save_path = /var/www/sites/$username/sessions
disable_functions = passthru,exec,system,chroot,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket
END
start
	fi
	chown -R $username:$username /var/www/sites/$username/conf/
	chmod +x /var/www/sites/$username/conf/php-cgi
	service httpd reload
	echo "============================================"
	echo "Create Virtual Host Complete!"
	echo "site:		http://$domain "
	echo "webroot:	/var/www/sites/$username/$domain"
	echo "webuser:	$username"
	echo "Please visit http://$domain/tz.php to check"
	echo "enjoy!"
	echo "============================================"
}

function install_vsftpd {
	yum -y install vsftpd db4-utils
	service vsftpd stop
	mv /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.bak
	if [ ! -d /var/www ];
        then
        mkdir /var/www
	fi
	cat >/etc/vsftpd/vsftpd.conf <<END
listen=YES
anonymous_enable=NO
local_enable=YES
write_enable=NO
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
xferlog_file=/var/log/vsftpd.log
xferlog_std_format=YES
ftpd_banner=Welcome to FTP service.
chroot_local_user=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=vsftpd.vu
rsa_cert_file=/etc/ssl/private/vsftpd.pem
user_config_dir=/etc/vsftpd_user_conf
guest_enable=YES
guest_username=nginx	
END
	cat >/etc/pam.d/vsftpd.vu <<END
auth	required	pam_userdb.so	db=/etc/vsftpd_login
account required	pam_userdb.so	db=/etc/vsftpd_login
END
	if [ ! -d /etc/vsftpd_user_conf ];
        then
        mkdir /etc/vsftpd_user_conf
	fi
	if [ ! -d /var/run/vsftpd/empty ];
		then
		mkdir -p /var/run/vsftpd/empty
	fi
	passwd=`get_password vsftpd`
	cat >~/.loguser.txt <<END
admin
$passwd
END
	db_load -T -t hash -f ~/.loguser.txt /etc/vsftpd_login.db
	cat >/etc/vsftpd_user_conf/admin <<END
local_root=/var/www/
write_enable=YES
anon_umask=022
anon_world_readable_only=NO
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
END
	chmod 600 ~/.loguser.txt
	chmod 600 /etc/vsftpd_login.db
	chmod 600 /etc/vsftpd_user_conf -R
	service vsftpd start
	echo 'vsftpd setup complete!'
	echo 'admin account is admin,password is in password file,home directory is /home/www'
	echo 'password file stored in .loguser.txt'
}

function remove_unneeded {
	yum -y remove httpd* php* samba* bind9* nscd
	service saslauthd stop
	service xinetd stop
	service udev-post stop
	chkconfig udev-post off
	chkconfig saslauthd off
	chkconfig xinetd off
}

function update_upgrade {
    # Run through the yum  update first. This should be done before
    # we try to install any package

rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm	
yum update -y
}

########################################################################
# START OF PROGRAM
########################################################################
export PATH=/bin:/usr/bin:/sbin:/usr/sbin

check_sanity
case "$1" in
lamp)
    install_lamp
    ;;
system)
    remove_unneeded
    update_upgrade
    ;;
vhost)
    install_vhost 
    ;;
ssh)
#    cat >> /etc/shells <<END
#/bin/false
#END
	useradd $2 -M -s /bin/false
	echo $2:$3 | chpasswd 
    ;;
vsftpd)
	install_vsftpd
	;;
sshport)
	#sed -i  s/'Port 22'/'Port kwxiaozhu'/ /etc/ssh/sshd_config
	sed -i  s/'^#Port [0-9]*'/'Port kwxiaozhu'/ /etc/ssh/sshd_config
	sed -i s/kwxiaozhu/$2/ /etc/ssh/sshd_config
	service sshd restart
	;;
*)
    echo 'Usage:' `basename $0` '[option]'
    echo 'Available option:'
    for option in system lamp vhost vsftpd ssh sshport
    do
        echo '  -' $option
    done
    ;;
esac