main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package main
  2. /*
  3. * 本检测工具基于SCD文档管理系统第二版本开发
  4. * 本版本中引入了crc校验及ccd提取外部程序,该程序由C++编写,在部署时需要根据目标机器进行源码编译。其源程序在scdcrc目录下,编译时可参考目录的编译说明。
  5. * 本版本中引入了java开发的xml校验(根据xsd校验)外部程序,该程序由java编写,在部署时需要在目标机器上安装jdk1.8。务必(!!!)并将操作系统安装或者设置为中文语言,设置命令如下:
  6. * 1:全局配置修改。vi /etc/sysconfig/i18n 输入LANG="zh_CN.UTF-8"或者LANG="en_US.UTF-8",执行source /etc/sysconfig/i18n,重启电脑生效
  7. * 2:临时修改。export LANG="zh_CN.UTF-8" 或者 export LANG="en_US.UTF-8"
  8. * 3: 查看liunx系统当前语言。命令: echo $LANG
  9. */
  10. // ***************** 重新生成api接口文档,终端运行生成命令:bee run -gendoc=true -downdoc=true ***************
  11. // ***************** 如果生成swagger文档时失败,可运行:bee generate docs生成,可查看详情生成过程 ***************
  12. // ***************** 其他异常问题可尝试执行:swag init ***************
  13. // @title SCD检测工具API
  14. // @version 1.0.0
  15. // @description SCD文档管理系统接口文档。本文档仅用于本项目的前端接口说明
  16. // @termsOfService http://swagger.io/terms/
  17. // @contact.name liling
  18. // @contact.url http://www.swagger.io/support
  19. // @contact.email 3116246@qq.com
  20. // @license.name none
  21. // @license.url -
  22. // @host localhost:9527
  23. // @BasePath /api
  24. // @securityDefinitions.token token AUTH
  25. import (
  26. "bytes"
  27. "crypto/md5"
  28. "encoding/binary"
  29. "encoding/hex"
  30. "fmt"
  31. "io"
  32. "io/fs"
  33. "net"
  34. "net/url"
  35. "os"
  36. "os/exec"
  37. "path/filepath"
  38. "scd_check_tools/arrayex"
  39. "scd_check_tools/conf"
  40. _ "scd_check_tools/conf"
  41. "scd_check_tools/db"
  42. "scd_check_tools/email"
  43. "scd_check_tools/global"
  44. "scd_check_tools/logger"
  45. "scd_check_tools/models/bo"
  46. "scd_check_tools/models/enum"
  47. "scd_check_tools/monitor"
  48. "scd_check_tools/sms"
  49. "scd_check_tools/test"
  50. "scd_check_tools/upgrade"
  51. //"syscall"
  52. //"regexp"
  53. "runtime"
  54. "scd_check_tools/mqtt"
  55. "scd_check_tools/tools"
  56. "sort"
  57. "strconv"
  58. "strings"
  59. "time"
  60. "github.com/astaxie/beego"
  61. //"github.com/astaxie/beego/logs"
  62. "github.com/astaxie/beego/context"
  63. _ "scd_check_tools/routers"
  64. //"github.com/shopspring/decimal"
  65. _ "scd_check_tools/docs"
  66. _ "scd_check_tools/models/enum"
  67. )
  68. var (
  69. cpunum = runtime.NumCPU() - 1
  70. )
  71. func main() {
  72. runtime.GOMAXPROCS(cpunum)
  73. logger.Logger.Init()
  74. //base64Str, _ := os.ReadFile("C:\\Users\\lenovo\\Desktop\\1666608995.jpg")
  75. //log.Println(string(base64Str))
  76. //tools.Base64MakePic(string(base64Str), "C:\\Users\\lenovo\\Desktop\\test.jpg")
  77. logger.Logger.Println(tools.NowTime() + " 当前操作系统:" + string(runtime.GOOS) + " " + runtime.GOARCH)
  78. conf.LoadAppConf()
  79. dbtype := tools.IsEmpty(conf.GlobalConfig["dbtype"])
  80. runmode := tools.IsEmpty(conf.GlobalConfig["runmode"])
  81. if runmode == "" {
  82. runmode = "dev"
  83. }
  84. if dbtype == "" || dbtype == "mysql" {
  85. db.ConnDB("conf/mysql-" + runmode + ".cnf")
  86. } else if dbtype == "sqlite" {
  87. db.ConnSqlite("conf/db.cnf")
  88. }
  89. go mqtt.Start()
  90. if runmode == "dev" {
  91. //自动生成接口权限定义
  92. new(ApiDoc).Run()
  93. }
  94. new(ApiDoc).CacheApiDoc()
  95. bo.LoadSysParam()
  96. //缓存系统代码定义
  97. bo.LoadAndCacheGlobalCode()
  98. monitor.StartDataMonitor()
  99. monitor.StartSystem()
  100. //初始化短信对象
  101. smspf := conf.GlobalConfig["sms.platform"]
  102. if smspf != "" {
  103. smsSend := sms.GetSmsInstance(smspf)
  104. smsSend.AppId = conf.GlobalConfig["sms."+smspf+".appid"]
  105. smsSend.AppKey = conf.GlobalConfig["sms."+smspf+".appkey"]
  106. smsSend.SignName = conf.GlobalConfig["sms.signname"]
  107. }
  108. //启动邮件发送对象
  109. email.EmailConfig.Load()
  110. //发送邮件调用参考:
  111. //err := new(email.Send).SendEmail("3116246@qq.com", "测试", "这是邮件发送测试")
  112. logger.Logger.Println("****** 当前程序运行版本:" + upgrade.GetVersion() + " 运行端口:" + conf.GlobalConfig["appport"] + " 运行环境:" + runmode + " ******")
  113. logger.Logger.Println("如果需要重新生成api接口文档,终端运行生成命令:bee run -gendoc=true -downdoc=true")
  114. go test.Start("")
  115. go func() {
  116. //将生成的swagger文件复制到web目录下
  117. dirchar := string(os.PathSeparator)
  118. swaggerdir, err := os.Stat("." + dirchar + "swagger")
  119. if os.IsNotExist(err) {
  120. //项目中没有启用swagger时,不处理
  121. return
  122. }
  123. if swaggerdir.IsDir() {
  124. filepath.Walk("."+dirchar+"swagger", func(pathitem string, info fs.FileInfo, err error) error {
  125. if info.IsDir() {
  126. return nil
  127. }
  128. src, _ := os.Open(pathitem)
  129. defer src.Close()
  130. dst, _ := os.Create("." + dirchar + "static" + dirchar + "swagger" + dirchar + info.Name())
  131. defer dst.Close()
  132. io.Copy(dst, src)
  133. return nil
  134. })
  135. }
  136. }()
  137. if string(runtime.GOOS) == "windows" {
  138. if runmode == "prod" {
  139. go func() {
  140. //先杀掉残留的Web2Cs.exe进程
  141. killcmd := exec.Command("taskkill.exe", "/f", "/im", "Web2Cs.exe")
  142. killcmd.Start()
  143. time.Sleep(1 * time.Second)
  144. dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  145. cmd := exec.Command("cmd.exe", "/c", "start "+dir+"/static/pc/Web2Cs.exe")
  146. cmd.Start()
  147. //隐藏CMD窗口
  148. //如果编译的非windows版本,需要注释下面的代码
  149. /*
  150. kernel32 := syscall.NewLazyDLL("kernel32.dll")
  151. user32 := syscall.NewLazyDLL("user32.dll")
  152. getConsoleWindow := kernel32.NewProc("GetConsoleWindow")
  153. hideWin := user32.NewProc("ShowWindowAsync")
  154. winHander, _, err := getConsoleWindow.Call()
  155. if winHander == 0 {
  156. logger.Logger.Error(err)
  157. return
  158. }
  159. code, _, err := hideWin.Call(winHander, 0)
  160. if code != 1 {
  161. logger.Logger.Error(err)
  162. return
  163. }
  164. */
  165. }()
  166. //检查Web2Cs.exe是否运行中,未运行时退出当前程序
  167. go func() {
  168. for {
  169. time.Sleep(3 * time.Second)
  170. param := []string{"/C", "wmic process list brief| findstr Web2Cs.exe"}
  171. cmd := exec.Command("cmd", param...)
  172. var stdout, stderr bytes.Buffer
  173. cmd.Stdout = &stdout
  174. cmd.Stderr = &stderr
  175. err := cmd.Run()
  176. if err != nil {
  177. logger.Logger.Error(err)
  178. }
  179. resultOut, _ := string(stdout.Bytes()), string(stderr.Bytes())
  180. if strings.ReplaceAll(resultOut, " ", "") == "" {
  181. break
  182. }
  183. }
  184. os.Exit(0)
  185. }()
  186. }
  187. }
  188. if conf.GlobalConfig["appport"] != "" {
  189. go bo.CheckSystemUser()
  190. beego.SetLevel(beego.LevelDebug)
  191. //beego.SetLogger(logs.AdapterFile, "{\"filename\": \"beego_log.log\"}")
  192. beego.SetStaticPath("/", "static/login.html")
  193. beego.SetStaticPath("/login", "static/login.html")
  194. beego.SetStaticPath("/logout", "static/login.html")
  195. beego.InsertFilter("/api/*", beego.BeforeRouter, AuthFilter)
  196. beego.Run(":" + conf.GlobalConfig["appport"])
  197. }
  198. }
  199. func BytesToInt(bys []byte) int {
  200. bytebuff := bytes.NewBuffer(bys)
  201. var data int64
  202. binary.Read(bytebuff, binary.BigEndian, &data)
  203. return int(data)
  204. }
  205. var AuthFilter = func(ctx *context.Context) {
  206. ip := ctx.Request.Header.Get("X-Real-IP")
  207. if net.ParseIP(ip) == nil {
  208. ips := ctx.Request.Header.Get("X-Forward-For")
  209. for _, i := range strings.Split(ips, ",") {
  210. if net.ParseIP(i) != nil {
  211. ip = i
  212. break
  213. }
  214. }
  215. if ip == "" {
  216. ip, _, _ = net.SplitHostPort(ctx.Request.RemoteAddr)
  217. }
  218. }
  219. if ip != "" {
  220. //当前IP是否需要检查访问授权,默认为需要
  221. isCheckThisIP := true
  222. if _, exist := global.AccessedIps.Load(ip); exist {
  223. //IP已经访问过系统,则无需检查
  224. isCheckThisIP = false
  225. }
  226. if isCheckThisIP && global.AllowAccessIps != "*" {
  227. //判断当前客户端是否在允许范围内
  228. ips := strings.Split(global.AllowAccessIps, ",")
  229. allowLogin := false
  230. for _, iplimt := range ips {
  231. if iplimt == ip {
  232. allowLogin = true
  233. break
  234. }
  235. tmppos := strings.Index(iplimt, ".*")
  236. if tmppos > 1 {
  237. //ip段
  238. if len(ip) < tmppos {
  239. continue
  240. }
  241. if ip[:tmppos] == iplimt[:tmppos] {
  242. allowLogin = true
  243. break
  244. }
  245. }
  246. }
  247. if !allowLogin {
  248. userInfo := map[string]interface{}{}
  249. userInfo["ip"] = ip
  250. userInfo["name"] = "系统内置访问控制"
  251. new(bo.SystemLog).Fail(enum.AuditType_Client, enum.LogType_commit, enum.OptEventType_System, enum.OptEventLevel_Hight, fmt.Sprintf("未授权终端(IP:%s)尝试访问系统被拦截", ip), userInfo)
  252. //c.Data["json"] = c.WarpError("系统限制:未授权的访问!")
  253. //c.ServeJSON()
  254. ctx.Redirect(430, "/static/430.html")
  255. return
  256. }
  257. }
  258. //将IP缓存到允许队列中,如果更改了允许访问的IP配置时,需要重新初始化该队列
  259. global.AccessedIps.Store(ip, 1)
  260. }
  261. u, err := url.Parse(strings.ReplaceAll(ctx.Request.RequestURI, "//", "/"))
  262. if err != nil {
  263. ctx.Redirect(500, "/error")
  264. return
  265. }
  266. uri := strings.ToLower(u.Path)
  267. if uri == "/api/logout" || uri == "/api/version" || uri == "/api/keep-alive" || arrayex.IndexOf(global.NoAuthRouter, uri) > -1 {
  268. return
  269. }
  270. var token string
  271. token = ctx.Request.Header.Get("Authorization")
  272. if token == "" {
  273. logger.Logger.Println("接口" + ctx.Request.RequestURI + "token标识缺失")
  274. ctx.ResponseWriter.WriteHeader(401)
  275. return
  276. }
  277. token = strings.ReplaceAll(strings.ReplaceAll(token, "Bearer ", ""), " ", "")
  278. if token == "" {
  279. logger.Logger.Println("接口" + ctx.Request.RequestURI + "token标识无效")
  280. ctx.ResponseWriter.WriteHeader(401)
  281. return
  282. }
  283. //校验该token有没有当前接口的访问权限
  284. if !bo.HasApiAccess(token, uri) {
  285. logger.Logger.Println("接口" + ctx.Request.RequestURI + "不能被token:" + token + "访问")
  286. ctx.ResponseWriter.WriteHeader(401)
  287. return
  288. }
  289. nonce := ctx.Request.Header.Get("auth_nonce")
  290. //判断是不是特殊的token(后台layui接口不能校验)
  291. if strings.HasPrefix(nonce, "police-s-admin-") && len(nonce) == 26 {
  292. return
  293. }
  294. //验证请求时间戳和随机数,防数据重放
  295. tim := ctx.Request.Header.Get("auth_time")
  296. if tim == "" {
  297. logger.Logger.Println("接口" + ctx.Request.RequestURI + " auth_time标识缺失")
  298. ctx.ResponseWriter.WriteHeader(401)
  299. //ctx.Redirect(301, "/login")
  300. return
  301. }
  302. nowhaomiao := time.Now().Unix()
  303. tim2 := tim[0:10]
  304. timint, er := strconv.Atoi(tim2)
  305. //接口请求有效时长为2秒内
  306. //log.Println(fmt.Sprintf("now:%d tim:%d", nowhaomiao, timint))
  307. if er != nil || (int(nowhaomiao)-timint) > 4 {
  308. logger.Logger.Println("接口" + ctx.Request.RequestURI + "请求超时。" + tim2 + ":" + strconv.Itoa(int(nowhaomiao)))
  309. ctx.ResponseWriter.WriteHeader(401)
  310. //ctx.Redirect(301, "/login")
  311. return
  312. }
  313. if nonce == "" {
  314. logger.Logger.Println("接口" + ctx.Request.RequestURI + " auth_nonce标识缺失")
  315. ctx.ResponseWriter.WriteHeader(401)
  316. //ctx.Redirect(301, "/login")
  317. return
  318. }
  319. kv, has := global.GoCahce.Get(nonce)
  320. if has == true || kv != nil {
  321. logger.Logger.Println("接口" + ctx.Request.RequestURI + " auth_nonce已存在,本次请求可能是接口重放攻击")
  322. ctx.ResponseWriter.WriteHeader(401)
  323. //ctx.Redirect(301, "/login")
  324. return
  325. }
  326. sign := ctx.Request.Header.Get("sign")
  327. if sign == "" {
  328. logger.Logger.Println("接口" + ctx.Request.RequestURI + "签名缺失")
  329. ctx.ResponseWriter.WriteHeader(401)
  330. //ctx.Redirect(301, "/login")
  331. return
  332. }
  333. //获取请求的所有参数,并进行签名对比,防数据篡改
  334. signParalist := map[string]string{"auth_time": tim, "auth_nonce": nonce}
  335. reqPara1 := ctx.Request.URL.Query()
  336. for k, _ := range reqPara1 {
  337. signParalist[(k)] = tools.IsEmpty(reqPara1[k][0])
  338. }
  339. if ctx.Request.MultipartForm == nil || len(ctx.Request.MultipartForm.File) == 0 {
  340. reqPara2 := ctx.Request.PostForm
  341. for k, _ := range reqPara2 {
  342. signParalist[(k)] = tools.IsEmpty(reqPara2[k][0])
  343. }
  344. }
  345. var entiy []string
  346. var keys []string
  347. for key := range signParalist {
  348. keys = append(keys, (key))
  349. }
  350. sort.Stable(sort.StringSlice(keys))
  351. for _, name := range keys {
  352. /*tmpStr := url.QueryEscape(signParalist[name])
  353. tmpStr = strings.ReplaceAll(tmpStr, "%28", "(")
  354. tmpStr = strings.ReplaceAll(tmpStr, "%29", ")")*/
  355. entiy = append(entiy, name+"="+signParalist[name])
  356. }
  357. newParalist := strings.Join(entiy, "&") // + token
  358. h := md5.New()
  359. h.Write([]byte(newParalist))
  360. cipherStr := h.Sum(nil)
  361. signstr := hex.EncodeToString(cipherStr) // 输出加密结果
  362. if sign != signstr {
  363. logger.Logger.Println("接口" + ctx.Request.RequestURI + "签名不一致,请检查参数值中是否有特殊字符。原始签名:" + sign + " 后台签名:" + signstr)
  364. logger.Logger.Println("接口" + ctx.Request.RequestURI + "签名参数:")
  365. logger.Logger.Println(newParalist)
  366. ctx.ResponseWriter.WriteHeader(401)
  367. //ctx.Redirect(401, "/login")
  368. return
  369. }
  370. //请求验证全部通过,更新session
  371. err = bo.UpdateSession(token)
  372. if err != nil {
  373. if uri != "/login" {
  374. logger.Logger.Error("接口" + ctx.Request.RequestURI + " token已过期:" + token)
  375. ctx.ResponseWriter.WriteHeader(401)
  376. //ctx.Redirect(401, "/login")
  377. }
  378. return
  379. }
  380. //3秒过期的随机数
  381. global.GoCahce.Set(nonce, nonce, 3*time.Second)
  382. }