我正在运行一个应用程序,它构建 ICMP ECHO 请求并将其发送到几个不同的 IP 地址。该应用程序是用 Crystal 编写的。当尝试从 Crystal docker 容器中打开套接字时,Crystal 会引发异常:Permission Denied。
在容器内,我运行ping 8.8.8.8
.
在macos上运行应用程序,我没有问题。
阅读 apparmor 和 seccomp 上的https://docs.docker.com/engine/security/apparmor/和https://docs.docker.com/engine/security/seccomp/页面,我确信我找到了解决方案,但问题仍未解决,即使以docker run --rm --security-opt seccomp=unconfined --security-opt apparmor=unconfined socket_permission
更新/编辑:深入研究之后capabilities(7)
,我在我的 dockerfile 中添加了以下行:RUN setcap cap_net_raw+ep bin/ping
尝试让套接字打开但没有更改。
谢谢!
相关水晶插座代码,完整的工作代码示例如下:
# send request
address = Socket::IPAddress.new host, 0
socket = IPSocket.new Socket::Family::INET, Socket::Type::DGRAM, Socket::Protocol::ICMP
socket.send slice, to: address
Dockerfile:
FROM crystallang/crystal:0.23.1
WORKDIR /opt
COPY src/ping.cr src/
RUN mkdir bin
RUN crystal -v
RUN crystal build -o bin/ping src/ping.cr
ENTRYPOINT ["/bin/sh","-c"]
CMD ["/opt/bin/ping"]
运行代码,首先是本机代码,然后是通过 docker:
#!/bin/bash
crystal run src/ping.cr
docker build -t socket_permission .
docker run --rm --security-opt seccomp=unconfined --security-opt apparmor=unconfined socket_permission
最后,一个 50 行的水晶脚本无法在 docker 中打开套接字:
require "socket"
TYPE = 8_u16
IP_HEADER_SIZE_8 = 20
PACKET_LENGTH_8 = 16
PACKET_LENGTH_16 = 8
MESSAGE = " ICMP"
def ping
sequence = 0_u16
sender_id = 0_u16
host = "8.8.8.8"
# initialize packet with MESSAGE
packet = Array(UInt16).new PACKET_LENGTH_16 do |i|
MESSAGE[ i % MESSAGE.size ].ord.to_u16
end
# build out ICMP header
packet[0] = (TYPE.to_u16 << 8)
packet[1] = 0_u16
packet[2] = sender_id
packet[3] = sequence
# calculate checksum
checksum = 0_u32
packet.each do |byte|
checksum += byte
end
checksum += checksum >> 16
checksum = checksum ^ 0xffff_ffff_u32
packet[1] = checksum.to_u16
# convert packet to 8 bit words
slice = Bytes.new(PACKET_LENGTH_8)
eight_bit_packet = packet.map do |word|
[(word >> 8), (word & 0xff)]
end.flatten.map(&.to_u8)
eight_bit_packet.each_with_index do |chr, i|
slice[i] = chr
end
# send request
address = Socket::IPAddress.new host, 0
socket = IPSocket.new Socket::Family::INET, Socket::Type::DGRAM, Socket::Protocol::ICMP
socket.send slice, to: address
# receive response
buffer = Bytes.new(PACKET_LENGTH_8 + IP_HEADER_SIZE_8)
count, address = socket.receive buffer
length = buffer.size
icmp_data = buffer[IP_HEADER_SIZE_8, length-IP_HEADER_SIZE_8]
end
ping