自己搭建的ngrok服务器如何添加身份验证

虽然成功搭建了ngrok服务器,本地能被访问
但有几个问题:
1. 没有设置密码账号,谁都可以用
2. 尝试连接ngrok.com会连接成功,但立即提示需要付费
3. 怎样给ngrokd服务端添加身份验证

纯粹是问问,分不多

控制台输出

服务端参数

 >ngrokd -help
Usage of ngrokd:
  -domain string
        Domain where the tunnels are hosted (default "ngrok.com")
  -httpAddr string
        Public address for HTTP connections, empty string to disable (default ":80")
  -httpsAddr string
        Public address listening for HTTPS connections, emptry string to disable (default ":443")
  -log string
        Write log messages to this file. 'stdout' and 'none' have special meanings (default "stdout")
  -log-level string
        The level of messages to log. One of: DEBUG, INFO, WARNING, ERROR (default "DEBUG")
  -tlsCrt string
        Path to a TLS certificate file
  -tlsKey string
        Path to a TLS key file
  -tunnelAddr string
        Public address listening for ngrok client (default ":4443")

客户端参数

 >ngrok -help
Usage: ngrok [OPTIONS] <local port or address>
Options:
  -authtoken string
        Authentication token for identifying an ngrok.com account
  -config string
        Path to ngrok configuration file. (default: $HOME/.ngrok)
  -hostname string
        Request a custom hostname from the ngrok server. (HTTP only) (requires CNAME of your DNS)
  -httpauth string
        username:password HTTP basic auth creds protecting the public tunnel endpoint
  -log string
        Write log messages to this file. 'stdout' and 'none' have special meanings (default "none")
  -log-level string
        The level of messages to log. One of: DEBUG, INFO, WARNING, ERROR (default "DEBUG")
  -proto string
        The protocol of the traffic over the tunnel {'http', 'https', 'tcp'} (default: 'http+https') (default "http+https")
  -subdomain string
        Request a custom subdomain from the ngrok server. (HTTP only)

参数倒是意味着 客户端可以发送身份验证信息启动
服务端....没有参数指定谁来处理这个验证消息
该不会要我去学狗浪吧(ˉ▽ ̄~) 切~~

https://blog.csdn.net/yjc_1111/article/details/79353718

真是频频遇到百度不能解决的问题,貌似很多程序员将解决方法放到了更大的互联网圈子,例如国外
在百度没搜到,但在必应国际版就找到了想要的结果了

犹如出了新手村寻找世界的真谛一般

解决方案如下

  • 修改ngrok源代码,当然 我没有深究其他解决方案,因为我对golang不太了解

参考地址 : server端增加authtoken验证支持

为了防止地址失效粘贴下:

 package server

import (
    "fmt"
    "io"
    "ngrok/conn"
    "ngrok/msg"
    "ngrok/util"
    "ngrok/version"
    "runtime/debug"
    "strings"
    "time"
    "os"
    "bufio"
)

const (
    pingTimeoutInterval = 30 * time.Second
    connReapInterval = 10 * time.Second
    controlWriteTimeout = 10 * time.Second
    proxyStaleDuration = 60 * time.Second
    proxyMaxPoolSize = 10
)

type Control struct {
    // auth message
    auth            *msg.Auth

    // actual connection
    conn            conn.Conn

    // put a message in this channel to send it over
    // conn to the client
    out             chan (msg.Message)

    // read from this channel to get the next message sent
    // to us over conn by the client
    in              chan (msg.Message)

    // the last time we received a ping from the client - for heartbeats
    lastPing        time.Time

    // all of the tunnels this control connection handles
    tunnels         []*Tunnel

    // proxy connections
    proxies         chan conn.Conn

    // identifier
    id              string

    // synchronizer for controlled shutdown of writer()
    writerShutdown  *util.Shutdown

    // synchronizer for controlled shutdown of reader()
    readerShutdown  *util.Shutdown

    // synchronizer for controlled shutdown of manager()
    managerShutdown *util.Shutdown

    // synchronizer for controller shutdown of entire Control
    shutdown        *util.Shutdown
}

