天天看點

ElasticSearch更新至6.8.4并使用xpack進行安全加強

一、引言

喜歡關注安全問題的朋友可能對MongoDB資料庫的lesuo事件有過了解,整件事情其實在一定程度上來說是可以進行規避的,如果使用者沒有使用MongoDB的預設安全設定或是直接裸跑在伺服器上就不會導緻資料外洩,也就不會被黑客用資料庫資料進行勒索。當然這個安全事故隻是一個例子而已,在我們的日常開發環境或一些生産環境上不免也會遇到這樣的安全問題,不管是伺服器安全、資料安全還是我們開發時使用的中間件的安全都是不能夠被忽略掉的。本文就為你簡單講解一下如何加強你的ElasticSearch,為你的海量資料保駕護航。

二、基本情況簡介及更新前準備

1、本次使用的環境是centos7和docker-compose 1.1.8。

首先我通過docker-compose方式分别部署了版本為6.6.0的一套ElasticSearch和一套Kibana服務,然後本次需要将ElasticSearch更新到6.8.4并加上安全驗證功能。

2、準備好6.8.4版本的ik分詞器放入現ElasticSearch配置對應的插件目錄;

3、環境介紹:

A、在根目錄下建立docker目錄存放一些配置檔案、日志紀錄和資料存儲
[[email protected] ~]# cd /docker/
[[email protected] docker]# ls
elasticsearch  kibana
[[email protected] docker]# pwd
/docker
[[email protected] docker]# ls
elasticsearch  kibana
[[email protected] docker]# ls elasticsearch/
config  data  data-bak  logs  plugins
[[email protected] docker]# ls kibana/
config  data
[[email protected] docker]#  
           
B、在opt目錄下建立docker-compose目錄存放docker-compose.yml以及一些中間件的docker-compose的yml檔案:
[[email protected] docker-compose]# ls
docker-compose.yml
[[email protected] docker-compose]# pwd
/opt/docker-compose
[[email protected] docker-compose]#
           

三、開始更新

1、更新ElasticSearch和Kibana:修改image對應的版本為6.8.4

[[email protected] docker-compose]# cat docker-compose.yml
version: '3'
services:
  elasticsearch:
    image: elasticsearch:6.8.4 //原先為6.6.0,本次需更新至6.8.4
    environment:
      TZ: Asia/Shanghai
    volumes:
      - /docker/elasticsearch/data:/usr/share/elasticsearch/data
      - /docker/elasticsearch/config:/usr/share/elasticsearch/config
      - /docker/elasticsearch/plugins:/usr/share/elasticsearch/plugins
      - /etc/localtime:/etc/localtime
    container_name: elasticsearch
    network_mode: host
    restart: always

  kibana:
    image: kibana:6.8.4  //原先為6.6.0,本次需更新至6.8.4
    environment:
      TZ: Asia/Shanghai
    volumes:
      - /docker/kibana/data:/usr/share/kibana/data
      - /docker/kibana/config:/usr/share/kibana/config
      - /etc/localtime:/etc/localtime
    container_name: kibana
    network_mode: "host"
    restart: always
[[email protected] docker-compose]#
           

修改好後docker-compose.yml後将原先運作的elasticSearch和kibana服務關閉,并重新開機

[[email protected] docker-compose]# docker-compose -f /opt/docker-compose/docker-compose.yml down
Stopping elasticsearch ... done
Stopping kibana        ... done
Removing elasticsearch ... done
Removing kibana        ... done
[[email protected] docker-compose]# docker-compose -f /opt/docker-compose/docker-compose.yml up -d
Pulling kibana (kibana:6.8.4)...
6.8.4: Pulling from library/kibana
d8d02d457314: Already exists
6962446443a4: Pull complete
628f51417676: Pull complete
4dc1cdc8a1d9: Pull complete
9d3bfb93ff44: Pull complete
7dcfacc7c91b: Pull complete
d98901bd2778: Pull complete
71248cd8cef2: Pull complete
Digest: sha256:c422412b8b554f484b375a97c561151a1456c29465b6e59e322bdaecc8ad7d85
Status: Downloaded newer image for kibana:6.8.4
Creating kibana ... done
Creating elasticsearch ..
[[email protected] docker-compose]# docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS               NAMES
d33777fc3863        elasticsearch:6.8.4   "/usr/local/bin/dock…"   10 seconds ago      Up 9 seconds                            elasticsearch
569cdde73001        kibana:6.8.4          "/usr/local/bin/kiba…"   10 seconds ago      Up 9 seconds                            kibana
[[email protected] docker-compose]#  

           

