Docker-java 在java中连接Docker (二) --安全连接

在上一篇文章中简单的进行docker的连接,但是会有暴露端口的漏洞存在,也就是说黑客获取了你的ip地址以及端口号以后可以对你的docker进行破坏(为所欲为),这种方式在实际项目中不可取,必须做安全连接,通过密钥的方式做认证。

如何在服务器上或者本地虚拟机上生成密钥文件可参考官方文档:https://docs.docker.com/engine/security/https/#create-a-ca-server-and-client-keys-with-openssl

或者跟着我的步骤

1.首先选择一个存放密钥文件的地方 我这里选择/home/user/certs来存放 /user/certs是我自己创建的  进到certs文件中运行openssl genrsa -aes256 -out ca-key.pem 4096 

[root@ywh certs]# openssl genrsa -aes256 -out ca-key.pem 4096
Generating RSA private key, 4096 bit long modulus
.........................++
..............................................................................................................................................++
e is 65537 (0x10001)
Enter pass phrase for ca-key.pem:               //这里会让设置密码我设置的是123456 这个以后会用到
Verifying - Enter pass phrase for ca-key.pem:   //这里是让你再次输入密码确认密码不会显示出来,你只管输入按回车就可以了
[root@ywh certs]# 

2.运行:openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem  最后还有个邮箱的我没有放上来 填什么都行

