-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.hs
More file actions
586 lines (536 loc) · 23.1 KB
/
Copy pathMain.hs
File metadata and controls
586 lines (536 loc) · 23.1 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
-- | Sanctify-PHP CLI entry point
-- SPDX-License-Identifier: MPL-2.0
module Main where
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hFlush, stdout, hPutStrLn, stderr)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import qualified Data.ByteString.Lazy.Char8 as BL8
import System.Directory (doesFileExist, doesDirectoryExist, listDirectory, getModificationTime)
import System.FilePath ((</>), takeExtension)
import Control.Monad (forM, forM_, filterM, when, unless, forever)
import Control.Concurrent (threadDelay)
import Data.Either (partitionEithers)
import Data.List (isPrefixOf, isSuffixOf)
import Data.Maybe (isJust, fromMaybe, catMaybes)
import Data.Time.Clock (UTCTime)
import qualified Data.Map.Strict as Map
import Sanctify.Parser
import Sanctify.AST
import Sanctify.Analysis.Security
import Sanctify.Analysis.Types (emptyTypeContext)
import Sanctify.WordPress.Constraints
import Sanctify.Transform.StrictTypes
import Sanctify.Transform.Sanitize
import Sanctify.Transform.TypeHints
import Sanctify.Emit (emitPhp, emitPhpIniRecommendations, emitNginxRules, emitGuixOverrides)
import Sanctify.Config
import qualified Sanctify.Report as SReport
-- | CLI options
data Options = Options
{ optCommand :: Command
, optInteractive :: Bool
, optWatch :: Bool
, optFormat :: OutputFormat
, optSeverity :: [Severity]
, optTypes :: [Text]
, optInPlace :: Bool
, optDiff :: Bool
, optVerbose :: Bool
}
data Command
= Analyze FilePath
| Fix FilePath
| Report FilePath
| ExportPhpIni FilePath
| ExportNginx FilePath
| ExportGuix FilePath
| Help
| Version
data OutputFormat = FormatText | FormatJSON | FormatSARIF | FormatHTML
deriving (Eq, Show)
data Severity = Critical | High | Medium | Low | Info
deriving (Eq, Show, Read)
main :: IO ()
main = do
args <- getArgs
opts <- parseArgs args
runCommand opts
-- | Parse command-line arguments
parseArgs :: [String] -> IO Options
parseArgs args = case args of
[] -> printHelp >> exitFailure
("--help":_) -> pure $ Options Help False False FormatText [] [] False False False
("-h":_) -> pure $ Options Help False False FormatText [] [] False False False
("--version":_) -> pure $ Options Version False False FormatText [] [] False False False
_ -> parseCommand args defaultOptions
where
defaultOptions = Options
{ optCommand = Help
, optInteractive = False
, optWatch = False
, optFormat = FormatText
, optSeverity = []
, optTypes = []
, optInPlace = False
, optDiff = False
, optVerbose = False
}
-- | Parse command and options
parseCommand :: [String] -> Options -> IO Options
parseCommand [] opts = pure opts
parseCommand ("analyze":rest) opts = parseOptions rest (opts { optCommand = Analyze "" })
parseCommand ("fix":rest) opts = parseOptions rest (opts { optCommand = Fix "" })
parseCommand ("report":rest) opts = parseOptions rest (opts { optCommand = Report "" })
parseCommand ("export":"--php-ini":rest) opts = parseOptions rest (opts { optCommand = ExportPhpIni "" })
parseCommand ("export":"--nginx":rest) opts = parseOptions rest (opts { optCommand = ExportNginx "" })
parseCommand ("export":"--guix":rest) opts = parseOptions rest (opts { optCommand = ExportGuix "" })
parseCommand (arg:rest) opts
| "--interactive" `isPrefixOf` arg = parseCommand rest (opts { optInteractive = True })
| "--watch" `isPrefixOf` arg = parseCommand rest (opts { optWatch = True })
| "--in-place" `isPrefixOf` arg = parseCommand rest (opts { optInPlace = True })
| "--diff" `isPrefixOf` arg = parseCommand rest (opts { optDiff = True })
| "-v" == arg || "--verbose" == arg = parseCommand rest (opts { optVerbose = True })
| "--format=json" `isPrefixOf` arg = parseCommand rest (opts { optFormat = FormatJSON })
| "--format=sarif" `isPrefixOf` arg = parseCommand rest (opts { optFormat = FormatSARIF })
| "--format=html" `isPrefixOf` arg = parseCommand rest (opts { optFormat = FormatHTML })
| "--format=text" `isPrefixOf` arg = parseCommand rest (opts { optFormat = FormatText })
| "--severity=" `isPrefixOf` arg =
let sevs = parseSeverities (drop 11 arg)
in parseCommand rest (opts { optSeverity = sevs })
| "--type=" `isPrefixOf` arg =
let types = T.splitOn "," $ T.pack $ drop 7 arg
in parseCommand rest (opts { optTypes = types })
| not ("-" `isPrefixOf` arg) = pure $ setPath arg opts
| otherwise = do
hPutStrLn stderr $ "Unknown option: " ++ arg
exitFailure
parseOptions :: [String] -> Options -> IO Options
parseOptions = parseCommand
setPath :: FilePath -> Options -> Options
setPath path opts = opts { optCommand = updatePath path (optCommand opts) }
where
updatePath p (Analyze _) = Analyze p
updatePath p (Fix _) = Fix p
updatePath p (Report _) = Report p
updatePath p (ExportPhpIni _) = ExportPhpIni p
updatePath p (ExportNginx _) = ExportNginx p
updatePath p (ExportGuix _) = ExportGuix p
updatePath _ cmd = cmd
parseSeverities :: String -> [Severity]
parseSeverities str = catMaybes $ map readSev $ splitOn ',' str
where
readSev s = case map toLower s of
"critical" -> Just Critical
"high" -> Just High
"medium" -> Just Medium
"low" -> Just Low
"info" -> Just Info
_ -> Nothing
toLower c | c >= 'A' && c <= 'Z' = toEnum (fromEnum c + 32)
| otherwise = c
splitOn _ [] = []
splitOn delim s = case break (== delim) s of
(a, []) -> [a]
(a, _:b) -> a : splitOn delim b
-- | Run the command
runCommand :: Options -> IO ()
runCommand opts = case optCommand opts of
Help -> printHelp
Version -> putStrLn "sanctify-php 0.2.0-alpha"
Analyze path -> analyzeCommandNew opts path
Fix path -> fixCommandNew opts path
Report path -> reportCommandNew opts path
ExportPhpIni path -> exportPhpIniCommand path
ExportNginx path -> exportNginxCommand path
ExportGuix path -> exportGuixCommand path
printHelp :: IO ()
printHelp = putStrLn $ unlines
[ "sanctify-php - Haskell-based PHP hardening and security analysis"
, ""
, "USAGE:"
, " sanctify <command> [options] <path>"
, ""
, "COMMANDS:"
, " analyze <path> Analyze PHP files for security issues"
, " fix <path> Auto-fix safe issues and report others"
, " report <path> Generate detailed report"
, " export Export configuration for infrastructure"
, ""
, "EXPORT SUBCOMMANDS:"
, " --php-ini <path> Generate recommended php.ini settings"
, " --nginx <path> Generate nginx security rules"
, " --guix <path> Generate Guix channel overrides"
, ""
, "OPTIONS:"
, " -h, --help Show this help"
, " --version Show version"
, " --interactive Interactive fix mode (prompt for each change)"
, " --watch Watch mode (re-analyze on file changes)"
, " --format=<fmt> Output format: text, json, sarif, html (default: text)"
, " --severity=<sevs> Filter by severity: critical,high,medium,low,info"
, " --type=<types> Filter by issue type (comma-separated)"
, " --in-place Apply fixes in-place (modifies files)"
, " --diff Show diff preview of changes"
, " -v, --verbose Verbose output"
, ""
, "EXAMPLES:"
, " # Basic analysis"
, " sanctify analyze ./wp-content/plugins/my-plugin/"
, ""
, " # Filter high and critical issues only"
, " sanctify analyze --severity=high,critical ./src/"
, ""
, " # Interactive fix with diff preview"
, " sanctify fix --interactive --diff ./theme/"
, ""
, " # Watch mode for development"
, " sanctify analyze --watch ./src/"
, ""
, " # Generate SARIF report for CI/CD"
, " sanctify report --format=sarif ./project/ > report.sarif"
, ""
, " # Export infrastructure configuration"
, " sanctify export --php-ini ./project/ >> php.ini"
, ""
, "For container integration, see:"
, " guix/wordpress-container.scm"
]
-- | Enhanced analyze command with watch mode and filtering
analyzeCommandNew :: Options -> FilePath -> IO ()
analyzeCommandNew opts path
| optWatch opts = watchMode opts path analyzeOnce
| otherwise = analyzeOnce opts path
analyzeOnce :: Options -> FilePath -> IO ()
analyzeOnce opts path = do
files <- findPhpFiles path
when (null files) $ do
putStrLn $ "No PHP files found in: " ++ path
exitFailure
when (optVerbose opts) $
putStrLn $ "Analyzing " ++ show (length files) ++ " PHP files..."
results <- forM files $ \file -> do
content <- TIO.readFile file
case parsePhpString file content of
Left err -> do
when (optVerbose opts) $
putStrLn $ " Parse error in " ++ file ++ ": " ++ show err
pure (file, [], [])
Right ast -> do
let secIssues = filterIssues opts $ analyzeSecurityIssues ast
let wpIssues = if isWordPressCode ast
then checkWordPressConstraints ast
else []
pure (file, secIssues, wpIssues)
-- Output results based on format
case optFormat opts of
FormatText -> outputTextResults opts results
FormatJSON -> outputJSONResults results
FormatSARIF -> outputSARIFResults results
FormatHTML -> outputHTMLResults results
let totalIssues = sum $ map (\(_, s, w) -> length s + length w) results
if totalIssues > 0
then exitFailure
else exitSuccess
-- | Filter issues by severity and type
filterIssues :: Options -> [SecurityIssue] -> [SecurityIssue]
filterIssues opts issues =
let bySeverity = if null (optSeverity opts)
then issues
else filter (\i -> issueSeverity i `elem` optSeverity opts) issues
byType = if null (optTypes opts)
then bySeverity
else filter (\i -> T.pack (show (issueType i)) `elem` optTypes opts) bySeverity
in byType
-- | Output results as text
outputTextResults :: Options -> [(FilePath, [SecurityIssue], [WordPressIssue])] -> IO ()
outputTextResults opts results = do
let totalSec = sum $ map (\(_, s, _) -> length s) results
let totalWp = sum $ map (\(_, _, w) -> length w) results
putStrLn ""
putStrLn $ "Found " ++ show totalSec ++ " security issues"
putStrLn $ "Found " ++ show totalWp ++ " WordPress issues"
putStrLn ""
forM_ results $ \(file, secIssues, wpIssues) ->
when (not (null secIssues) || not (null wpIssues)) $ do
putStrLn $ file ++ ":"
forM_ secIssues $ \issue ->
putStrLn $ " [" ++ show (issueSeverity issue) ++ "] " ++ T.unpack (issueDescription issue)
++ " (line " ++ show (posLine $ issueLocation issue) ++ ")"
forM_ wpIssues $ \issue ->
putStrLn $ " [WP:" ++ show (wpIssueType issue) ++ "] " ++ T.unpack (wpDescription issue)
putStrLn ""
-- | Output results as JSON
outputJSONResults :: [(FilePath, [SecurityIssue], [WordPressIssue])] -> IO ()
outputJSONResults results = do
putStrLn "{"
putStrLn " \"issues\": ["
let allIssues = concatMap (\(file, sec, wp) ->
map (\i -> " {\"file\": \"" ++ file ++ "\", \"type\": \"security\", \"severity\": \"" ++ show (issueSeverity i) ++ "\", \"message\": \"" ++ T.unpack (issueDescription i) ++ "\", \"line\": " ++ show (posLine $ issueLocation i) ++ "}") sec
++ map (\i -> " {\"file\": \"" ++ file ++ "\", \"type\": \"wordpress\", \"message\": \"" ++ T.unpack (wpDescription i) ++ "\"}") wp) results
putStrLn $ concat $ insertCommas allIssues
putStrLn " ]"
putStrLn "}"
where
insertCommas [] = []
insertCommas [x] = [x]
insertCommas (x:xs) = (x ++ ",") : insertCommas xs
-- | Output results as SARIF
outputSARIFResults :: [(FilePath, [SecurityIssue], [WordPressIssue])] -> IO ()
outputSARIFResults results = do
putStrLn "{"
putStrLn " \"version\": \"2.1.0\","
putStrLn " \"$schema\": \"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json\","
putStrLn " \"runs\": [{"
putStrLn " \"tool\": {"
putStrLn " \"driver\": {"
putStrLn " \"name\": \"sanctify-php\","
putStrLn " \"version\": \"0.2.0-alpha\""
putStrLn " }"
putStrLn " },"
putStrLn " \"results\": ["
let sarifResults = concatMap (\(file, sec, _) ->
map (\i -> " {\"ruleId\": \"" ++ show (issueType i) ++ "\", \"level\": \"" ++ severityToLevel (issueSeverity i) ++ "\", \"message\": {\"text\": \"" ++ T.unpack (issueDescription i) ++ "\"}, \"locations\": [{\"physicalLocation\": {\"artifactLocation\": {\"uri\": \"" ++ file ++ "\"}, \"region\": {\"startLine\": " ++ show (posLine $ issueLocation i) ++ "}}}]}") sec) results
putStrLn $ concat $ insertCommas sarifResults
putStrLn " ]"
putStrLn " }]"
putStrLn "}"
where
severityToLevel Critical = "error"
severityToLevel High = "error"
severityToLevel Medium = "warning"
severityToLevel Low = "note"
severityToLevel Info = "note"
insertCommas [] = []
insertCommas [x] = [x]
insertCommas (x:xs) = (x ++ ",") : insertCommas xs
-- | Output results as HTML
outputHTMLResults :: [(FilePath, [SecurityIssue], [WordPressIssue])] -> IO ()
outputHTMLResults results = do
putStrLn "<!DOCTYPE html><html><head><title>Sanctify-PHP Report</title>"
putStrLn "<style>body{font-family:sans-serif;margin:20px;}h1{color:#333;}.issue{margin:10px 0;padding:10px;border-left:4px solid #ccc;}.critical{border-color:#d32f2f;}.high{border-color:#f57c00;}.medium{border-color:#fbc02d;}.low{border-color:#388e3c;}</style>"
putStrLn "</head><body><h1>Sanctify-PHP Security Report</h1>"
forM_ results $ \(file, secIssues, wpIssues) ->
unless (null secIssues && null wpIssues) $ do
putStrLn $ "<h2>" ++ file ++ "</h2>"
forM_ secIssues $ \issue ->
putStrLn $ "<div class='issue " ++ map toLower (show (issueSeverity issue)) ++ "'>"
++ "<strong>" ++ show (issueSeverity issue) ++ "</strong>: "
++ T.unpack (issueDescription issue)
++ " (line " ++ show (posLine $ issueLocation issue) ++ ")</div>"
putStrLn "</body></html>"
where
toLower c | c >= 'A' && c <= 'Z' = toEnum (fromEnum c + 32)
| otherwise = c
-- | Watch mode - re-analyze on file changes
watchMode :: Options -> FilePath -> (Options -> FilePath -> IO ()) -> IO ()
watchMode opts path action = do
putStrLn "Watch mode enabled. Press Ctrl+C to exit."
initialMTimes <- getFileMTimes path
action opts path
watchLoop initialMTimes
where
watchLoop lastMTimes = do
threadDelay 1000000 -- 1 second
currentMTimes <- getFileMTimes path
if currentMTimes /= lastMTimes
then do
putStrLn "\n=== Files changed, re-analyzing... ===\n"
action opts path
watchLoop currentMTimes
else watchLoop lastMTimes
getFileMTimes :: FilePath -> IO (Map.Map FilePath UTCTime)
getFileMTimes dir = do
files <- findPhpFiles dir
mtimes <- forM files $ \f -> do
mtime <- getModificationTime f
pure (f, mtime)
pure $ Map.fromList mtimes
-- | Old analyze command (kept for compatibility)
analyzeCommand :: FilePath -> IO ()
analyzeCommand path = analyzeOnce (Options (Analyze path) False False FormatText [] [] False False False) path
-- | Enhanced fix command with interactive mode and diff preview
fixCommandNew :: Options -> FilePath -> IO ()
fixCommandNew opts path
| optWatch opts = watchMode opts path fixOnce
| otherwise = fixOnce opts path
fixOnce :: Options -> FilePath -> IO ()
fixOnce opts path = do
files <- findPhpFiles path
when (optVerbose opts) $
putStrLn $ "Processing " ++ show (length files) ++ " PHP files..."
fixed <- forM files $ \file -> do
content <- TIO.readFile file
case parsePhpString file content of
Left err -> do
when (optVerbose opts) $
hPutStrLn stderr $ " Parse error in " ++ file ++ ": " ++ show err
pure Nothing
Right ast -> do
let transformed = applyTransforms ast
let output = emitPhp transformed
if content == output
then pure Nothing
else do
if optInteractive opts
then interactiveFix file content output opts
else autoFix file content output opts
let fixedCount = length $ filter isJust fixed
putStrLn $ "\nFixed " ++ show fixedCount ++ " file(s)."
unless (optInPlace opts) $
putStrLn "Use --in-place to apply changes."
-- | Interactive fix mode
interactiveFix :: FilePath -> Text -> Text -> Options -> IO (Maybe FilePath)
interactiveFix file original modified opts = do
putStrLn $ "\n" ++ file ++ ":"
when (optDiff opts) $
showDiff original modified
putStr "Apply this fix? [y/N/d(iff)/s(kip all)] "
hFlush stdout
response <- getLine
case map toLower $ take 1 response of
"y" -> do
when (optInPlace opts) $
TIO.writeFile file modified
putStrLn " ✓ Applied"
pure $ Just file
"d" -> do
showDiff original modified
interactiveFix file original modified opts
"s" -> do
putStrLn " Skipping remaining files..."
exitSuccess
_ -> do
putStrLn " Skipped"
pure Nothing
where
toLower c | c >= 'A' && c <= 'Z' = toEnum (fromEnum c + 32)
| otherwise = c
-- | Auto fix mode
autoFix :: FilePath -> Text -> Text -> Options -> IO (Maybe FilePath)
autoFix file original modified opts = do
when (optVerbose opts) $
putStrLn $ " Would fix: " ++ file
when (optDiff opts) $ do
putStrLn $ "\n" ++ file ++ ":"
showDiff original modified
when (optInPlace opts) $
TIO.writeFile file modified
pure $ Just file
-- | Show unified diff between two texts
showDiff :: Text -> Text -> IO ()
showDiff original modified = do
let origLines = T.lines original
let modLines = T.lines modified
putStrLn "--- original"
putStrLn "+++ modified"
putStrLn $ "@@ -1," ++ show (length origLines) ++ " +1," ++ show (length modLines) ++ " @@"
showDiffLines origLines modLines
where
showDiffLines [] [] = pure ()
showDiffLines (o:os) (m:ms)
| o == m = do
putStrLn $ " " ++ T.unpack o
showDiffLines os ms
| otherwise = do
putStrLn $ "-" ++ T.unpack o
putStrLn $ "+" ++ T.unpack m
showDiffLines os ms
showDiffLines (o:os) [] = do
putStrLn $ "-" ++ T.unpack o
showDiffLines os []
showDiffLines [] (m:ms) = do
putStrLn $ "+" ++ T.unpack m
showDiffLines [] ms
-- | Old fix command (kept for compatibility)
fixCommand :: FilePath -> IO ()
fixCommand path = fixOnce (Options (Fix path) False False FormatText [] [] False False False) path
-- | Apply safe transformations
applyTransforms :: PhpFile -> PhpFile
applyTransforms = addStrictTypes . addAbspathCheck . addTypeHintsFile
where
addTypeHintsFile file = addAllTypeHints emptyTypeContext file
-- | Enhanced report command with multiple output formats
reportCommandNew :: Options -> FilePath -> IO ()
reportCommandNew opts path = do
files <- findPhpFiles path
when (optVerbose opts) $
putStrLn $ "Generating report for " ++ show (length files) ++ " PHP files..."
fileReports <- forM files $ \file -> do
content <- TIO.readFile file
case parsePhpString file content of
Left _ -> pure $ SReport.generateFileReport file [] [] 0 0 False
Right ast -> do
let secIssues = filterIssues opts $ analyzeSecurityIssues ast
let wpIssues = if isWordPressCode ast
then checkWordPressConstraints ast
else []
let autoFixed = length $ filter (canAutoFix . issueType) secIssues
let manual = length secIssues - autoFixed
pure $ SReport.generateFileReport file secIssues wpIssues autoFixed manual False
case optFormat opts of
FormatText -> do
report <- SReport.generateReport defaultConfig fileReports
TIO.putStrLn $ SReport.renderText report
FormatJSON -> do
report <- SReport.generateReport defaultConfig fileReports
BL8.putStrLn $ SReport.renderJson report
FormatSARIF -> do
report <- SReport.generateReport defaultConfig fileReports
BL8.putStrLn $ SReport.renderSarif report
FormatHTML -> do
report <- SReport.generateReport defaultConfig fileReports
TIO.putStrLn $ SReport.renderHtml report
where
canAutoFix :: IssueType -> Bool
canAutoFix MissingStrictTypes = True
canAutoFix _ = False
-- | Old report command (kept for compatibility)
reportCommand :: FilePath -> IO ()
reportCommand path = reportCommandNew (Options (Report path) False False FormatText [] [] False False False) path
-- | Export php.ini recommendations
exportPhpIniCommand :: FilePath -> IO ()
exportPhpIniCommand path = do
issues <- collectIssues path
TIO.putStrLn $ emitPhpIniRecommendations issues
-- | Export nginx rules
exportNginxCommand :: FilePath -> IO ()
exportNginxCommand path = do
issues <- collectIssues path
TIO.putStrLn $ emitNginxRules issues
-- | Export Guix overrides
exportGuixCommand :: FilePath -> IO ()
exportGuixCommand path = do
issues <- collectIssues path
TIO.putStrLn $ emitGuixOverrides issues
-- | Collect all issues from a path
collectIssues :: FilePath -> IO [SecurityIssue]
collectIssues path = do
files <- findPhpFiles path
concat <$> forM files (\file -> do
content <- TIO.readFile file
case parsePhpString file content of
Left _ -> pure []
Right ast -> pure $ analyzeSecurityIssues ast)
-- | Find all PHP files in a path
findPhpFiles :: FilePath -> IO [FilePath]
findPhpFiles path = do
isFile <- doesFileExist path
if isFile
then if takeExtension path == ".php"
then pure [path]
else pure []
else do
isDir <- doesDirectoryExist path
if isDir
then do
entries <- listDirectory path
let fullPaths = map (path </>) entries
files <- filterM doesFileExist fullPaths
dirs <- filterM doesDirectoryExist fullPaths
let phpFiles = filter ((== ".php") . takeExtension) files
subFiles <- concat <$> mapM findPhpFiles dirs
pure $ phpFiles ++ subFiles
else pure []