-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathask.lua
More file actions
9742 lines (8404 loc) · 402 KB
/
Copy pathask.lua
File metadata and controls
9742 lines (8404 loc) · 402 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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[
Analyst's Shark Knife (ASK) - Wireshark Lua Plugin Suite
A comprehensive suite of plugins for security analytics and IOC research
Features:
- DNS Registration Info (RDAP)
- ARIN IP Registration Data (RDAP) - IPv4 & IPv6
- IP Reputation (AbuseIPDB, VirusTotal)
- URL Categorization & Reputation (urlscan.io, VirusTotal, AlienVault OTX, URLhaus)
- Domain Reputation (VirusTotal, AlienVault OTX)
- IP Intelligence (Shodan, IPinfo, GreyNoise, AlienVault OTX, ThreatFox)
- TLS/SSL Certificate Analysis (Direct certificate inspection + Certificate Transparency)
- Email Analysis (SMTP/IMF)
Version: 0.2.7
Author: Walter Hofstetter
License: GPL-2.0
--]]
-------------------------------------------------
-- Register plugin info with Wireshark
-------------------------------------------------
set_plugin_info({
version = "0.2.7",
author = "Walter Hofstetter",
description = "Analyst's Shark Knife (ASK) - Comprehensive suite for security analytics and IOC research. Provides DNS registration info (RDAP), IP reputation (AbuseIPDB, VirusTotal), URL categorization (urlscan.io, VirusTotal, AlienVault OTX, URLhaus), IP intelligence (Shodan, IPinfo, GreyNoise, AlienVault OTX, ThreatFox), TLS certificate analysis, certificate transparency analysis, DNS analytics, and email analysis.",
repository = "https://github.com/netwho/ask"
})
-------------------------------------------------
-- Utility Functions (must be defined before CONFIG)
-------------------------------------------------
local function log_message(message)
print("[ASK] " .. message)
end
local function trim_and_strip_control(text)
if not text then
return ""
end
local trimmed = string.gsub(text, "^%s+", "")
trimmed = string.gsub(trimmed, "%s+$", "")
return string.gsub(trimmed, "%c+", "")
end
-- Read API key from file in home directory
local function read_api_key_from_file(service_name)
-- Determine home directory based on platform
local home_dir
if package.config:sub(1,1) == "\\" then
-- Windows
home_dir = os.getenv("USERPROFILE")
else
-- Unix-like (macOS, Linux)
home_dir = os.getenv("HOME")
end
if not home_dir then
log_message("Cannot read API key file: HOME/USERPROFILE environment variable not set")
return nil
end
-- Determine path separator
local path_sep = package.config:sub(1,1) == "\\" and "\\" or "/"
-- Try new directory first (.ask), then fall back to old directory (.ioc_researcher) for backward compatibility
local config_dirs = {
home_dir .. path_sep .. ".ask",
home_dir .. path_sep .. ".ioc_researcher" -- Backward compatibility
}
local key_file = nil
for _, config_dir in ipairs(config_dirs) do
local test_file = config_dir .. path_sep .. service_name .. "_API_KEY.txt"
log_message("Checking for API key file: " .. test_file)
local file = io.open(test_file, "r")
if file then
key_file = test_file
file:close()
break
end
end
if not key_file then
local dirs_msg = package.config:sub(1,1) == "\\" and
"%USERPROFILE%\\.ask\\ or %USERPROFILE%\\.ioc_researcher\\" or
"~/.ask/ or ~/.ioc_researcher/"
log_message("API key file not found in " .. dirs_msg)
return nil
end
log_message("Reading API key from: " .. key_file)
-- Try to read the file
local file = io.open(key_file, "r")
if file then
local key = nil
for line in file:lines() do
local trimmed = trim_and_strip_control(line)
if trimmed ~= "" then
key = trimmed
break
end
end
file:close()
if key and key ~= "" then
log_message("Successfully loaded API key for " .. service_name .. " from file (length: " .. string.len(key) .. " chars)")
return key
else
log_message("API key file for " .. service_name .. " exists but contains no valid data")
end
else
log_message("API key file not found: " .. key_file)
end
return nil
end
-- Get API key from environment variable, file, or fallback
local function get_api_key(service_name, env_var_name, fallback_value)
-- Priority: 1. Environment variable, 2. File, 3. Fallback
local key = os.getenv(env_var_name)
if key and key ~= "" then
return key
end
key = read_api_key_from_file(service_name)
if key and key ~= "" then
return key
end
return fallback_value or ""
end
-------------------------------------------------
-- Configuration
-------------------------------------------------
-- API Keys (set these in your environment or modify directly)
-- Get free API keys from:
-- AbuseIPDB: https://www.abuseipdb.com/api
-- urlscan.io: https://urlscan.io/user/signup
-- VirusTotal: https://www.virustotal.com/gui/join-us
-- Shodan: https://account.shodan.io/register
local CONFIG = {
-- AbuseIPDB API Configuration
-- Free tier: 1,000 requests/day
-- API key priority: 1. Environment variable, 2. ~/.ask/ABUSEIPDB_API_KEY.txt, 3. Hardcoded fallback
ABUSEIPDB_API_KEY = get_api_key("ABUSEIPDB", "ABUSEIPDB_API_KEY", "bc591215b84ecb07aa9d95ae0865ac1d12b5ecd4570ee5d96cc6ef54584bedccb0f99bfcf3410668"),
ABUSEIPDB_ENABLED = true,
-- urlscan.io API Configuration
-- Free tier: 100 scans/day, 10,000 searches/day
-- API key priority: 1. Environment variable, 2. ~/.ask/URLSCAN_API_KEY.txt
URLSCAN_API_KEY = get_api_key("URLSCAN", "URLSCAN_API_KEY", ""),
URLSCAN_ENABLED = true,
-- VirusTotal API Configuration
-- Free tier: 4 requests/minute, 500 requests/day
-- API key priority: 1. Environment variable, 2. ~/.ask/VIRUSTOTAL_API_KEY.txt
VIRUSTOTAL_API_KEY = get_api_key("VIRUSTOTAL", "VIRUSTOTAL_API_KEY", ""),
VIRUSTOTAL_ENABLED = true,
-- Shodan API Configuration
-- NOTE: Host lookup endpoint requires paid membership ($49 one-time minimum)
-- Free tier accounts cannot access IP host information
-- API key priority: 1. Environment variable, 2. ~/.ask/SHODAN_API_KEY.txt
SHODAN_API_KEY = get_api_key("SHODAN", "SHODAN_API_KEY", ""),
SHODAN_ENABLED = true,
-- IPinfo API Configuration
-- Free tier: 50,000 requests/month (Lite API - country/ASN only)
-- Paid tiers: Core/Plus/Business provide VPN/Proxy/Tor detection, hosting detection, abuse contacts
-- API key priority: 1. Environment variable, 2. ~/.ask/IPINFO_API_KEY.txt
IPINFO_API_KEY = get_api_key("IPINFO", "IPINFO_API_KEY", ""),
IPINFO_ENABLED = true,
-- GreyNoise API Configuration
-- Community API: Free, no API key required
-- Rate limit: 50 searches per week (combined with Visualizer)
-- Identifies internet scanners vs legitimate services (RIOT dataset)
GREYNOISE_ENABLED = true,
GREYNOISE_API_URL = "https://api.greynoise.io/v3/community",
-- AlienVault OTX API Configuration
-- Free tier: Unlimited requests (community-driven threat intelligence)
-- Registration: https://otx.alienvault.com (free account required)
-- Provides IP, domain, URL, and file hash reputation with pulse data
-- API key priority: 1. Environment variable, 2. ~/.ask/OTX_API_KEY.txt
OTX_API_KEY = get_api_key("OTX", "OTX_API_KEY", ""),
OTX_ENABLED = true,
OTX_API_URL = "https://otx.alienvault.com/api/v1",
-- Abuse.ch API Configuration (URLhaus + ThreatFox)
-- Free tier: Fair use policy (free Auth-Key required)
-- Registration: https://auth.abuse.ch (free Auth-Key)
-- URLhaus: Malware URL detection, payload information, host lookups
-- ThreatFox: IOC search (IP, domain, URL, hash), malware family identification
-- API key priority: 1. Environment variable, 2. ~/.ask/ABUSECH_API_KEY.txt
ABUSECH_API_KEY = get_api_key("ABUSECH", "ABUSECH_API_KEY", ""),
ABUSECH_ENABLED = true,
URLHAUS_API_URL = "https://urlhaus-api.abuse.ch/v1",
THREATFOX_API_URL = "https://threatfox-api.abuse.ch/api/v1",
-- RDAP Configuration (no API key required)
RDAP_ENABLED = true,
RDAP_BOOTSTRAP_URL = "https://rdap.org",
-- ARIN RDAP Configuration (supports IPv4 and IPv6)
ARIN_RDAP_ENABLED = true,
ARIN_RDAP_URL = "https://rdap.arin.net/registry",
-- Certificate Transparency (crt.sh - no API key required)
CERT_TRANSPARENCY_ENABLED = true,
CRT_SH_URL = "https://crt.sh",
-- Caching Configuration
CACHE_ENABLED = true,
CACHE_TTL_REPUTATION = 3600, -- 1 hour for reputation data
CACHE_TTL_REGISTRATION = 86400, -- 24 hours for registration data
-- Rate limiting awareness (requests per minute)
RATE_LIMIT_DELAY = 0.1, -- seconds between requests
MAX_RETRIES = 3,
RETRY_DELAY = 1, -- seconds
}
-------------------------------------------------
-- Additional Utility Functions
-------------------------------------------------
-- Check if openssl is available
-- Uses cached result to avoid repeated shell commands
local openssl_check_cache = nil -- nil = not checked, true/false = result
-- Forward declaration - execute_silent is defined later but we need it here
-- This will be set after execute_silent is defined
local execute_silent_early = nil
local function check_openssl_available()
-- Return cached result if available
if openssl_check_cache ~= nil then
return openssl_check_cache
end
local is_windows = package.config:sub(1,1) == "\\"
local result
if is_windows then
-- Windows: Use 'where' command to find openssl
if execute_silent_early then
-- Use silent execution to avoid cmd window flash
result = execute_silent_early("where openssl")
else
-- Fallback during early init (before execute_silent is defined)
local handle = io.popen("where openssl 2>nul")
if handle then
result = handle:read("*a")
handle:close()
end
end
if result and result ~= "" and not string.find(result, "Could not find") and not string.find(result, "INFO:") then
openssl_check_cache = true
return true, result
end
else
-- Unix-like (macOS, Linux) - no window issues
handle = io.popen("which openssl 2>&1")
if handle then
result = handle:read("*a")
handle:close()
if result and result ~= "" and not string.find(result, "not found") then
openssl_check_cache = true
return true, result
end
end
-- Try direct execution test
local test_handle = io.popen("openssl version 2>&1")
if test_handle then
local version_output = test_handle:read("*a")
test_handle:close()
if version_output and string.find(version_output, "OpenSSL") then
openssl_check_cache = true
return true, version_output
end
end
end
openssl_check_cache = false
return false, nil
end
-- Check if curl is available
local function check_curl_available()
local result
local is_windows = package.config:sub(1,1) == "\\"
if is_windows then
-- Windows: Use 'where' to find curl.exe
if execute_silent_early then
-- Use silent execution to avoid cmd window flash
result = execute_silent_early("where curl.exe")
else
-- Fallback during early init
local handle = io.popen("where curl.exe 2>nul")
if handle then
result = handle:read("*a")
handle:close()
end
end
if result and result ~= "" and not string.find(result, "Could not find") and not string.find(result, "INFO:") then
return true, result
end
else
-- Unix-like: Use 'which' command (no window issues)
handle = io.popen("which curl 2>&1")
if handle then
result = handle:read("*a")
handle:close()
if result and result ~= "" and not string.find(result, "not found") then
return true, result
end
end
-- Fallback: Try running curl directly to check version
local test_handle = io.popen("curl --version 2>&1")
if test_handle then
local test_output = test_handle:read("*a")
test_handle:close()
if test_output and string.find(test_output, "curl") then
return true, "curl (found via version check)"
end
end
end
return false, "curl not found in PATH"
end
-- Initialize curl availability variable
-- On Windows, defer the check to first use to avoid cmd window flash on plugin load
local curl_available = nil -- nil means not checked yet
local curl_path = nil
-- Lazy curl check function
local function ensure_curl_checked()
if curl_available == nil then
curl_available, curl_path = check_curl_available()
if not curl_available then
log_message("WARNING: curl not found. HTTP requests will fail. Install curl first.")
else
log_message("curl found at: " .. string.gsub(curl_path or "", "\n", ""))
end
end
return curl_available
end
-- On Unix, check immediately (no window flash issue)
-- On Windows, defer to first use
if package.config:sub(1,1) ~= "\\" then
ensure_curl_checked()
end
-------------------------------------------------
-- Silent Command Execution (Windows)
-------------------------------------------------
-- Execute command silently on Windows (suppress command window)
-- This function uses VBScript to run commands without any visible window
local function execute_silent(cmd)
local is_windows = package.config:sub(1,1) == "\\"
if is_windows then
-- On Windows, use a temp file approach to capture output silently
-- VBScript with WScript.Shell.Run uses window style 0 (hidden)
local temp_out = os.tmpname()
local temp_bat = os.tmpname() .. ".bat"
-- Create a batch file that runs the command and captures output
local bat_file = io.open(temp_bat, "w")
if bat_file then
-- Write batch file that runs command silently
bat_file:write("@echo off\r\n")
bat_file:write(cmd .. " > \"" .. temp_out .. "\" 2>&1\r\n")
bat_file:close()
-- Create VBScript to run batch file hidden
local temp_vbs = os.tmpname() .. ".vbs"
local vbs_file = io.open(temp_vbs, "w")
if vbs_file then
-- WshShell.Run with 0 = hidden window, True = wait for completion
vbs_file:write('Set WshShell = CreateObject("WScript.Shell")\n')
vbs_file:write('WshShell.Run "cmd /c \"\"' .. temp_bat:gsub("\\", "\\\\") .. '\"\"", 0, True\n')
vbs_file:close()
-- Execute VBScript (this call itself may briefly flash, but much less than multiple commands)
os.execute('cscript //nologo "' .. temp_vbs .. '"')
-- Read output
local output = ""
local out_file = io.open(temp_out, "r")
if out_file then
output = out_file:read("*a") or ""
out_file:close()
end
-- Cleanup
os.remove(temp_vbs)
os.remove(temp_bat)
os.remove(temp_out)
return output, true -- Return output and success flag
end
os.remove(temp_bat)
end
-- Fallback: direct io.popen if VBScript approach fails
local handle = io.popen(cmd .. " 2>&1")
if handle then
local result = handle:read("*a") or ""
handle:close()
return result, true
end
return "", false
else
-- On Unix-like systems, use io.popen normally (no window issues)
local handle = io.popen(cmd .. " 2>&1")
if handle then
local result = handle:read("*a") or ""
local success = handle:close()
return result, success
end
return "", false
end
end
-- Now that execute_silent is defined, make it available for tool checks
execute_silent_early = execute_silent
-------------------------------------------------
-- ASK Documents Directory and Logging
-------------------------------------------------
-- Global variable to store ASK documents directory
local ASK_DOCS_DIR = nil
-- Initialize ASK directory in Documents folder
local function init_ask_directory()
-- Determine home directory based on platform
local home_dir
local path_sep
local is_windows = package.config:sub(1,1) == "\\"
if is_windows then
-- Windows
home_dir = os.getenv("USERPROFILE")
path_sep = "\\"
else
-- Unix-like (macOS, Linux)
home_dir = os.getenv("HOME")
path_sep = "/"
end
if not home_dir then
log_message("WARNING: Cannot determine home directory - logging disabled")
return nil
end
-- Build path: Documents/ASK
local docs_base = home_dir .. path_sep .. "Documents"
local docs_dir = docs_base .. path_sep .. "ASK"
-- First, try to write to the directory (it might already exist)
local test_file = docs_dir .. path_sep .. ".ask_test"
local f = io.open(test_file, "w")
if f then
f:close()
os.remove(test_file)
log_message("ASK directory initialized: " .. docs_dir)
return docs_dir
end
-- Directory doesn't exist, try to create it
-- On Windows, avoid os.execute/io.popen during init to prevent cmd window flash
-- Use Lua's lfs if available, otherwise just try pure Lua approaches
if is_windows then
-- On Windows, we avoid shell commands during plugin load
-- The directory will be created lazily when first log write is attempted
-- For now, check if Documents exists and ASK can be created
local docs_test = io.open(docs_base .. path_sep .. ".ask_test_docs", "w")
if docs_test then
docs_test:close()
os.remove(docs_base .. path_sep .. ".ask_test_docs")
-- Documents exists, but ASK subfolder doesn't
-- We'll create it on first log write using PowerShell with -WindowStyle Hidden
-- For now, just return the path and create lazily
log_message("ASK directory path set (will create on first use): " .. docs_dir)
return docs_dir
end
log_message("WARNING: Cannot access Documents folder - logging disabled")
return nil
else
-- Unix-like: mkdir -p is safe and doesn't show any window
local result = os.execute('mkdir -p "' .. docs_dir .. '" 2>/dev/null')
-- Verify directory was created
f = io.open(test_file, "w")
if f then
f:close()
os.remove(test_file)
log_message("ASK directory initialized: " .. docs_dir)
return docs_dir
end
end
log_message("WARNING: Cannot write to ASK directory - logging disabled")
return nil
end
-- Get current date string for log filename (YYYY-MM-DD format)
local function get_date_string()
return os.date("%Y-%m-%d")
end
-- Get current timestamp for log entries
local function get_timestamp()
return os.date("%Y-%m-%d %H:%M:%S")
end
-- Ensure ASK directory exists (lazy creation for Windows)
local function ensure_ask_directory()
if not ASK_DOCS_DIR then
return false
end
local path_sep = package.config:sub(1,1) == "\\" and "\\" or "/"
local test_file = ASK_DOCS_DIR .. path_sep .. ".ask_test"
-- Check if directory exists by trying to write a test file
local f = io.open(test_file, "w")
if f then
f:close()
os.remove(test_file)
return true
end
-- Directory doesn't exist, try to create it
if package.config:sub(1,1) == "\\" then
-- Windows: Use execute_silent to avoid cmd window flash
local cmd = 'mkdir "' .. ASK_DOCS_DIR .. '"'
execute_silent(cmd)
else
os.execute('mkdir -p "' .. ASK_DOCS_DIR .. '" 2>/dev/null')
end
-- Verify it was created
f = io.open(test_file, "w")
if f then
f:close()
os.remove(test_file)
return true
end
return false
end
-- Append content to daily log file
local function append_to_log(query_type, query_target, result_content)
if not ASK_DOCS_DIR then
return false, "Logging not initialized"
end
-- Ensure directory exists (lazy creation)
if not ensure_ask_directory() then
return false, "Cannot create ASK directory: " .. ASK_DOCS_DIR
end
local path_sep = package.config:sub(1,1) == "\\" and "\\" or "/"
local log_filename = "ASK-" .. get_date_string() .. ".log"
local log_path = ASK_DOCS_DIR .. path_sep .. log_filename
local f = io.open(log_path, "a")
if not f then
return false, "Cannot open log file: " .. log_path
end
-- Write log entry
f:write(string.rep("=", 80) .. "\n")
f:write("Timestamp: " .. get_timestamp() .. "\n")
f:write("Query Type: " .. (query_type or "Unknown") .. "\n")
f:write("Query Target: " .. (query_target or "Unknown") .. "\n")
f:write(string.rep("-", 80) .. "\n")
f:write(result_content .. "\n")
f:write("\n")
f:close()
return true, log_path
end
-- Copy text to clipboard (platform-dependent)
local clipboard_backend = nil
local function command_exists(command)
local check_cmd
if package.config:sub(1,1) == "\\" then
check_cmd = "where " .. command .. " >nul 2>&1"
else
check_cmd = "which " .. command .. " >/dev/null 2>&1"
end
local status = os.execute(check_cmd)
return status == 0 or status == true
end
local function get_clipboard_backend()
if clipboard_backend ~= nil then
return clipboard_backend
end
if command_exists("pbcopy") then
clipboard_backend = "pbcopy"
elseif command_exists("xclip") then
clipboard_backend = "xclip"
elseif command_exists("xsel") then
clipboard_backend = "xsel"
else
clipboard_backend = false
end
return clipboard_backend
end
local function copy_to_clipboard(text)
if not text or text == "" then
return false, "No text to copy"
end
local success = false
local cmd
if package.config:sub(1,1) == "\\" then
-- Windows: Use clip command via execute_silent to avoid cmd window flash
local temp_file = os.tmpname()
local f = io.open(temp_file, "w")
if f then
f:write(text)
f:close()
cmd = 'type "' .. temp_file .. '" | clip'
local result = execute_silent(cmd)
os.remove(temp_file)
-- execute_silent returns (output, success), check if it ran
success = true -- clip doesn't output anything, assume success if no error
end
else
local backend = get_clipboard_backend()
if backend == "pbcopy" then
cmd = 'echo ' .. string.format('%q', text) .. ' | pbcopy'
local result = os.execute(cmd)
success = (result == 0 or result == true)
elseif backend == "xclip" then
cmd = 'echo ' .. string.format('%q', text) .. ' | xclip -selection clipboard'
local result = os.execute(cmd)
success = (result == 0 or result == true)
elseif backend == "xsel" then
cmd = 'echo ' .. string.format('%q', text) .. ' | xsel --clipboard'
local result = os.execute(cmd)
success = (result == 0 or result == true)
end
end
if success then
return true, "Copied to clipboard"
else
return false, "Clipboard command not available"
end
end
-- Initialize ASK directory on load
ASK_DOCS_DIR = init_ask_directory()
local function show_error_window(title, message)
local win = TextWindow.new(title or "ASK Error")
win:set(message)
end
local function show_result_window(title, content)
local win = TextWindow.new(title or "ASK Results")
win:set(content)
end
-- Enhanced result window with copy and log buttons
local function show_result_window_with_buttons(title, content, query_type, query_target)
local win = TextWindow.new(title or "ASK Results")
-- Set content directly without button text
win:set(content)
-- Add copy button
win:add_button("Copy to Clipboard", function()
local success, msg = copy_to_clipboard(content)
if success then
log_message("Copied to clipboard: " .. title)
else
log_message("Failed to copy to clipboard: " .. msg)
show_error_window("Clipboard Error", "Failed to copy to clipboard:\n" .. msg)
end
end)
-- Add log button
win:add_button("Save to Log", function()
local success, msg = append_to_log(query_type, query_target, content)
if success then
log_message("Saved to log: " .. msg)
-- Show confirmation
local confirm_win = TextWindow.new("Log Saved")
confirm_win:set("Result saved to:\n" .. msg .. "\n\nQuery Type: " .. query_type .. "\nQuery Target: " .. query_target)
else
log_message("Failed to save to log: " .. msg)
show_error_window("Log Error", "Failed to save to log:\n" .. msg)
end
end)
end
-- Extract field value from packet fields
local function get_field_value(fieldname, fieldtype, fields)
fieldtype = fieldtype or "value"
for i, field in ipairs(fields) do
if field.name == fieldname then
if fieldtype == "display" then
return field.display
elseif fieldtype == "value" then
return field.value
end
end
end
return nil
end
-- Forward declarations for IP validation functions
local is_valid_ipv4, is_valid_ipv6, is_valid_ip, extract_ip_from_string
-- Validate IP address (IPv4)
is_valid_ipv4 = function(ip)
if not ip or ip == "" then return false end
local parts = {}
for part in string.gmatch(ip, "(%d+)") do
table.insert(parts, part)
end
if #parts ~= 4 then return false end
for _, part in ipairs(parts) do
local num = tonumber(part)
if not num or num < 0 or num > 255 then
return false
end
end
return true
end
-- Validate IP address (IPv6) - basic validation
is_valid_ipv6 = function(ip)
if not ip or ip == "" then return false end
-- Basic IPv6 validation - check for colons and valid hex characters
if string.find(ip, ":") == nil then return false end
-- More comprehensive validation would check for proper IPv6 format
-- For now, accept anything with colons that looks like IPv6
return string.find(ip, "^%s*[%x:]+%s*$") ~= nil
end
-- Validate IP address (IPv4 or IPv6)
is_valid_ip = function(ip)
return is_valid_ipv4(ip) or is_valid_ipv6(ip)
end
-- Check if an IPv4 address is RFC 1918 private address
local function is_rfc1918_private(ip)
if not ip or not is_valid_ipv4(ip) then
return false
end
-- Parse IP address into octets
local parts = {}
for part in string.gmatch(ip, "(%d+)") do
table.insert(parts, tonumber(part))
end
if #parts ~= 4 then return false end
local octet1, octet2 = parts[1], parts[2]
-- RFC 1918 private address ranges:
-- 10.0.0.0/8 (10.0.0.0 to 10.255.255.255)
-- 172.16.0.0/12 (172.16.0.0 to 172.31.255.255)
-- 192.168.0.0/16 (192.168.0.0 to 192.168.255.255)
if octet1 == 10 then
return true
elseif octet1 == 172 and octet2 >= 16 and octet2 <= 31 then
return true
elseif octet1 == 192 and octet2 == 168 then
return true
end
return false
end
-- Format RFC 1918 private address information
local function format_rfc1918_info(ip)
local result = "=== RFC 1918 Private Address ===\n\n"
result = result .. "IP Address: " .. ip .. "\n\n"
result = result .. "This is a private (LAN) IP address as defined by RFC 1918.\n"
result = result .. "Private addresses are not routable on the public Internet.\n\n"
result = result .. "--- RFC 1918 Private Address Ranges ---\n"
result = result .. "• 10.0.0.0/8 (10.0.0.0 to 10.255.255.255)\n"
result = result .. "• 172.16.0.0/12 (172.16.0.0 to 172.31.255.255)\n"
result = result .. "• 192.168.0.0/16 (192.168.0.0 to 192.168.255.255)\n\n"
result = result .. "--- Why No External Information? ---\n"
result = result .. "External threat intelligence services (Shodan, VirusTotal, AbuseIPDB, etc.)\n"
result = result .. "cannot provide information about private addresses because:\n\n"
result = result .. "• Private addresses are not publicly routable\n"
result = result .. "• They exist only within local networks (LANs)\n"
result = result .. "• Multiple networks can use the same private IP ranges\n"
result = result .. "• External services cannot reach or scan these addresses\n\n"
result = result .. "--- What You Can Do ---\n"
result = result .. "• Check your local network documentation\n"
result = result .. "• Review internal firewall logs\n"
result = result .. "• Check local DNS records\n"
result = result .. "• Use internal network scanning tools\n"
result = result .. "• Review local network monitoring systems\n"
return result
end
-- URL encode a string for use in query parameters
local function url_encode(str)
if not str then return "" end
-- Encode special characters
str = string.gsub(str, "([^%w%-%.%_%~])", function(c)
return string.format("%%%02X", string.byte(c))
end)
return str
end
-- Extract IP address from string that might contain hostname or other text
-- Handles formats like: "hostname (192.168.1.1)" or "192.168.1.1" or "hostname 192.168.1.1"
extract_ip_from_string = function(str)
if not str or str == "" then return nil end
-- First, try to find IP in parentheses: "hostname (192.168.1.1)" or "hostname (2001:db8::1)"
local ip_in_parens = string.match(str, "%(([^%)]+)%)")
if ip_in_parens then
-- Check if it's a valid IPv4
if is_valid_ipv4(ip_in_parens) then
return ip_in_parens
end
-- Check if it's a valid IPv6
if is_valid_ipv6(ip_in_parens) then
return ip_in_parens
end
end
-- Try to find IPv4 address pattern in the string (more specific pattern)
-- Pattern: 1-3 digits, dot, 1-3 digits, dot, 1-3 digits, dot, 1-3 digits
local ipv4_pattern = "(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?)"
-- Try to match at word boundaries or start/end of string
for ip in string.gmatch(str, ipv4_pattern) do
if is_valid_ipv4(ip) then
return ip
end
end
-- Try to find IPv6 address pattern (more comprehensive)
-- IPv6 can have various formats: 2001:db8::1, 2001:db8:0:0:0:0:0:1, etc.
local ipv6_patterns = {
"([%x:]+::[%x:]+)", -- Compressed format with ::
"([%x:]+:[%x:]+:[%x:]+:[%x:]+:[%x:]+:[%x:]+:[%x:]+:[%x:]+)", -- Full format
}
for _, pattern in ipairs(ipv6_patterns) do
local ipv6 = string.match(str, pattern)
if ipv6 and is_valid_ipv6(ipv6) then
return ipv6
end
end
-- If the whole string is a valid IP, return it
if is_valid_ip(str) then
return str
end
return nil
end
-- Validate email address
local function is_valid_email(email)
if not email or email == "" then return false end
-- Extract email from angle brackets if present
local clean_email = email
local left_bracket = string.find(email, "<")
if left_bracket then
local right_bracket = string.find(email, ">", left_bracket)
if right_bracket then
clean_email = string.sub(email, left_bracket + 1, right_bracket - 1)
end
end
-- Basic email validation
return string.find(clean_email, "^%s*[%w%._%-]+@[%w%._%-]+%.[%w%._%-]+%s*$") ~= nil
end
-- Extract email address from field (handles "Name <email@domain.com>" format)
local function extract_email(email_field)
if not email_field then return nil end
local left_bracket = string.find(email_field, "<")
if left_bracket then
local right_bracket = string.find(email_field, ">", left_bracket)
if right_bracket then
return string.sub(email_field, left_bracket + 1, right_bracket - 1)
end
end
return email_field
end
-- Validate domain name
local function is_valid_domain(domain)
if not domain or domain == "" then return false end
-- Basic domain validation
return string.find(domain, "^%s*[%w%._-]+%.[%w%._-]+%s*$") ~= nil
end
-- Validate URL
local function is_valid_url(url)
if not url or url == "" then return false end
return string.find(url, "^https?://") ~= nil
end
-- HTTP POST request with error handling
local function http_post(url, headers, body)
if not ensure_curl_checked() then
return nil, "curl is not available. Please install curl to use this feature."
end
-- Build curl command
local cmd = "curl -s -S --max-time 30"
-- Add headers
if headers then
for key, value in pairs(headers) do
cmd = cmd .. " -H '" .. key .. ": " .. value .. "'"
end
end
-- Add POST data
if body then
cmd = cmd .. " -d '" .. string.gsub(body, "'", "'\\''") .. "'"
end
-- Add URL (must be last)
cmd = cmd .. " '" .. string.gsub(url, "'", "'\\''") .. "'"
log_message("Executing curl POST for: " .. url)
local handle = io.popen(cmd)
if not handle then
return nil, "Failed to execute curl command"
end
local result = handle:read("*a")
local exit_code
local close_success, close_result = pcall(function() return handle:close() end)
if close_success then
exit_code = close_result
end
local is_success = false
if exit_code == nil then
is_success = (result and result ~= "")
elseif exit_code == true or exit_code == 0 then
is_success = true
elseif exit_code == false then
is_success = false
else
is_success = false
end
if result and result ~= "" then
if string.find(result, "^curl:") or string.find(result, "curl: %d+") then
return nil, "curl error: " .. string.sub(result, 1, 300)
end
if string.find(result, '"status":%s*[45]%d%d') or string.find(result, '"errorCode"') or string.find(result, '"error"') then
local error_msg = string.match(result, '"message"%s*:%s*"([^"]*)"') or
string.match(result, '"title"%s*:%s*"([^"]*)"') or
string.match(result, '"error"%s*:%s*"([^"]*)"') or
string.match(result, '"detail"%s*:%s*"([^"]*)"')
if error_msg then
if string.find(error_msg, "Expected") or string.find(error_msg, "parse") or string.find(error_msg, "JSON") then
return nil, "HTTP error: Malformed JSON response from server\n\n" ..
"Error details: " .. error_msg .. "\n\n" ..