[root@ywh certs]# openssl genrsa -aes256 -out ca-key.pem 4096
Generating RSA private key, 4096 bit long modulus
.........................++
..............................................................................................................................................++
e is 65537 (0x10001)
Enter pass phrase for ca-key.pem:   //输入你刚才的密码
Verifying - Enter pass phrase for ca-key.pem:
[root@ywh certs]# openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
Enter pass phrase for ca-key.pem:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn       //从这开始让你输入一些信息以便进行加密,其实填什么也无所谓
State or Province Name (full name) []:ywh
Locality Name (eg, city) [Default City]:bj
Organization Name (eg, company) [Default Company Ltd]:xx
Organizational Unit Name (eg, section) []:xx
Common Name (eg, your name or your server's hostname) []:192.168.0.3   //值得注意的是这里要填写你的ip地址

3.运行:openssl genrsa -out server-key.pem 4096 生成server-key.pem

[root@ywh certs]# openssl genrsa -out server-key.pem 4096
Generating RSA private key, 4096 bit long modulus
................................................................++
.........................++
e is 65537 (0x10001)

4.运行:openssl req -subj "/CN=192.168.0.3" -sha256 -new -key server-key.pem -out server.csr  CN中写你在上面填写的IP

openssl req -subj "/CN=192.168.0.3" -sha256 -new -key server-key.pem -out server.csr

5.运行:echo subjectAltName = DNS:192.168.0.3,IP:192.168.0.3,IP:0.0.0.0,IP:127.0.0.1 >> extfile.cnf  配置哪些主机可以访问你 0.0.0.0代表所有主机都可以通过密钥文件的方式访问

6.运行:echo extendedKeyUsage = serverAuth >> extfile.cnf

7.运行:openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem  -CAcreateserial -out server-cert.pem -extfile extfile.cnf


[root@ywh certs]# openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
>   -CAcreateserial -out server-cert.pem -extfile extfile.cnf
Signature ok
subject=/CN=192.168.0.3
Getting CA Private Key
Enter pass phrase for ca-key.pem:

8.运行:openssl genrsa -out key.pem 4096

9.运行:openssl req -subj '/CN=client' -new -key key.pem -out client.csr

10.运行:echo extendedKeyUsage = clientAuth >> extfile.cnf

11.运行:openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile.cnf

[root@ywh certs]# openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
>   -CAcreateserial -out cert.pem -extfile extfile.cnf
Signature ok
subject=/CN=client
Getting CA Private Key
Enter pass phrase for ca-key.pem:

12.rm -v client.csr server.csr 删除临时文件 

     配置权限chmod -v 0400 ca-key.pem key.pem server-key.pem 

     和chmod -v 0444 ca.pem server-cert.pem cert.pem

[root@ywh certs]# rm -v client.csr server.csr
rm:是否删除普通文件 "client.csr"?y
已删除"client.csr"
rm:是否删除普通文件 "server.csr"?y
已删除"server.csr"
[root@ywh certs]# chmod -v 0400 ca-key.pem key.pem server-key.pem
mode of "ca-key.pem" changed from 0644 (rw-r--r--) to 0400 (r--------)
mode of "key.pem" changed from 0644 (rw-r--r--) to 0400 (r--------)
mode of "server-key.pem" changed from 0644 (rw-r--r--) to 0400 (r--------)
[root@ywh certs]# chmod -v 0444 ca.pem server-cert.pem cert.pem
mode of "ca.pem" changed from 0644 (rw-r--r--) to 0444 (r--r--r--)
mode of "server-cert.pem" changed from 0644 (rw-r--r--) to 0444 (r--r--r--)
mode of "cert.pem" changed from 0644 (rw-r--r--) to 0444 (r--r--r--)
[root@ywh certs]# 

现在在/home/user/certs下应该有8个文件

[root@ywh certs]# ll
总用量 32
-r--------. 1 root root 3326 8月  30 10:44 ca-key.pem
-r--r--r--. 1 root root 2065 8月  30 10:48 ca.pem
-rw-r--r--. 1 root root   17 8月  30 11:04 ca.srl
-r--r--r--. 1 root root 1895 8月  30 11:04 cert.pem
-rw-r--r--. 1 root root  117 8月  30 11:04 extfile.cnf
-r--------. 1 root root 3243 8月  30 11:03 key.pem
-r--r--r--. 1 root root 1899 8月  30 11:02 server-cert.pem
-r--------. 1 root root 3247 8月  30 10:53 server-key.pem

13.找docker.service文件 vi /lib/systemd/system/docker.service下的ExecStart添加

-D --tlsverify=true --tlscert=/home/user/certs/server-cert.pem --tlskey=/home/user/certs/server-key.pem --tlscacert=/home/user/certs/ca.pem -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd -D --tlsverify=true --tlscert=/home/user/certs/server-cert.pem --tlskey=/home/user/certs/server-key.pem --tlscacert=/home/user/certs/ca.pem -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock
ExecReload=/bin/kill -s HUP $MAINPID
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
#TasksMax=infinity
TimeoutStartSec=0
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
# kill only the docker process, not all processes in the cgroup
KillMode=process
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

14.运行

systemctl daemon-reload 

service docker restart  //重启docker

systemctl status docker //这条命令可以看见你是否设置的生效

配置好安全连接以后在地址栏中是不可以访问的了,如果还可以访问是不对的 因为你没有使用密钥文件的方式访问

这时候需要通过密钥来认证以后才能访问了,首先把密钥文件下载到本机的磁盘上,可以使用【sz  你的文件名】命令把文件传输到本机磁盘上

如果显示没有sz命令,可以使用yum install lrzsz下载,下载完可以直接使用,可以看到我在f://data//local下载了四个文件

docker-java官方推荐连接方式为:(这种连接方式是在你对2375做了安全连接以后才能用的,如果没有做安全连接请使用我上一篇文章的方法进行连接)

//进行安全认证
DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerTlsVerify(true)
		.withDockerCertPath("F:/data/local/").withDockerHost("tcp://192.168.0.3:2375")
		.withDockerConfig("F:/data/local/").withApiVersion("1.38").withRegistryUrl("https://index.docker.io/v1/")
		.withRegistryUsername("dockeruser").withRegistryPassword("ilovedocker")
		.withRegistryEmail("[email protected]").build();
DockerCmdExecFactory dockerCmdExecFactory =  new  JerseyDockerCmdExecFactory()
		  .withReadTimeout(1000)
		  .withConnectTimeout(1000)
		  .withMaxTotalConnections(100)
		  .withMaxPerRouteConnections(10);
//进行连接
DockerClient dockerClient = DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(dockerCmdExecFactory).build();
Info info = dockerClient.infoCmd().exec();
System.out.println(info);

dockerHost:地址是你docker所在的宿主机的外网地址以及你开放的端口号

dockercertPath:放入的是你密钥在windows的文件存放地址

dockerconfig:放的是什么我不太清楚,但是我放入密钥文件地址也没出错

apiVersion:dockerAPI的版本,可通过docker version命令在宿主机上获取版本号

RegistryUrl:这个按着默认的写即可

.withRegistryUsername("dockeruser"):默认

.withRegistryPassword("ilovedocker"):默认

.withRegistryEmail("[email protected]"):默认

输出:跟在地址栏访问获得的结果是一样的,都是以json格式展示

com.github.dockerjava.api.model.Info@2e54db99
[architecture=x86_64,containers=1,containersStopped=1,containersPaused=0,containersRunning=0,cpuCfsPeriod=true,cpuCfsQuota=true,cpuShares=true,cpuSet=true,debug=true,discoveryBackend=<null>,dockerRootDir=/var/lib/docker,driver=overlay2,driverStatuses=[[Backing Filesystem, xfs], [Supports d_type, true], [Native Overlay Diff, true]],systemStatus=<null>,plugins={Volume=[local], Network=[bridge, host, macvlan, null, overlay], 
Authorization=null, Log=[awslogs, fluentd, gcplogs, gelf, journald, json-file, logentries, splunk, syslog]},executionDriver=<null>,
loggingDriver=json-file,
experimentalBuild=false,httpProxy=,httpsProxy=,id=MID4:FUBP:XWQB:TBNV:LPLN:IUIU:32MG:HBYM:6O2K:HBUW:257R:7DY4,ipv4Forwarding=true,bridgeNfIptables=true,
bridgeNfIp6tables=true,images=1,indexServerAddress=https://index.docker.io/v1/,initPath=<null>,initSha1=<null>,kernelVersion=3.10.0-862.el7.x86_64,labels={},
memoryLimit=true,memTotal=1910075392,name=ywh,ncpu=4,nEventsListener=0,nfd=24,nGoroutines=47,noProxy=,oomKillDisable=true,osType=linux,oomScoreAdj=<null>,
operatingSystem=CentOS Linux 7 (Core),registryConfig=com.github.dockerjava.api.model.InfoRegistryConfig@6d24ffa1[indexConfigs={docker.io=com.github.dockerjava.api.model.InfoRegistryConfig$IndexConfig@65a4798f[mirrors=[https://tpp5ie36.mirror.aliyuncs.com/],name=docker.io,official=true,secure=true]},insecureRegistryCIDRs=[127.0.0.0/8],mirrors=[https://tpp5ie36.mirror.aliyuncs.com/]],sockets=<null>,swapLimit=true,systemTime=2018-08-30T11:38:18.472151804+08:00,serverVersion=18.06.1-ce,clusterStore=,clusterAdvertise=,swarm=SwarmInfo[nodeID=,nodeAddr=,localNodeState=INACTIVE,controlAvailable=false,error=,remoteManagers=<null>,nodes=<null>,managers=<null>,clusterInfo=<null>]]

以上就可以在java中连接docker-api了,可以进行安全的连接了,没有密钥文件是不可能访问到的。

猜你喜欢

转载自blog.csdn.net/qq_36956154/article/details/82180551
今日推荐