使用stunnel进行ssl加密

stunnel是个功能很简单的软件,就是进行ssl加密。可以帮助我们把http加密为https,也可以对普通的tcp链接进行ssl加密。stunnel的安装非常简单,就想详细写了。在centos下是只用用yum安装的,debian下就直接aptitude安装了。使用stunnel的配置如果不对客户端进行证书校验的话那么主要是2方面的配置。

1.配置ssl证书。stunnel配置证书有两种方式。老的方式是使用http://www.stunnel.org/static/stunnel.html介绍的先把key放最前面,然后依次放证书链。类似

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

这种形式,如果服务器证书不是由根CA签发的,那么就需要类型nginx配置证书链那样把后面中间证书都逆序依次追加在后面。每个证书之间预留一个空行(不过我自己测试时不需要空行也是可以的)。这时的配置文件如下:

[bash]

; Sample stunnel configuration file by Michal Trojnara 2002-2006
; Some options used here may not be adequate for your particular configuration
; Please make sure you understand them (especially the effect of chroot jail)

; Certificate/key is needed in server mode and optional in client mode
cert = /etc/stunnel/test.crt
; Some security enhancements for UNIX systems – comment them out on Win32
chroot = /var/run/stunnel/
setuid = nobody
setgid = nobody
; PID is created inside chroot jail
pid = /stunnel.pid

; Some performance tunings
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1
compression = rle

; Workaround for Eudora bug
;options = DONT_INSERT_EMPTY_FRAGMENTS

; Authentication stuff
;verify = 2
; Don’t forget to c_rehash CApath
; CApath is located inside chroot jail
;CApath = /certs
; It’s often easier to use CAfile
;CAfile = /etc/stunnel/certs.pem
;CAfile = /usr/share/ssl/certs/ca-bundle.crt
; Don’t forget to c_rehash CRLpath
; CRLpath is located inside chroot jail
;CRLpath = /crls
; Alternatively you can use CRLfile
;CRLfile = /etc/stunnel/crls.pem

; Some debugging stuff useful for troubleshooting
;debug = 7
output = stunnel.log

; Use it for client mode
;client = yes

; Service-level configuration

#[pop3s]
#accept  = 995
#connect = 110

#[imaps]
#accept  = 993
#connect = 143

#[ssmtp]
#accept  = 465
#connect = 25

[https]
accept  = 443
connect = 80
;TIMEOUTclose = 0

; vim:ft=dosini

[/bash]

2.使用key和cert分成2个文件的形式,这个形式就和现在nginx的配置完全一样了。配置文件如下

 

[bash]

; Sample stunnel configuration file by Michal Trojnara 2002-2006
; Some options used here may not be adequate for your particular configuration
; Please make sure you understand them (especially the effect of chroot jail)

; Certificate/key is needed in server mode and optional in client mode
cert = /etc/stunnel/cert.crt
key = /etc/stunnel/cert.key

; Some security enhancements for UNIX systems – comment them out on Win32
chroot = /var/run/stunnel/
setuid = nobody
setgid = nobody
; PID is created inside chroot jail
pid = /stunnel.pid

; Some performance tunings
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1
compression = rle

; Workaround for Eudora bug
;options = DONT_INSERT_EMPTY_FRAGMENTS

; Authentication stuff
;verify = 2
; Don’t forget to c_rehash CApath
; CApath is located inside chroot jail
;CApath = /certs
; It’s often easier to use CAfile
;CAfile = /etc/stunnel/certs.pem
;CAfile = /usr/share/ssl/certs/ca-bundle.crt
; Don’t forget to c_rehash CRLpath
; CRLpath is located inside chroot jail
;CRLpath = /crls
; Alternatively you can use CRLfile
;CRLfile = /etc/stunnel/crls.pem

; Some debugging stuff useful for troubleshooting
;debug = 7
output = stunnel.log

; Use it for client mode
;client = yes

; Service-level configuration

#[pop3s]
#accept  = 995
#connect = 110

#[imaps]
#accept  = 993
#connect = 143

#[ssmtp]
#accept  = 465
#connect = 25

[https]
accept  = 443
connect = 80
;TIMEOUTclose = 0

; vim:ft=dosini

[/bash]

需要注意有key的文件的权限都要是600才行。如果有其他的需求就对应地改一下配置文件好了,比如对客户端进行证书校验,参考模板修改就行了。

发表在 Web server | 留下评论

常用perl模块的使用

1.   Net::Ping,perl的ping模块,范例:

[pl]

#!/usr/bin/perl -w
use strict;
use Net::Ping;
sub ping_check{
my $dest=shift;
my $mp = Net::Ping->new("icmp");
if($mp->ping($dest,2)){
print "$dest is alive\n";
}else {
print "$dest is dead\n";
}

$mp->close;
}
while (my $host=<>){
chomp $host;
&ping_check($host);

} [/pl]