2、添加ElasticSearch安全驗證配置

  修改/docker/elasticsearch/config目錄下的elasticsearch.yml配置檔案,添加配置:

[[email protected] config]# cat elasticsearch.yml
cluster.name: "qgs-elasticsearch"
http.port: 9201
transport.tcp.port: 9301
network.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin: "*"
# 添加 x-pack驗證,打開安全驗證和傳輸安全驗證
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
[[email protected] config]#
           

修改好配置後重新開機ElasticSerch服務并進入到容器内部進行使用者權限設定:

進入到容器内部通過以下指令建立elasticsearch的使用者名密碼:elasticsearch.keystore

[[email protected] elasticsearch]# bin/elasticsearch-setup-passwords -h
Sets the passwords for reserved users
Commands
--------
auto - Uses randomly generated passwords  //設定預設的使用者名密碼
interactive - Uses passwords entered by a user //對預設的使用者elastic設定自己的密碼

Non-option arguments:
command

Option         Description
------         -----------
-h, --help     show help
-s, --silent   show minimal output
-v, --verbose  show verbose output
[[email protected] elasticsearch]# bin/elasticsearch-keystore create   //建立elasticsearch.keystore檔案
An elasticsearch keystore already exists. Overwrite? [y/N]y
Created elasticsearch keystore in /usr/share/elasticsearch/config
[[email protected] elasticsearch]# bin/elasticsearch-setup-passwords interactive  //設定密碼指令
Enter password for [elastic]: //輸入要設定的密碼
Reenter password for [elastic]:
Enter password for [apm_system]:
Reenter password for [apm_system]:
Enter password for [kibana]:
Reenter password for [kibana]:
Enter password for [logstash_system]:
Reenter password for [logstash_system]:
Enter password for [beats_system]:
Reenter password for [beats_system]:
Enter password for [remote_monitoring_user]:
Reenter password for [remote_monitoring_user]:
Changed password for user [apm_system]
Changed password for user [kibana]
Changed password for user [logstash_system]
Changed password for user [beats_system]
Changed password for user [remote_monitoring_user]
Changed password for user [elastic]
           

注意

在執行指令 bin/elasticsearch-setup-passwords interactive的時候可能會出現以下錯誤:
Possible causes include:
 * The password for the 'elastic' user has already been changed on this cluster
 * Your elasticsearch node is running against a different keystore
 * This tool used the keystore at /usr/share/elasticsearch/config/elasticsearch.keystore
           

出現這個錯誤表面是密碼已經設定過了,如果忘記了之前設定的密碼可以根據以下操作進行密碼重置:

  • 關閉ElasticSearch的xpack安全驗證(即修改/docker/elasticsearch/config/elasticsearch.yml

    中的xpack.security.enabled和xpack.security.transport.ssl.enabled為false);

  • 重新開機ElasticSearch服務
  • 重新開機好後用以下指令删除索引 .secutity-6
curl -XDELETE http://localhost:9201/.secutity-6
           
  • 删除好後再重新按照上面設定密碼的操作打開xpack驗證重新開機ElasticSearch服務進入容器内部進行密碼設定

設定好使用者名密碼後測試是否成功:

浏覽器中通路es服務如果彈出提示框要輸入使用者名密碼則說明開啟安全驗證是成功的,然後輸入設定的使用者名密碼進行登入進行登入

ElasticSearch更新至6.8.4并使用xpack進行安全加強

登入成功方可檢視到以下界面:

ElasticSearch更新至6.8.4并使用xpack進行安全加強

3、添加Kibana安全驗證配置

修改/docker/kibana/config目錄下的kibana.yml檔案,修改内容如下:

[[email protected] kibana]# cat config/kibana.yml
# Default Kibana configuration from kibana-docker.
server.name: kibana
server.host: "0.0.0.0"
elasticsearch.url: http://localhost:9201  //配置ElasticSearch的服務位址
elasticsearch.username: "elastic"         //配置ElasticSearch的使用者名
elasticsearch.password: "[email protected]"       //配置ElasticSearch的密碼
xpack.monitoring.ui.container.elasticsearch.enabled: false
[[email protected] kibana]#
           

重新開機kibana服務後在浏覽器上通路對應ip和kibana的端口正常結果如下:

ElasticSearch更新至6.8.4并使用xpack進行安全加強

