Elasticsearch

ElasticSearch,Kibana,filebeat,Logstashを構築してaccesslog解析

2024年3月31日



目的

– Elasticsearch,Kibana,filebeat,Logstashを構築してaccesslogを解析、視覚化する
– ※ 3/22 kibanaにてログを検出しない事象切り分け中(手順:accesslogを収集テスト1(logstash設定))

環境

– Elasticsearch + Kibanaサーバ
– ホスト:192.168.y.y
– Ubuntu 20.04
– Elasticsearch 8.12.2
– Kibana 8.12.2

– accesslog収集対象クライアント(filebeat + logstash)
– ホスト:192.168.x.x
– filebeat 8.12.2
– logstash 1.8.12.2-1
– 収集対象ログ /var/log/test_accesslog.log

参考

– filebeat
– https://192.168.y.y:5601/app/home#/tutorial/logstashLogs

– logstash
– https://www.elastic.co/guide/en/logstash/7.17/logstash-settings-file.html
– https://blog.estampie.work/archives/2265
– https://wisdom-gate.jp/blog/2019/04/30/elastic-stack%E3%81%AE%E6%AD%A9%E3%81%8D%E3%81%8B%E3%81%9F5/

Elasticsearch導入

インストール

– GPG公開鍵ダウンロード


$ wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-keyring.gpg

– apt-transport-https install


$ sudo apt-get install apt-transport-https

– apt list更新


$ echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list

– apt update


$ sudo apt update

– elasticsearch install


$ sudo apt install elasticsearch

--------------------------- Security autoconfiguration information ------------------------------

Authentication and authorization are enabled.
TLS for the transport and HTTP layers is enabled and configured.

The generated password for the elastic built-in superuser is : Fhde3Z0NxCbKY6OH_GQy
※パスワードはメモしておく。kibanaからelasticsearchにアクセスする際に必要

サービス起動

– 自動起動ON


$ systemctl enable elasticsearch.service

– サービス起動


$ systemctl start elasticsearch.service

Elasticsearch設定

– rootユーザで変更する

/etc/elasticsearch/elasticsearch.yml

– ホスト情報


node.name: elastic01.murci.local
network.host: 0.0.0.0
http.port: 9200

– SSL無効化(クライアントからの接続にはhttpを使用)


xpack.security.enabled: false
xpack.security.enrollment.enabled: false
xpack.security.http.ssl:  enabled: false
xpack.security.transport.ssl:  enabled: false

– 接続許可対象


http.host: 0.0.0.0

サービス再起動


# systemctl restart elasticsearch.service

Kibana導入

– クライアントからKibanaへhttpsでアクセスさせるため、事前に自己署名証明書を作成する

SSL自己署名証明書の作成

– rootユーザで実行する
– ドメイン定義


# vi /etc/ssl/openssl.cnf
-----追記
[ murci.local ]
subjectAltName = DNS:murci.local

– 作業ディレクトリ(/etc/ssl/private)に移動


# pwd
/etc/ssl/private

– 秘密鍵の生成


# openssl genrsa -aes128 2048 > server.key

– パスワードを消す


# openssl rsa -in server.key -out server.key

– CSRの生成


# openssl req -utf8 -new -key server.key -out server.key -out server.csr

– 自己署名証明書の生成


# openssl x509 -in server.csr -out server.crt -req -signkey server.key -extfile /etc/ssl/openssl.cnf -extensions murci.local -days 3650

Kibanaインストール

– apt install


$ sudo apt install kibana

– SSL証明書、秘密鍵をコピー


# cp /etc/ssl/private/{server.crt,server.key} /etc/kibana/
# chown kibana /etc/kibana/{server.crt,server.key}
# ll /etc/kibana
:
total 36
-rw-r--r--   1 kibana kibana 1419 Mar  7 02:47 server.crt
-rw-------   1 kibana kibana 1675 Mar  7 02:47 server.key

Kibana設定

– rootユーザで変更する

/etc/kibana/kibana.yml


# =================== System: Kibana Server ===================
server.port: 5601
server.host: "0.0.0.0"    ※すべてのホストからのアクセスを許可

# =================== System: Kibana Server (Optional) ===================
server.ssl.enabled: true
server.ssl.certificate: /etc/kibana/server.crt
server.ssl.key: /etc/kibana/server.key

# =================== System: Elasticsearch ===================
elasticsearch.hosts: ["http://localhost:9200"]

サービス起動

– 自動起動ON


$ systemctl enable kibana.service

– サービス起動


$ systemctl start kibana.service

ブラウザでKibanaへアクセス

– 下記URLへログインする
– https://192.168.y.y:5601
– Username : elastic
– Password : Elasticsearchのインストール時にメモしたパスワード

Filebeat導入

– accesslogを収集する対象のクライアントにて実行する

Filebeatインストール

– パッケージダウンロード、インストール


$ curl -L -O https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-8.12.2-darwin-x86_64.tar.gz
$ tar xzvf filebeat-8.12.2-darwin-x86_64.tar.gz
$ cd filebeat-8.12.2-darwin-x86_64/
$ dpkg -i filebeat-8.12.2-amd64.deb

Filebeat設定

– rootユーザで変更する

/etc/filebeat/filebeat.yml

– Outputは、直接Elasticsearchに送信するか、logstashでデータ加工を行うか選択できる


# ============================== Filebeat inputs ===============================
filebeat.inputs:

# filestream is an input for collecting log messages from files.
#- type: filestream
- type: log 

  # Unique ID among all inputs, an ID is required.
  id: test_accesslog

  # Change to true to enable this input configuration.
  enabled: true

  paths:
    - /var/log/test_accesslog.log   ※収集対象のログファイルを指定

# ---------------------------- Elasticsearch Output ----------------------------
output.elasticsearch:
  # Array of hosts to connect to.
  hosts: ["192.168.y.y:9200"]

  # Authentication credentials - either API key or username/password.
  #api_key: "id:api_key"
  username: "elastic"
  password: "xxxxxxxxxxxx"    ※Elasticsearchのインストール時にメモしたパスワード

# ------------------------------ Logstash Output -------------------------------
#output.logstash:
  # The Logstash hosts
  hosts: ["localhost:5044"]

サービス起動

– 自動起動ON


$ systemctl enable filebeat.service

– サービス起動


$ systemctl start filebeat.service

Logstash導入

– accesslogを収集する対象のクライアントにて実行する

Logstashインストール

– apt-transport-https install


$ sudo apt-get install apt-transport-https

– apt list更新


$ echo "deb [signed-by=/usr/share/keyrings/elastic-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-8.x.list

– logstash install


$ sudo apt install logstash

Logstash設定

– rootユーザで変更する

/etc/logstash/logstash.yml
– 下記追記する


input {
  file {
    #    path => "/usr/share/logstash/example-data/apache_log"
    path => "/var/log/test_accesslog.log"
    mode => "read"
    file_completed_action => "log"
    file_completed_log_path => "/var/log/test_accesslog.log"
  }
}
filter {
  grok {        ※grokでログの各カラムのデータ型を定義する
    match => { "message" => '%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response:int} (?:-|%{NUMBER:bytes:int}) %{QS:referrer} %{QS:agent}' }
  }
  date {
    match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
    locale => "en"
  }
}
output {
  elasticsearch {
    hosts => [ "192.168.y.y:9200" ]
    index => "test_accesslog"
  }
}

サービス起動

– 自動起動ON


$ systemctl enable logstash.service

– サービス起動


$ systemctl start logstash.service

accesslogを収集テスト1(logstash設定)

– accesslogを収集する設定を行う

ブラウザでKibanaへアクセス

– 下記URLへログインする
– https://192.168.y.y:5601
– Username : elastic
– Password : Elasticsearchのインストール時にメモしたパスワード

Index Management

– Indexを作成する
– 「≡」> 「Management」 > 「Data」 > 「Index Management」 > 「Create index」 >
– Name : test_accesslog

Data Views

– Data Viewsを作成する
– 「≡」>「Management」>「Kibana」>「DataViews」>「Create data view」>
– Name : test_accesslog
– Index Pattern : test_accesslog ※前述で作成したIndexを指定する
– Timestamp field : timestamp ※logstash.ymlで設定した「type:date」が反映されていれば、プルダウンから選択可能

Dashboard

– 前述の設定後に、実際にaccesslogが取り込まれているかを確認する
– 「≡」>「Analytics」>「Dashboard」>「Create Dashboard」>「Create visualization」>左上のプルダウンから「Find a data view」で「test_accesslog」を検索する
– 右上のプルダウンから日時指定をする(デフォルトで直近15分前までのログ)
– データがグラフで表示されることを確認
– ※ 3/22時点で未運用、kibanaにてログを検出しない事象切り分け中

accesslogを収集テスト2(手動コマンド)

– コマンドでIndexとMappingを作成する
– クライアントからデータを送信して、Elasticsearchが正常に受領できるか確認する
– Elasticsearchサーバ(localhost)にて下記コマンド実行する場合を想定

Index作成