2.File::Copy 主要提供了copy和move函数

[pl]

#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;
my $filein=$ARGV[0];
my $fileout=$ARGV[1];
copy($filein,$fileout) or die "copy $filein to $fileout failed\n";
move($fileout,"$fileout.test") or die "mv  $fileout to  $fileout.txt failed\n";

[/pl]

3.File::Rsync;

[pl]

#!/usr/bin/perl
use strict;
use warnings;
use File::Rsync;
my $filein=$ARGV[0];
my $fileout=$ARGV[1];
&rsync_file($filein,$fileout);
sub rsync_file{
my $localdir=shift;
my $remotedir=shift;
print "rsync file from $localdir to $remotedir\n";
my $obj = File::Rsync->new( { archive => 1, compress => 1 ,del=>1} );
$obj->exec( { src => $localdir, dest => $remotedir } ) or warn "rsync failed\n";

}

[/pl]

需要注意在使用rsync的时候Rsync->new里面的参数del,del表示删除目标文件中有但是源文件没有的文件。

另外就是如果我们是同步两个目录,应该使用rsync dir1/ dir2这样的形式。

如果使用sync dir1 dir2的话,结果就是dir1被放到dir2下面去了,也不要使用rsync dir1/* dir2的形式,否则当dir1是空文件夹的时候会报错。

4.  Net::OpenSSH

[pl]

#!/usr/bin/perl
use strict;
use warnings;
use Net::OpenSSH;
my $rhost=shift;
my $cmd=shift;
&remotessh_cmd($rhost,$cmd);

sub remotessh_cmd{
my $host=shift;
my $cmd=shift;
chomp $host;
my $private_key_path=’/root/.ssh/id_rsa’;
my $ruser="root";
my %opt=("user"=>$ruser,"key_path"=>$private_key_path,"timeout"=>3,"kill_ssh_on_timeout" => 1);
my $ssh= Net::OpenSSH->new($host,%opt);
$ssh->error and die "Couldn’t establish SSH connection: ". $ssh->error;
my $out=$ssh->capture($cmd);
print "SSH result:$out";
$ssh->error and die "remote command failed:".$ssh->error;
}

[/pl]

如果不是太在意执行结果的输出,可以直接使用 $ssh->system($cmd)来操作,需要注意执行返回值的问题,比如你强制杀掉某个进程,如果这个进程不存在了返回值就不是0,需要用$ssh->system(“$cmd;exit0”)这样的形式。

5.Getopt::Std

这个就不用多说了,解析参数用的。

getopts(“f:s:ul:”,\%options);

然后对$options{‘f’}等等进行判断是否存在,如果存在的话那么-f指定的参数就是$options{‘f’}。

6. Expect;

perl里面使用expect脚本也简单的,下面是用expect的签发证书的脚本中的一部分。

[pl]

my $exp = Expect->spawn ($cmd) or die "Cannot spawn : $cmd \n";
$exp->log_stdout(0);
$exp->log_file("expect.log");#记录整个文件
$exp->expect(30,
[ qr#Enter pass phrase for $choice{dir}/$choice{file}.key:#i => sub { my $exp = shift;
$exp->send("$choice{‘passwd’}\r");
exp_continue; }],

…………………….

)

[/pl]

发表在 Perl Script | 留下评论

perl正则匹配时的环视和命名捕获

perl的正则匹配里有几个有用的匹配方式

1.非捕获型匹配

[perl]
#!/usr/bin/perl
use warnings;
use strict;
my $line="123d4f5g7h8";
if($line=~/(?:5)(\w)/){
print "match $1\n";
}
[/perl]

这样就表示捕获5后面的一个字母或者数字,由于(?:5)是不占用空间的,所以我们还是用$1对捕获的字符串进行引用.

2.命名捕获

[pl]

#!/usr/bin/perl
use warnings;
use strict;
my $line="123d4f5g7h8";
if($line=~/(?:5)(?<var1>\w)/){
print "match $+{var1}\n";
}

[/pl]

我们可以使用(?<NAME>xxx)来把保存匹配的字符串存放在制定的变量里面.引用的时候需要使用$+{NAME}来进行引用.

3.顺序环视

[pl]

(?=xxx)

*******|xxx********

[/pl]

(?=xxx)匹配xxx前面的位置。而(?!xxx)就是匹配除了xxx前面位置的其他所有地方。

4.逆序环视

[pl]

(?<=xxx)

[/pl]

匹配 **********xxx|*********,也就是xxx以后的那个位置,同理(?<!xxx)与(?!xxx)的类似。

另外,在匹配时可以指定的几个常用选项是

/i  忽略字母的大小写

/x  忽略中间的空格  /\d{2}  ([\W]) \d{2} \1 \d{2}/x等价于/\d{2}([\W])\d{2}\1\d{2}/

/s 将串视为单行,”.”可以匹配换行符 。 /a.*bc/s匹配字符串axxxxx \nxxxxbc,但/a.*bc/则不匹配该字符串。

/m  多行匹配。 在此情况下,^符号匹配字符串的起始或新的一行的起始;$符号匹配任意行的末尾。

/o 只编译一次,注意有内插变量的时候谨慎使用

/g 匹配所有可能的模式

发表在 Perl Script | 留下评论

找出IO消耗较高的进程

   经常碰见服务器IO比较慢,这个是最不能忍受的,因为基本的命令行操作都会非常慢。网上搜了下,可以按照这个方式直接找出耗IO最高的进程名。

  1.先停掉syslog然后打开block dump
    service syslog stop
    echo 1 > /proc/sys/vm/block_dump
2.从dmesg的中找到消耗IO的进程
dmesg | grep -E “READ|WRITE|dirtied” | grep -E -o ‘([a-zA-Z]*)’ | sort |uniq -c|sort -k1 -gr

排前的比较占用io。如果只想关系到读或者写的也可以直接只搜READ和WRITE。

3.恢复系统。

     echo 0 > /proc/sys/vm/block_dump
    service syslog start

发表在 Admin, System | 留下评论

linux上的rdp客户端

由于工作需要,经常得在linux下登陆windows的远程桌面.找到了一个比较好的客户端

aptitude intall remmina即可..

 

发表在 Admin | 留下评论

OOM续

最近维护测试服务器越来越多出现OOM。每次都是改改内核参数,貌似有点用处。但是这个治标不治本,源头没有找到。

自己先了解了一下一些基础性的东西。每次OOM后查看messages日志都能看到

[text]

<span>Jun 18 17:10:23 free-72-222 kernel: oom-killer: gfp_mask=0xd0
Jun 18 17:10:23 free-72-222 kernel: Mem-info:
Jun 18 17:10:23 free-72-222 kernel: DMA per-cpu:
Jun 18 17:10:23 free-72-222 kernel: cpu 0 hot: low 2, high 6, batch 1
Jun 18 17:10:23 free-72-222 kernel: cpu 0 cold: low 0, high 2, batch 1
Jun 18 17:10:23 free-72-222 kernel: cpu 1 hot: low 2, high 6, batch 1
Jun 18 17:10:23 free-72-222 kernel: cpu 1 cold: low 0, high 2, batch 1
Jun 18 17:10:23 free-72-222 kernel: cpu 2 hot: low 2, high 6, batch 1
Jun 18 17:10:27 free-72-222 kernel: cpu 2 cold: low 0, high 2, batch 1
Jun 18 17:10:27 free-72-222 kernel: cpu 3 hot: low 2, high 6, batch 1
Jun 18 17:10:27 free-72-222 kernel: cpu 3 cold: low 0, high 2, batch 1
Jun 18 17:10:27 free-72-222 kernel: Normal per-cpu:
Jun 18 17:10:27 free-72-222 kernel: cpu 0 hot: low 32, high 96, batch 16
Jun 18 17:10:27 free-72-222 kernel: cpu 0 cold: low 0, high 32, batch 16
Jun 18 17:10:27 free-72-222 kernel: cpu 1 hot: low 32, high 96, batch 16
Jun 18 17:10:27 free-72-222 kernel: cpu 1 cold: low 0, high 32, batch 16
Jun 18 17:10:27 free-72-222 kernel: cpu 2 hot: low 32, high 96, batch 16
Jun 18 17:10:27 free-72-222 kernel: cpu 2 cold: low 0, high 32, batch 16

Jun 20 14:46:44 free-72-222 kernel: cpu 2 cold: low 0, high 32, batch 16
Jun 20 14:46:44 free-72-222 kernel: cpu 1 cold: low 0, high 32, batch 16
Jun 20 14:46:44 free-72-222 kernel: cpu 2 hot: low 32, high 96, batch 16
Jun 20 14:46:44 free-72-222 kernel: cpu 2 cold: low 0, high 32, batch 16
Jun 20 14:46:44 free-72-222 kernel: cpu 3 hot: low 32, high 96, batch 16
Jun 20 14:46:44 free-72-222 kernel: cpu 3 cold: low 0, high 32, batch 16
Jun 20 14:46:44 free-72-222 kernel:
Jun 20 14:46:44 free-72-222 kernel: Free pages:       35748kB (24320kB HighMem)
Jun 20 14:46:44 free-72-222 kernel: protections[]: 0 0 0
Jun 20 14:46:44 free-72-222 kernel: protections[]: 0 0 0
Jun 20 14:46:44 free-72-222 kernel: protections[]: 0 0 0
Jun 20 14:46:44 free-72-222 kernel: protections[]: 0 0 0
Jun 20 14:46:44 free-72-222 kernel: Normal free:3304kB min:3336kB low:6672kB high:10008kB active:617956kB inactive:0kB pre
sent:729088kB pages_scanned:1293 all_unreclaimable? no
Jun 20 14:46:44 free-72-222 kernel: protections[]: 0 0 0
Jun 20 14:46:44 free-72-222 kernel: HighMem free:24320kB min:512kB low:1024kB high:1536kB active:2836904kB inactive:486976
kB present:3358720kB pages_scanned:0 all_unreclaimable? no
Jun 20 14:46:44 free-72-222 kernel: protections[]: 0 0 0
Jun 20 14:46:44 free-72-222 kernel: DMA: 3*4kB 2*8kB 6*16kB 4*32kB 5*64kB 1*128kB 1*256kB 2*512kB 2*1024kB 2*2048kB 0*4096
kB = 8124kB
Jun 20 14:46:44 free-72-222 kernel: Normal: 0*4kB 1*8kB 0*16kB 1*32kB 1*64kB 1*128kB 0*256kB 0*512kB 1*1024kB 1*2048kB 0*4
096kB = 3304kB
Jun 20 14:46:44 free-72-222 kernel: HighMem: 5942*4kB 5*8kB 0*16kB 0*32kB 0*64kB 0*128kB 0*256kB 1*512kB 0*1024kB 0*2048kB
 0*4096kB = 24320kB
Jun 20 14:46:44 free-72-222 kernel: 428935 pagecache pages
Jun 20 14:46:44 free-72-222 kernel: Swap cache: add 0, delete 0, find 0/0, race 0+0
Jun 20 14:46:44 free-72-222 kernel: 0 bounce buffer pages
Jun 20 14:46:44 free-72-222 kernel: Free swap:            0kB
Jun 20 14:46:44 free-72-222 kernel: 1026048 pages of RAM
Jun 20 14:46:44 free-72-222 kernel: 839680 pages of HIGHMEM
Jun 20 14:46:44 free-72-222 kernel: 10594 reserved pages
Jun 20 14:46:44 free-72-222 kernel: 413640 pages shared
Jun 20 14:46:44 free-72-222 kernel: 0 pages swap cached
Jun 20 14:46:44 free-72-222 kernel: Out of Memory: Killed process 19148 (java).</span>

[/text]

这样的日志,对于里面的

[text]

Jun 20 14:46:44 free-72-222 kernel: DMA: 3*4kB 2*8kB 6*16kB 4*32kB 5*64kB 1*128kB 1*256kB 2*512kB 2*1024kB 2*2048kB 0*4096
kB = 8124kB
Jun 20 14:46:44 free-72-222 kernel: Normal: 0*4kB 1*8kB 0*16kB 1*32kB 1*64kB 1*128kB 0*256kB 0*512kB 1*1024kB 1*2048kB 0*4
096kB = 3304kB
Jun 20 14:46:44 free-72-222 kernel: HighMem: 5942*4kB 5*8kB 0*16kB 0*32kB 0*64kB 0*128kB 0*256kB 1*512kB 0*1024kB 0*2048kB
 0*4096kB = 24320kB

[/text]

就能看出OOM发生的当时实际的Normal,HigMem的空闲内存值分布是 2304KB,24320KB。

另外我们也可以根据

[text]

# cat /proc/buddyinfo
Node 0, zone      DMA      3      2      6      4      5      1      1      2      2      2      0
Node 0, zone   Normal     28      1      1      1   2413    918    161     12      1      1      0
Node 0, zone  HighMem    126   8173  18550   1254     22      0      0      1      0      0      0

[/text]

查看系统当前的内存情况。对于buddyinfo  的解释参考

http://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-buddyinfo.html

对于messages日志

其实就是

第1列*4kB 第2列*8kB 第3列*16kB 第4列*32kB 第5列*64kB 第6列*128kB 第7列*256kB 第8列*512kB 第9列*1024kB 第10列*2048kB 第11列*4096kB

总的和就是当时剩余的内存值。

我们可以使用命令

echo m > /proc/sysrq-trigger

让内核把当前的buddyinfo信息打印到messages日志中

[text]

<span># cat /proc/buddyinfo    ;echo m > /proc/sysrq-trigger
Node 0, zone      DMA      3      2      6      4      5      1      1      2      2      2      0
Node 0, zone   Normal      0      0      0      1   2403    918    161     12      1      1      0
Node 0, zone  HighMem      0      0  18372   1254     22      0      0      1      0      0      0</span>

<span>[root@test1 /var/log]
# grep Normal: /var/log/messages |tail -n 1
Jun 20 15:44:39 free-72-222 kernel: Normal: 0*4kB 2*8kB 1*16kB 0*32kB 2410*64kB 918*128kB 161*256kB 12*512kB 1*1024kB 1*2048kB 0*4096kB = 322208kB</span>

<span>[root@test1/var/log]
# grep HighMem: /var/log/messages |tail -n 1
Jun 20 15:44:39 free-72-222 kernel: HighMem: 0*4kB 0*8kB 18372*16kB 1254*32kB 22*64kB 0*128kB 0*256kB 1*512kB 0*1024kB 0*2048kB 0*4096kB = 336000kB</span>

[/text]

这里面空闲的内存值加起来和free的结果是一直的

[text]

<span># free -m
                   total       used       <span>free</span>     shared    buffers     cached
Mem:          4000       3351        <span>648</span>          0        257       2046
-/+ buffers/cache:       1047       2952
Swap:            0             0              0</span>

[/text]

再回到系统对进程内存分配控制的2个内核参数

/proc/sys/vm/overcommit_memory 可以有个三个值

[text]

0 (default): as before: guess about how much overcommitment is reasonable,

1: never refuse any <code>malloc()</code>,

2: be precise about the overcommit – never commit a virtual address space larger than swap space plus a fraction <code>overcommit_ratio</code> of the physical memory. Here <code>/proc/sys/vm/overcommit_ratio</code> (by default 50) is another user-settable parameter. It is possible to set <code>overcommit_ratio</code> to values larger than 100.

[/text]

简单地说vm.overcommit_memory = 0,这时候可以申请到比较多的内存,但是仍然会在一定的时候申请失败;vm.overcommit_memory = 1,所有的malloc都会成功;

vm.overcommit_memory = 2,当前可以申请的内存大小是

overcommit_ratio*物理内存大小+sawp的大小,<code>/proc/sys/vm/overcommit_ratio

 默认值是50.这个时候

/proc/sys/vm/overcommit_ratio

 设置过小会浪费内存,造成一部分内存不能被使用,设置过大又失去意义。需要根据实际情况调整。

另外就是还可以根据/proc/meminfo查看当前的内存状态。

[text]

<span><code><span><code>[root@test /var/log]
#  echo m > /proc/sysrq-trigger            </code></span></code></span>

<span><code>[root@test /var/log]
# cat /proc/buddyinfo
Node 0, zone      DMA      3      2      6      4      5      1      1      2      2      2      0
Node 0, zone   Normal      0      0      1      1   2360    918    161     12      1      1      0
Node 0, zone  HighMem      0      0  17900   1254     22      0      0      1      0      0      0</code></span>

<span><code>[root@test /var/log]
# grep HighMem: /var/log/messages |tail -n 1
Jun 20 16:02:37 free-72-222 kernel: HighMem: 0*4kB 0*8kB 17948*16kB 1254*32kB 22*64kB 0*128kB 0*256kB 1*512kB 0*1024kB 0*2048kB 0*4096kB = 329216kB</code></span>

<span><code>[root@test /var/log]
# grep Normal: /var/log/messages |tail -n 1
Jun 20 16:02:37 free-72-222 kernel: Normal: 0*4kB 0*8kB 1*16kB 1*32kB 2371*64kB 918*128kB 161*256kB 12*512kB 1*1024kB 1*2048kB 0*4096kB = 319728kB</code></span>

<span><code>[root@test /var/log]
# cat /proc/meminfo
MemTotal:      4096132 kB
MemFree:        655324 kB
Buffers:        265820 kB
Cached:        2101480 kB
SwapCached:          0 kB
Active:        2690184 kB
Inactive:       595584 kB
HighTotal:     3350528 kB
HighFree:       328256 kB
LowTotal:       745604 kB
LowFree:        327068 kB
SwapTotal:           0 kB
SwapFree:            0 kB
Dirty:            1236 kB
Writeback:           0 kB
Mapped:         969720 kB
Slab:            94556 kB
CommitLimit:   2048064 kB
Committed_AS:  4843488 kB
PageTables:       4580 kB
VmallocTotal:   114680 kB
VmallocUsed:      1232 kB
VmallocChunk:   112956 kB</code></span>

[/text]

从上面可以看到/proc/meminfo里的LowFree和HighFree和buddyinfo 以及messages里打印的是相同的。

另外我们也能看到buffer和cache占用了大量的内存,会不会是某些进程频繁地malloc+free,系统来不及回收造成了最后的OOM?有个<a href="http://www.kernel.org/doc/Documentation/sysctl/vm.txt">参数/proc/sys/vm/drop_caches</a> 可以调整

内核对buffer和caches的处理:

[text]

 Writing to this will cause the kernel to drop clean caches, dentries and
 inodes from memory, causing that memory to become free.

 To free pagecache:
 echo 1 &gt; /proc/sys/vm/drop_caches
 To free dentries and inodes:
 echo 2 &gt; /proc/sys/vm/drop_caches
 To free pagecache, dentries and inodes:
 echo 3 &gt; /proc/sys/vm/drop_caches

 As this is a non-destructive operation and dirty objects are not freeable, the
 user should run `sync' first.&lt;/code&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;

[/text]

<span><span><span><code>执行sync同步后可以试试echo 3 &gt; /proc/sys/vm/drop_caches把buffer和cache都释放出来,不过实际上感觉这样也是治标不治本。还是得从应用这个源头去找原因。最后查出来时jvm的参数设置的有问题,机器的内存就2G,但是jvm堆栈内存设置的过大,所以导致多次的OOM。另外还有此查出来是自动挂载NFS的automount有bug,导致产生了巨多的网络链接,没有办法只有重启机器,重启后就OK了。

发表在 System | 留下评论

openssl签发证书时设置subjectAltName

很简单地表述一下需求,就是希望一个证书能给多个域名使用(非通配符证书).

直接上脚本吧,第一个是生成根CA的证书,因为是在以前的基础上完成的,所以实际是将就自己以前写的一个多级CA签发证书的脚本做的。原文见这里

pm@debian:~/test/ca$ cat makerootca.sh 
#!/bin/bash
DIR=`pwd`
mkdir -p $DIR/demoCA/private
mkdir -p $DIR/demoCA/newcerts
mkdir -p $DIR/autoget
touch $DIR/demoCA/index.txt
echo 01 > $DIR/demoCA/serial
openssl genrsa -des3 -out $DIR/demoCA/private/cakey.pem 2048
openssl req -new -x509 -days 3650 -key $DIR/demoCA/private/cakey.pem -out $DIR/demoCA/careq.pem

然后是签发二级CA的脚本

pm@debian:~/test/ca$ cat no2ca.sh

#!/bin/bash
NAME=$1
DIR=$(pwd)/autoget
openssl genrsa -des3 -out $DIR/$NAME.key 2048
openssl rsa -in $DIR/$NAME.key -out $DIR/$NAME.key
openssl req -new -days 3650 -key $DIR/$NAME.key -out $DIR/$NAME.csr
openssl ca -extensions v3_ca -in $DIR/$NAME.csr -config ./openssl.cnf -days 3000 -out $DIR/$NAME.crt -cert $DIR/../demoCA/careq.pem -keyfile $DIR/../demoCA/private/cakey.pem

签发三级CA的脚本:
pm@debian:~/test/ca$ cat no3ca.sh 
#!/bin/bash
[ $# -ne 1 ] && echo “$0 NAME” && exit
NAME=$1
DIR=$(pwd)/autoget
openssl genrsa -des3 -out $DIR/$NAME.key 2048
openssl rsa -in $DIR/$NAME.key -out $DIR/$NAME.key
openssl req -new -days 3650 -key $DIR/$NAME.key -out $DIR/$NAME.csr
openssl ca -in $DIR/$NAME.csr -extensions v3_ca -config ./openssl.cnf -days 3650 -out $DIR/$NAME.crt -cert $DIR/no2.crt -keyfile $DIR/no2.key
签发有多个common name的证书脚本

pm@debian:~/test/ca$ cat no4domain.sh 
#!/bin/bash
[ $# -ne 1 ] && echo “$0 NAME” && exit
NAME=$1
DIR=$(pwd)/autoget
openssl genrsa -des3 -out $DIR/$NAME.key 2048
openssl rsa -in $DIR/$NAME.key -out $DIR/$NAME.key
openssl req -new -days 3650 -key $DIR/$NAME.key -out $DIR/$NAME.csr -config ./openssl1.cnf
openssl ca -in $DIR/$NAME.csr -extensions v3_ca -config ./openssl1.cnf -days 3650 -out $DIR/$NAME.crt -cert $DIR/no3.crt -keyfile $DIR/no3.key

对应的配置文件是

openssl.cnf文件:

HOME = .
RANDFILE = $ENV::HOME/.rnd
oid_section = new_oids
[ new_oids ]
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
# several ctificates with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem # The private key
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extentions to add to the cert
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = default # use public key default MD
preserve = no # keep passed DN ordering
policy = policy_match
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
string_mask = utf8only
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
0.organizationName_default = Internet Widgits Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
basicConstraints=CA:FALSE
nsComment = “OpenSSL Generated Certificate”
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = CA:true
[ crl_ext ]
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
basicConstraints=CA:FALSE
nsComment = “OpenSSL Generated Certificate”
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
[ tsa ]
default_tsa = tsa_config1 # the default TSA section
[ tsa_config1 ]
dir = ./demoCA # TSA root directory
serial = $dir/tsaserial # The current serial number (mandatory)
crypto_device = builtin # OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem # The TSA signing certificate
# (optional)
certs = $dir/cacert.pem # Certificate chain to include in reply
# (optional)
signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
default_policy = tsa_policy1 # Policy if request did not specify it
# (optional)
other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional)
digests = md5, sha1 # Acceptable message digests (mandatory)
accuracy = secs:1, millisecs:500, microsecs:100 # (optional)
clock_precision_digits = 0 # number of digits after dot. (optional)
ordering = yes # Is ordering defined for timestamps?
# (optional, default: no)
tsa_name = yes # Must the TSA name be included in the reply?
# (optional, default: no)
ess_cert_id_chain = no # Must the ESS cert id chain be included?
# (optional, default: no)

openssl1.cnf

HOME = .
RANDFILE = $ENV::HOME/.rnd
oid_section = new_oids
[ new_oids ]
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
# several ctificates with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem # The private key
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extentions to add to the cert
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = default # use public key default MD
preserve = no # keep passed DN ordering
policy = policy_match
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
string_mask = utf8only
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
0.organizationName_default = Internet Widgits Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
0.commonName = Common Name1 (e.g. server FQDN or YOUR name1)
0.commonName_max = 64
1.commonName = Common Name2 (e.g. server FQDN or YOUR name2)
1.commonName_max = 64
2.commonName = Common Name3 (e.g. server FQDN or YOUR name2)
2.commonName_max = 64
3.commonName = Common Name3 (e.g. server FQDN or YOUR name2)
3.commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
basicConstraints=CA:FALSE
nsComment = “OpenSSL Generated Certificate”
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = CA:true
[ crl_ext ]
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
basicConstraints=CA:FALSE
nsComment = “OpenSSL Generated Certificate”
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
[ tsa ]
default_tsa = tsa_config1 # the default TSA section
[ tsa_config1 ]
dir = ./demoCA # TSA root directory
serial = $dir/tsaserial # The current serial number (mandatory)
crypto_device = builtin # OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem # The TSA signing certificate
# (optional)
certs = $dir/cacert.pem # Certificate chain to include in reply
# (optional)
signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
default_policy = tsa_policy1 # Policy if request did not specify it
# (optional)
other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional)
digests = md5, sha1 # Acceptable message digests (mandatory)
accuracy = secs:1, millisecs:500, microsecs:100 # (optional)
clock_precision_digits = 0 # number of digits after dot. (optional)
ordering = yes # Is ordering defined for timestamps?
# (optional, default: no)
tsa_name = yes # Must the TSA name be included in the reply?
# (optional, default: no)
ess_cert_id_chain = no # Must the ESS cert id chain be included?
# (optional, default: no)

测试了一下,chrome和firefox只能查看最后一个证书 。

========================================

然后就尝试签发有subjectAltName的证书。

对于no4domain.sh 脚本,制定使用的extension配置段,比如v3_ca 

pm@debian:~/test/ca$ cat no4domain.sh |grep -v “^#”
[ $# -ne 1 ] && echo “$0 NAME” && exit
NAME=$1
DIR=$(pwd)/autoget
openssl genrsa -des3 -out $DIR/$NAME.key 2048
openssl rsa -in $DIR/$NAME.key -out $DIR/$NAME.key
openssl req -new -days 3650 -key $DIR/$NAME.key -out $DIR/$NAME.csr -config ./openssl2.cnf
openssl ca -in $DIR/$NAME.csr -extensions v3_ca -config ./openssl2.cnf -days 3650 -out $DIR/$NAME.crt -cert $DIR/no3.crt -keyfile $DIR/no3.key

 

 

pm@debian:~/test/ca$ cat openssl2.cnf |grep -v “^#”|grep -v “^$”
HOME = .
RANDFILE = $ENV::HOME/.rnd
oid_section = new_oids
[ new_oids ]
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = ./demoCA # Where everything is kept
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file.
# several ctificates with same subject.
new_certs_dir = $dir/newcerts # default place for new certs.
certificate = $dir/cacert.pem # The CA certificate
serial = $dir/serial # The current serial number
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL
private_key = $dir/private/cakey.pem # The private key
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extentions to add to the cert
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # how long to certify for
default_crl_days= 30 # how long before next CRL
default_md = default # use public key default MD
preserve = no # keep passed DN ordering
policy = policy_match
[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
string_mask = utf8only
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
0.organizationName_default = Internet Widgits Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name
[ usr_cert ]
basicConstraints=CA:FALSE
nsComment = “OpenSSL Generated Certificate”
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = CA:true
subjectAltName=DNS:*.xx1.net,DNS:*.xx2.net,DNS:xx.com
[ crl_ext ]
authorityKeyIdentifier=keyid:always
[ proxy_cert_ext ]
basicConstraints=CA:FALSE
nsComment = “OpenSSL Generated Certificate”
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
proxyCertInfo=critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo
[ tsa ]
default_tsa = tsa_config1 # the default TSA section
[ tsa_config1 ]
dir = ./demoCA # TSA root directory
serial = $dir/tsaserial # The current serial number (mandatory)
crypto_device = builtin # OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem # The TSA signing certificate
# (optional)
certs = $dir/cacert.pem # Certificate chain to include in reply
# (optional)
signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
default_policy = tsa_policy1 # Policy if request did not specify it
# (optional)
other_policies = tsa_policy2, tsa_policy3 # acceptable policies (optional)
digests = md5, sha1 # Acceptable message digests (mandatory)
accuracy = secs:1, millisecs:500, microsecs:100 # (optional)
clock_precision_digits = 0 # number of digits after dot. (optional)
ordering = yes # Is ordering defined for timestamps?
# (optional, default: no)
tsa_name = yes # Must the TSA name be included in the reply?
# (optional, default: no)
ess_cert_id_chain = no # Must the ESS cert id chain be included?
# (optional, default: no)

这时就可以使用这个证书给多个域名使用了。使用curl的时候可以看到提示subjectAltName matched。

 

发表在 Web server | 留下评论

OOM-killer

  今天碰见个应用。一启动就被干掉了,jboss没有打出什么日志,然后看了下messages里面有OOM-killer.

Jun  1 10:09:15 test kernel: Out of Memory: Killed process 10645 (java).
Jun  1 10:12:28 test kernel: oom-killer: gfp_mask=0x4d0
Jun  1 10:12:28 test kernel: Mem-info:

然后自己第一想到的是直接把OOM-killer关闭掉

echo "0" > /proc/sys/vm/oom-kill 
  

启动应用后就惨了,直接把机器整来hang住了等不进去了,还是用虚拟机,直接强制重启,修复磁盘……

然后就

/etc/sysctl.conf 里添加

vm.lower_zone_protection=300

重新启动应用终于好了。

参考:http://www.redhat.com/archives/taroon-list/2007-August/msg00006.html

 

发表在 Admin | 留下评论

3种常用的ssh端口映射

openssh客户端除了可以作为一个ssh登陆客户端外,还能做一些简单的端口映射,非常使用的。常见的用法有三种:
1.
-D [bind_address:]port
Specifies a local “dynamic” application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and ssh will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file.
-D 指定一个本地端口(如果本地有多个IP的话也可以指定监听某一个IP的端口),充当socks代理的作用的。然后每当有一个到这个端口的链接时,这个链接就被转发到通过ssh隧道转发,
然后再从远程服务器上去链接目的地址。1-1024的端口只有root能转发。
ssh -D 8080 $server
然后浏览器设置代理为127.0.0.1:8080,就可以这样翻墙了。

2. -L [bind_address:]port:host:hostport
Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and aconnection is made to host port hostport from the remote machine. Port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser canforward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However,an explicit bind_address may be used to bind the connection to a specific address. The bind_address of “localhost”indicates that the listening port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces.
-L是指定一个本地端口,port。适用与比如A子网内只有某台服务器A1可以访问另外一个子网B内B1的服务器的某个端口的时候,
在A1服务器上执行 ssh -L 8080:127.0.0.1:80 $b1host
然后A子网内的其他服务器可以通过 http://A1host:8080/ 访问到B1上80端口的web页面。
ssh -L 9091:127.0.0.1:22 blog.gnuers.org
然后就可以本地浏览器打开http://127.0.0.1:9091打开我的blog。

3. -R [bind_address:]port:host:hostport
Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side. This works by allocating a socket to listen to port on the remote side, and whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the local machine. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square braces.

By default, the listening socket on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address ‘*’, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server’s GatewayPorts option is enabled (see sshd_config(5)).

If the port argument is ‘0’, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward the allocated port will be printed to the standard output.
-R 是在远程服务器上指定监听某个端口,当链接远程服务器的这个端口时,数据会转发到本地的hostport上来。
简单的说一种场景,我自己的笔记本是在一个路由器下面,如果这个时候我希望能直接从VPS上sftp链接我的个人笔记本把一些数据上传到笔记本内。
这时就可以使用-R 了。
ssh -R 9090:127.0.0.1:22 blog.gnuers.org
然后在VPS上直接 sftp -P 9090 user@127.0.0.1 就直接登陆上我的笔记本上传东西了。

发表在 System | 留下评论

linux下配置drivel

为了方便有时在linux下更新blog,就安装了一个drivel。
服务器地址选为http://xxx.gnuers.org/xmlrpc.php就行了。

测试一下效果

发表在 System | 留下评论