3
1

More than 3 years have passed since last update.

自分用ngrokをauthtoken対応にする(self hosted ngrok)

Last updated at Posted at 2019-11-11

はじめに

前回、自分用ngrokを構築する(self hosted ngrok)でドメイン取得し、自分専用のngrokを立ち上げたが、もともとのソースではngrokクライアントに対する認証が無い状態だった。
これでは、不特定のngrokから接続できる状態でセキュリティ上まずい。

ngrokクライアントから渡せるauthtokenを使ったクライアント認証を実装したい。

どう実現するか

すでに実現した例が紹介されているので、下記を参考にする。
Linux搭建Ngrok服务器及身份认证实现内网穿透

改修ポイント

サーバーの下記コードを改修し、authtokenを受けるようにする。
ngrok/src/ngrok/server/control.go

diff -up ../ngrok/src/ngrok/server/control.go src/ngrok/server/control.go

--- ../ngrok/src/ngrok/server/control.go        2019-10-30 18:45:30.153107856 +0900
+++ src/ngrok/server/control.go 2019-11-12 05:20:31.559657500 +0900
@@ -10,6 +10,8 @@ import (
        "runtime/debug"
        "strings"
        "time"
+       "os"
+       "bufio"
 )

 const (
@@ -82,6 +84,37 @@ func NewControl(ctlConn conn.Conn, authM
                ctlConn.Close()
        }

+
+
+
+       readLine := func(token string, filename string) (bool, error) {
+       if token == "" {
+               return false, nil;
+       }
+       f, err := os.Open(filename)
+       if err != nil {
+            return false, err
+       }
+       buf := bufio.NewReader(f)
+       for {
+               line, err := buf.ReadString('\n')
+               line = strings.TrimSpace(line)
+                       if line == token {
+                               return true, nil
+                       }
+                       if err != nil {
+                               if err == io.EOF {
+                                       return false, nil
+                               }
+                       return false, err
+                       }
+               }
+               return false, nil
+       }
+
+
+
+
        // register the clientid
        c.id = authMsg.ClientId
        if c.id == "" {
@@ -101,6 +134,13 @@ func NewControl(ctlConn conn.Conn, authM
                return
        }

+       authd, err := readLine(authMsg.User, "authtokens.txt")
+
+       if authd != true {
+       failAuth(fmt.Errorf("authtoken %s invalid", "is"));
+       return
+       }
+
        // register the control
        if replaced := controlRegistry.Add(c.id, c); replaced != nil {
                replaced.shutdown.WaitComplete()

設定

ngrokdを実行するディレクトリにauthtokens.txtを作り、トークンを書き込む。
自分の場合は、適当な文字列をSHA512ハッシュにして配置した。

接続

クライアント側の設定ファイル.ngrokへ、auth_token行を追加し、設定したSHA512列を記入し起動、接続できればOK。

3
1
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
3
1