-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathknoxcli
executable file
·623 lines (542 loc) · 17.5 KB
/
knoxcli
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
#!/bin/bash
# This is an auto-generated file. Tread with caution!
read -r -d '' filecontent <<EOR
clilogo()
{
cat <<EOH
\\\`\\\`\\\`
██╗ ██╗███╗ ██╗ ██████╗ ██╗ ██╗ ██████╗██╗ ██╗
██║ ██╔╝████╗ ██║██╔═══██╗╚██╗██╔╝██╔════╝██║ ██║
█████╔╝ ██╔██╗ ██║██║ ██║ ╚███╔╝ ██║ ██║ ██║
██╔═██╗ ██║╚██╗██║██║ ██║ ██╔██╗ ██║ ██║ ██║
██║ ██╗██║ ╚████║╚██████╔╝██╔╝ ██╗╚██████╗███████╗██║
╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝╚═╝
\\\`\\\`\\\`
EOH
}
EOR
. <(echo "$filecontent")
read -r -d '' filecontent <<EOR
#!/bin/bash
AKCFG=\${ACCUKNOX_CFG:-~/.accuknox.cfg}
[[ -f "\$AKCFG" ]] && source \$AKCFG
DIR=/tmp/\$\$
TMP=\$DIR/\$(basename \$0)
LOGLEVEL=\${LOGLEVEL:-1} #0=dbg, 1=info, 2=warn, 3=err
ak_dbg()
{
[[ \$LOGLEVEL -gt 0 ]] && return
echo "\$*"
}
ak_info()
{
[[ \$LOGLEVEL -gt 1 ]] && return
echo "\$*"
}
ak_warn()
{
[[ \$LOGLEVEL -gt 2 ]] && return
echo "\$*"
}
ak_err()
{
[[ \$LOGLEVEL -gt 3 ]] && return
echo "\$*"
}
ak_help()
{
cat <<EOH
## Setting AccuKnox configuration
* Please note that AccuKnox configuration ('.accuknox.cfg') would be needed to run the cli. [ref](https://github.com/accuknox/tools/tree/main/api-samples#setting-accuknoxcfg)
* Use API_VERBOSE=2 <cmd> ... to dump the request response of all the AccuKnox API calls.
EOH
}
ak_api()
{
apiverbosity=\${API_VERBOSE:-0}
[[ \$apiverbosity -gt 0 ]] && echo "API: [\$1]"
unset apicmd
unset json_string
read -r -d '' apicmd << EOH
curl \$CURLOPTS "\$1" \
-H "authorization: Bearer \$TOKEN" \
-H 'content-type: application/json' \
-H "x-tenant-id: \$TENANT_ID"
EOH
if [ "\$data_raw" != "" ]; then
apicmd="\$apicmd --data-raw '\$data_raw'"
fi
[[ \$apiverbosity -gt 1 ]] && echo "\$apicmd"
json_string=\`eval "\$apicmd"\`
if ! jq -e . >/dev/null 2>&1 <<<"\$json_string"; then
echo "API call failed: [\$json_string]"
exit 1
fi
[[ \$apiverbosity -gt 1 ]] && echo "\$json_string"
unset data_raw
}
ak_prereq()
{
[[ "\$DIR" != "" ]] && mkdir -p \$DIR
command -v jq >/dev/null 2>&1 || { echo >&2 "require 'jq' to be installed. Aborting."; exit 1; }
}
function ak_cleanup {
[[ "\$DIR" != "" ]] && rm -rf \$DIR
}
trap ak_cleanup EXIT
ak_prereq
EOR
. <(echo "$filecontent")
read -r -d '' filecontent <<EOR
#!/bin/bash
arg_shortopts=""
arg_longopts=" "
declare -a arg_desclist
declare -A arg_handlers
declare -A arg_nvlist
argopt()
{
mand=""
arg=""
handler="none"
sopt=""
desc=""
lopt=""
soptdesc=""
optdesc=""
OPTS=\$(getopt -o "s:l:d:" --long "needval sopt: lopt: desc: reqarg mandatory handler:" -n 'parse-options' -- "\$@")
eval set -- "\$OPTS"
while true; do
case "\$1" in
--sopt | -s ) sopt="\$2"; shift 2;;
--lopt | -l ) lopt="\$2"; shift 2;;
--desc | -d ) desc="\$2"; shift 2;;
--handler) handler="\$2"; shift 2;;
--needval) arg=":"; shift 1;;
--mandatory) mand="*"; shift 1;;
-h | --help ) return 2;;
-- ) shift; break ;;
* ) break ;;
esac
done
[[ "\$lopt" == "" ]] && echo "ERROR(argopt): long option is a mandatory field!" && return 1
[[ "\$sopt" != "" ]] && soptdesc="-\$sopt | "
[[ "\$arg" != "" ]] && optdesc="[value] "
arg_desclist+=("\$soptdesc--\$lopt \$optdesc=> \$desc. \$mand")
arg_handlers["\$lopt"]=\$handler
[[ "\$sopt" != "" ]] && arg_shortopts="\$arg_shortopts\$sopt\$arg"
arg_longopts="\$arg_longopts\$lopt\$arg "
arg_nvlist["\$lopt"]=\$arg
return 0
}
arghelp()
{
echo "Supported options:"
echo ;
printf "\t%s\n" "\${arg_desclist[@]}"
}
arghandle()
{
handler=\${arg_handlers["\$1"]}
needval=\${arg_nvlist["\$1"]}
[[ "\$needval" == ":" ]] && \$handler "\$1" "\$2" && return 2
\$handler "\$1"
return 1
}
arginit()
{
arg_shortopts=()
arg_longopts=()
arg_desclist=()
arg_handlers=()
arg_nvlist=()
}
argrun()
{
[[ "\$arg_shortopts" == "" ]] && [[ "\$arg_longopts" == "" ]] && echo "no cmdopt() specified" && return
OPTS=\`getopt -o \$arg_shortopts --long "\$arg_longopts" -n 'parse-options' -- "\$@"\`
eval set -- "\$OPTS"
while true; do
case "\$1" in
-h | --help) arghandle "help"; return 2;;
--) shift; break ;;
*) arghandle \${1/--/} "\$2"; shift \$?;;
esac
done
}
EOR
. <(echo "$filecontent")
# ----------- [asset] command handler -----------------------
read -r -d '' filecontent <<EOR
asset_help()
{
echo ;
}
asset_cmd()
{
echo "Executing image..."
}
EOR
. <(echo "$filecontent")
# ----------- end of [asset] command handler ----------------
# ----------- [asset_list] command handler -----------------------
read -r -d '' filecontent <<EOR
filter=""
assetjq=".results[] | select(.vulnerabilities.Critical >= 2)"
al_help()
{
cat <<EOH
### [asset list] options
List the assets.
EOH
arghelp
cat <<EOH
Examples:
1. knoxcli asset list
... list all the assets
2. knoxcli asset list --filter "asset_category=Container" --assetjq ".results[] | select(.vulnerabilities.Critical >= 3)"
... list all the
#### Asset Categories list
1. Container
2. Storage
EOH
}
al_generic_handler()
{
case "\$1" in
"filter" ) filter="\$2" ;;
"assetjq" ) assetjq="\$2" ;;
*) echo "UNHANDLER argopt";;
esac
}
asset_list_cmd()
{
arginit
argopt --lopt "filter" --sopt "f" --needval --handler "al_generic_handler" \
--desc "filter to be used with image list"
argopt --lopt "assetjq" --needval --handler "al_generic_handler" \
--desc "jq based filter to use with asset list"
argopt --sopt "h" --lopt "help" --handler "al_help" \
--desc "help for cluster list"
argrun "\$@"
[[ \$? -ne 0 ]] && return 1
ak_api "\$CSPM_URL/api/v1/assets?page=1&page_size=20&\$filter"
echo \$json_string | jq -r "\$assetjq"
}
EOR
. <(echo "$filecontent")
# ----------- end of [asset_list] command handler ----------------
# ----------- [cluster] command handler -----------------------
read -r -d '' filecontent <<EOR
cluster_help()
{
cat <<EOH
## [cluster] command
[cluster] command operates on Kubernetes and Virtual Machines based clusters.
EOH
}
cluster_cmd()
{
echo "check further [cluster] options ..."
}
EOR
. <(echo "$filecontent")
# ----------- end of [cluster] command handler ----------------
# ----------- [cluster_alerts] command handler -----------------------
read -r -d '' filecontent <<EOR
clusterjq='.[] | select(.ClusterName|test("idt")'
alertjq='.'
etime=\$(date +%s) # current time
stime=\$((\$etime-2*24*60*60)) # etime - 2 days
alerttype="kubearmor"
filters=""
cluster_alerts_query()
{
for((pgid=1;;pgid++)); do
data_raw="{\"Namespace\":[],\"FromTime\":\$stime,\"ToTime\":\$etime,\"PageId\":\$pgid,\"PageSize\":50,\"Filters\":[\$filters],\"ClusterID\":[\$cidlist],\"View\":\"List\",\"Type\":\"\$alerttype\",\"WorkloadType\":[],\"WorkloadName\":[],\"WorkspaceID\":\$TENANT_ID}"
ak_api "\$CWPP_URL/monitors/v1/alerts/events?orderby=desc"
acnt=\$(echo \$json_string | jq '.response | length')
[[ \$acnt -le 0 ]] && break
echo \$json_string | jq "\$alertjq"
done
}
ca_generic_handler()
{
case "\$1" in
type ) alerttype="\$2" ;;
clusterjq ) clusterjq="\$2" ;;
alertjq ) alertjq="\$2" ;;
filters ) filters="\$2" ;;
stime ) stime="\$2" ;;
etime ) etime="\$2" ;;
* ) echo "UNKNOWN argopt" ;;
esac
}
ca_help()
{
cat <<EOH
### [cluster alerts] options
Show alerts in the context of clusters. These alerts could be from KubeArmor, Network policies, Admission controllers or anything else as reported in "Monitors & Alerts" option in AccuKnox Control Plane.
EOH
arghelp
cat <<EOH
Examples:
1. knoxcli cluster alerts --alertjq '.response[] | select(.Resource // "unknown" | test("ziggy"))'
... list all the alerts containing 'ziggy' in the Resource filter
2. knoxcli cluster alerts --filters '{"field":"HostName","value":"store54055","op":"match"}' --alertjq '.response[] | "hostname=\(.HostName),resource=\(.Resource//""),UID=\(.UID),operation=\(.Operation)"'
... get all alerts for HostName="store54055" and print the response in following csv format hostname,resource,UID,operation
> **Difference between --alertjq and --filters?** <br>
> --filters are passed directly to the AccuKnox API. --alertjq operates on the output of the AccuKnox API response. It is recommended to use --filters as far as possible. However, you can use regex/jq based matching criteria with --alertjq.
EOH
}
cluster_alerts_args()
{
arginit
argopt --lopt "type" --needval --handler "ca_generic_handler" \
--desc "set alert type (default: \$alerttype)"
argopt --lopt "clusterjq" --needval --handler "ca_generic_handler" \
--desc "jq filter to be used on cluster list output (default: '\$clusterjq')"
argopt --lopt "alertjq" --needval --handler "ca_generic_handler" \
--desc "jq filter to be used on cluster list output (default: '\$alertjq')"
argopt --sopt "f" --needval --lopt "filters" --handler "ca_generic_handler" \
--desc "Alert filters to be passed to API (default: '\$filters')"
argopt --sopt "s" --needval --lopt "stime" --handler "ca_generic_handler" \
--desc "start time in epoch format (default: \$stimestr)"
argopt --sopt "e" --needval --lopt "etime" --handler "ca_generic_handler" \
--desc "end time in epoch format (default: now)"
argopt --sopt "h" --lopt "help" --handler "ca_help" \
--desc "help with the options"
argrun "\$@"
[[ \$? -ne 0 ]] && return 1
[[ \$etime -lt \$stime ]] && echo "etime should be greater than stime" && return 2
return 0
}
cluster_alerts_cmd()
{
cluster_alerts_args "\$@"
[[ \$? -ne 0 ]] && return 1
ak_api "\$CWPP_URL/cluster-onboarding/api/v1/get-onboarded-clusters?wsid=\$TENANT_ID"
final_json=\$(echo \$json_string | jq -r "\$clusterjq")
cidlist=""
while read cline; do
cid=\${cline/ */}
cname=\${cline/* /}
[[ "\$cidlist" != "" ]] && cidlist="\$cidlist,"
cidlist="\$cidlist\"\$cid\""
done < <(echo \$final_json | jq -r '. | "\(.ID) \(.ClusterName)"')
cluster_alerts_query
}
EOR
. <(echo "$filecontent")
# ----------- end of [cluster_alerts] command handler ----------------
# ----------- [cluster_list] command handler -----------------------
read -r -d '' filecontent <<EOR
clusterjq='.[] | "id=\(.ID),name=\(.ClusterName),status=\(.Status)"'
nodejq='.result[].NodeName'
show_nodes=0
cluster_list_get_node_list()
{
echo "List of nodes in cluster [\$cname]:"
data_raw="{\"workspace_id\":\$TENANT_ID,\"cluster_id\":[\$cid],\"from_time\":[],\"to_time\":[]}"
ak_api "\$CWPP_URL/cm/api/v1/cluster-management/nodes-in-cluster"
echo \$json_string | jq -r "\$nodejq"
}
cl_generic_handler()
{
case "\$1" in
"nodejq" ) nodejq="\$2" ;;
"clusterjq" ) clusterjq="\$2" ;;
"nodes" ) show_nodes=1 ;;
*) echo "UNHANDLER argopt";;
esac
}
cl_help()
{
cat <<EOH
### [cluster list] options
List the cluster and corresponding nodes or any other entities (namespaces, workloads) as part of the cluster.
EOH
arghelp
cat <<EOH
Examples:
1. knoxcli cluster list --clusterjq '.[] | select(.ClusterName|test("idt."))' --nodes
... list all the clusters with idt substring in its names and list all the nodes in those clusters
2. knoxcli cluster list --clusterjq '.[] | select((.type == "vm") and (.Status == "Inactive")) | "id=\(.ID),name=\(.ClusterName),status=\(.Status)"'
... list all the Inactive VM clusters and print their ID,name,status
EOH
}
cluster_list_cmd()
{
arginit
argopt --lopt "clusterjq" --needval --handler "cl_generic_handler" \
--desc "jq filter to be used on cluster list output (default: '\$clusterjq')"
argopt --lopt "nodejq" --needval --handler "cl_generic_handler" \
--desc "jq filter to be used on node list output (default: '\$nodejq')"
argopt --sopt "n" --lopt "nodes" --handler "cl_generic_handler" \
--desc "lists nodes from the clusters"
argopt --sopt "h" --lopt "help" --handler "cl_help" \
--desc "help for cluster list"
argrun "\$@"
[[ \$? -ne 0 ]] && return 1
ak_api "\$CWPP_URL/cluster-onboarding/api/v1/get-onboarded-clusters?wsid=\$TENANT_ID"
final_json=\$(echo \$json_string | jq -r "\$clusterjq")
echo \$final_json | jq .
[[ \$show_nodes -eq 0 ]] && return
while read cline; do
cid=\${cline/ */}
cname=\${cline/* /}
cluster_list_get_node_list
done < <(echo \$final_json | jq -r '. | "\(.ID) \(.ClusterName)"')
}
EOR
. <(echo "$filecontent")
# ----------- end of [cluster_list] command handler ----------------
# ----------- [cluster_policy] command handler -----------------------
read -r -d '' filecontent <<EOR
clusterjq='.[]'
policyjq='.'
polout="policydump"
operation="list"
cluster_policy_dump_policy_file()
{
ak_api "\$CWPP_URL/policymanagement/v2/policy/\$1"
echo "\$json_string" | jq -r .yaml > \$polpath
[[ \$? -ne 0 ]] && echo "could not get policy with ID=[\$1]" && return
}
cluster_policy_get_policy_list()
{
polperpage=10
for((pgprev=0;;pgprev+=\$polperpage)); do
pgnext=\$((\$pgprev + \$polperpage))
echo "fetching policies \$pgprev to \$pgnext ..."
data_raw="{\"workspace_id\":\$TENANT_ID,\"workload\":\"k8s\",\"page_previous\":\$pgprev,\"page_next\":\$pgnext,\"filter\":{\"cluster_id\":[\$1],\"namespace_id\":[],\"workload_id\":[],\"kind\":[],\"node_id\":[],\"pod_id\":[],\"type\":[],\"status\":[],\"tags\":[],\"name\":{\"regex\":[]},\"tldr\":{\"regex\":[]}}}"
ak_api "\$CWPP_URL/policymanagement/v2/list-policy"
pcnt=\$(echo "\$json_string" | jq '.list_of_policies | length')
[[ \$pcnt -eq 0 ]] && echo "finished" && break
final_json=\$(echo "\$json_string" | jq -r "\$policyjq")
[[ "\$final_json" == "" ]] && continue
while read pline; do
arr=(\$pline)
if [ "\$operation" == "dump" ]; then
poldir=\$cpath/\${arr[2]}
mkdir -p \$poldir 2>/dev/null
polpath=\$poldir/\${arr[1]}.yaml
echo \$polpath
else
polpath=/dev/stdout
fi
cluster_policy_dump_policy_file \${arr[0]}
done < <(echo \$final_json | jq -r '.list_of_policies[] | "\(.policy_id) \(.name) \(.namespace_name)"')
done
}
cp_help()
{
cat <<EOH
### [cluster policy] options
Enlist the cluster policies. These include all policies, including, KubeArmor, Network, Admission Controller policies.
EOH
arghelp
cat <<EOH
Examples:
1. knoxcli cluster policy --clusterjq '.[] | select(.ClusterName|test("gke"))' --policyjq '.list_of_policies[] | select(.name|test("crypto"))'
... get all the policies have 'crypto' in their name for all the clusters having 'gke' in their name
2. knoxcli cluster policy --clusterjq '.[] | select(.ClusterName|test("gke"))' --policyjq '.list_of_policies[] | select(.namespace_name // "notpresent"|test("agents"))'
... get all the policies in namespace agents ... if no namespace is present then "notpresent" is substituted.
EOH
}
cp_generic_handler()
{
case "\$1" in
operation) operation="\$2"; shift 2;;
clusterjq) clusterjq="\$2"; shift 2;;
policyjq) policyjq="\$2"; shift 2;;
dumpdir) polout="\$2"; operation="dump"; shift 2;;
help ) cp_help; return 2;;
* ) echo "UNKNOWN OPT" ;;
esac
}
cluster_policy_cmd()
{
arginit
argopt --lopt "operation" --needval --handler "cp_generic_handler" \
--desc "[list|dump] Dump the policies in folder or list the policies. default:\$operation"
argopt --lopt "clusterjq" --needval --handler "cp_generic_handler" \
--desc "jq filter to be used on cluster list output (default: '\$clusterjq')"
argopt --lopt "policyjq" --needval --handler "cp_generic_handler" \
--desc "jq filter to be used on policy list output (default: '\$policyjq')"
argopt --sopt "d" --lopt "dumpdir" --needval --handler "cp_generic_handler" \
--desc "Policy dump directory"
argopt --sopt "h" --lopt "help" --handler "cp_help" \
--desc "help with the options"
argrun "\$@"
[[ \$? -ne 0 ]] && return 1
[[ "\$operation" != "list" ]] && [[ "\$operation" != "dump" ]] && \
echo "invalid operation [\$operation]!" && return 1
ak_api "\$CWPP_URL/cluster-onboarding/api/v1/get-onboarded-clusters?wsid=\$TENANT_ID"
filter_json=\$(echo \$json_string | jq -r "\$clusterjq")
while read cline; do
cid=\${cline/ */}
cname=\${cline/* /}
if [ "\$operation" == "dump" ]; then
cpath=\$polout/\$cname
mkdir \$cpath 2>/dev/null
fi
echo "fetching policies for cluster [\$cname] ..."
cluster_policy_get_policy_list \$cid
done < <(echo "\$filter_json" | jq -r '. | "\(.ID) \(.ClusterName)"')
}
EOR
. <(echo "$filecontent")
# ----------- end of [cluster_policy] command handler ----------------
# Processing starts here ...
unset cmd
while true; do
[[ ${1:--} == -* ]] && break #if arg is empty or starts with '-'
[[ "$cmd" != "" ]] && cmd="${cmd}_"
cmd="$cmd$1"
shift
done
case "$cmd" in
"asset")
asset_cmd "$@"
;;
"asset_list")
asset_list_cmd "$@"
;;
"cluster")
cluster_cmd "$@"
;;
"cluster_alerts")
cluster_alerts_cmd "$@"
;;
"cluster_list")
cluster_list_cmd "$@"
;;
"cluster_policy")
cluster_policy_cmd "$@"
;;
"version")
echo "version: v0.2"
;;
* | help)
[[ "$(type -t clilogo)" == "function" ]] && clilogo
echo "# $(basename $0) command options"
echo "\`\`\`"
echo "$0"
echo -en "\tasset\n"
echo -en "\tasset list\n"
echo -en "\tcluster\n"
echo -en "\tcluster alerts\n"
echo -en "\tcluster list\n"
echo -en "\tcluster policy\n"
echo -en "\tversion\n"
echo -en "\thelp\n"
echo "\`\`\`"
asset_cmd --help
asset_list_cmd --help
cluster_cmd --help
cluster_alerts_cmd --help
cluster_list_cmd --help
cluster_policy_cmd --help
;;
esac