aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/world/shell.lux
blob: 3fd76261b482ec67e768a1d89683cbfbe4e35223 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
(.module:
  [library
   [lux "*"
    ["@" target]
    ["jvm" ffi {"+" [import:]}]
    [abstract
     [monad {"+" [do]}]]
    [control
     ["[0]" function]
     ["[0]" try {"+" [Try]}]
     ["[0]" exception {"+" [exception:]}]
     ["[0]" io {"+" [IO]}]
     [security
      ["?" policy {"+" [Context Safety Safe]}]]
     [concurrency
      ["[0]" atom {"+" [Atom]}]
      ["[0]" async {"+" [Async]}]]
     [parser
      [environment {"+" [Environment]}]]]
    [data
     ["[0]" product]
     ["[0]" text
      ["%" format {"+" [format]}]
      [encoding
       ["[0]" utf8]]]
     [collection
      ["[0]" array {"+" [Array]}]
      ["[0]" list ("[1]\[0]" mix functor)]
      ["[0]" dictionary]]]
    [math
     [number {"+" [hex]}
      ["n" nat]]]]]
  [//
   [file {"+" [Path]}]])

(type: .public Exit
  Int)

(template [<code> <name>]
  [(def: .public <name>
     Exit
     <code>)]

  [+0 normal]
  [+1 error]
  )

(type: .public (Process !)
  (Interface
   (: (-> [] (! (Try Text)))
      read)
   (: (-> [] (! (Try Text)))
      error)
   (: (-> Text (! (Try Any)))
      write)
   (: (-> [] (! (Try Any)))
      destroy)
   (: (-> [] (! (Try Exit)))
      await)))

(def: (async_process process)
  (-> (Process IO) (Process Async))
  (`` (implementation
       (~~ (template [<method>]
             [(def: <method>
                (|>> (\ process <method>)
                     async.future))]

             [read]
             [error]
             [write]
             [destroy]
             [await]
             )))))

(type: .public Command
  Text)

(type: .public Argument
  Text)

(type: .public (Shell !)
  (Interface
   (: (-> [Environment Path Command (List Argument)] (! (Try (Process !))))
      execute)))

(def: .public (async shell)
  (-> (Shell IO) (Shell Async))
  (implementation
   (def: (execute input)
     (async.future
      (do (try.with io.monad)
        [process (\ shell execute input)]
        (in (..async_process process)))))))

... https://en.wikipedia.org/wiki/Code_injection#Shell_injection
(type: (Policy ?)
  (Interface
   (: (-> Command (Safe Command ?))
      command)
   (: (-> Argument (Safe Argument ?))
      argument)
   (: (All (_ a) (-> (Safe a ?) a))
      value)))

(type: (Sanitizer a)
  (-> a a))

(type: Replacer
  (-> Text Text))

(def: (replaced bad replacer)
  (-> Text Replacer (-> Text Text))
  (text.replaced bad (replacer bad)))

