0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OSS版Kongのソースコードをいじってみる

Last updated at Posted at 2025-03-10

Proxy利用時に表示される文字列をソースコードレベルで書き換えられるかをOSS版で検証した時のメモ。
ビルド方法などは割愛。

やりたいこと

Routeが設定されていない時にProxyにアクセスすると以下のようなメッセージが出る。

$ curl localhost:8000 -i
HTTP/1.1 404 Not Found
Date: Mon, 10 Mar 2025 09:10:09 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Content-Length: 106
X-Kong-Response-Latency: 0
Server: kong/3.10.0
X-Kong-Request-Id: 24d95832204ab4150af76d221c535268

{
  "message":"no Route matched with those values",
  "request_id":"24d95832204ab4150af76d221c535268"
}

このno Route matched with those values404 Not Foundのところを書き換える。
ここでは各文字列の最後に!!!を挿入することで書き換え可能かどうかを検証する。
なお、Exit Transformer Pluginで書き換えられそうなものだが、404 Not FoundのところはHTTPステータスラインといってプラグインでは書き換えが出来ない箇所になる。
具体的には、nginxのソースのこの辺でハードコーディングされている。

no Route ...の書き換え

これはkong/runloop/handler.luaこの辺で定義されている。
Luaの場合、ビルドは特に不要なのでファイルを編集してプロセスをリロードすればOK。
以下のように編集する。

kong/runloop/handler.lua
        return kong.response.error(404, "no Route matched with those values!!!")

Kongのプロセスを再起動する。

kong stop
kong start

404 Not Foundの書き換え

nginxのソースのこの辺でハードコーディングされている文字列を書き換える。
Kongはバイナリの中ではnginxを取り込んでいるが、nginxのコード自体はリポジトリ内に抱えておらず、OpenRestyのコードをビルド時に引っ張ってきている
OpenRestyのビルド時にOpenRestyもまたnginxのコードを引っ張ってきているので、最終的にKongの中にnginxが取り込まれる仕組みとなっているっぽい。
またKongはbuild/openresty/patches/以下にパッチを用意し、ビルド時にパッチを適用することでnginxやOpenRestyに修正を加えている。
この仕組みを利用しパッチファイルを用意してビルドすれば、nginxやOpenRestyの書き換えが可能となるはずだ。
他のパッチを参考にし、ここでは以下のパッチを作成する。

build/openresty/patches/nginx-1.27.1_13-modify-header.patch
diff --git a/bundle/nginx-1.27.1/src/http/ngx_http_header_filter_module.c b/bundle/nginx-1.27.1/src/http/ngx_http_header_filter_module.c
index abcdefg..hijklmn 100644
--- a/bundle/nginx-1.27.1/src/http/ngx_http_header_filter_module.c
+++ b/bundle/nginx-1.27.1/src/http/ngx_http_header_filter_module.c
@@ -64,7 +64,7 @@ static ngx_str_t ngx_http_status_lines[] = {
     ngx_string("400 Bad Request"),
     ngx_string("401 Unauthorized"),
     ngx_string("402 Payment Required"),
     ngx_string("403 Forbidden"),
-    ngx_string("404 Not Found"),
+    ngx_string("404 Not Found!!!"),
     ngx_string("405 Not Allowed"),
     ngx_string("406 Not Acceptable"),
     ngx_null_string,  /* "407 Proxy Authentication Required" */

パッチを作成後、リビルドしてKongを再起動する。

動作確認

それぞれ文字列が書き換わっているか確認する。

$ curl -is localhost:8000 | grep "HTTP\|Route"
HTTP/1.1 404 Not Found!!!
  "message":"no Route matched with those values!!!",

それぞれ期待した通りに文字列が書き換わっている。
問題なさそうだ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?