Erlang如何限制节点对集群的访问之net_kernel:allow

来源:互联网 发布:网络摄像头电源多少伏 编辑:程序博客网 时间:2024/04/27 22:12

本文转载自yufeng.info


默认情况下Erlang的集群访问是全授权的,只要cookie认证过了后,新加入的节点可以访问集群里面的任何机器,这给运维带来很大风险。目前erlang有二种方法可以限制 1. IP网段限制,参看这里 2. 节点名称限制。这个是通过net_kernel:allow来实现的,参看:

allow/1
Limits access to the specified set of nodes. Any access attempts made from (or to) nodes not in Nodes will be rejected.

Returns error if any element in Nodes is not an atom.

我们假设集群有节点x,y,z, foo:
1. 有个节点叫foo, 它只允许来自x,y节点的请求,其他的节点访问被拒;
2. z只能访问x,其他拒

我们来试验下:

view source
print?
$ erl -name foo@127.0.0.1
Erlang R14B04 (erts-5.8.5) 1 [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
  
Eshell V5.8.5  (abort with ^G)
(foo@127.0.0.1)1> net_kernel:allow(['x@127.0.0.1','y@127.0.0.1']).
ok
(foo@127.0.0.1)2>

在其他终端运行:

view source
print?
$ erl -name x@127.0.0.1
Erlang R14B04 (erts-5.8.5) 1 [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
  
Eshell V5.8.5  (abort with ^G)
(x@127.0.0.1)1> net_adm:ping('foo@127.0.0.1').
pong
(x@127.0.0.1)2> 
  
$ erl -name y@127.0.0.1
Erlang R14B04 (erts-5.8.5) 1 [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
  
Eshell V5.8.5  (abort with ^G)
(y@127.0.0.1)1> net_adm:ping('foo@127.0.0.1').
pong
(y@127.0.0.1)2> 
  
$ erl -name z@127.0.0.1
Erlang R14B04 (erts-5.8.5) 1 [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
  
Eshell V5.8.5  (abort with ^G)
(z@127.0.0.1)1> net_adm:ping('foo@127.0.0.1').
pang
(z@127.0.0.1)2> net_adm:ping('y@127.0.0.1').
pong
(z@127.0.0.1)3> net_kernel:disconnect('y@127.0.0.1').
true
(z@127.0.0.1)4> net_kernel:allow(['x@127.0.0.1']).
ok
(z@127.0.0.1)5> net_adm:ping('y@127.0.0.1').         
  
=ERROR REPORT==== 24-Oct-2011::01:23:34 ===
** Connection attempt with disallowed node'y@127.0.0.1'** 
pang

同时我们会在foo的终端上看到:

view source
print?
=ERROR REPORT==== 24-Oct-2011::01:08:20 ===
** Connection attempt from disallowed node'z@127.0.0.1'** 
(foo@127.0.0.1)2>

看代码:

view source
print?
...
%% dist_util.erl
%%                                                                                                                           
%% check if connecting node is allowed to connect                                                                            
%% with allow-node-scheme                                                                                                    
%%                                                                                                                           
is_allowed(#hs_data{other_node = Node,
                    allowed =Allowed} =HSData) ->
    caselists:member(Node,Allowed)of
        falsewhenAllowed=/= [] ->
            send_status(HSData, not_allowed),
            error_msg("** Connection attempt from "
                      "disallowed node ~w ** ~n", [Node]),
            ?shutdown(Node);
        _ -> true
    end.
...

可以知道如果Allowed空的话,代表不做任何限制,否则net_kernel:allow限制主动和被动连接的节点。

祝玩得开心!