– index作成
– 認証する場合は、”curl -u elastic ~”


$ curl -X PUT "http://127.0.0.1:9200/test_accesslog?pretty"
{                                                                                    
  "acknowledged" : true,  
  "shards_acknowledged" : true,                                                      
  "index" : "test_accesslog"                                                            
}    

– index作成確認


$ curl http://127.0.0.1:9200/test_accesslog/_settings?pretty
{
  "test_accesslog" : {
    "settings" : {
      "index" : {
        "routing" : {
          "allocation" : {
            "include" : {
              "_tier_preference" : "data_content"
            }
          }
        },
        "number_of_shards" : "1",
        "provided_name" : "test_accesslog",
        "creation_date" : "1711600014873",
        "number_of_replicas" : "1",
        "uuid" : "g1uXv1E4RMGCM4PPbwzlTQ",
        "version" : {
          "created" : "8500010"
        }
      }
    }
  }
}

– index削除


$ curl -X DELETE "http://127.0.0.1:9200/test_accesslog"

Index,mapping作成

– indexとmapping作成
– 下記の11フィールドを設定する


$ curl -X PUT "127.0.0.1:9200/test_accesslog" -H 'Content-Type: application/json' -d '{
  "mappings": {
    "properties": {
      "clientip": { "type": "ip" },
      "ident": { "type": "keyword" },
      "auth": { "type": "keyword" },
      "timestamp": { "type": "date", "format": "dd/MMM/yyyy:HH:mm:ss Z" },
      "verb": { "type": "keyword" },
      "request": { "type": "text" },
      "httpversion": { "type": "float" },
      "response": { "type": "integer" },
      "bytes": { "type": "integer" },
      "referrer": { "type": "text" },
      "agent": { "type": "text" }
    }
  }
}'

– mapping作成確認
– fieldは自動でアルファベット順にソートされる


# curl "http://127.0.0.1:9200/test_accesslog/_mapping/?pretty"
Enter host password for user 'elastic':
{
  "test_accesslog" : {
    "mappings" : {
      "properties" : {
        "agent" : {
          "type" : "text"
        },
        "auth" : {
          "type" : "keyword"
        },
        "bytes" : {
          "type" : "integer"
        },
        "clientip" : {
          "type" : "ip"
        },
        "httpversion" : {
          "type" : "float"
        },
        "ident" : {
          "type" : "keyword"
        },
        "referrer" : {
          "type" : "text"
        },
        "request" : {
          "type" : "text"
        },
        "response" : {
          "type" : "integer"
        },
        "timestamp" : {
          "type" : "date",
          "format" : "dd/MMM/yyyy:HH:mm:ss Z"
        },
        "verb" : {
          "type" : "keyword"
        }
      }
    }
  }
}
root@host1

Data Views作成

– Data Viewsを作成する(GUI)
– 「≡」>「Management」>「Kibana」>「DataViews」>「Create data view」>
– Name : test_accesslog
– Index Pattern : test_accesslog ※前述で作成したIndexを指定する
– Timestamp field : timestamp ※mapping作成で設定した「type:date」が反映されていれば、プルダウンから選択可能
– 保存する

実データ送信

– 実データをコマンドで送信する
– ※ mappingに存在するfieldと一致しないと取り込まれない


$ curl -X POST "192.168.y.y:9200/test_accesslog/_doc" -H 'Content-Type: application/json' -d '
{
  "clientip": "192.168.1.3",
  "ident": "-",
  "auth": "-",
  "timestamp": "27/Mar/2024:00:59:33 +0000",
  "verb": "GET",
  "request": "/api/project/taten/detail/?cdnkn2=2023&cdnkn3=132159&sugyu=1",
  "httpversion": "1.1",
  "response": 200,
  "bytes": 60,
  "referrer": "http://192.168.10.8:9082/",
  "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
}'

正常性確認

Dashboard

– 前述の設定後に、実際にaccesslogが取り込まれているかを確認する
– 「≡」>「Analytics」>「Dashboard」>「Create Dashboard」>「Create visualization」>左上のプルダウンから「Find a data view」で「test_accesslog」を検索する
– 右上のプルダウンから日時指定をする(デフォルトで直近15分前までのログ)
– データがグラフで表示されることを確認
– ※ 3/28正常に取り込まれることを確認

CATEGORIES & TAGS

Elasticsearch,

Author:


comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

関連記事

カテゴリー

むるし

フリーランスのインフラ系エンジニア。
備忘録で色々書いていきます。
お問い合わせは↓
mo-gyu@murci.net
LPIC303 Security

%d人のブロガーが「いいね」をつけました。