arguments.go 9.4 KB

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