main.go 13 KB

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