arguments.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. package executor
  2. import (
  3. config "github.com/OliveTin/OliveTin/internal/config"
  4. "github.com/OliveTin/OliveTin/internal/entities"
  5. log "github.com/sirupsen/logrus"
  6. "fmt"
  7. "net/mail"
  8. "net/url"
  9. "regexp"
  10. "strings"
  11. "time"
  12. )
  13. var (
  14. typecheckRegex = map[string]string{
  15. "very_dangerous_raw_string": "",
  16. "int": `^\d+$`,
  17. "unicode_identifier": `^[\w\-\.\_\d]+$`,
  18. "ascii": `^[a-zA-Z0-9]+$`,
  19. "ascii_identifier": `^[a-zA-Z0-9\-\._]+$`,
  20. "ascii_sentence": `^[a-zA-Z0-9\-\._, ]+$`,
  21. }
  22. )
  23. func parseCommandForReplacements(shellCommand string, values map[string]string, entity any) (string, error) {
  24. r := regexp.MustCompile(`{{ *?([a-zA-Z0-9_]+?) *?}}`)
  25. foundArgumentNames := r.FindAllStringSubmatch(shellCommand, -1)
  26. for _, match := range foundArgumentNames {
  27. argName := match[1]
  28. argValue, argProvided := values[argName]
  29. if !argProvided {
  30. return "", fmt.Errorf("required arg not provided: %v", argName)
  31. }
  32. shellCommand = strings.ReplaceAll(shellCommand, match[0], argValue)
  33. }
  34. return shellCommand, nil
  35. }
  36. func parseActionExec(values map[string]string, action *config.Action, entity *entities.Entity) ([]string, error) {
  37. if action == nil {
  38. return nil, fmt.Errorf("action is nil")
  39. }
  40. if err := validateArguments(values, action); err != nil {
  41. return nil, err
  42. }
  43. parsed := make([]string, len(action.Exec))
  44. for i, a := range action.Exec {
  45. arg, err := parseCommandForReplacements(a, values, entity)
  46. if err != nil {
  47. return nil, err
  48. }
  49. parsed[i] = entities.ParseTemplateWithArgs(arg, entity, values)
  50. }
  51. logParsedExec(action, parsed, values)
  52. return parsed, nil
  53. }
  54. func validateArguments(values map[string]string, action *config.Action) error {
  55. for _, arg := range action.Arguments {
  56. if err := typecheckActionArgument(&arg, values[arg.Name], action); err != nil {
  57. return err
  58. }
  59. log.WithFields(log.Fields{"name": arg.Name, "value": values[arg.Name]}).Debugf("Arg assigned")
  60. }
  61. return nil
  62. }
  63. func logParsedExec(action *config.Action, parsed []string, values map[string]string) {
  64. redacted := redactExecArgs(parsed, action.Arguments, values)
  65. log.WithFields(log.Fields{"actionTitle": action.Title, "cmd": redacted}).Infof("Action parse args - After (Exec)")
  66. }
  67. func parseActionArguments(values map[string]string, action *config.Action, entity *entities.Entity) (string, error) {
  68. log.WithFields(log.Fields{
  69. "actionTitle": action.Title,
  70. "cmd": action.Shell,
  71. }).Infof("Action parse args - Before")
  72. rawShellCommand, err := parseCommandForReplacements(action.Shell, values, entity)
  73. for _, arg := range action.Arguments {
  74. argName := arg.Name
  75. argValue := values[argName]
  76. err := typecheckActionArgument(&arg, argValue, action)
  77. if err != nil {
  78. return "", err
  79. }
  80. log.WithFields(log.Fields{
  81. "name": argName,
  82. "value": argValue,
  83. }).Debugf("Arg assigned")
  84. }
  85. parsedShellCommand := entities.ParseTemplateWithArgs(rawShellCommand, entity, values)
  86. redactedShellCommand := redactShellCommand(parsedShellCommand, action.Arguments, values)
  87. if err != nil {
  88. return "", err
  89. }
  90. log.WithFields(log.Fields{
  91. "actionTitle": action.Title,
  92. "cmd": redactedShellCommand,
  93. }).Infof("Action parse args - After")
  94. return parsedShellCommand, nil
  95. }
  96. //gocyclo:ignore
  97. func redactShellCommand(shellCommand string, arguments []config.ActionArgument, argumentValues map[string]string) string {
  98. for _, arg := range arguments {
  99. if arg.Type == "password" {
  100. argValue, exists := argumentValues[arg.Name]
  101. if !exists {
  102. log.Warnf("Redact shell command: Argument %s not found in values", arg.Name)
  103. continue
  104. }
  105. if argValue == "" {
  106. continue
  107. }
  108. shellCommand = strings.ReplaceAll(shellCommand, argValue, "<redacted>")
  109. }
  110. }
  111. return shellCommand
  112. }
  113. //gocyclo:ignore
  114. func redactExecArgs(execArgs []string, arguments []config.ActionArgument, argumentValues map[string]string) []string {
  115. redacted := make([]string, len(execArgs))
  116. for i, arg := range execArgs {
  117. redacted[i] = redactShellCommand(arg, arguments, argumentValues)
  118. }
  119. return redacted
  120. }
  121. func typecheckActionArgument(arg *config.ActionArgument, value string, action *config.Action) error {
  122. if arg.Type == "confirmation" {
  123. return nil
  124. }
  125. if arg.Name == "" {
  126. return fmt.Errorf("argument name cannot be empty")
  127. }
  128. return typecheckActionArgumentFound(value, action, arg)
  129. }
  130. func typecheckActionArgumentFound(value string, action *config.Action, arg *config.ActionArgument) error {
  131. if value == "" {
  132. return typecheckNull(arg)
  133. }
  134. if len(arg.Choices) > 0 {
  135. return typecheckChoice(value, arg)
  136. }
  137. return TypeSafetyCheck(arg.Name, value, arg.Type)
  138. }
  139. // TypeSafetyCheck checks argument values match a specific type. The types are
  140. // defined in typecheckRegex, and, you guessed it, uses regex to check for allowed
  141. // characters.
  142. //
  143. //gocyclo:ignore
  144. func TypeSafetyCheck(name string, value string, argumentType string) error {
  145. switch argumentType {
  146. case "password":
  147. return nil
  148. case "raw_string_multiline":
  149. return nil
  150. case "email":
  151. return typeSafetyCheckEmail(value)
  152. case "url":
  153. return typeSafetyCheckUrl(value)
  154. case "datetime":
  155. return typeSafetyCheckDatetime(value)
  156. }
  157. return typeSafetyCheckRegex(name, value, argumentType)
  158. }
  159. func typecheckNull(arg *config.ActionArgument) error {
  160. if arg.RejectNull {
  161. return fmt.Errorf("null values are not allowed")
  162. }
  163. return nil
  164. }
  165. func typecheckChoice(value string, arg *config.ActionArgument) error {
  166. if arg.Entity != "" {
  167. return typecheckChoiceEntity(value, arg)
  168. }
  169. for _, choice := range arg.Choices {
  170. if value == choice.Value {
  171. return nil
  172. }
  173. }
  174. return fmt.Errorf("argument value is not one of the predefined choices")
  175. }
  176. func typecheckChoiceEntity(value string, arg *config.ActionArgument) error {
  177. templateChoice := arg.Choices[0].Value
  178. for _, ent := range entities.GetEntityInstances(arg.Entity) {
  179. choice := entities.ParseTemplateWith(templateChoice, ent)
  180. if value == choice {
  181. return nil
  182. }
  183. }
  184. return fmt.Errorf("argument value cannot be found in entities")
  185. }
  186. func typeSafetyCheckEmail(value string) error {
  187. _, err := mail.ParseAddress(value)
  188. log.Errorf("Email check: %v, %v", err, value)
  189. if err != nil {
  190. return err
  191. }
  192. return nil
  193. }
  194. func typeSafetyCheckDatetime(value string) error {
  195. _, err := time.Parse("2006-01-02T15:04:05", value)
  196. if err != nil {
  197. return err
  198. }
  199. return nil
  200. }
  201. func typeSafetyCheckRegex(name string, value string, argumentType string) error {
  202. pattern := ""
  203. if strings.HasPrefix(argumentType, "regex:") {
  204. pattern = strings.Replace(argumentType, "regex:", "", 1)
  205. } else {
  206. found := false
  207. pattern, found = typecheckRegex[argumentType]
  208. if !found {
  209. return fmt.Errorf("argument type not implemented %v for arg: %v", argumentType, name)
  210. }
  211. }
  212. matches, _ := regexp.MatchString(pattern, value)
  213. if !matches {
  214. log.WithFields(log.Fields{
  215. "name": name,
  216. "value": value,
  217. "type": argumentType,
  218. "pattern": pattern,
  219. }).Warn("Arg type check safety failure")
  220. return fmt.Errorf("invalid argument %v, doesn't match %v", name, argumentType)
  221. }
  222. return nil
  223. }
  224. func typeSafetyCheckUrl(value string) error {
  225. _, err := url.ParseRequestURI(value)
  226. return err
  227. }
  228. func checkShellArgumentSafety(action *config.Action) error {
  229. if action.Shell == "" {
  230. return nil
  231. }
  232. unsafe := map[string]struct{}{"url": {}, "email": {}, "raw_string_multiline": {}, "very_dangerous_raw_string": {}}
  233. for _, arg := range action.Arguments {
  234. if _, bad := unsafe[arg.Type]; bad {
  235. return fmt.Errorf("unsafe argument type '%s' cannot be used with Shell execution. Use 'exec' instead. See https://docs.olivetin.app/action_execution/shellvsexec.html", arg.Type)
  236. }
  237. }
  238. return nil
  239. }
  240. func mangleInvalidArgumentValues(req *ExecutionRequest) {
  241. for _, arg := range req.Binding.Action.Arguments {
  242. if arg.Type == "datetime" {
  243. mangleInvalidDatetimeValues(req, &arg)
  244. }
  245. mangleCheckboxValues(req, &arg)
  246. }
  247. }
  248. func mangleCheckboxValues(req *ExecutionRequest, arg *config.ActionArgument) {
  249. if arg.Type != "checkbox" {
  250. return
  251. }
  252. log.Infof("Checking checkbox values for argument %s in action %s", arg.Name, req.Binding.Action.Title)
  253. for i, _ := range arg.Choices {
  254. choice := &arg.Choices[i]
  255. if req.Arguments[arg.Name] == choice.Title {
  256. log.WithFields(log.Fields{
  257. "arg": arg.Name,
  258. "oldValue": req.Arguments[arg.Name],
  259. "newValue": choice.Value,
  260. "actionTitle": req.Binding.Action.Title,
  261. }).Infof("Mangled checkbox value")
  262. req.Arguments[arg.Name] = choice.Value
  263. }
  264. }
  265. }
  266. func mangleInvalidDatetimeValues(req *ExecutionRequest, arg *config.ActionArgument) {
  267. value, exists := req.Arguments[arg.Name]
  268. if !exists || value == "" {
  269. return
  270. }
  271. timestamp, err := time.Parse("2006-01-02T15:04", value)
  272. if err == nil {
  273. log.WithFields(log.Fields{
  274. "arg": arg.Name,
  275. "value": value,
  276. "actionTitle": req.Binding.Action.Title,
  277. }).Warnf("Mangled invalid datetime value without seconds to :00 seconds, this issue is commonly caused by Android browsers.")
  278. req.Arguments[arg.Name] = timestamp.Format("2006-01-02T15:04:05")
  279. }
  280. }