mirror of
https://github.com/lyc8503/EasierConnect.git
synced 2025-12-24 12:57:54 +08:00
Compare commits
6 Commits
TestBuild1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ded56b0a89 | ||
|
|
376593ea55 | ||
|
|
e01671c606 | ||
|
|
ce01fd449c | ||
|
|
ca19bd5fa4 | ||
|
|
840f6aeec9 |
12
README.md
12
README.md
@@ -1,14 +1,22 @@
|
||||
# EasierConnect
|
||||
# NJUConnect
|
||||
|
||||
> 🚫 **[Disclaimer]**
|
||||
> 本程序**按原样提供**, 作者**不对程序的正确性或可靠性提供保证**, 请使用者自行判断具体场景是否适合使用该程序, **使用该程序造成的问题或后果由使用者自行承担**.
|
||||
>
|
||||
> 本程序为 EasyConnect 客户端的开源实现, 旨在帮助高校学生在校外访问校内资源, 没有绕过相关流量审计或安全审查的功能. EasyConnect 的一切权利属深信服所有, 若相关人员对该程序有异议, 请邮箱联系我. (admin@lyc8503.site)
|
||||
> 本程序为 NJU VPN 客户端的开源实现, 旨在帮助高校学生在校外访问校内资源, 没有绕过相关流量审计或安全审查的功能. 官方客户端的一切权利属深信服所有, 若相关人员对该程序有异议, 请邮箱联系我. (me@lyc8503.net)
|
||||
|
||||
---
|
||||
|
||||
虽然 NJU 使用的 VPN 是 EasyConnect,但此程序已不再与 EasyConnect 更新后的服务端兼容。南京大学的服务端~~疑似因没付钱~~从未更新过而一直可以使用,目前仅支持南大师生使用。其他问题请勿邮件我,我也无法回复。
|
||||
|
||||
---
|
||||
|
||||
由于深信服官方要求, 本项目不再维护, 如有需求建议使用虚拟机或 [docker-easyconnect](https://github.com/Hagb/docker-easyconnect) 的解决方案.
|
||||
|
||||
~~p.s. 倒也不至于删库跑路, 如果没特殊需要不用 fork...~~
|
||||
|
||||
最后的版本有两个, Build 14 和 Build 15 分别对应 master 和 dev 分支, 可以在 releases 中直接下载.
|
||||
|
||||
代码仅供学习交流, 撤回 AGPLv3 的相关开源许可证.
|
||||
|
||||
感谢所有 issue 提出者和 Contributor 做出的贡献~
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"EasierConnect/parser"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"runtime"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/tcpip/stack"
|
||||
)
|
||||
|
||||
// local socks5 binding
|
||||
var SocksBind string
|
||||
var DebugDump bool
|
||||
var ParseServConfig bool
|
||||
|
||||
type EasyConnectClient struct {
|
||||
queryConn net.Conn
|
||||
clientIp []byte
|
||||
@@ -36,53 +27,6 @@ func NewEasyConnectClient(server string) *EasyConnectClient {
|
||||
}
|
||||
}
|
||||
|
||||
func StartClient(host string, port int, username string, password string, twfId string) {
|
||||
server := fmt.Sprintf("%s:%d", host, port)
|
||||
|
||||
client := NewEasyConnectClient(server)
|
||||
|
||||
var ip []byte
|
||||
var err error
|
||||
if twfId != "" {
|
||||
if len(twfId) != 16 {
|
||||
panic("len(twfid) should be 16!")
|
||||
}
|
||||
ip, err = client.LoginByTwfId(twfId)
|
||||
} else {
|
||||
ip, err = client.Login(username, password)
|
||||
if err == ERR_NEXT_AUTH_SMS {
|
||||
fmt.Print(">>>Please enter your sms code<<<:")
|
||||
smsCode := ""
|
||||
_, err := fmt.Scan(&smsCode)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
return
|
||||
}
|
||||
|
||||
ip, err = client.AuthSMSCode(smsCode)
|
||||
} else if err == ERR_NEXT_AUTH_TOTP {
|
||||
fmt.Print(">>>Please enter your TOTP Auth code<<<:")
|
||||
TOTPCode := ""
|
||||
_, err := fmt.Scan(&TOTPCode)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
return
|
||||
}
|
||||
|
||||
ip, err = client.AuthTOTP(TOTPCode)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
log.Printf("Login success, your IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
|
||||
|
||||
client.ServeSocks5(SocksBind, DebugDump)
|
||||
|
||||
runtime.KeepAlive(client)
|
||||
}
|
||||
|
||||
func (client *EasyConnectClient) Login(username string, password string) ([]byte, error) {
|
||||
client.username = username
|
||||
client.password = password
|
||||
@@ -131,12 +75,6 @@ func (client *EasyConnectClient) LoginByTwfId(twfId string) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Parse Server config
|
||||
if ParseServConfig {
|
||||
parser.ParseResourceLists(client.server, twfId, DebugDump)
|
||||
parser.ParseConfLists(client.server, twfId, DebugDump)
|
||||
}
|
||||
|
||||
client.token = (*[48]byte)([]byte(agentToken + twfId))
|
||||
|
||||
// Query IP (keep the connection used so it's not closed too early, otherwise i/o stream will be closed)
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
package config
|
||||
|
||||
const PathConf string = "/por/conf.csp"
|
||||
const PathRlist string = "/por/rclist.csp"
|
||||
@@ -1,37 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/cornelk/hashmap"
|
||||
"log"
|
||||
)
|
||||
|
||||
// domain[ip]
|
||||
var dnsRules *hashmap.Map[string, string]
|
||||
|
||||
func AppendSingleDnsRule(domain, ip string, debug bool) {
|
||||
if dnsRules == nil {
|
||||
dnsRules = hashmap.New[string, string]()
|
||||
}
|
||||
|
||||
if debug {
|
||||
log.Printf("AppendSingleDnsRule: %s[%s]", domain, ip)
|
||||
}
|
||||
|
||||
dnsRules.Set(domain, ip)
|
||||
}
|
||||
|
||||
func GetSingleDnsRule(domain string) (string, bool) {
|
||||
return dnsRules.Get(domain)
|
||||
}
|
||||
|
||||
func IsDnsRuleAvailable() bool {
|
||||
return dnsRules != nil
|
||||
}
|
||||
|
||||
func GetDnsRuleLen() int {
|
||||
if IsDnsRuleAvailable() {
|
||||
return dnsRules.Len()
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/cornelk/hashmap"
|
||||
"log"
|
||||
)
|
||||
|
||||
// domain[[]int {min, max}]
|
||||
var domainRules *hashmap.Map[string, []int]
|
||||
|
||||
func AppendSingleDomainRule(domain string, ports []int, debug bool) {
|
||||
if domainRules == nil {
|
||||
domainRules = hashmap.New[string, []int]()
|
||||
}
|
||||
|
||||
if debug {
|
||||
log.Printf("AppendSingleDomainRule: %s[%v]", domain, ports)
|
||||
}
|
||||
|
||||
domainRules.Set(domain, ports)
|
||||
}
|
||||
|
||||
func GetSingleDomainRule(domain string) ([]int, bool) {
|
||||
return domainRules.Get(domain)
|
||||
}
|
||||
|
||||
func IsDomainRuleAvailable() bool {
|
||||
return domainRules != nil
|
||||
}
|
||||
|
||||
func GetDomainRuleLen() int {
|
||||
if IsDomainRuleAvailable() {
|
||||
return domainRules.Len()
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
)
|
||||
|
||||
var Ipv4RangeRules *[]Ipv4RangeRule
|
||||
|
||||
// Ipv4RangeRule Ipv4 rule with range
|
||||
type Ipv4RangeRule struct {
|
||||
Rule string
|
||||
Ports []int
|
||||
CIDR bool
|
||||
}
|
||||
|
||||
func AppendSingleIpv4RangeRule(rule string, ports []int, cidr bool, debug bool) {
|
||||
if Ipv4RangeRules == nil {
|
||||
Ipv4RangeRules = &[]Ipv4RangeRule{}
|
||||
}
|
||||
|
||||
if debug {
|
||||
log.Printf("AppendSingleIpv4RangeRule: %s%v cidr: %v", rule, ports, cidr)
|
||||
}
|
||||
|
||||
*Ipv4RangeRules = append(*Ipv4RangeRules, Ipv4RangeRule{Rule: rule, Ports: ports, CIDR: cidr})
|
||||
}
|
||||
|
||||
func GetIpv4Rules() *[]Ipv4RangeRule {
|
||||
return Ipv4RangeRules
|
||||
}
|
||||
|
||||
func IsIpv4RuleAvailable() bool {
|
||||
return Ipv4RangeRules != nil
|
||||
}
|
||||
|
||||
func GetIpv4RuleLen() int {
|
||||
if IsDomainRuleAvailable() {
|
||||
return len(*Ipv4RangeRules)
|
||||
} else {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
@@ -1,207 +0,0 @@
|
||||
package config
|
||||
|
||||
type ConfWeb struct {
|
||||
Conf Conf
|
||||
LocalConf struct {
|
||||
Session struct {
|
||||
NameFix string `xml:"nameFix,attr" json:"nameFix"`
|
||||
} `xml:"Session,attr" json:"Session"`
|
||||
} `xml:"LocalConf,attr" json:"LocalConf"`
|
||||
}
|
||||
|
||||
type Conf struct {
|
||||
EMM struct {
|
||||
NetworkWhiteList struct {
|
||||
ForbidIntranet string `xml:"forbid_intranet,attr"`
|
||||
ForbidInternet string `xml:"forbid_internet,attr"`
|
||||
} `xml:"NetworkWhiteList"`
|
||||
TicketEnable string `xml:"TicketEnable"`
|
||||
TicketLoginType string `xml:"TicketLoginType"`
|
||||
TicketLoginCode string `xml:"TicketLoginCode"`
|
||||
MdmPolicyEnable string `xml:"MdmPolicyEnable"`
|
||||
RdbUpdateTime string `xml:"RdbUpdateTime"`
|
||||
} `xml:"EMM"`
|
||||
AworkName string `xml:"AworkName"`
|
||||
WebSecLogin struct {
|
||||
LastLoginRes string `xml:"LastLoginRes"`
|
||||
LastLoginTime string `xml:"LastLoginTime"`
|
||||
LastLoginType string `xml:"LastLoginType"`
|
||||
LastOsType string `xml:"LastOsType"`
|
||||
LastLoginIp string `xml:"LastLoginIp"`
|
||||
LastLoginFails string `xml:"LastLoginFails"`
|
||||
LastLoginSuccTime string `xml:"LastLoginSuccTime"`
|
||||
LastLoginSwitch string `xml:"LastLoginSwitch"`
|
||||
} `xml:"WebSecLogin"`
|
||||
SysTray struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
SSLTrayIconMd5 string `xml:"SSLTrayIconMd5,attr"`
|
||||
SysShortCutName string `xml:"SysShortCutName,attr"`
|
||||
SSLTrayIconPath string `xml:"SSLTrayIconPath,attr"`
|
||||
} `xml:"SysTray"`
|
||||
Webagent struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
Address string `xml:"address,attr"`
|
||||
} `xml:"Webagent"`
|
||||
Mline struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
Number string `xml:"number,attr"`
|
||||
List string `xml:"list,attr"`
|
||||
Interval string `xml:"interval,attr"`
|
||||
Timeout string `xml:"timeout,attr"`
|
||||
} `xml:"Mline"`
|
||||
Vpnline struct {
|
||||
Address string `xml:"address,attr"`
|
||||
} `xml:"Vpnline"`
|
||||
Htp struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
Auto string `xml:"auto,attr"`
|
||||
Param string `xml:"param,attr"`
|
||||
Port string `xml:"port,attr"`
|
||||
Mtu string `xml:"mtu,attr"`
|
||||
} `xml:"Htp"`
|
||||
WebCache struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
Mode string `xml:"mode,attr"`
|
||||
Count string `xml:"count,attr"`
|
||||
URL string `xml:"url,attr"`
|
||||
} `xml:"WebCache"`
|
||||
WebOpt string `xml:"WebOpt"`
|
||||
Bandwidth struct {
|
||||
Recvlimit string `xml:"recvlimit,attr"`
|
||||
Sendlimit string `xml:"sendlimit,attr"`
|
||||
} `xml:"Bandwidth"`
|
||||
TcpApplication struct {
|
||||
UserMode string `xml:"userMode,attr"`
|
||||
Compress string `xml:"compress,attr"`
|
||||
Maxthread string `xml:"maxthread,attr"`
|
||||
Maxsession string `xml:"maxsession,attr"`
|
||||
} `xml:"TcpApplication"`
|
||||
L3VPN struct {
|
||||
IptunDns string `xml:"iptunDns,attr"`
|
||||
IptunDnsBak string `xml:"iptunDnsBak,attr"`
|
||||
} `xml:"L3VPN"`
|
||||
SCache struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
Gwid string `xml:"gwid,attr"`
|
||||
ID string `xml:"id,attr"`
|
||||
Cfgmd5 string `xml:"cfgmd5,attr"`
|
||||
Dllmd5 string `xml:"dllmd5,attr"`
|
||||
} `xml:"SCache"`
|
||||
DnsRuleExceptions struct {
|
||||
Text string `xml:",chardata"`
|
||||
Exception []string `xml:"Exception"`
|
||||
} `xml:"DnsRuleExceptions"`
|
||||
UsbKey struct {
|
||||
Version string `xml:"version,attr"`
|
||||
Certinput string `xml:"certinput,attr"`
|
||||
Typeinfo string `xml:"typeinfo,attr"`
|
||||
Typecount string `xml:"typecount,attr"`
|
||||
} `xml:"UsbKey"`
|
||||
CDC struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
LogKey string `xml:"LogKey,attr"`
|
||||
UseUsersLog string `xml:"useUsersLog,attr"`
|
||||
LogInterval string `xml:"LogInterval,attr"`
|
||||
GrpIdInt string `xml:"GrpIdInt,attr"`
|
||||
AuthPast string `xml:"AuthPast,attr"`
|
||||
} `xml:"CDC"`
|
||||
Autorule struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
EnableLimit string `xml:"enable_limit,attr"`
|
||||
GatherRuleLimit string `xml:"gather_rule_limit,attr"`
|
||||
Mode string `xml:"mode,attr"`
|
||||
Count string `xml:"count,attr"`
|
||||
RuleLimit string `xml:"rule_limit,attr"`
|
||||
Domain string `xml:"domain,attr"`
|
||||
} `xml:"Autorule"`
|
||||
Other struct {
|
||||
LoginName string `xml:"login_name,attr"`
|
||||
SddnEnable string `xml:"sddn_enable,attr"`
|
||||
Sslctx string `xml:"sslctx,attr"`
|
||||
Displayhost string `xml:"displayhost,attr"`
|
||||
DenyNormalAccess string `xml:"denyNormalAccess,attr"`
|
||||
EnableAutoRelogin string `xml:"enableAutoRelogin,attr"`
|
||||
Autorelogininterval string `xml:"autorelogininterval,attr"`
|
||||
Autorelogintimes string `xml:"autorelogintimes,attr"`
|
||||
IsRelogin string `xml:"isRelogin,attr"`
|
||||
RelogTimeLast string `xml:"RelogTimeLast,attr"`
|
||||
RelogIPLast string `xml:"RelogIPLast,attr"`
|
||||
AutoStartCS string `xml:"autoStartCS,attr"`
|
||||
PwpRemindMsg string `xml:"pwp_remind_msg,attr"`
|
||||
Svpnlanaddr string `xml:"svpnlanaddr,attr"`
|
||||
IsPubUser string `xml:"isPubUser,attr"`
|
||||
IsExtern string `xml:"isExtern,attr"`
|
||||
IsHidUser string `xml:"isHidUser,attr"`
|
||||
Enablesavepwd string `xml:"enablesavepwd,attr"`
|
||||
EnableCsRcWindows string `xml:"enable_cs_rc_windows,attr"`
|
||||
Enableautologin string `xml:"enableautologin,attr"`
|
||||
ChgPwdEnable string `xml:"chg_pwd_enable,attr"`
|
||||
ChgPhoneEnable string `xml:"chg_phone_enable,attr"`
|
||||
ChgNoteEnable string `xml:"chg_note_enable,attr"`
|
||||
AuthSms string `xml:"auth_sms,attr"`
|
||||
Mobilephone string `xml:"mobilephone,attr"`
|
||||
UserNote string `xml:"user_note,attr"`
|
||||
PswMinlen string `xml:"psw_minlen,attr"`
|
||||
PptpGrpolicy string `xml:"pptp_grpolicy,attr"`
|
||||
PptpDetaddr string `xml:"pptp_detaddr,attr"`
|
||||
Vpntype string `xml:"vpntype,attr"`
|
||||
Deviceversion string `xml:"deviceversion,attr"`
|
||||
UserAuthPast string `xml:"UserAuthPast,attr"`
|
||||
UserPwd string `xml:"UserPwd,attr"`
|
||||
AccessibleAddr string `xml:"AccessibleAddr,attr"`
|
||||
} `xml:"Other"`
|
||||
RemoteApp struct {
|
||||
AccountPolicy string `xml:"account_policy,attr"`
|
||||
SessionKeeptime string `xml:"session_keeptime,attr"`
|
||||
MapDisk string `xml:"MapDisk,attr"`
|
||||
MapClipboard string `xml:"MapClipboard,attr"`
|
||||
MapPrinter string `xml:"MapPrinter,attr"`
|
||||
VirtualPrinter string `xml:"VirtualPrinter,attr"`
|
||||
RappResuse string `xml:"rapp_resuse,attr"`
|
||||
VirtualPrintMode string `xml:"VirtualPrintMode,attr"`
|
||||
UseRdp string `xml:"UseRdp,attr"`
|
||||
PrintPaper string `xml:"PrintPaper"`
|
||||
PrivateFolderName string `xml:"PrivateFolderName"`
|
||||
SRAPOption struct {
|
||||
LossCompressor struct {
|
||||
Type string `xml:"type,attr"`
|
||||
Ratio string `xml:"ratio,attr"`
|
||||
Quality string `xml:"quality,attr"`
|
||||
} `xml:"LossCompressor"`
|
||||
GlyphCompress struct {
|
||||
Option string `xml:"option,attr"`
|
||||
JpegQuality string `xml:"jpeg_quality,attr"`
|
||||
} `xml:"GlyphCompress"`
|
||||
NoLossCompressor struct {
|
||||
BmpCompressor string `xml:"bmp_compressor,attr"`
|
||||
CompressorType string `xml:"compressor_type,attr"`
|
||||
} `xml:"NoLossCompressor"`
|
||||
CacheHash struct {
|
||||
OpType string `xml:"op_type,attr"`
|
||||
} `xml:"CacheHash"`
|
||||
StreamMerge struct {
|
||||
Type string `xml:"type,attr"`
|
||||
Threshold string `xml:"threshold,attr"`
|
||||
Uptime string `xml:"uptime,attr"`
|
||||
} `xml:"StreamMerge"`
|
||||
} `xml:"SRAPOption"`
|
||||
} `xml:"RemoteApp"`
|
||||
SSLCipherSuite struct {
|
||||
EC string `xml:"EC"`
|
||||
TCP string `xml:"TCP"`
|
||||
L3VPN string `xml:"L3VPN"`
|
||||
} `xml:"SSLCipherSuite"`
|
||||
SSLEigenvalue struct {
|
||||
TCP string `xml:"TCP"`
|
||||
L3VPN string `xml:"L3VPN"`
|
||||
} `xml:"SSLEigenvalue"`
|
||||
Logo struct {
|
||||
Custom string `xml:"custom,attr"`
|
||||
LogoMd5 string `xml:"LogoMd5,attr"`
|
||||
LogoPath string `xml:"LogoPath,attr"`
|
||||
} `xml:"Logo"`
|
||||
WebHttpEnable struct {
|
||||
HttpPort string `xml:"httpPort,attr"`
|
||||
Enable string `xml:"enable,attr"`
|
||||
} `xml:"WebHttpEnable"`
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package config
|
||||
|
||||
type RcData struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Name string `xml:"name,attr"`
|
||||
Type string `xml:"type,attr"`
|
||||
Proto string `xml:"proto,attr"`
|
||||
Svc string `xml:"svc,attr"`
|
||||
Host string `xml:"host,attr"`
|
||||
Port string `xml:"port,attr"`
|
||||
EnableDisguise string `xml:"enable_disguise,attr"`
|
||||
Note string `xml:"note,attr"`
|
||||
Attr string `xml:"attr,attr"`
|
||||
AppPath string `xml:"app_path,attr"`
|
||||
RcGrpID string `xml:"rc_grp_id,attr"`
|
||||
RcLogo string `xml:"rc_logo,attr"`
|
||||
Authorization string `xml:"authorization,attr"`
|
||||
AuthSpID string `xml:"auth_sp_id,attr"`
|
||||
Selectid string `xml:"selectid,attr"`
|
||||
}
|
||||
|
||||
type ResourceWeb struct {
|
||||
Resource Resource
|
||||
LocalConf struct {
|
||||
Session struct {
|
||||
NameFix string `xml:"nameFix,attr" json:"nameFix"`
|
||||
} `xml:"Session,attr" json:"Session"`
|
||||
} `xml:"LocalConf,attr" json:"LocalConf"`
|
||||
}
|
||||
|
||||
type Resource struct {
|
||||
Rcs struct {
|
||||
Rc []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Name string `xml:"name,attr"`
|
||||
Type string `xml:"type,attr"`
|
||||
Proto string `xml:"proto,attr"`
|
||||
Svc string `xml:"svc,attr"`
|
||||
Host string `xml:"host,attr"`
|
||||
Port string `xml:"port,attr"`
|
||||
EnableDisguise string `xml:"enable_disguise,attr"`
|
||||
Note string `xml:"note,attr"`
|
||||
Attr string `xml:"attr,attr"`
|
||||
AppPath string `xml:"app_path,attr"`
|
||||
RcGrpID string `xml:"rc_grp_id,attr"`
|
||||
RcLogo string `xml:"rc_logo,attr"`
|
||||
Authorization string `xml:"authorization,attr"`
|
||||
AuthSpID string `xml:"auth_sp_id,attr"`
|
||||
Selectid string `xml:"selectid,attr"`
|
||||
} `xml:"Rc"`
|
||||
} `xml:"Rcs"`
|
||||
RcGroups struct {
|
||||
Group []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Name string `xml:"name,attr"`
|
||||
Type string `xml:"type,attr"`
|
||||
Logowidth string `xml:"logowidth,attr"`
|
||||
Logoheight string `xml:"logoheight,attr"`
|
||||
LoadBalance string `xml:"load_balance,attr"`
|
||||
ShowNote string `xml:"show_note,attr"`
|
||||
} `xml:"Group"`
|
||||
} `xml:"RcGroups"`
|
||||
SD struct {
|
||||
Global struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
SDRedirectFile string `xml:"SDRedirectFile,attr"`
|
||||
} `xml:"Global"`
|
||||
Policy struct {
|
||||
ID string `xml:"id,attr"`
|
||||
} `xml:"Policy"`
|
||||
DesktopFormat struct {
|
||||
Safedesk string `xml:"safedesk,attr"`
|
||||
Com string `xml:"com,attr"`
|
||||
Infrared string `xml:"infrared,attr"`
|
||||
Bluetooth string `xml:"bluetooth,attr"`
|
||||
Printer string `xml:"printer,attr"`
|
||||
Changedesk string `xml:"changedesk,attr"`
|
||||
RegisterUnMon string `xml:"register_un_mon,attr"`
|
||||
SafedeskLocalTransport string `xml:"safedesk_local_transport,attr"`
|
||||
RappInSafedesk string `xml:"rapp_in_safedesk,attr"`
|
||||
} `xml:"DesktopFormat"`
|
||||
Internet struct {
|
||||
Tempbuf string `xml:"tempbuf,attr"`
|
||||
History string `xml:"history,attr"`
|
||||
Tables string `xml:"tables,attr"`
|
||||
Cookies string `xml:"cookies,attr"`
|
||||
} `xml:"Internet"`
|
||||
Iplist struct {
|
||||
Iplist string `xml:"iplist,attr"`
|
||||
} `xml:"iplist"`
|
||||
Rclist struct {
|
||||
Rclist string `xml:"rclist,attr"`
|
||||
} `xml:"rclist"`
|
||||
} `xml:"SD"`
|
||||
Dns struct {
|
||||
Dnsserver string `xml:"dnsserver,attr"`
|
||||
Data string `xml:"data,attr"`
|
||||
Filter string `xml:"filter,attr"`
|
||||
} `xml:"Dns"`
|
||||
FileLock struct {
|
||||
Data string `xml:"data,attr"`
|
||||
Filecount string `xml:"filecount,attr"`
|
||||
Maxfilecount string `xml:"maxfilecount,attr"`
|
||||
} `xml:"FileLock"`
|
||||
UB struct {
|
||||
IndexInner string `xml:"index_inner,attr"`
|
||||
Ubdllinfo string `xml:"ubdllinfo,attr"`
|
||||
} `xml:"UB"`
|
||||
Easylink struct {
|
||||
ElnkRc struct {
|
||||
ID string `xml:"Id"`
|
||||
ElnkRewrite string `xml:"ElnkRewrite"`
|
||||
Mode string `xml:"Mode"`
|
||||
MapAddr string `xml:"MapAddr"`
|
||||
} `xml:"ElnkRc"`
|
||||
} `xml:"Easylink"`
|
||||
Other struct {
|
||||
DefaultRcId string `xml:"defaultRcId,attr"`
|
||||
AllocateVip string `xml:"allocateVip,attr"`
|
||||
Balanceinfo string `xml:"balanceinfo,attr"`
|
||||
} `xml:"Other"`
|
||||
UrlWarrentRules struct {
|
||||
Enable string `xml:"enable,attr"`
|
||||
Filter string `xml:"filter,attr"`
|
||||
Tips string `xml:"tips,attr"`
|
||||
} `xml:"UrlWarrentRules"`
|
||||
MSGINFO string `xml:"MSG_INFO"`
|
||||
WebSsoInfos string `xml:"WebSsoInfos"`
|
||||
VSP struct {
|
||||
Misc struct {
|
||||
SDTitle string `xml:"SDTitle,attr"`
|
||||
ShowRcInSD string `xml:"ShowRcInSD,attr"`
|
||||
ShowUserShortCutIconInSD string `xml:"ShowUserShortCutIconInSD,attr"`
|
||||
} `xml:"Misc"`
|
||||
WallPaper struct {
|
||||
Type string `xml:"Type,attr"`
|
||||
URL string `xml:"Url,attr"`
|
||||
Compress string `xml:"Compress,attr"`
|
||||
MD5 string `xml:"MD5,attr"`
|
||||
} `xml:"WallPaper"`
|
||||
Inject struct {
|
||||
Type string `xml:"Type,attr"`
|
||||
} `xml:"Inject"`
|
||||
NavBar struct {
|
||||
IconUrl string `xml:"IconUrl,attr"`
|
||||
MD5 string `xml:"MD5,attr"`
|
||||
} `xml:"NavBar"`
|
||||
OfflineVisit struct {
|
||||
Enable string `xml:"Enable,attr"`
|
||||
VisitTime string `xml:"VisitTime,attr"`
|
||||
IsBind string `xml:"IsBind,attr"`
|
||||
} `xml:"OfflineVisit"`
|
||||
RedirectData struct {
|
||||
ProcessType string `xml:"ProcessType,attr"`
|
||||
UseCustomDefine string `xml:"UseCustomDefine,attr"`
|
||||
} `xml:"RedirectData"`
|
||||
Crypto struct {
|
||||
Type string `xml:"Type,attr"`
|
||||
Length string `xml:"Length,attr"`
|
||||
Ctx string `xml:"Ctx,attr"`
|
||||
} `xml:"Crypto"`
|
||||
ReDirect struct {
|
||||
NameRule string `xml:"NameRule,attr"`
|
||||
Ctx string `xml:"Ctx,attr"`
|
||||
} `xml:"ReDirect"`
|
||||
FileExport struct {
|
||||
Enable string `xml:"Enable,attr"`
|
||||
AuditLog string `xml:"AuditLog,attr"`
|
||||
MaxAuditFileSize string `xml:"MaxAuditFileSize,attr"`
|
||||
Compress string `xml:"Compress,attr"`
|
||||
} `xml:"FileExport"`
|
||||
ActiveXProxyInstall struct {
|
||||
Enable string `xml:"Enable,attr"`
|
||||
} `xml:"ActiveXProxyInstall"`
|
||||
LocalCommunication struct {
|
||||
Enable string `xml:"Enable,attr"`
|
||||
} `xml:"LocalCommunication"`
|
||||
ExecutableProcess struct {
|
||||
Enable string `xml:"Enable,attr"`
|
||||
} `xml:"ExecutableProcess"`
|
||||
} `xml:"VSP"`
|
||||
StaticSd struct {
|
||||
SpecileFile string `xml:"SpecileFile"`
|
||||
SpecileKey struct {
|
||||
Text string `xml:",chardata"`
|
||||
KeyList []string `xml:"KeyList"`
|
||||
} `xml:"SpecileKey"`
|
||||
SpecileProc struct {
|
||||
ProcList string `xml:"ProcList"`
|
||||
} `xml:"SpecileProc"`
|
||||
DefaultExecutableProcess struct {
|
||||
WhiteListItem []struct {
|
||||
FileName string `xml:"FileName"`
|
||||
Value string `xml:"Value"`
|
||||
VerifyType string `xml:"VerifyType"`
|
||||
} `xml:"WhiteListItem"`
|
||||
} `xml:"DefaultExecutableProcess"`
|
||||
NotifySize string `xml:"NotifySize"`
|
||||
EnTopTool string `xml:"EnTopTool"`
|
||||
ActiveXProxyProcess struct {
|
||||
Process struct {
|
||||
Name string `xml:"Name,attr"`
|
||||
} `xml:"Process"`
|
||||
} `xml:"ActiveXProxyProcess"`
|
||||
RedirectObjectRule struct {
|
||||
Count string `xml:"Count,attr"`
|
||||
Rule []struct {
|
||||
ObjectType string `xml:"ObjectType,attr"`
|
||||
Disable string `xml:"Disable,attr"`
|
||||
MatchRule string `xml:"MatchRule,attr"`
|
||||
ObjectName string `xml:"ObjectName,attr"`
|
||||
ProcessName string `xml:"ProcessName,attr"`
|
||||
} `xml:"Rule"`
|
||||
} `xml:"RedirectObjectRule"`
|
||||
DeniService struct {
|
||||
Count string `xml:"Count,attr"`
|
||||
Service []struct {
|
||||
Name string `xml:"name,attr"`
|
||||
} `xml:"Service"`
|
||||
} `xml:"DeniService"`
|
||||
InterceptSet struct {
|
||||
Count string `xml:"Count,attr"`
|
||||
Item []struct {
|
||||
Type string `xml:"Type,attr"`
|
||||
Name string `xml:"Name,attr"`
|
||||
} `xml:"Item"`
|
||||
} `xml:"InterceptSet"`
|
||||
InjectAgentWhiteList struct {
|
||||
Count string `xml:"Count,attr"`
|
||||
ProcName []struct {
|
||||
Name string `xml:"name,attr"`
|
||||
} `xml:"ProcName"`
|
||||
} `xml:"InjectAgentWhiteList"`
|
||||
VBRule struct {
|
||||
Text string `xml:",chardata"`
|
||||
Enable string `xml:"Enable,attr"`
|
||||
ProcName []string `xml:"ProcName"`
|
||||
} `xml:"VBRule"`
|
||||
NetDrvInfo struct {
|
||||
WorkMode string `xml:"WorkMode,attr"`
|
||||
WhiteListItem []struct {
|
||||
FileName string `xml:"FileName,attr"`
|
||||
VerifyType string `xml:"VerifyType,attr"`
|
||||
Value string `xml:"Value,attr"`
|
||||
} `xml:"WhiteListItem"`
|
||||
} `xml:"NetDrvInfo"`
|
||||
DenyProcess struct {
|
||||
Item []struct {
|
||||
FileName string `xml:"FileName,attr"`
|
||||
Info string `xml:"Info,attr"`
|
||||
} `xml:"Item"`
|
||||
} `xml:"DenyProcess"`
|
||||
WhitePipeOfProcess struct {
|
||||
EnablePipeRule string `xml:"EnablePipeRule,attr"`
|
||||
Item []struct {
|
||||
FileName string `xml:"FileName,attr"`
|
||||
Info string `xml:"Info,attr"`
|
||||
PipeName string `xml:"PipeName,attr"`
|
||||
} `xml:"Item"`
|
||||
} `xml:"WhitePipeOfProcess"`
|
||||
Drivers struct {
|
||||
Enable string `xml:"Enable,attr"`
|
||||
Driver []struct {
|
||||
Name string `xml:"Name,attr"`
|
||||
Enable string `xml:"Enable,attr"`
|
||||
} `xml:"Driver"`
|
||||
} `xml:"Drivers"`
|
||||
UsbWhiteProcess struct {
|
||||
Rule []struct {
|
||||
ProcessName string `xml:"ProcessName,attr"`
|
||||
Info string `xml:"Info,attr"`
|
||||
Type string `xml:"Type,attr"`
|
||||
} `xml:"Rule"`
|
||||
} `xml:"UsbWhiteProcess"`
|
||||
} `xml:"StaticSd"`
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
@@ -13,25 +12,6 @@ import (
|
||||
tls "github.com/refraction-networking/utls"
|
||||
)
|
||||
|
||||
type FakeHeartBeatExtension struct {
|
||||
*tls.GenericExtension
|
||||
}
|
||||
|
||||
func (e *FakeHeartBeatExtension) Len() int {
|
||||
return 5
|
||||
}
|
||||
|
||||
func (e *FakeHeartBeatExtension) Read(b []byte) (n int, err error) {
|
||||
if len(b) < e.Len() {
|
||||
return 0, io.ErrShortBuffer
|
||||
}
|
||||
b[1] = 0x0f
|
||||
b[3] = 1
|
||||
b[4] = 1
|
||||
|
||||
return e.Len(), io.EOF
|
||||
}
|
||||
|
||||
func DumpHex(buf []byte) {
|
||||
stdoutDumper := hex.Dumper(os.Stdout)
|
||||
defer stdoutDumper.Close()
|
||||
@@ -56,11 +36,8 @@ func TLSConn(server string) (*tls.UConn, error) {
|
||||
conn.SetTLSVers(tls.VersionTLS11, tls.VersionTLS11, []tls.TLSExtension{})
|
||||
conn.HandshakeState.Hello.Vers = tls.VersionTLS11
|
||||
conn.HandshakeState.Hello.CipherSuites = []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.FAKE_TLS_EMPTY_RENEGOTIATION_INFO_SCSV}
|
||||
conn.HandshakeState.Hello.CompressionMethods = []uint8{1, 0}
|
||||
conn.HandshakeState.Hello.CompressionMethods = []uint8{0}
|
||||
conn.HandshakeState.Hello.SessionId = []byte{'L', '3', 'I', 'P', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
|
||||
conn.Extensions = []tls.TLSExtension{
|
||||
&FakeHeartBeatExtension{},
|
||||
}
|
||||
|
||||
log.Println("tls: connected to: ", conn.RemoteAddr())
|
||||
|
||||
@@ -212,11 +189,11 @@ func StartProtocol(endpoint *EasyConnectEndpoint, server string, token *[48]byte
|
||||
for counter < 5 {
|
||||
err := BlockRXStream(server, token, ipRev, endpoint, debug)
|
||||
if err != nil {
|
||||
log.Print("Error occurred while receiving, retrying: " + err.Error())
|
||||
log.Print("Error occurred while recv, retrying: " + err.Error())
|
||||
}
|
||||
counter += 1
|
||||
}
|
||||
panic("receive retry limit exceeded.")
|
||||
panic("recv retry limit exceeded.")
|
||||
}
|
||||
|
||||
go RX()
|
||||
|
||||
126
core/socks.go
126
core/socks.go
@@ -1,17 +1,13 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"math"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"EasierConnect/core/config"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
|
||||
"gvisor.dev/gvisor/pkg/tcpip/header"
|
||||
@@ -25,121 +21,33 @@ func ServeSocks5(ipStack *stack.Stack, selfIp []byte, bindAddr string) {
|
||||
|
||||
log.Printf("socks dial: %s", addr)
|
||||
|
||||
parts := strings.Split(addr, ":")
|
||||
if network != "tcp" {
|
||||
return nil, errors.New("only support tcp")
|
||||
}
|
||||
|
||||
parts := strings.Split(addr, ":")
|
||||
target, err := net.ResolveIPAddr("ip", parts[0])
|
||||
if err != nil {
|
||||
return nil, errors.New("resolve ip addr failed: " + parts[0])
|
||||
}
|
||||
|
||||
ip := parts[0]
|
||||
port, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid port: " + parts[1])
|
||||
}
|
||||
|
||||
var allowedPorts = []int{1, 65535} // [0] -> Min, [1] -> Max
|
||||
var useL3transport = true
|
||||
var hasDnsRule = false
|
||||
|
||||
var target *net.IPAddr
|
||||
|
||||
if config.IsDomainRuleAvailable() {
|
||||
allowedPorts, useL3transport = config.GetSingleDomainRule(ip)
|
||||
addrTarget := tcpip.FullAddress{
|
||||
NIC: defaultNIC,
|
||||
Port: uint16(port),
|
||||
Addr: tcpip.Address(target.IP),
|
||||
}
|
||||
|
||||
if config.IsDnsRuleAvailable() {
|
||||
var dnsRules string
|
||||
dnsRules, hasDnsRule = config.GetSingleDnsRule(ip)
|
||||
|
||||
if hasDnsRule {
|
||||
ip = dnsRules
|
||||
}
|
||||
bind := tcpip.FullAddress{
|
||||
NIC: defaultNIC,
|
||||
Addr: tcpip.Address(selfIp),
|
||||
}
|
||||
|
||||
target, err = net.ResolveIPAddr("ip", ip)
|
||||
if err != nil {
|
||||
return nil, errors.New("resolve ip addr failed: " + ip)
|
||||
}
|
||||
|
||||
if !useL3transport && config.IsDomainRuleAvailable() {
|
||||
log.Printf("final ip: %s", target.IP.String())
|
||||
allowedPorts, useL3transport = config.GetSingleDomainRule(target.IP.String())
|
||||
}
|
||||
|
||||
if !useL3transport && config.IsIpv4RuleAvailable() {
|
||||
if DebugDump {
|
||||
log.Printf("Ipv4Rule is available ")
|
||||
}
|
||||
for _, rule := range *config.GetIpv4Rules() {
|
||||
if rule.CIDR {
|
||||
_, cidr, _ := net.ParseCIDR(rule.Rule)
|
||||
if DebugDump {
|
||||
log.Printf("Cidr test: %s %s %v", target.IP, rule.Rule, cidr.Contains(target.IP))
|
||||
}
|
||||
|
||||
if cidr.Contains(target.IP) {
|
||||
if DebugDump {
|
||||
log.Printf("Cidr matched: %s %s", target.IP, rule.Rule)
|
||||
}
|
||||
|
||||
useL3transport = true
|
||||
allowedPorts = rule.Ports
|
||||
}
|
||||
} else {
|
||||
if DebugDump {
|
||||
log.Printf("raw match test: %s %s", target.IP, rule.Rule)
|
||||
}
|
||||
|
||||
ip1 := net.ParseIP(strings.Split(rule.Rule, "~")[0])
|
||||
ip2 := net.ParseIP(strings.Split(rule.Rule, "~")[1])
|
||||
|
||||
if bytes.Compare(target.IP, ip1) >= 0 && bytes.Compare(target.IP, ip2) <= 0 {
|
||||
if DebugDump {
|
||||
log.Printf("raw matched: %s %s", ip1, ip2)
|
||||
}
|
||||
|
||||
useL3transport = true
|
||||
allowedPorts = rule.Ports
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if config.IsDomainRuleAvailable() {
|
||||
allowAllWebSitesPorts, allowAllWebSites := config.GetSingleDomainRule("*")
|
||||
|
||||
if allowAllWebSites {
|
||||
if allowAllWebSitesPorts[0] > 0 && allowAllWebSitesPorts[1] > 0 {
|
||||
allowedPorts[0] = int(math.Min(float64(allowedPorts[0]), float64(allowAllWebSitesPorts[0])))
|
||||
allowedPorts[1] = int(math.Max(float64(allowedPorts[1]), float64(allowAllWebSitesPorts[1])))
|
||||
|
||||
useL3transport = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("Addr: %s, AllowedPorts: %v, useL3transport: %v, useCustomDns: %v, ResolvedIp: %s", addr, allowedPorts, useL3transport, hasDnsRule, ip)
|
||||
|
||||
if (!useL3transport && hasDnsRule) || (useL3transport && port >= allowedPorts[0] && port <= allowedPorts[1]) {
|
||||
if network != "tcp" {
|
||||
return nil, errors.New("only support tcp")
|
||||
}
|
||||
|
||||
addrTarget := tcpip.FullAddress{
|
||||
NIC: defaultNIC,
|
||||
Port: uint16(port),
|
||||
Addr: tcpip.Address(target.IP),
|
||||
}
|
||||
|
||||
bind := tcpip.FullAddress{
|
||||
NIC: defaultNIC,
|
||||
Addr: tcpip.Address(selfIp),
|
||||
}
|
||||
|
||||
return gonet.DialTCPWithBind(context.Background(), ipStack, bind, addrTarget, header.IPv4ProtocolNumber)
|
||||
}
|
||||
goDialer := &net.Dialer{}
|
||||
goDial := goDialer.DialContext
|
||||
|
||||
log.Printf("skip: %s", addr)
|
||||
|
||||
return goDial(ctx, network, addr)
|
||||
return gonet.DialTCPWithBind(context.Background(), ipStack, bind, addrTarget, header.IPv4ProtocolNumber)
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -49,11 +49,11 @@ func (ep *EasyConnectEndpoint) ARPHardwareType() header.ARPHardwareType {
|
||||
return header.ARPHardwareNone
|
||||
}
|
||||
|
||||
func (ep *EasyConnectEndpoint) AddHeader(stack.PacketBufferPtr) {}
|
||||
func (ep *EasyConnectEndpoint) AddHeader(buffer *stack.PacketBuffer) {}
|
||||
|
||||
func (ep *EasyConnectEndpoint) WritePackets(list stack.PacketBufferList) (int, tcpip.Error) {
|
||||
for _, packetBuffer := range list.AsSlice() {
|
||||
var buf []byte
|
||||
buf := []byte{}
|
||||
for _, t := range packetBuffer.AsSlices() {
|
||||
buf = append(buf, t...)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
@@ -22,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
var ERR_NEXT_AUTH_SMS = errors.New("SMS Code required")
|
||||
var ERR_NEXT_AUTH_TOTP = errors.New("current user's TOTP bound")
|
||||
var ERR_NEXT_AUTH_TOTP = errors.New("Current user's TOTP bound")
|
||||
|
||||
func WebLogin(server string, username string, password string) (string, error) {
|
||||
server = "https://" + server
|
||||
@@ -43,16 +42,16 @@ func WebLogin(server string, username string, password string) (string, error) {
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, resp.Body)
|
||||
buf := make([]byte, 40960)
|
||||
n, _ := resp.Body.Read(buf)
|
||||
|
||||
twfId := string(regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf.Bytes())[1])
|
||||
twfId := string(regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf[:n])[1])
|
||||
log.Printf("Twf Id: %s", twfId)
|
||||
|
||||
rsaKey := string(regexp.MustCompile(`<RSA_ENCRYPT_KEY>(.*)</RSA_ENCRYPT_KEY>`).FindSubmatch(buf.Bytes())[1])
|
||||
rsaKey := string(regexp.MustCompile(`<RSA_ENCRYPT_KEY>(.*)</RSA_ENCRYPT_KEY>`).FindSubmatch(buf[:n])[1])
|
||||
log.Printf("RSA Key: %s", rsaKey)
|
||||
|
||||
rsaExpMatch := regexp.MustCompile(`<RSA_ENCRYPT_EXP>(.*)</RSA_ENCRYPT_EXP>`).FindSubmatch(buf.Bytes())
|
||||
rsaExpMatch := regexp.MustCompile(`<RSA_ENCRYPT_EXP>(.*)</RSA_ENCRYPT_EXP>`).FindSubmatch(buf[:n])
|
||||
rsaExp := ""
|
||||
if rsaExpMatch != nil {
|
||||
rsaExp = string(rsaExpMatch[1])
|
||||
@@ -62,7 +61,7 @@ func WebLogin(server string, username string, password string) (string, error) {
|
||||
}
|
||||
log.Printf("RSA Exp: %s", rsaExp)
|
||||
|
||||
csrfMatch := regexp.MustCompile(`<CSRF_RAND_CODE>(.*)</CSRF_RAND_CODE>`).FindSubmatch(buf.Bytes())
|
||||
csrfMatch := regexp.MustCompile(`<CSRF_RAND_CODE>(.*)</CSRF_RAND_CODE>`).FindSubmatch(buf[:n])
|
||||
csrfCode := ""
|
||||
if csrfMatch != nil {
|
||||
csrfCode = string(csrfMatch[1])
|
||||
@@ -107,14 +106,13 @@ func WebLogin(server string, username string, password string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
io.Copy(&buf, resp.Body)
|
||||
n, _ = resp.Body.Read(buf)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// log.Printf("First stage login response: %s", string(buf[:n]))
|
||||
|
||||
// SMS Code Process
|
||||
if strings.Contains(buf.String(), "<NextService>auth/sms</NextService>") || strings.Contains(buf.String(), "<NextAuth>2</NextAuth>") {
|
||||
if strings.Contains(string(buf[:n]), "<NextService>auth/sms</NextService>") || strings.Contains(string(buf[:n]), "<NextAuth>2</NextAuth>") {
|
||||
log.Print("SMS code required.")
|
||||
|
||||
addr = server + "/por/login_sms.csp?apiversion=1"
|
||||
@@ -128,13 +126,12 @@ func WebLogin(server string, username string, password string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
io.Copy(&buf, resp.Body)
|
||||
n, _ := resp.Body.Read(buf)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if !strings.Contains(buf.String(), "验证码已发送到您的手机") && !strings.Contains(buf.String(), "<USER_PHONE>") {
|
||||
if !strings.Contains(string(buf[:n]), "验证码已发送到您的手机") && !strings.Contains(string(buf[:n]), "<USER_PHONE>") {
|
||||
debug.PrintStack()
|
||||
return "", errors.New("unexpected sms resp: " + buf.String())
|
||||
return "", errors.New("unexpected sms resp: " + string(buf[:n]))
|
||||
}
|
||||
|
||||
log.Printf("SMS Code is sent or still valid.")
|
||||
@@ -143,24 +140,24 @@ func WebLogin(server string, username string, password string) (string, error) {
|
||||
}
|
||||
|
||||
// TOTP Authnication Process (Edited by JHong)
|
||||
if strings.Contains(buf.String(), "<NextService>auth/token</NextService>") || strings.Contains(buf.String(), "<NextServiceSubType>totp</NextServiceSubType>") {
|
||||
if strings.Contains(string(buf[:n]), "<NextService>auth/token</NextService>") || strings.Contains(string(buf[:n]), "<NextServiceSubType>totp</NextServiceSubType>") {
|
||||
log.Print("TOTP Authnication required.")
|
||||
return twfId, ERR_NEXT_AUTH_TOTP
|
||||
}
|
||||
|
||||
if strings.Contains(buf.String(), "<NextAuth>-1</NextAuth>") || !strings.Contains(buf.String(), "<NextAuth>") {
|
||||
if strings.Contains(string(buf[:n]), "<NextAuth>-1</NextAuth>") || !strings.Contains(string(buf[:n]), "<NextAuth>") {
|
||||
log.Print("No NextAuth found.")
|
||||
} else {
|
||||
debug.PrintStack()
|
||||
return "", errors.New("Not implemented auth: " + buf.String())
|
||||
return "", errors.New("Not implemented auth: " + string(buf[:n]))
|
||||
}
|
||||
|
||||
if !strings.Contains(buf.String(), "<Result>1</Result>") {
|
||||
if !strings.Contains(string(buf[:n]), "<Result>1</Result>") {
|
||||
debug.PrintStack()
|
||||
return "", errors.New("Login FAILED: " + buf.String())
|
||||
return "", errors.New("Login FAILED: " + string(buf[:n]))
|
||||
}
|
||||
|
||||
twfIdMatch := regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf.Bytes())
|
||||
twfIdMatch := regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf[:n])
|
||||
if twfIdMatch != nil {
|
||||
twfId = string(twfIdMatch[1])
|
||||
log.Printf("Update twfId: %s", twfId)
|
||||
@@ -177,6 +174,8 @@ func AuthSms(server string, username string, password string, twfId string, smsC
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}}
|
||||
|
||||
buf := make([]byte, 40960)
|
||||
|
||||
addr := "https://" + server + "/por/login_sms1.csp?apiversion=1"
|
||||
log.Printf("SMS Request: " + addr)
|
||||
form := url.Values{
|
||||
@@ -192,16 +191,15 @@ func AuthSms(server string, username string, password string, twfId string, smsC
|
||||
return "", err
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, resp.Body)
|
||||
n, _ := resp.Body.Read(buf)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if !strings.Contains(buf.String(), "Auth sms suc") {
|
||||
if !strings.Contains(string(buf[:n]), "Auth sms suc") {
|
||||
debug.PrintStack()
|
||||
return "", errors.New("SMS Code verification FAILED: " + buf.String())
|
||||
return "", errors.New("SMS Code verification FAILED: " + string(buf[:n]))
|
||||
}
|
||||
|
||||
twfId = string(regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf.Bytes())[1])
|
||||
twfId = string(regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf[:n])[1])
|
||||
log.Print("SMS Code verification SUCCESS")
|
||||
|
||||
return twfId, nil
|
||||
@@ -214,6 +212,8 @@ func TOTPAuth(server string, username string, password string, twfId string, TOT
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}}
|
||||
|
||||
buf := make([]byte, 40960)
|
||||
|
||||
addr := "https://" + server + "/por/login_token.csp"
|
||||
log.Printf("TOTP token Request: " + addr)
|
||||
form := url.Values{
|
||||
@@ -229,17 +229,15 @@ func TOTPAuth(server string, username string, password string, twfId string, TOT
|
||||
return "", err
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, resp.Body)
|
||||
|
||||
n, _ := resp.Body.Read(buf)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if !strings.Contains(buf.String(), "suc") {
|
||||
if !strings.Contains(string(buf[:n]), "suc") {
|
||||
debug.PrintStack()
|
||||
return "", errors.New("TOTP token verification FAILED: " + buf.String())
|
||||
return "", errors.New("TOTP token verification FAILED: " + string(buf[:n]))
|
||||
}
|
||||
|
||||
twfId = string(regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf.Bytes())[1])
|
||||
twfId = string(regexp.MustCompile(`<TwfID>(.*)</TwfID>`).FindSubmatch(buf[:n])[1])
|
||||
log.Print("TOTP verification SUCCESS")
|
||||
|
||||
return twfId, nil
|
||||
@@ -255,18 +253,15 @@ func ECAgentToken(server string, twfId string) (string, error) {
|
||||
// When you establish a HTTPS connection to server and send a valid request with TWFID to it
|
||||
// The **TLS ServerHello SessionId** is the first part of token
|
||||
log.Printf("ECAgent Request: /por/conf.csp & /por/rclist.csp")
|
||||
_, err = io.WriteString(conn, "GET /por/conf.csp HTTP/1.1\r\nHost: "+server+"\r\nCookie: TWFID="+twfId+"\r\n\r\nGET /por/rclist.csp HTTP/1.1\r\nHost: "+server+"\r\nCookie: TWFID="+twfId+"\r\n\r\n")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
io.WriteString(conn, "GET /por/conf.csp HTTP/1.1\r\nHost: "+server+"\r\nCookie: TWFID="+twfId+"\r\n\r\nGET /por/rclist.csp HTTP/1.1\r\nHost: "+server+"\r\nCookie: TWFID="+twfId+"\r\n\r\n")
|
||||
|
||||
log.Printf("Server Session ID: %q", conn.HandshakeState.ServerHello.SessionId)
|
||||
|
||||
buf := make([]byte, 8)
|
||||
buf := make([]byte, 40960)
|
||||
n, err := conn.Read(buf)
|
||||
if n == 0 || err != nil {
|
||||
debug.PrintStack()
|
||||
return "", errors.New("ECAgent Request invalid: error " + err.Error() + "\n" + string(buf[:]))
|
||||
return "", errors.New("ECAgent Request invalid: error " + err.Error() + "\n" + string(buf[:n]))
|
||||
}
|
||||
|
||||
return hex.EncodeToString(conn.HandshakeState.ServerHello.SessionId)[:31] + "\x00", nil
|
||||
|
||||
21
go.mod
21
go.mod
@@ -4,18 +4,19 @@ go 1.19
|
||||
|
||||
require github.com/refraction-networking/utls v1.2.0
|
||||
|
||||
require github.com/pquerna/otp v1.4.0
|
||||
|
||||
require (
|
||||
fyne.io/fyne/v2 v2.3.0
|
||||
github.com/cornelk/hashmap v1.0.8
|
||||
github.com/dlclark/regexp2 v1.8.0
|
||||
gvisor.dev/gvisor v0.0.0-20230128000341-b7014294633b
|
||||
tailscale.com v1.36.0
|
||||
gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c
|
||||
tailscale.com v1.34.2
|
||||
)
|
||||
|
||||
require (
|
||||
fyne.io/systray v1.10.1-0.20221115204952-d16a6177e6f1 // indirect
|
||||
github.com/andybalholm/brotli v1.0.4 // indirect
|
||||
github.com/benoitkugler/textlayout v0.3.0 // indirect
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/fredbi/uri v0.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.5.4 // indirect
|
||||
@@ -37,15 +38,13 @@ require (
|
||||
github.com/stretchr/testify v1.8.0 // indirect
|
||||
github.com/tevino/abool v1.2.0 // indirect
|
||||
github.com/yuin/goldmark v1.4.1 // indirect
|
||||
go4.org/mem v0.0.0-20210711025021-927187094b94 // indirect
|
||||
golang.org/x/crypto v0.3.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20221205204356-47842c84f3db // indirect
|
||||
golang.org/x/crypto v0.1.0 // indirect
|
||||
golang.org/x/image v0.0.0-20220601225756-64ec528b34cd // indirect
|
||||
golang.org/x/mobile v0.0.0-20211207041440-4e6c2922fdee // indirect
|
||||
golang.org/x/net v0.5.0 // indirect
|
||||
golang.org/x/sys v0.4.0 // indirect
|
||||
golang.org/x/text v0.6.0 // indirect
|
||||
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 // indirect
|
||||
golang.org/x/net v0.1.0 // indirect
|
||||
golang.org/x/sys v0.3.1-0.20221220025402-2204b6615fb8 // indirect
|
||||
golang.org/x/text v0.4.0 // indirect
|
||||
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
honnef.co/go/js/dom v0.0.0-20210725211120-f030747120f2 // indirect
|
||||
)
|
||||
|
||||
40
go.sum
40
go.sum
@@ -58,6 +58,8 @@ github.com/benoitkugler/textlayout-testdata v0.1.1 h1:AvFxBxpfrQd8v55qH59mZOJOQj
|
||||
github.com/benoitkugler/textlayout-testdata v0.1.1/go.mod h1:i/qZl09BbUOtd7Bu/W1CAubRwTWrEXWq6JwMkw8wYxo=
|
||||
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
||||
github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
@@ -68,15 +70,11 @@ github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnht
|
||||
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
|
||||
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
||||
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cornelk/hashmap v1.0.8 h1:nv0AWgw02n+iDcawr5It4CjQIAcdMMKRrs10HOJYlrc=
|
||||
github.com/cornelk/hashmap v1.0.8/go.mod h1:RfZb7JO3RviW/rT6emczVuC/oxpdz4UsSB2LJSclR1k=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.8.0 h1:rJD5HeGIT/2b5CDk63FVCwZA3qgYElfg+oQK7uH5pfE=
|
||||
github.com/dlclark/regexp2 v1.8.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -257,6 +255,8 @@ github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZ
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
|
||||
github.com/pquerna/otp v1.4.0 h1:wZvl1TIVxKRThZIBiwOOHOGP/1+nZyWBil9Y2XNEDzg=
|
||||
github.com/pquerna/otp v1.4.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/refraction-networking/utls v1.2.0 h1:U5f8wkij2NVinfLuJdFP3gCMwIHs+EzvhxmYdXgiapo=
|
||||
github.com/refraction-networking/utls v1.2.0/go.mod h1:NPq+cVqzH7D1BeOkmOcb5O/8iVewAsiVt2x1/eO0hgQ=
|
||||
@@ -321,7 +321,6 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
|
||||
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
|
||||
go4.org/mem v0.0.0-20210711025021-927187094b94 h1:OAAkygi2Js191AJP1Ds42MhJRgeofeKGjuoUqNp1QC4=
|
||||
go4.org/mem v0.0.0-20210711025021-927187094b94/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g=
|
||||
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
@@ -330,8 +329,8 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A=
|
||||
golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
|
||||
golang.org/x/crypto v0.1.0 h1:MDRAIl0xIo9Io2xV565hzXHw3zVseKrJKodhohM5CjU=
|
||||
golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -343,8 +342,7 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
|
||||
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
|
||||
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
|
||||
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
|
||||
golang.org/x/exp v0.0.0-20221205204356-47842c84f3db h1:D/cFflL63o2KSLJIwjlcIt8PR064j/xsmdEJL/YvY/o=
|
||||
golang.org/x/exp v0.0.0-20221205204356-47842c84f3db/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
|
||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
@@ -416,8 +414,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b
|
||||
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211118161319-6a13c67c3ce4/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw=
|
||||
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
|
||||
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
|
||||
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -489,8 +487,8 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.1-0.20221220025402-2204b6615fb8 h1:/VqMvhQCyzfuc826eNrpWmMb3AwD2Sxz/HMsYIhwcIs=
|
||||
golang.org/x/sys v0.3.1-0.20221220025402-2204b6615fb8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -501,13 +499,13 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
|
||||
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
|
||||
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 h1:Dpdu/EMxGMFgq0CeYMh4fazTD2vtlZRYE7wyynxJb9U=
|
||||
golang.org/x/time v0.0.0-20220609170525-579cf78fd858/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 h1:GZokNIeuVkl3aZHJchRrr13WCsols02MLUcz1U9is6M=
|
||||
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
@@ -681,8 +679,8 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gvisor.dev/gvisor v0.0.0-20230128000341-b7014294633b h1:XFXNTjVvJrnFnXCo3TjLyMi/GqFqb/Hh5mfDW5aY5uw=
|
||||
gvisor.dev/gvisor v0.0.0-20230128000341-b7014294633b/go.mod h1:94x/o/BlxPAbw4phqHRac0/IzpcQRUP7ZQldDWV3TKU=
|
||||
gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c h1:m5lcgWnL3OElQNVyp3qcncItJ2c0sQlSGjYK2+nJTA4=
|
||||
gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c/go.mod h1:TIvkJD0sxe8pIob3p6T8IzxXunlp6yfgktvTNp+DGNM=
|
||||
honnef.co/go/js/dom v0.0.0-20210725211120-f030747120f2 h1:oomkgU6VaQDsV6qZby2uz1Lap0eXmku8+2em3A/l700=
|
||||
honnef.co/go/js/dom v0.0.0-20210725211120-f030747120f2/go.mod h1:sUMDUKNB2ZcVjt92UnLy3cdGs+wDAcrPdV3JP6sVgA4=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
@@ -695,5 +693,5 @@ honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9
|
||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
||||
tailscale.com v1.36.0 h1:wJXQMp6DB8Y+HHSbDuHYckmeqiqZ3dU/lWg2/MRd6uM=
|
||||
tailscale.com v1.36.0/go.mod h1:YIVXRZAr+Bzm3pICntGE6KjXzkQP5xOiliA8DrGW5W4=
|
||||
tailscale.com v1.34.2 h1:g6n9HEZjQfTQfXyeiGeuxPPqSQKhtdmXIbyUxd76O9U=
|
||||
tailscale.com v1.34.2/go.mod h1:xA1XYcaHK0BIyCETEkTuaj3M3uOe/zNJ5G/Sb9oNU3k=
|
||||
|
||||
@@ -1,439 +0,0 @@
|
||||
package listener
|
||||
|
||||
import (
|
||||
"EasierConnect/core"
|
||||
"EasierConnect/core/config"
|
||||
"EasierConnect/parser"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
REGEXP "regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"encoding/hex"
|
||||
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Env_ struct {
|
||||
privateKey *rsa.PrivateKey
|
||||
publicKey *rsa.PublicKey
|
||||
regexp *REGEXP.Regexp
|
||||
}
|
||||
|
||||
type ECAgentResult_ struct {
|
||||
server string
|
||||
port string
|
||||
twfID string
|
||||
}
|
||||
|
||||
var Env Env_
|
||||
var ECAgentResult ECAgentResult_
|
||||
var ECAgentPort int
|
||||
|
||||
/** This is a quick implementation of ECAgent listener protocol
|
||||
*/
|
||||
|
||||
func HelloServer(w http.ResponseWriter, req *http.Request) {
|
||||
reqMap := make(map[string]string)
|
||||
log.Printf("Simple ECAgent #> ClientRequest: %s \n", req.RequestURI)
|
||||
|
||||
if req.RequestURI == "/ECAgent/" {
|
||||
_, err := w.Write([]byte("Init ECAgent env successfully. You can login to vpn now."))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
constructRespon := func(operate, result, message, debug string) string {
|
||||
return "(\"{\\\"type\\\":\\\"" + operate + "\\\",\\\"result\\\":\\\"" + result + "\\\",\\\"message\\\":\\\"" + message + "\\\",\\\"debug\\\":\\\"" + debug + "\\\"}\");"
|
||||
}
|
||||
|
||||
form := Env.regexp.FindAllString(req.RequestURI, -1)
|
||||
|
||||
for _, ent := range form {
|
||||
entry := strings.Split(ent, "=")
|
||||
reqMap[entry[0]] = entry[1]
|
||||
|
||||
if core.DebugDump {
|
||||
fmt.Printf("request > %s\n", ent)
|
||||
}
|
||||
}
|
||||
|
||||
response := strings.Builder{}
|
||||
|
||||
action := reqMap["op"]
|
||||
//token := reqMap["token"]
|
||||
//Guid := reqMap["Guid"]
|
||||
callback := reqMap["callback"]
|
||||
|
||||
response.WriteString(callback)
|
||||
|
||||
//TODO:: Optimize & reformat
|
||||
switch {
|
||||
case action == "InitECAgent":
|
||||
response.WriteString(constructRespon(action, "1", "", "CSCM_EXIST, init ok"))
|
||||
break
|
||||
case action == "GetEncryptKey":
|
||||
//https://github.com/creationix/jsbn/blob/master/README.md
|
||||
|
||||
modulus := fmt.Sprintf("%02X", Env.publicKey.N)
|
||||
response.WriteString(constructRespon(action, modulus, "", "CSCM_EXIST, init ok"))
|
||||
break
|
||||
case action == "DoConfigure":
|
||||
/*
|
||||
op=DoConfigure
|
||||
arg1=
|
||||
token= hex_md5(session + '__md5_salt_for_ecagent_session__')
|
||||
Guid=
|
||||
callback=EA_cbxxxxx
|
||||
*/
|
||||
arg1 := reqMap["arg1"]
|
||||
|
||||
Configure := strings.Split(arg1, "%20")
|
||||
|
||||
switch Configure[0] {
|
||||
case "SET":
|
||||
switch Configure[1] {
|
||||
case "SERVADDR":
|
||||
server := Configure[2]
|
||||
port := Configure[3]
|
||||
|
||||
ECAgentResult.server = server
|
||||
ECAgentResult.port = port
|
||||
|
||||
log.Printf("server: %s port: %s\n", server, port)
|
||||
|
||||
break
|
||||
case "TWFID":
|
||||
EncryptedTwfIDHex := Configure[2]
|
||||
|
||||
EncryptedTwfID, err := hex.DecodeString(EncryptedTwfIDHex)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
DecryptedTwfid, err := rsa.DecryptPKCS1v15(rand.Reader, Env.privateKey, EncryptedTwfID)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
|
||||
if ECAgentResult.twfID == "" {
|
||||
ECAgentResult.twfID = string(DecryptedTwfid[:])
|
||||
|
||||
log.Printf("Encrypted twfid: %s \n", EncryptedTwfIDHex)
|
||||
log.Printf("Decrypted twfid: %s \n", ECAgentResult.twfID)
|
||||
|
||||
go startClient(ECAgentResult)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
response.WriteString(constructRespon(action, "1", "", ""))
|
||||
break
|
||||
case action == "CheckProxySetting":
|
||||
response.WriteString(constructRespon(action, "-1", "", ""))
|
||||
break
|
||||
case action == "TestProxyServer":
|
||||
response.WriteString(constructRespon(action, "-1", "", ""))
|
||||
break
|
||||
case action == "GetConfig":
|
||||
//op=GetConfig&arg1=1&token=&Guid=&callback=EA_cbxxxxx
|
||||
|
||||
if reqMap["arg1"] == "1" {
|
||||
conf := config.Conf{}
|
||||
_, ok := parser.ParseXml(&conf, ECAgentResult.server, config.PathConf, ECAgentResult.twfID)
|
||||
|
||||
confWeb := config.ConfWeb{Conf: conf}
|
||||
|
||||
if ok {
|
||||
result, err := json.Marshal(confWeb)
|
||||
if err != nil {
|
||||
fmt.Println("Cannot convert Json.", err)
|
||||
return
|
||||
}
|
||||
|
||||
replacementMap := map[string]string{}
|
||||
|
||||
sh1t := strings.ReplaceAll(strings.ReplaceAll(string(result), "\\", "\\\\"), "\"", "\\\"")
|
||||
|
||||
for from, to := range replacementMap {
|
||||
sh1t = strings.ReplaceAll(sh1t, from, to)
|
||||
}
|
||||
|
||||
response.WriteString("(\"" + sh1t + "\");")
|
||||
} else {
|
||||
response.WriteString("(\"" + "\");")
|
||||
}
|
||||
} else if reqMap["arg1"] == "2" {
|
||||
res := config.Resource{}
|
||||
_, ok := parser.ParseXml(&res, ECAgentResult.server, config.PathRlist, ECAgentResult.twfID)
|
||||
|
||||
ResourceList := config.ResourceWeb{Resource: res}
|
||||
|
||||
if ok {
|
||||
result, err := json.Marshal(ResourceList)
|
||||
if err != nil {
|
||||
fmt.Println("Cannot convert Json.", err)
|
||||
return
|
||||
}
|
||||
|
||||
replacementMap := map[string]string{
|
||||
"ID": "id",
|
||||
"Name": "name",
|
||||
"Type": "type",
|
||||
"Proto": "proto",
|
||||
"Svc": "svc",
|
||||
"Host": "host",
|
||||
"Port": "port",
|
||||
"EnableDisguise": "enable_disguise",
|
||||
"Note": "note",
|
||||
"Attr": "attr",
|
||||
"AppPath": "app_path",
|
||||
"RcGrpID": "rc_grp_id",
|
||||
"RcLogo": "rc_logo",
|
||||
"Authorization": "authorization",
|
||||
"AuthSpID": "auth_sp_id",
|
||||
"Selectid": "selectid",
|
||||
}
|
||||
|
||||
sh1t := strings.ReplaceAll(strings.ReplaceAll(string(result), "\\", "\\\\"), "\"", "\\\"")
|
||||
|
||||
for from, to := range replacementMap {
|
||||
sh1t = strings.ReplaceAll(sh1t, from, to)
|
||||
}
|
||||
|
||||
response.WriteString("(\"" + sh1t + "\");")
|
||||
} else {
|
||||
response.WriteString("(\"" + "\");")
|
||||
}
|
||||
}
|
||||
break
|
||||
case action == "CheckReLogin":
|
||||
response.WriteString(constructRespon(action, "1", "", ""))
|
||||
break
|
||||
case action == "UpdateControls":
|
||||
response.WriteString(constructRespon(action, "1", "", ""))
|
||||
break
|
||||
case action == "DoQueryService":
|
||||
//TODO:: handle diff types
|
||||
response.WriteString(constructRespon(action, "26", "", ""))
|
||||
break
|
||||
case action == "StartService":
|
||||
response.WriteString(constructRespon(action, "1", "", ""))
|
||||
break
|
||||
case action == "doXmlConfigure":
|
||||
response.WriteString(constructRespon(action, "1", "", ""))
|
||||
break
|
||||
case action == "__check_alive__":
|
||||
response.Reset()
|
||||
response.WriteString("e(\"1\");")
|
||||
break
|
||||
default:
|
||||
log.Printf("Unknown action %s\n", action)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
|
||||
|
||||
if core.DebugDump {
|
||||
fmt.Printf("response > %s \n", response.String())
|
||||
}
|
||||
|
||||
_, err := w.Write([]byte(response.String()))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func startClient(config ECAgentResult_) {
|
||||
port, err := strconv.Atoi(config.port)
|
||||
if err != nil {
|
||||
log.Fatal("Cannot parse port!")
|
||||
}
|
||||
|
||||
log.Printf("Starting Client ..... \n")
|
||||
|
||||
core.StartClient(config.server, port, "", "", config.twfID)
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
generate Pkcs1 keys (to decrypt the twfID from javascript's request)
|
||||
*/
|
||||
func generateKey() {
|
||||
var err error
|
||||
// generate private key
|
||||
Env.privateKey, err = rsa.GenerateKey(rand.Reader, 1024)
|
||||
if err != nil {
|
||||
log.Fatal("Failed generating private key")
|
||||
}
|
||||
|
||||
go Env.privateKey.Precompute()
|
||||
// validate private key
|
||||
err = Env.privateKey.Validate()
|
||||
if err != nil {
|
||||
log.Fatal("Failed validating private key")
|
||||
}
|
||||
|
||||
Env.publicKey = &Env.privateKey.PublicKey
|
||||
}
|
||||
|
||||
func initRegExp() {
|
||||
var err error
|
||||
Env.regexp, err = REGEXP.Compile("[a-zA-Z0-9]*=[a-zA-Z0-9_.%]*")
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
Create the cert which server uses
|
||||
*/
|
||||
func generateServerCert() (string, string) {
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
x509temple := x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
NotBefore: time.UnixMilli(0),
|
||||
NotAfter: time.Now().Add(time.Hour * 24 * 365),
|
||||
|
||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
|
||||
IsCA: true,
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||
}
|
||||
cert, err := x509.CreateCertificate(rand.Reader, &x509temple, &x509temple, &privateKey.PublicKey, privateKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
buffer := &bytes.Buffer{}
|
||||
err = pem.Encode(buffer, &pem.Block{Type: "CERTIFICATE", Bytes: cert})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
certStr := buffer.String()
|
||||
buffer.Reset()
|
||||
|
||||
certPrivKey := x509.MarshalPKCS1PrivateKey(privateKey)
|
||||
|
||||
err = pem.Encode(buffer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: certPrivKey})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
key := buffer.String()
|
||||
|
||||
return certStr, key
|
||||
}
|
||||
|
||||
// TODO:: Move to utils\FileUtils.go
|
||||
func createTempFile(fileNamePattern, data string) *os.File {
|
||||
f, err := os.CreateTemp("", fileNamePattern)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
defer func(f *os.File) {
|
||||
err := f.Close()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}(f)
|
||||
|
||||
_, err = f.Write([]byte(data))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
func checkPort() {
|
||||
ECAgentPort = 54530
|
||||
Ports := []int{54530, 54541, 54552, 54563, 54574, 54585, 54596, 54607}
|
||||
/* available ports: 54530, 54541, 54552, 54563, 54574, 54585, 54596, 54607
|
||||
*/
|
||||
|
||||
log.Printf("Checking available port...")
|
||||
|
||||
for index, port := range Ports {
|
||||
ln, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
|
||||
ln.Close()
|
||||
|
||||
if err == nil {
|
||||
ECAgentPort = port
|
||||
break
|
||||
}
|
||||
|
||||
if index == 7 {
|
||||
log.Fatal("Cannot find available port!")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func StartECAgent() {
|
||||
Env = Env_{}
|
||||
ECAgentResult = ECAgentResult_{}
|
||||
|
||||
checkPort()
|
||||
initRegExp()
|
||||
generateKey()
|
||||
|
||||
cert, key := generateServerCert()
|
||||
certFile := createTempFile("ECAgent-*.crt", cert)
|
||||
keyFile := createTempFile("ECAgent-*.key", key)
|
||||
|
||||
go func() {
|
||||
<-time.After(500 * time.Millisecond)
|
||||
url := fmt.Sprintf("https://127.0.0.1:%v/ECAgent/", ECAgentPort)
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
err := exec.Command("cmd", "/c", "start", url).Run()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
case "darwin":
|
||||
err := exec.Command("open", url).Run()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
default:
|
||||
err := exec.Command("xdg-open", url).Run()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
log.Printf(fmt.Sprintf("ECAgent is Listening on %v. (EXPERIMENT)\n", ECAgentPort))
|
||||
|
||||
//TODO:: Handle port in use error
|
||||
http.HandleFunc("/ECAgent/", HelloServer)
|
||||
if err := http.ListenAndServeTLS(fmt.Sprintf(":%v", ECAgentPort), certFile.Name(), keyFile.Name(), nil); err != nil {
|
||||
log.Fatal("ListenAndServe: ", err)
|
||||
}
|
||||
}
|
||||
67
main.go
67
main.go
@@ -2,30 +2,75 @@ package main
|
||||
|
||||
import (
|
||||
"EasierConnect/core"
|
||||
"EasierConnect/listener"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/pquerna/otp/totp"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// CLI args
|
||||
host, port, username, password, twfId := "", 0, "", "", ""
|
||||
host, port, username, password, socksBind, twfId, totpKey := "", 0, "", "", "", "", ""
|
||||
flag.StringVar(&host, "server", "", "EasyConnect server address (e.g. vpn.nju.edu.cn, sslvpn.sysu.edu.cn)")
|
||||
flag.StringVar(&username, "username", "", "Your username")
|
||||
flag.StringVar(&password, "password", "", "Your password")
|
||||
flag.StringVar(&core.SocksBind, "socks-bind", ":1080", "The addr socks5 server listens on (e.g. 0.0.0.0:1080)")
|
||||
flag.StringVar(&totpKey, "totp-key", "", "If provided, this program will automatically generate TOTP code using this key and and input it, instead of asking user.")
|
||||
flag.StringVar(&socksBind, "socks-bind", ":1080", "The addr socks5 server listens on (e.g. 0.0.0.0:1080)")
|
||||
flag.StringVar(&twfId, "twf-id", "", "Login using twfID captured (mostly for debug usage)")
|
||||
flag.IntVar(&port, "port", 443, "EasyConnect port address (e.g. 443)")
|
||||
core.DebugDump = false
|
||||
core.ParseServConfig = true
|
||||
flag.BoolVar(&core.DebugDump, "debug-dump", false, "Enable traffic debug dump (only for debug usage)")
|
||||
flag.BoolVar(&core.ParseServConfig, "parse", true, "parse server config")
|
||||
debugDump := false
|
||||
flag.BoolVar(&debugDump, "debug-dump", false, "Enable traffic debug dump (only for debug usage)")
|
||||
flag.Parse()
|
||||
|
||||
if host == "" || ((username == "" || password == "") && twfId == "") {
|
||||
log.Printf("Starting as ECAgent mode. For more infomations: `EasierConnect --help`.\n")
|
||||
listener.StartECAgent()
|
||||
} else {
|
||||
core.StartClient(host, port, username, password, twfId)
|
||||
log.Fatal("Missing required cli args, refer to `EasierConnect --help`.")
|
||||
}
|
||||
server := fmt.Sprintf("%s:%d", host, port)
|
||||
|
||||
client := core.NewEasyConnectClient(server)
|
||||
|
||||
var ip []byte
|
||||
var err error
|
||||
if twfId != "" {
|
||||
if len(twfId) != 16 {
|
||||
panic("len(twfid) should be 16!")
|
||||
}
|
||||
ip, err = client.LoginByTwfId(twfId)
|
||||
} else {
|
||||
ip, err = client.Login(username, password)
|
||||
if err == core.ERR_NEXT_AUTH_SMS {
|
||||
fmt.Print(">>>Please enter your sms code<<<:")
|
||||
smsCode := ""
|
||||
fmt.Scan(&smsCode)
|
||||
|
||||
ip, err = client.AuthSMSCode(smsCode)
|
||||
} else if err == core.ERR_NEXT_AUTH_TOTP {
|
||||
TOTPCode := ""
|
||||
|
||||
if totpKey == "" {
|
||||
fmt.Print(">>>Please enter your TOTP Auth code<<<:")
|
||||
fmt.Scan(&TOTPCode)
|
||||
} else {
|
||||
TOTPCode, err = totp.GenerateCode(totpKey, time.Now())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Printf("Generated TOTP code %s", TOTPCode)
|
||||
}
|
||||
|
||||
ip, err = client.AuthTOTP(TOTPCode)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
log.Printf("Login success, your IP: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
|
||||
|
||||
client.ServeSocks5(socksBind, debugDump)
|
||||
|
||||
runtime.KeepAlive(client)
|
||||
}
|
||||
|
||||
@@ -1,296 +0,0 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"EasierConnect/core/config"
|
||||
"fmt"
|
||||
"github.com/dlclark/regexp2"
|
||||
"log"
|
||||
"math"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var domainRegExp *regexp.Regexp
|
||||
|
||||
func StringArrToIntArr(strArr []string) [4]int {
|
||||
var intArr [4]int
|
||||
|
||||
for index, str := range strArr {
|
||||
intArr[index], _ = strconv.Atoi(str)
|
||||
}
|
||||
|
||||
return intArr
|
||||
}
|
||||
|
||||
func getMaskByIpRange(fromIp string, toIp string) (ones int, bits int) {
|
||||
fromIpSplit := StringArrToIntArr(strings.Split(fromIp, "."))
|
||||
toIpSplit := StringArrToIntArr(strings.Split(toIp, "."))
|
||||
|
||||
fromIpSplit[3] = int(math.Max(float64(fromIpSplit[3]-1), 0))
|
||||
toIpSplit[3] = int(math.Min(float64(toIpSplit[3]+1), 255))
|
||||
|
||||
var mask [4]byte
|
||||
for i := 3; i >= 0; i-- {
|
||||
mask[i] = uint8(255 - toIpSplit[i] + fromIpSplit[i])
|
||||
}
|
||||
|
||||
return net.IPv4Mask(mask[0], mask[1], mask[2], mask[3]).Size()
|
||||
}
|
||||
|
||||
// from https://github.com/dromara/hutool/blob/fc091b01a23271e02f3174c45942105048155c90/hutool-core/src/main/java/cn/hutool/core/net/Ipv4Util.java#L114
|
||||
func getIPsInRange(from, to string) *[]string {
|
||||
ipf := StringArrToIntArr(strings.Split(from, "."))
|
||||
ipt := StringArrToIntArr(strings.Split(to, "."))
|
||||
|
||||
ips := make([]string, 4096)
|
||||
|
||||
equ := func(condition bool, yes int, no int) int {
|
||||
if condition {
|
||||
return yes
|
||||
} else {
|
||||
return no
|
||||
}
|
||||
}
|
||||
|
||||
var a, b, c int
|
||||
|
||||
for a = ipf[0]; a <= ipt[0]; a++ {
|
||||
for b = equ(a == ipf[0], ipf[1], 0); b <= equ(a == ipt[0], ipt[1], 255); b++ {
|
||||
for c = equ(b == ipf[1], ipf[2], 0); c <= equ(b == ipt[1], ipt[2], 255); c++ {
|
||||
for d := equ(c == ipf[2], ipf[3], 0); d <= equ(c == ipt[2], ipt[3], 255); d++ {
|
||||
ips = append(ips, strconv.Itoa(a)+"."+strconv.Itoa(b)+"."+strconv.Itoa(c)+"."+strconv.Itoa(d))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &ips
|
||||
}
|
||||
|
||||
func countByIpRange(from string, to string) int {
|
||||
count := 1
|
||||
ipf := StringArrToIntArr(strings.Split(from, "."))
|
||||
ipt := StringArrToIntArr(strings.Split(to, "."))
|
||||
|
||||
for i := 3; i >= 0; i-- {
|
||||
count += (ipt[i] - ipf[i]) * int(math.Pow(256, float64(3-i)))
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
func processSingleIpRule(rule, port string, debug bool, waitChan *chan int) {
|
||||
appendRule := func(value *string, isIPV4RangeRule bool, isCIDR bool) {
|
||||
minValue := port
|
||||
maxValue := port
|
||||
|
||||
if strings.Contains(port, "~") {
|
||||
minValue = strings.Split(port, "~")[0]
|
||||
maxValue = strings.Split(port, "~")[1]
|
||||
}
|
||||
|
||||
minValueInt, err := strconv.Atoi(minValue)
|
||||
if err != nil {
|
||||
log.Printf("Cannot parse port value from string")
|
||||
return
|
||||
}
|
||||
|
||||
maxValueInt, err := strconv.Atoi(maxValue)
|
||||
if err != nil {
|
||||
log.Printf("Cannot parse port value from string")
|
||||
return
|
||||
}
|
||||
|
||||
if debug {
|
||||
log.Printf("Appending Domain rule for: %s%v isIpv4RangeRule: %v isCIDR: %v", *value, []int{minValueInt, maxValueInt}, isIPV4RangeRule, isCIDR)
|
||||
}
|
||||
|
||||
if isIPV4RangeRule {
|
||||
config.AppendSingleIpv4RangeRule(*value, []int{minValueInt, maxValueInt}, isCIDR, debug)
|
||||
} else {
|
||||
config.AppendSingleDomainRule(*value, []int{minValueInt, maxValueInt}, debug)
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Contains(rule, "~") { // ip range 1.1.1.7~1.1.7.9
|
||||
from := strings.Split(rule, "~")[0]
|
||||
to := strings.Split(rule, "~")[1]
|
||||
size := countByIpRange(from, to)
|
||||
|
||||
mask, k := getMaskByIpRange(from, to)
|
||||
|
||||
if debug {
|
||||
log.Printf("Handling rule for: %s-%s mask: %v", from, to, mask)
|
||||
}
|
||||
|
||||
// mask == 0 -> cannot cover to cidr
|
||||
if mask != 0 && mask <= 28 {
|
||||
if debug {
|
||||
log.Printf("using Cidr %s-%s mask: %v %v", from, to, mask, k)
|
||||
}
|
||||
|
||||
cidr := fmt.Sprintf("%s/%v", from, mask)
|
||||
|
||||
appendRule(&cidr, true, true)
|
||||
} else {
|
||||
if size > 4096 {
|
||||
log.Printf("Super large rule detected for: %s-%s mask: %v", from, to, mask)
|
||||
|
||||
appendRule(&rule, true, false)
|
||||
} else {
|
||||
if size > 1024 {
|
||||
log.Printf("Large rule detected for: %s-%s mask: %v", from, to, mask)
|
||||
}
|
||||
|
||||
for _, domain := range *getIPsInRange(from, to) {
|
||||
appendRule(&domain, false, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else { // http://domain.example.com/path/to&something=good#extra
|
||||
appendRule(&rule, false, false)
|
||||
|
||||
if domainRegExp == nil {
|
||||
domainRegExp, _ = regexp.Compile("(?:\\w+\\.)+\\w+")
|
||||
}
|
||||
|
||||
pureDomain := domainRegExp.FindString(rule)
|
||||
|
||||
appendRule(&pureDomain, false, false) //TODO::FIXME:: remove this when using Http(s) proxy
|
||||
}
|
||||
|
||||
*waitChan <- 1
|
||||
}
|
||||
|
||||
func processDnsData(dnsData string, debug bool) {
|
||||
for _, ent := range strings.Split(dnsData, ";") {
|
||||
dnsEntry := strings.Split(ent, ":")
|
||||
|
||||
if len(dnsEntry) >= 3 {
|
||||
RcID := dnsEntry[0]
|
||||
domain := dnsEntry[1]
|
||||
ip := dnsEntry[2]
|
||||
|
||||
if debug {
|
||||
log.Printf("[%s] %s %s", RcID, domain, ip)
|
||||
}
|
||||
|
||||
if domain != "" && ip != "" {
|
||||
config.AppendSingleDnsRule(domain, ip, debug)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func processRcsData(rcsData config.Resource, debug bool, waitChan *chan int, cpuNumber *int) {
|
||||
RcsLen := len(rcsData.Rcs.Rc)
|
||||
for RcsIndex, ent := range rcsData.Rcs.Rc {
|
||||
if debug {
|
||||
log.Printf("[%s] %s %s", ent.Name, ent.Host, ent.Port)
|
||||
}
|
||||
|
||||
if ent.Host == "" || ent.Port == "" {
|
||||
log.Printf("Found null entry when processing RcsData: [%s] %s %s", ent.Name, ent.Host, ent.Port)
|
||||
continue
|
||||
}
|
||||
|
||||
domains := strings.Split(ent.Host, ";")
|
||||
ports := strings.Split(ent.Port, ";")
|
||||
|
||||
if len(domains) >= 1 && len(ports) >= 1 {
|
||||
for index, domain := range domains {
|
||||
portRange := ports[index]
|
||||
|
||||
if *cpuNumber > 0 {
|
||||
*cpuNumber--
|
||||
} else {
|
||||
<-*waitChan
|
||||
}
|
||||
processSingleIpRule(domain, portRange, debug, waitChan)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("Progress: %v/100 (ResourceList.Rcs)", int(float32(RcsIndex)/float32(RcsLen)*100))
|
||||
}
|
||||
}
|
||||
|
||||
func ParseResourceLists(host, twfID string, debug bool) {
|
||||
ResourceList := config.Resource{}
|
||||
res, ok := ParseXml(&ResourceList, host, config.PathRlist, twfID)
|
||||
|
||||
cpuNumber := runtime.NumCPU()
|
||||
waitChan := make(chan int, cpuNumber)
|
||||
|
||||
if !ok || ResourceList.Rcs.Rc == nil || len(ResourceList.Rcs.Rc) <= 0 || ResourceList.Dns.Data == "" {
|
||||
if res != "" {
|
||||
log.Printf("try parsing by regexp")
|
||||
|
||||
escapeReplacementMap := map[string]string{
|
||||
" ": string(rune(160)),
|
||||
"&": "&",
|
||||
""": "\"",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
}
|
||||
|
||||
for from, to := range escapeReplacementMap {
|
||||
res = strings.ReplaceAll(res, from, to)
|
||||
}
|
||||
|
||||
resUrlDecodedValue, err := url.QueryUnescape(res)
|
||||
if err != nil {
|
||||
log.Printf("Cannot do UrlDecode")
|
||||
return
|
||||
}
|
||||
|
||||
ResourceListRegexp := regexp2.MustCompile("(?<=\" host=\").*?(?=\" enable_disguise=)", 0)
|
||||
ResourceListMatches, _ := ResourceListRegexp.FindStringMatch(resUrlDecodedValue)
|
||||
for ; ResourceListMatches != nil; ResourceListMatches, _ = ResourceListRegexp.FindNextMatch(ResourceListMatches) {
|
||||
|
||||
if debug {
|
||||
log.Printf("ResourceListMatch -> " + ResourceListMatches.String() + "\n")
|
||||
}
|
||||
|
||||
ResourceListData := ResourceListMatches.String()
|
||||
|
||||
ResourceListDataHost := strings.Split(ResourceListData, "\" port=\"")[0]
|
||||
ResourceListDataPort := strings.Split(ResourceListData, "\" port=\"")[1]
|
||||
|
||||
entry := config.RcData{Host: ResourceListDataHost, Port: ResourceListDataPort}
|
||||
ResourceList.Rcs.Rc = append(ResourceList.Rcs.Rc, entry)
|
||||
}
|
||||
|
||||
processRcsData(ResourceList, debug, &waitChan, &cpuNumber)
|
||||
|
||||
log.Printf("Parsed %v Domain rules", config.GetDomainRuleLen())
|
||||
log.Printf("Parsed %v Ipv4 rules", config.GetIpv4RuleLen())
|
||||
|
||||
DnsDataRegexp := regexp2.MustCompile("(?<=<Dns dnsserver=\"\" data=\")[0-9A-Za-z:;.-]*?(?=\")", 0)
|
||||
DnsDataRegexpMatches, _ := DnsDataRegexp.FindStringMatch(resUrlDecodedValue)
|
||||
|
||||
processDnsData(DnsDataRegexpMatches.String(), debug)
|
||||
|
||||
log.Printf("Parsed %v Dns rules", config.GetDnsRuleLen())
|
||||
}
|
||||
} else {
|
||||
log.Printf("try parsing by goXml")
|
||||
|
||||
processRcsData(ResourceList, debug, &waitChan, &cpuNumber)
|
||||
|
||||
log.Printf("Parsed %v Domain rules", config.GetDomainRuleLen())
|
||||
log.Printf("Parsed %v Ipv4 rules", config.GetIpv4RuleLen())
|
||||
|
||||
processDnsData(ResourceList.Dns.Data, debug)
|
||||
|
||||
log.Printf("Parsed %v Dns rules", config.GetDnsRuleLen())
|
||||
}
|
||||
}
|
||||
|
||||
func ParseConfLists(host, twfID string, debug bool) {
|
||||
conf := config.Conf{}
|
||||
_, _ = ParseXml(&conf, host, config.PathConf, twfID)
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ParseXml(in any, host string, path string, twfid string) (string, bool) {
|
||||
c := &http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}}
|
||||
|
||||
addr := "https://" + host + path
|
||||
req, err := http.NewRequest("GET", addr, nil)
|
||||
req.Header.Set("Cookie", "TWFID="+twfid)
|
||||
req.Header.Set("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
log.Printf("Cannot request %s \n", path)
|
||||
return "", false
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, resp.Body)
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
}
|
||||
}(resp.Body)
|
||||
|
||||
// log.Printf("%s \n", string(buf[:]))
|
||||
|
||||
err = xml.Unmarshal(buf.Bytes(), &in)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
log.Printf("Cannot parse %s \n", path)
|
||||
|
||||
return buf.String(), false
|
||||
} else {
|
||||
log.Printf("Parsed %s \n", path)
|
||||
|
||||
return buf.String(), true
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user