main.go 13 KB

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