func NewControl(ctlConn conn.Conn, authMsg *msg.Auth) {
    var err error

    // create the object
    c := &Control{
        auth:            authMsg,
        conn:            ctlConn,
        out:             make(chan msg.Message),
        in:              make(chan msg.Message),
        proxies:         make(chan conn.Conn, 10),
        lastPing:        time.Now(),
        writerShutdown:  util.NewShutdown(),
        readerShutdown:  util.NewShutdown(),
        managerShutdown: util.NewShutdown(),
        shutdown:        util.NewShutdown(),
    }

    failAuth := func(e error) {
        _ = msg.WriteMsg(ctlConn, &msg.AuthResp{Error: e.Error()})
        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 == "" {
        // it's a new session, assign an ID
        if c.id, err = util.SecureRandId(16); err != nil {
            failAuth(err)
            return
        }
    }

    // set logging prefix
    ctlConn.SetType("ctl")
    ctlConn.AddLogPrefix(c.id)

    if authMsg.Version != version.Proto {
        failAuth(fmt.Errorf("Incompatible versions. Server %s, client %s. Download a new version at http://ngrok.com", version.MajorMinor(), authMsg.Version))
        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()
    }

    // start the writer first so that the following messages get sent
    go c.writer()

    // Respond to authentication
    c.out <- &msg.AuthResp{
        Version:   version.Proto,
        MmVersion: version.MajorMinor(),
        ClientId:  c.id,
    }

    // As a performance optimization, ask for a proxy connection up front
    c.out <- &msg.ReqProxy{}

    // manage the connection
    go c.manager()
    go c.reader()
    go c.stopper()
}

// Register a new tunnel on this control connection
func (c *Control) registerTunnel(rawTunnelReq *msg.ReqTunnel) {
    for _, proto := range strings.Split(rawTunnelReq.Protocol, "+") {
        tunnelReq := *rawTunnelReq
        tunnelReq.Protocol = proto

        c.conn.Debug("Registering new tunnel")
        t, err := NewTunnel(&tunnelReq, c)
        if err != nil {
            c.out <- &msg.NewTunnel{Error: err.Error()}
            if len(c.tunnels) == 0 {
                c.shutdown.Begin()
            }

            // we're done
            return
        }

        // add it to the list of tunnels
        c.tunnels = append(c.tunnels, t)

        // acknowledge success
        c.out <- &msg.NewTunnel{
            Url:      t.url,
            Protocol: proto,
            ReqId:    rawTunnelReq.ReqId,
        }

        rawTunnelReq.Hostname = strings.Replace(t.url, proto + "://", "", 1)
    }
}

func (c *Control) manager() {
    // don't crash on panics
    defer func() {
        if err := recover(); err != nil {
            c.conn.Info("Control::manager failed with error %v: %s", err, debug.Stack())
        }
    }()

    // kill everything if the control manager stops
    defer c.shutdown.Begin()

    // notify that manager() has shutdown
    defer c.managerShutdown.Complete()

    // reaping timer for detecting heartbeat failure
    reap := time.NewTicker(connReapInterval)
    defer reap.Stop()

    for {
        select {
        case <-reap.C:
            if time.Since(c.lastPing) > pingTimeoutInterval {
                c.conn.Info("Lost heartbeat")
                c.shutdown.Begin()
            }

        case mRaw, ok := <-c.in:
        // c.in closes to indicate shutdown
            if !ok {
                return
            }

            switch m := mRaw.(type) {
            case *msg.ReqTunnel:
                c.registerTunnel(m)

            case *msg.Ping:
                c.lastPing = time.Now()
                c.out <- &msg.Pong{}
            }
        }
    }
}

func (c *Control) writer() {
    defer func() {
        if err := recover(); err != nil {
            c.conn.Info("Control::writer failed with error %v: %s", err, debug.Stack())
        }
    }()

    // kill everything if the writer() stops
    defer c.shutdown.Begin()

    // notify that we've flushed all messages
    defer c.writerShutdown.Complete()

    // write messages to the control channel
    for m := range c.out {
        c.conn.SetWriteDeadline(time.Now().Add(controlWriteTimeout))
        if err := msg.WriteMsg(c.conn, m); err != nil {
            panic(err)
        }
    }
}

func (c *Control) reader() {
    defer func() {
        if err := recover(); err != nil {
            c.conn.Warn("Control::reader failed with error %v: %s", err, debug.Stack())
        }
    }()

    // kill everything if the reader stops
    defer c.shutdown.Begin()

    // notify that we're done
    defer c.readerShutdown.Complete()

    // read messages from the control channel
    for {
        if msg, err := msg.ReadMsg(c.conn); err != nil {
            if err == io.EOF {
                c.conn.Info("EOF")
                return
            } else {
                panic(err)
            }
        } else {
            // this can also panic during shutdown
            c.in <- msg
        }
    }
}

func (c *Control) stopper() {
    defer func() {
        if r := recover(); r != nil {
            c.conn.Error("Failed to shut down control: %v", r)
        }
    }()

    // wait until we're instructed to shutdown
    c.shutdown.WaitBegin()

    // remove ourself from the control registry
    controlRegistry.Del(c.id)

    // shutdown manager() so that we have no more work to do
    close(c.in)
    c.managerShutdown.WaitComplete()

    // shutdown writer()
    close(c.out)
    c.writerShutdown.WaitComplete()

    // close connection fully
    c.conn.Close()

    // shutdown all of the tunnels
    for _, t := range c.tunnels {
        t.Shutdown()
    }

    // shutdown all of the proxy connections
    close(c.proxies)
    for p := range c.proxies {
        p.Close()
    }

    c.shutdown.Complete()
    c.conn.Info("Shutdown complete")
}

func (c *Control) RegisterProxy(conn conn.Conn) {
    conn.AddLogPrefix(c.id)

    conn.SetDeadline(time.Now().Add(proxyStaleDuration))
    select {
    case c.proxies <- conn:
        conn.Info("Registered")
    default:
        conn.Info("Proxies buffer is full, discarding.")
        conn.Close()
    }
}

// Remove a proxy connection from the pool and return it
// If not proxy connections are in the pool, request one
// and wait until it is available
// Returns an error if we couldn't get a proxy because it took too long
// or the tunnel is closing
func (c *Control) GetProxy() (proxyConn conn.Conn, err error) {
    var ok bool

    // get a proxy connection from the pool
    select {
    case proxyConn, ok = <-c.proxies:
        if !ok {
            err = fmt.Errorf("No proxy connections available, control is closing")
            return
        }
    default:
    // no proxy available in the pool, ask for one over the control channel
        c.conn.Debug("No proxy in pool, requesting proxy from control . . .")
        if err = util.PanicToError(func() {
            c.out <- &msg.ReqProxy{}
        }); err != nil {
            return
        }

            select {
            case proxyConn, ok = <-c.proxies:
                if !ok {
                    err = fmt.Errorf("No proxy connections available, control is closing")
                    return
                }

            case <-time.After(pingTimeoutInterval):
                err = fmt.Errorf("Timeout trying to get proxy connection")
                return
            }
    }
    return
}

// Called when this control is replaced by another control
// this can happen if the network drops out and the client reconnects
// before the old tunnel has lost its heartbeat
func (c *Control) Replaced(replacement *Control) {
    c.conn.Info("Replaced by control: %s", replacement.conn.Id())

    // set the control id to empty string so that when stopper()
    // calls registry.Del it won't delete the replacement
    c.id = ""

    // tell the old one to shutdown
    c.shutdown.Begin()
}

修改了 ngrok/src/ngrok/server/control.go

以防版本不同,列出修改的具体内容

在 func NewControl(){} 内添加了一个方法,然后

 func NewControl(ctlConn conn.Conn, authMsg *msg.Auth) {
     //省略
     //读取文件方法
     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
}
    //省略
    //调用验证
    authd, err := readLine(authMsg.User, "authtokens.txt")

    if authd != true {
        failAuth(fmt.Errorf("authtoken %s invalid", "is"));
        return
}
     //省略
 }

这个验证直接 比较是否相等如 "123456" 或 "abcd:123456" 并没区别,看自己设计吧

修改后重新编译服务端 , 在执行文件同目录建立一个 用户文件,"authtokens.txt"

//如果 客户端参数 
-authtoken "username:password"
//服务端authtokens.txt包含相同字符串,每一个token一行,循环遍历比较
username:password

至于编译我是参照
一分钟实现内网穿透(ngrok服务器搭建)

ngrok版本 1.7
ubuntu 18.04
VMware 12pro

启动ngrok 客户端 偶现连接到其他端口,如配置的是http:8088 https:8089 连接时,http和https都连接到了8089,更有可能连接到 未配置的80端口去,以至于无法访问,当然 如果只使用80 端口 应该不会出现大问题

老兄为什么我按照你这样配置,然后还是没有身份验证?

可以修改一下源码,制定authtokens.txt的绝对路径即可