Files
nps/server/proxy/https.go
T

374 lines
11 KiB
Go
Raw Normal View History

2019-03-30 12:03:17 +08:00
package proxy
import (
"io"
2019-08-10 11:15:25 +08:00
"net"
"net/http"
"net/url"
2025-01-23 17:31:55 +08:00
"strings"
2019-08-10 11:15:25 +08:00
"sync"
2020-01-08 21:57:14 +08:00
"ehang.io/nps/lib/cache"
"ehang.io/nps/lib/common"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
2019-08-10 11:15:25 +08:00
"github.com/astaxie/beego/logs"
2019-03-30 12:03:17 +08:00
"github.com/pkg/errors"
)
type HttpsServer struct {
httpServer
listener net.Listener
httpsListenerMap sync.Map
2024-05-28 17:56:36 +08:00
hostIdCertMap sync.Map
2019-03-30 12:03:17 +08:00
}
2019-04-21 23:03:58 +08:00
func NewHttpsServer(l net.Listener, bridge NetBridge, useCache bool, cacheLen int) *HttpsServer {
2019-03-30 12:03:17 +08:00
https := &HttpsServer{listener: l}
https.bridge = bridge
2019-04-08 17:01:08 +08:00
https.useCache = useCache
if useCache {
https.cache = cache.New(cacheLen)
}
2019-03-30 12:03:17 +08:00
return https
}
2024-05-28 17:56:36 +08:00
// start https server
2019-03-30 12:03:17 +08:00
func (https *HttpsServer) Start() error {
2024-05-28 17:56:36 +08:00
conn.Accept(https.listener, func(c net.Conn) {
serverName, rb := GetServerNameFromClientHello(c)
if serverName == "" {
serverName = getFallbackServerName()
}
2024-05-28 17:56:36 +08:00
r := buildHttpsRequest(serverName)
if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil {
c.Close()
logs.Debug("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String())
return
} else {
if host.CertFilePath == "" || host.KeyFilePath == "" {
logs.Debug("加载客户端本地证书")
https.handleHttps2(c, serverName, rb, r)
2019-03-30 12:03:17 +08:00
} else {
2024-05-28 17:56:36 +08:00
logs.Debug("使用上传证书")
2025-01-23 17:31:55 +08:00
// 判断是路径还是证书,-----BEGIN 开头的为证书
if strings.Contains(host.CertFilePath, "-----BEGIN") || strings.Contains(host.KeyFilePath, "-----BEGIN") {
logs.Debug("通过上传文件加载证书")
https.cert(host, c, rb, host.CertFilePath, host.KeyFilePath)
} else {
logs.Debug("通过路径加载证书")
if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) {
c.Close()
logs.Error("证书或秘钥文件不存在", host.KeyFilePath, host.CertFilePath)
return
}
cert, err := common.ReadAllFromFile(host.CertFilePath)
if err != nil {
c.Close()
logs.Error("加载证书失败", err)
return
}
key, err := common.ReadAllFromFile(host.KeyFilePath)
if err != nil {
c.Close()
logs.Error("加载证书秘钥失败", err)
return
}
https.cert(host, c, rb, string(cert), string(key))
}
2024-05-28 17:56:36 +08:00
}
}
})
//var err error
//if https.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
// https.errorContent = []byte("nps 404")
//}
//if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
// conn.Accept(https.listener, func(c net.Conn) {
// https.handleHttps(c)
// })
//} else {
// //start the default listener
// certFile := beego.AppConfig.String("https_default_cert_file")
// keyFile := beego.AppConfig.String("https_default_key_file")
// if common.FileExists(certFile) && common.FileExists(keyFile) {
// l := NewHttpsListener(https.listener)
// https.NewHttps(l, certFile, keyFile)
// https.httpsListenerMap.Store("default", l)
// }
// conn.Accept(https.listener, func(c net.Conn) {
// serverName, rb := GetServerNameFromClientHello(c)
// //if the clientHello does not contains sni ,use the default ssl certificate
// if serverName == "" {
// serverName = "default"
// }
// var l *HttpsListener
// if v, ok := https.httpsListenerMap.Load(serverName); ok {
// l = v.(*HttpsListener)
// } else {
// r := buildHttpsRequest(serverName)
// if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil {
// c.Close()
// logs.Notice("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String())
// return
// } else {
// if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) {
// //if the host cert file or key file is not set ,use the default file
// if v, ok := https.httpsListenerMap.Load("default"); ok {
// l = v.(*HttpsListener)
// } else {
// c.Close()
// logs.Error("the key %s cert %s file is not exist", host.KeyFilePath, host.CertFilePath)
// return
// }
// } else {
// l = NewHttpsListener(https.listener)
// https.NewHttps(l, host.CertFilePath, host.KeyFilePath)
// https.httpsListenerMap.Store(serverName, l)
// }
// }
// }
// acceptConn := conn.NewConn(c)
// acceptConn.Rb = rb
// l.acceptConn <- acceptConn
// })
//}
return nil
}
func getFallbackServerName() string {
global := file.GetDb().GetGlobal()
if global == nil {
return ""
}
serverName := strings.TrimSpace(global.ServerUrl)
if serverName == "" {
return ""
}
if strings.Contains(serverName, "://") {
if u, err := url.Parse(serverName); err == nil && u.Host != "" {
serverName = u.Host
}
}
if i := strings.Index(serverName, "/"); i >= 0 {
serverName = serverName[:i]
}
serverName = common.GetIpByAddr(serverName)
serverName = strings.TrimSpace(serverName)
if serverName == "" {
return ""
}
ip := net.ParseIP(serverName)
if ip != nil && ip.IsUnspecified() {
return ""
}
return serverName
}
2024-05-28 17:56:36 +08:00
func (https *HttpsServer) cert(host *file.Host, c net.Conn, rb []byte, certFileUrl string, keyFileUrl string) {
var l *HttpsListener
i := 0
https.hostIdCertMap.Range(func(key, value interface{}) bool {
i++
// 如果host Id 不存在,则删除map
if id, ok := key.(int); ok {
var err error
_, err = file.GetDb().GetHostById(id)
if err != nil {
// 说明这个host已经不存了,需要释放Listener
logs.Error(err)
if oldL, ok := https.httpsListenerMap.Load(value); ok {
err := oldL.(*HttpsListener).Close()
if err != nil {
logs.Error(err)
2019-03-30 12:03:17 +08:00
}
2024-05-28 17:56:36 +08:00
https.httpsListenerMap.Delete(value)
https.hostIdCertMap.Delete(key)
2025-12-06 00:31:32 +08:00
logs.Debug("Listener 已释放")
2019-03-30 12:03:17 +08:00
}
}
2024-05-28 17:56:36 +08:00
}
return true
})
2025-12-06 00:31:32 +08:00
logs.Debug("当前 Listener 连接数量", i)
2024-05-28 17:56:36 +08:00
if cert, ok := https.hostIdCertMap.Load(host.Id); ok {
if cert == certFileUrl {
// 证书已经存在,直接加载
if v, ok := https.httpsListenerMap.Load(certFileUrl); ok {
l = v.(*HttpsListener)
}
} else {
// 证书修改过,重新加载证书
l = NewHttpsListener(https.listener)
https.NewHttps(l, certFileUrl, keyFileUrl)
if oldL, ok := https.httpsListenerMap.Load(cert); ok {
err := oldL.(*HttpsListener).Close()
if err != nil {
logs.Error(err)
}
https.httpsListenerMap.Delete(cert)
}
https.httpsListenerMap.Store(certFileUrl, l)
https.hostIdCertMap.Store(host.Id, certFileUrl)
}
} else {
// 第一次加载证书
l = NewHttpsListener(https.listener)
https.NewHttps(l, certFileUrl, keyFileUrl)
https.httpsListenerMap.Store(certFileUrl, l)
https.hostIdCertMap.Store(host.Id, certFileUrl)
2019-03-30 12:03:17 +08:00
}
2024-05-28 17:56:36 +08:00
acceptConn := conn.NewConn(c)
acceptConn.Rb = rb
l.acceptConn <- acceptConn
}
// handle the https which is just proxy to other client
func (https *HttpsServer) handleHttps2(c net.Conn, hostName string, rb []byte, r *http.Request) {
var targetAddr string
var host *file.Host
var err error
if host, err = file.GetDb().GetInfoByHost(hostName, r); err != nil {
c.Close()
logs.Debug("the url %s can't be parsed!", hostName)
return
}
if err := https.CheckFlowAndConnNum(host.Client); err != nil {
logs.Debug("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
c.Close()
return
}
defer host.Client.AddConn()
if err = https.auth(r, conn.NewConn(c), host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
logs.Warn("auth error", err, r.RemoteAddr)
return
}
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
logs.Warn(err.Error())
}
logs.Info("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil)
2019-03-30 12:03:17 +08:00
}
2019-04-08 18:02:54 +08:00
// close
2019-03-30 12:03:17 +08:00
func (https *HttpsServer) Close() error {
return https.listener.Close()
}
2019-04-08 18:02:54 +08:00
// new https server by cert and key file
2019-03-30 12:03:17 +08:00
func (https *HttpsServer) NewHttps(l net.Listener, certFile string, keyFile string) {
go func() {
2024-05-28 17:56:36 +08:00
//logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile))
logs.Error(https.NewServerWithTls(0, "https", l, certFile, keyFile))
2019-03-30 12:03:17 +08:00
}()
}
2024-05-28 17:56:36 +08:00
// handle the https which is just proxy to other client
2019-03-30 12:03:17 +08:00
func (https *HttpsServer) handleHttps(c net.Conn) {
hostName, rb := GetServerNameFromClientHello(c)
var targetAddr string
2019-03-30 16:35:43 +08:00
r := buildHttpsRequest(hostName)
2019-03-30 12:03:17 +08:00
var host *file.Host
var err error
if host, err = file.GetDb().GetInfoByHost(hostName, r); err != nil {
c.Close()
logs.Notice("the url %s can't be parsed!", hostName)
return
}
if err := https.CheckFlowAndConnNum(host.Client); err != nil {
logs.Warn("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
c.Close()
return
}
defer host.Client.AddConn()
if err = https.auth(r, conn.NewConn(c), host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
logs.Warn("auth error", err, r.RemoteAddr)
return
}
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
logs.Warn(err.Error())
}
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
2023-05-29 11:51:30 +08:00
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Client.Flow, host.Target.LocalProxy, nil)
2019-03-30 12:03:17 +08:00
}
type HttpsListener struct {
acceptConn chan *conn.Conn
parentListener net.Listener
}
2019-04-08 18:02:54 +08:00
// https listener
2019-03-30 12:03:17 +08:00
func NewHttpsListener(l net.Listener) *HttpsListener {
return &HttpsListener{parentListener: l, acceptConn: make(chan *conn.Conn)}
}
2019-04-08 18:02:54 +08:00
// accept
2019-03-30 12:03:17 +08:00
func (httpsListener *HttpsListener) Accept() (net.Conn, error) {
httpsConn := <-httpsListener.acceptConn
if httpsConn == nil {
return nil, errors.New("get connection error")
}
return httpsConn, nil
}
2019-04-08 18:02:54 +08:00
// close
2019-03-30 12:03:17 +08:00
func (httpsListener *HttpsListener) Close() error {
return nil
}
2019-04-08 18:02:54 +08:00
// addr
2019-03-30 12:03:17 +08:00
func (httpsListener *HttpsListener) Addr() net.Addr {
return httpsListener.parentListener.Addr()
}
// get server name from connection by read full client hello bytes
2019-03-30 12:03:17 +08:00
func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
header := make([]byte, 5)
headerN, err := io.ReadFull(c, header)
2019-03-30 12:03:17 +08:00
if err != nil {
return "", header[:headerN]
2019-03-30 12:03:17 +08:00
}
if header[0] != 0x16 {
return "", header
2019-04-17 14:17:59 +08:00
}
recordLen := int(header[3])<<8 | int(header[4])
if recordLen <= 0 {
return "", header
}
body := make([]byte, recordLen)
bodyN, err := io.ReadFull(c, body)
if err != nil {
return "", append(header, body[:bodyN]...)
}
rawBytes := append(header, body...)
2019-03-30 12:03:17 +08:00
clientHello := new(crypt.ClientHelloMsg)
if !clientHello.Unmarshal(body) {
return "", rawBytes
}
return clientHello.GetServerName(), rawBytes
2019-03-30 12:03:17 +08:00
}
2019-03-30 16:35:43 +08:00
2019-04-08 18:02:54 +08:00
// build https request
2019-03-30 16:35:43 +08:00
func buildHttpsRequest(hostName string) *http.Request {
r := new(http.Request)
r.RequestURI = "/"
r.URL = new(url.URL)
r.URL.Scheme = "https"
r.Host = hostName
return r
}