Skip to content

Commit d701a74

Browse files
committed
add sni matcher
1 parent 524aba0 commit d701a74

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

tls/sni.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package tls
2+
3+
import (
4+
"crypto/tls"
5+
6+
tcp "github.com/mrhaoxx/OpenNG/tcp"
7+
utils "github.com/mrhaoxx/OpenNG/utils"
8+
)
9+
10+
type SniMatcher struct {
11+
Snis utils.GroupRegexp
12+
Rewrite string
13+
}
14+
15+
func (m *SniMatcher) Handle(c *tcp.Conn) tcp.SerRet {
16+
hellov, ok := c.Load(tcp.KeyTLS)
17+
18+
if !ok {
19+
return tcp.Continue
20+
}
21+
hello := hellov.(*tls.ClientHelloInfo)
22+
if m.Snis == nil || m.Snis.MatchString(hello.ServerName) {
23+
c.IdentifiyProtocol(m.Rewrite)
24+
return tcp.Upgrade
25+
}
26+
27+
return tcp.Continue
28+
}

ui/builtin.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,23 @@ var refs_assertions = map[string]Assert{
200200
},
201201
},
202202
},
203+
"builtin::tls::snimatcher": {
204+
Type: "map",
205+
Required: true,
206+
Sub: AssertMap{
207+
"snis": {
208+
Type: "list",
209+
Desc: "list of server name patterns to match",
210+
Sub: AssertMap{
211+
"_": {Type: "string"},
212+
},
213+
},
214+
"rewrite": {
215+
Type: "string",
216+
Desc: "protocol rewrite string",
217+
},
218+
},
219+
},
203220
"builtin::http::midware": {
204221
Type: "map",
205222
Required: true,
@@ -1878,6 +1895,26 @@ var refs = map[string]Inst{
18781895
"builtin::net::interface::sys": func(*ArgNode) (any, error) {
18791896
return &net.SysInterface{}, nil
18801897
},
1898+
"builtin::tls::snimatcher": func(spec *ArgNode) (any, error) {
1899+
snis := spec.MustGet("snis").ToStringList()
1900+
rewrite := spec.MustGet("rewrite").ToString()
1901+
1902+
var hosts utils.GroupRegexp = nil
1903+
if len(snis) > 0 {
1904+
for _, sni := range snis {
1905+
r, err := regexp2.Compile(sni, regexp2.RE2)
1906+
if err != nil {
1907+
return nil, err
1908+
}
1909+
hosts = append(hosts, r)
1910+
}
1911+
}
1912+
1913+
return &tls.SniMatcher{
1914+
Snis: hosts,
1915+
Rewrite: rewrite,
1916+
}, nil
1917+
},
18811918
}
18821919

18831920
func Register(name string, inst Inst, assert Assert) {

0 commit comments

Comments
 (0)