From f72c00164318c56d4493326e301a71a100f99cd4 Mon Sep 17 00:00:00 2001 From: Christian Boltz Date: Thu, 18 May 2023 22:12:44 +0200 Subject: [PATCH] aa-status: Fix malformed json output In some cases (if profiles in complain and enforce mode are loaded), the `i` loop runs more than once, which also means `j == 0` is true in the middle of the json. This causes invalid json. This patch fixes this. This is a regression related to 22aa9b61615b72c20d96f8eeeac0a3f6ff0a5d1e / https://gitlab.com/apparmor/apparmor/-/merge_requests/964 / https://gitlab.com/apparmor/apparmor/-/issues/295 which fixed another case of invalid json if a process was unconfined while having a profile defined. Note: I also tested this patch for the "unconfined, but has a profile defined" case to ensure it doesn't break what 22aa9b61615b72c20d96f8eeeac0a3f6ff0a5d1e fixed. --- binutils/aa_status.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/binutils/aa_status.c b/binutils/aa_status.c index a61cfb0b7..6cd2acf43 100644 --- a/binutils/aa_status.c +++ b/binutils/aa_status.c @@ -620,6 +620,7 @@ static int detailed_processes(FILE *outf, filters_t *filters, bool json, struct process *processes, size_t nprocesses) { int ret; size_t i; + int need_finish = 0; if (json) { fprintf(outf, "\"processes\": {"); @@ -677,19 +678,22 @@ static int detailed_processes(FILE *outf, filters_t *filters, bool json, } else { fprintf(outf, "%s\"%s\": [{\"profile\": \"%s\", \"pid\": \"%s\", \"status\": \"%s\"}", // first element will be a unique executable - j == 0 ? "" : "], ", + j == 0 && !need_finish ? "" : "], ", filtered[j].exe, filtered[j].profile, filtered[j].pid, filtered[j].mode); } + need_finish = 1; } - if (j > 0) { - fprintf(outf, "]"); - } + } free_processes(filtered, nfiltered); } if (json) { - fprintf(outf, "}}\n"); + if (need_finish > 0) { + fprintf(outf, "]"); + } + + fprintf(outf, "}\n"); } exit: