arguments.go 8.8 KB

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