(def: safe_common_command
  (-> Replacer (Sanitizer Command))
  (let [x0A (text.of_char (hex "0A"))
        xFF (text.of_char (hex "FF"))]
    (function (_ replacer)
      (|>> (..replaced x0A replacer)
           (..replaced xFF replacer)
           (..replaced "\" replacer)
           (..replaced "&" replacer)
           (..replaced "#" replacer)
           (..replaced ";" replacer)
           (..replaced "`" replacer)
           (..replaced "|" replacer)
           (..replaced "*" replacer)
           (..replaced "?" replacer)
           (..replaced "~" replacer)
           (..replaced "^" replacer)
           (..replaced "$" replacer)
           (..replaced "<" replacer) (..replaced ">" replacer)
           (..replaced "(" replacer) (..replaced ")" replacer)
           (..replaced "[" replacer) (..replaced "]" replacer)
           (..replaced "{" replacer) (..replaced "}" replacer)))))

(def: (policy safe_command safe_argument)
  (Ex (_ ?) (-> (Sanitizer Command) (Sanitizer Argument) (Policy ?)))
  (?.with_policy
    (: (Context Safety Policy)
       (function (_ (^open "?\[0]"))
         (implementation
          (def: command (|>> safe_command ?\can_upgrade))
          (def: argument (|>> safe_argument ?\can_upgrade))
          (def: value ?\can_downgrade))))))

(def: unix_policy
  (let [replacer (: Replacer
                    (|>> (format "\")))
        safe_command (: (Sanitizer Command)
                        (..safe_common_command replacer))
        safe_argument (: (Sanitizer Argument)
                         (|>> (..replaced "'" replacer)
                              (text.enclosed' "'")))]
    (..policy safe_command safe_argument)))

(def: windows_policy
  (let [replacer (: Replacer
                    (function.constant " "))
        safe_command (: (Sanitizer Command)
                        (|>> (..safe_common_command replacer)
                             (..replaced "%" replacer)
                             (..replaced "!" replacer)))
        safe_argument (: (Sanitizer Argument)
                         (|>> (..replaced "%" replacer)
                              (..replaced "!" replacer)
                              (..replaced text.double_quote replacer)
                              (text.enclosed' text.double_quote)))]
    (..policy safe_command safe_argument)))

(with_expansions [<jvm> (as_is (import: java/lang/String
                                 ["[1]::[0]"
                                  (toLowerCase [] java/lang/String)])

                               (def: (jvm::arguments_array arguments)
                                 (-> (List Argument) (Array java/lang/String))
                                 (product.right
                                  (list\mix (function (_ argument [idx output])
                                              [(++ idx) (jvm.write! idx
                                                                    (:as java/lang/String argument)
                                                                    output)])
                                            [0 (jvm.array java/lang/String (list.size arguments))]
                                            arguments)))

                               (import: (java/util/Map k v)
                                 ["[1]::[0]"
                                  (put [k v] v)])

                               (def: (jvm::load_environment input target)
                                 (-> Environment
                                     (java/util/Map java/lang/String java/lang/String)
                                     (java/util/Map java/lang/String java/lang/String))
                                 (list\mix (function (_ [key value] target')
                                             (exec
                                               (java/util/Map::put (:as java/lang/String key)
                                                                   (:as java/lang/String value)
                                                                   target')
                                               target'))
                                           target
                                           (dictionary.entries input)))
                               
                               (import: java/io/Reader
                                 ["[1]::[0]"
                                  (read [] "io" "try" int)])

                               (import: java/io/BufferedReader
                                 ["[1]::[0]"
                                  (new [java/io/Reader])
                                  (readLine [] "io" "try" "?" java/lang/String)])

                               (import: java/io/InputStream)
                               
                               (import: java/io/InputStreamReader
                                 ["[1]::[0]"
                                  (new [java/io/InputStream])])

                               (import: java/io/OutputStream
                                 ["[1]::[0]"
                                  (write [[byte]] "io" "try" void)])

                               (import: java/lang/Process
                                 ["[1]::[0]"
                                  (getInputStream [] "io" "try" java/io/InputStream)
                                  (getErrorStream [] "io" "try" java/io/InputStream)
                                  (getOutputStream [] "io" "try" java/io/OutputStream)
                                  (destroy [] "io" "try" void)
                                  (waitFor [] "io" "try" int)])

                               (exception: .public no_more_output)

                               (def: (default_process process)
                                 (-> java/lang/Process (IO (Try (Process IO))))
                                 (do [! (try.with io.monad)]
                                   [jvm_input (java/lang/Process::getInputStream process)
                                    jvm_error (java/lang/Process::getErrorStream process)
                                    jvm_output (java/lang/Process::getOutputStream process)
                                    .let [jvm_input (|> jvm_input
                                                        java/io/InputStreamReader::new
                                                        java/io/BufferedReader::new)
                                          jvm_error (|> jvm_error
                                                        java/io/InputStreamReader::new
                                                        java/io/BufferedReader::new)]]
                                   (in (: (Process IO)
                                          (`` (implementation
                                               (~~ (template [<name> <stream>]
                                                     [(def: (<name> _)
                                                        (do !
                                                          [output (java/io/BufferedReader::readLine <stream>)]
                                                          (case output
                                                            {#.Some output}
                                                            (in output)

                                                            #.None
                                                            (\ io.monad in (exception.except ..no_more_output [])))))]

                                                     [read jvm_input]
                                                     [error jvm_error]
                                                     ))
                                               (def: (write message)
                                                 (java/io/OutputStream::write (\ utf8.codec encoded message) jvm_output))
                                               (~~ (template [<name> <method>]
                                                     [(def: (<name> _)
                                                        (<method> process))]

                                                     [destroy java/lang/Process::destroy]
                                                     [await java/lang/Process::waitFor]
                                                     ))))))))

                               (import: java/io/File
                                 ["[1]::[0]"
                                  (new [java/lang/String])])

                               (import: java/lang/ProcessBuilder
                                 ["[1]::[0]"
                                  (new [[java/lang/String]])
                                  (environment [] "try" (java/util/Map java/lang/String java/lang/String))
                                  (directory [java/io/File] java/lang/ProcessBuilder)
                                  (start [] "io" "try" java/lang/Process)])

                               (import: java/lang/System
                                 ["[1]::[0]"
                                  ("static" getProperty [java/lang/String] "io" "try" java/lang/String)])

                               ... https://en.wikipedia.org/wiki/Code_injection#Shell_injection
                               (def: windows?
                                 (IO (Try Bit))
                                 (\ (try.with io.monad) each
                                    (|>> java/lang/String::toLowerCase (text.starts_with? "windows"))
                                    (java/lang/System::getProperty "os.name")))

                               (implementation: .public default
                                 (Shell IO)

                                 (def: (execute [environment working_directory command arguments])
                                   (do [! (try.with io.monad)]
                                     [.let [builder (|> (list& command arguments)
                                                        ..jvm::arguments_array
                                                        java/lang/ProcessBuilder::new
                                                        (java/lang/ProcessBuilder::directory (java/io/File::new working_directory)))]
                                      _ (|> builder
                                            java/lang/ProcessBuilder::environment
                                            (\ try.functor each (..jvm::load_environment environment))
                                            (\ io.monad in))
                                      process (java/lang/ProcessBuilder::start builder)]
                                     (..default_process process))))
                               )]
  (for [@.old (as_is <jvm>)
        @.jvm (as_is <jvm>)]
       (as_is)))

(type: .public (Mock s)
  (Interface
   (: (-> s (Try [s Text]))
      on_read)
   (: (-> s (Try [s Text]))
      on_error)
   (: (-> Text s (Try s))
      on_write)
   (: (-> s (Try s))
      on_destroy)
   (: (-> s (Try [s Exit]))
      on_await)))

(`` (implementation: (mock_process state mock)
      (All (_ s) (-> (Atom s) (Mock s) (Process IO)))

      (~~ (template [<name> <mock>]
            [(def: (<name> _)
               (do [! io.monad]
                 [|state| (atom.read! state)]
                 (case (\ mock <mock> |state|)
                   {#try.Success [|state| output]}
                   (do !
                     [_ (atom.write! |state| state)]
                     (in {#try.Success output}))
                   
                   {#try.Failure error}
                   (in {#try.Failure error}))))]

            [read on_read]
            [error on_error]
            [await on_await]
            ))
      (def: (write message)
        (do [! io.monad]
          [|state| (atom.read! state)]
          (case (\ mock on_write message |state|)
            {#try.Success |state|}
            (do !
              [_ (atom.write! |state| state)]
              (in {#try.Success []}))
            
            {#try.Failure error}
            (in {#try.Failure error}))))
      (def: (destroy _)
        (do [! io.monad]
          [|state| (atom.read! state)]
          (case (\ mock on_destroy |state|)
            {#try.Success |state|}
            (do !
              [_ (atom.write! |state| state)]
              (in {#try.Success []}))
            
            {#try.Failure error}
            (in {#try.Failure error}))))))

(implementation: .public (mock mock init)
  (All (_ s)
    (-> (-> [Environment Path Command (List Argument)]
            (Try (Mock s)))
        s
        (Shell IO)))

  (def: execute
    (|>> mock
         (\ try.monad each (..mock_process (atom.atom init)))
         io.io)))