From 6c5969c5ea9ac2e3f22e0096e186907a3c45df50 Mon Sep 17 00:00:00 2001
From: bjdgyc <bjdgyc@163.com>
Date: Fri, 31 Dec 2021 16:35:33 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9profile.xml=E8=87=AA=E5=8A=A8?=
 =?UTF-8?q?=E8=8E=B7=E5=8F=96hash?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 server/base/cfg.go             |  1 +
 server/base/config.go          |  1 +
 server/conf/files/profile.xml  | 34 ----------------------------------
 server/conf/server-sample.toml |  3 ++-
 server/handler/link_auth.go    |  9 ++++++---
 server/handler/server.go       | 16 +++++++++-------
 server/handler/start.go        | 12 ++++++++++++
 7 files changed, 31 insertions(+), 45 deletions(-)
 delete mode 100644 server/conf/files/profile.xml

diff --git a/server/base/cfg.go b/server/base/cfg.go
index d6f27be..49a9c92 100644
--- a/server/base/cfg.go
+++ b/server/base/cfg.go
@@ -32,6 +32,7 @@ var (
 type ServerConfig struct {
 	// LinkAddr      string `json:"link_addr"`
 	Conf           string `json:"conf"`
+	Profile        string `json:"profile"`
 	ServerAddr     string `json:"server_addr"`
 	ServerDTLSAddr string `json:"server_dtls_addr"`
 	ServerDTLS     bool   `json:"server_dtls"`
diff --git a/server/base/config.go b/server/base/config.go
index f86282e..b7edc7b 100644
--- a/server/base/config.go
+++ b/server/base/config.go
@@ -21,6 +21,7 @@ type config struct {
 
 var configs = []config{
 	{Typ: cfgStr, Name: "conf", Usage: "config file", ValStr: "./conf/server.toml", Short: "c"},
+	{Typ: cfgStr, Name: "profile", Usage: "profile.xml file", ValStr: "./conf/profile.xml"},
 	{Typ: cfgStr, Name: "server_addr", Usage: "服务监听地址", ValStr: ":443"},
 	{Typ: cfgBool, Name: "server_dtls", Usage: "开启DTLS", ValBool: false},
 	{Typ: cfgStr, Name: "server_dtls_addr", Usage: "DTLS监听地址", ValStr: ":4433"},
diff --git a/server/conf/files/profile.xml b/server/conf/files/profile.xml
deleted file mode 100644
index 0df0912..0000000
--- a/server/conf/files/profile.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<AnyConnectProfile xmlns="http://schemas.xmlsoap.org/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-                   xsi:schemaLocation="http://schemas.xmlsoap.org/encoding/ AnyConnectProfile.xsd">
-
-    <ClientInitialization>
-        <UseStartBeforeLogon UserControllable="false">false</UseStartBeforeLogon>
-        <StrictCertificateTrust>false</StrictCertificateTrust>
-        <RestrictPreferenceCaching>false</RestrictPreferenceCaching>
-        <RestrictTunnelProtocols>IPSec</RestrictTunnelProtocols>
-        <BypassDownloader>true</BypassDownloader>
-        <WindowsVPNEstablishment>AllowRemoteUsers</WindowsVPNEstablishment>
-        <LinuxVPNEstablishment>AllowRemoteUsers</LinuxVPNEstablishment>
-        <CertEnrollmentPin>pinAllowed</CertEnrollmentPin>
-        <CertificateMatch>
-            <KeyUsage>
-                <MatchKey>Digital_Signature</MatchKey>
-            </KeyUsage>
-            <ExtendedKeyUsage>
-                <ExtendedMatchKey>ClientAuth</ExtendedMatchKey>
-            </ExtendedKeyUsage>
-        </CertificateMatch>
-
-        <BackupServerList>
-            <HostAddress>localhost</HostAddress>
-        </BackupServerList>
-    </ClientInitialization>
-
-    <ServerList>
-        <HostEntry>
-            <HostName>VPN Server</HostName>
-            <HostAddress>localhost</HostAddress>
-        </HostEntry>
-    </ServerList>
-</AnyConnectProfile>
\ No newline at end of file
diff --git a/server/conf/server-sample.toml b/server/conf/server-sample.toml
index 0539481..b3af587 100644
--- a/server/conf/server-sample.toml
+++ b/server/conf/server-sample.toml
@@ -6,10 +6,11 @@
 #数据文件
 db_type = "sqlite3"
 db_source = "./conf/anylink.db"
-#证书文件
+#证书文件 使用跟nginx一样的证书即可
 cert_file = "./conf/vpn_cert.pem"
 cert_key = "./conf/vpn_cert.key"
 files_path = "./conf/files"
+profile = "./conf/profile.xml"
 #日志目录,为空写入标准输出
 #log_path = "./log"
 log_path = ""
diff --git a/server/handler/link_auth.go b/server/handler/link_auth.go
index 9d2a6be..6c98138 100644
--- a/server/handler/link_auth.go
+++ b/server/handler/link_auth.go
@@ -14,6 +14,8 @@ import (
 	"github.com/bjdgyc/anylink/sessdata"
 )
 
+var profileHash = ""
+
 func LinkAuth(w http.ResponseWriter, r *http.Request) {
 	// 判断anyconnect客户端
 	userAgent := strings.ToLower(r.UserAgent())
@@ -89,7 +91,7 @@ func LinkAuth(w http.ResponseWriter, r *http.Request) {
 	other := &dbdata.SettingOther{}
 	_ = dbdata.SettingGet(other)
 	rd := RequestData{SessionId: sess.Sid, SessionToken: sess.Sid + "@" + sess.Token,
-		Banner: other.Banner}
+		Banner: other.Banner, ProfileHash: profileHash}
 	w.WriteHeader(http.StatusOK)
 	tplRequest(tpl_complete, w, rd)
 	base.Debug("login", cr.Auth.Username)
@@ -125,6 +127,7 @@ type RequestData struct {
 	SessionId    string
 	SessionToken string
 	Banner       string
+	ProfileHash  string
 }
 
 var auth_request = `<?xml version="1.0" encoding="UTF-8"?>
@@ -176,8 +179,8 @@ var auth_complete = `<?xml version="1.0" encoding="UTF-8"?>
         <vpn-profile-manifest>
             <vpn rev="1.0">
                 <file type="profile" service-type="user">
-                    <uri>/files/profile.xml</uri>
-                    <hash type="sha1">A8B0B07FBA93D06E8501E40AB807AEE2464E73B7</hash>
+                    <uri>/profile.xml</uri>
+                    <hash type="sha1">{{.ProfileHash}}</hash>
                 </file>
             </vpn>
         </vpn-profile-manifest>
diff --git a/server/handler/server.go b/server/handler/server.go
index aef9fb1..0168c98 100644
--- a/server/handler/server.go
+++ b/server/handler/server.go
@@ -6,6 +6,7 @@ import (
 	"log"
 	"net"
 	"net/http"
+	"os"
 	"time"
 
 	"github.com/bjdgyc/anylink/base"
@@ -26,14 +27,14 @@ func startTls() {
 	)
 
 	// 判断证书文件
-	//_, err = os.Stat(certFile)
-	//if errors.Is(err, os.ErrNotExist) {
+	// _, err = os.Stat(certFile)
+	// if errors.Is(err, os.ErrNotExist) {
 	//	// 自动生成证书
 	//	certs[0], err = selfsign.GenerateSelfSignedWithDNS("vpn.anylink")
-	//} else {
+	// } else {
 	//	// 使用自定义证书
 	//	certs[0], err = tls.LoadX509KeyPair(certFile, keyFile)
-	//}
+	// }
 
 	certs[0], err = tls.LoadX509KeyPair(certFile, keyFile)
 	if err != nil {
@@ -77,9 +78,10 @@ func initRoute() http.Handler {
 	r.HandleFunc("/", LinkAuth).Methods(http.MethodPost)
 	r.HandleFunc("/CSCOSSLC/tunnel", LinkTunnel).Methods(http.MethodConnect)
 	r.HandleFunc("/otp_qr", LinkOtpQr).Methods(http.MethodGet)
-	// r.HandleFunc("/profile.xml", func(w http.ResponseWriter, r *http.Request) {
-	// 	w.Write([]byte(auth_profile))
-	// }).Methods(http.MethodGet)
+	r.HandleFunc("/profile.xml", func(w http.ResponseWriter, r *http.Request) {
+		b, _ := os.ReadFile(base.Cfg.Profile)
+		w.Write(b)
+	}).Methods(http.MethodGet)
 	r.PathPrefix("/files/").Handler(
 		http.StripPrefix("/files/",
 			http.FileServer(http.Dir(base.Cfg.FilesPath)),
diff --git a/server/handler/start.go b/server/handler/start.go
index 5399bec..30ef2a0 100644
--- a/server/handler/start.go
+++ b/server/handler/start.go
@@ -1,6 +1,10 @@
 package handler
 
 import (
+	"crypto/sha1"
+	"encoding/hex"
+	"os"
+
 	"github.com/bjdgyc/anylink/admin"
 	"github.com/bjdgyc/anylink/base"
 	"github.com/bjdgyc/anylink/dbdata"
@@ -22,6 +26,14 @@ func Start() {
 		base.Fatal("LinkMode is err")
 	}
 
+	// 计算profile.xml的hash
+	b, err := os.ReadFile(base.Cfg.Profile)
+	if err != nil {
+		panic(err)
+	}
+	ha := sha1.Sum(b)
+	profileHash = hex.EncodeToString(ha[:])
+
 	go admin.StartAdmin()
 	go startTls()
 	go startDtls()