用go语言和正则表达式写的linux危险命令拦截

需求如下:

package main

import "fmt"
import "regexp"

func main() {
 var s = "cat a /dev/vda"
 fmt.Println(CheckComm(s))
}

//命令验证
func CheckComm(s string) bool {
 reg := "^(ls|cat|top|echo|history|head|tail)"
 match,_ := regexp.MatchString(reg, s)
 ispass := match
 fmt.Println("筛选只读命令:", ispass)
 
 if ispass {
  return ispass
 }

 reg = "while|for|if"
 match,_ = regexp.MatchString(reg, s)
 ispass = !match
 fmt.Println("排除Shell关键字:", ispass)
 
 if !ispass {
  return ispass
 }
 
 reg = "^(dd|alias|fsck|rm)"
 match,_ = regexp.MatchString(reg, s)
 ispass = !match
 fmt.Println("排除危险命令:", ispass)
 
 if !ispass {
  reg = "^(dd|alias|fsck|rm)\\s+[^\\s]+\\s+[^\\s]*/tmp"
  match,_ = regexp.MatchString(reg, s)
  ispass = match
  fmt.Println("筛选完整安全的参数:", ispass)

  if !ispass {
   return ispass
  }
 }
 
 reg = "[^\\s]+\\s+[^\\s]+\\s+[^\\s]*/dev/vda"
 match,_ = regexp.MatchString(reg, s)
 ispass = !match
 fmt.Println("排除危险的参数:", ispass)
 
 if !ispass {
  return ispass
 }

 return ispass
}

  

posted @ 2021-01-14 13:33  你好创造者  阅读(233)  评论(0编辑  收藏  举报