四、添加自定義使用者組

        以上的操作是使用ElasticSearch的預設使用者elastic,擁有最高的操作權限。當然我們在實際的應用場景中我們也可以自己定義使用者組,使用自定義的使用者權限。

  • 首先在/docker/elasticsearch/config目錄下建立users 、user_roles倆目錄
[[email protected] elasticsearch]# cd config/
[[email protected] config]# ls
elasticsearch.keystore  elasticsearch.yml  jvm.options  log4j2.properties  synonyms
[[email protected] config]# touch users
[[email protected] config]# touch users_roles
[[email protected] config]# chmod -R 777 users
[[email protected] config]# chmod -R 777 users_roles
[[email protected] config]# ls
elasticsearch.keystore  elasticsearch.yml  jvm.options  log4j2.properties  synonyms  users  users_roles
[[email protected] config]#
           
  • 進入到ElasticSearch容器内并檢視自定義使用者相關指令
[[email protected]]# docker exec -it elasticsearch bash
[[email protected] elasticsearch]# bin/elasticsearch-users -h
Manages elasticsearch file users
Commands
--------
useradd - Adds a file user                                             //添加使用者指令
userdel - Deletes a file based user                                    //删除使用者
passwd - Changes the password of an existing file based user           //修改現有使用者密碼
roles - Edit roles of an existing user                                 //修改使用者角色
list - List existing file based users and their corresponding roles    //展示現有的使用者資料
Non-option arguments:
command
Option         Description
------         -----------
-h, --help     show help
-s, --silent   show minimal output
-v, --verbose  show verbose output
           
  • 添加自定義使用者
[[email protected] elasticsearch]# bin/elasticsearch-users useradd testElastic
Enter new password:
Retype new password:
eruserlocalhost elasticsearch]# bin/elasticsearch-users roles testElastic -a super
[[email protected] elasticsearch]#
           
  • 添加好自定義使用者後同理根據以上的方式測試使用者是否可用;

五、如何接入現有springboot項目

  • 首先在項目的application.yml配置中找到ES的配置,添加token項:
# es配置資訊:
elasticsearch:
  host: 192.168.X.XXX
  port: 920
  url: http://192.168.X.XXX:9201
  token: 這裡填寫ElasticSearch中配置的使用者名密碼生成的token
  reactorConfig:
    connectTimeout: 3000
    soTimeout: 3000
    ioThreadCount: 4
  requestConfig:
    connectionRequestTimeout: 3000
  maxRetryTimeout: 6000
           
注:這裡的token是使用Base64的方式進行加密的,我們可以在控制台輸入以下指令進行擷取token:
## echo -n ES配置的使用者名:ES配置的使用者密碼 | base64
[email protected]:~$ echo -n test:test | base64
dGVzdDp0ZXN0
[email protected]:~$
           
  • 修改項目中ES配置類:
@Configuration
public class ESConfig {
    @Value("${elasticsearch.url}")
    private String url;
    @Value("${elasticsearch.token}")
    private String token;

    @Value("${sync.elasticsearch.url}")
    private String syncLogUrl;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Bean(destroyMethod = "close", name = "highLevelClient")
    public RestHighLevelClient highLevelClient() {
        RestClientBuilder builder = RestClient.builder(HttpHost.create(url));
        //添加es安全認證
        Header[] defaultHeaders = new Header[]{new BasicHeader("Authorization", "Basic " + token.trim())};
        builder.setDefaultHeaders(defaultHeaders);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        logger.info("Elasticsearch init url:{}", url);
        return client;
    }

    @Bean(destroyMethod = "close", name = "syncLogHighLevelClient")
    public RestHighLevelClient syncLogHighLevelClient() {
        RestClientBuilder builder = RestClient.builder(HttpHost.create(syncLogUrl));
        //添加es安全認證
        Header[] defaultHeaders = new Header[]{new BasicHeader("Authorization", "Basic " + token.trim())};
        builder.setDefaultHeaders(defaultHeaders);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        logger.info("Elasticsearch init url:{}", syncLogUrl);
        return client;
    }
}
           
這裡主要是在每一次請求ES的時候在請求頭上添加我們配置的token。

六、注意事項

  • 在設定ElasticSearch或Kibana的端口時盡量避免使用一些預設的端口,這樣可以避免别人一看這個端口就知道這個服務是做什麼用的;
  • 在設定使用者名密碼時,盡量将密碼複雜度提高;
  • 在使用中間件服務時盡量不使用預設的配置;

這裡粗略的講解了一下如何給ElasticSearch更新并做簡單的安全加強,如若有不妥之處,請及時聯系我進行更正,以便誤導。

繼續閱讀