Sample Header Ad - 728x90

Sanitize input that is used to update script

0 votes
1 answer
1103 views
Looking at a bash-script that takes input from Git commit comment to update itself. Simplified: script:
#!/bin/bash

comment=''

printf '%s\n' "$comment"

upgrade_script() {
        # Download latest:
        curl -o updated_script https://path/to/file 

        # Get comment:
        new_comment="$(curl https://path/to/comment) "

        # Update comment='' with new_comment:
        sed -i "3,0 s/comment=''/comment='$new_comment'/" updated_script
}
Issue is if comment has characters that either breaks sed or mangles bash. E.g:
# that's all she wrote!  => comment='that's all she wrote!
# use /need/ over /want/ => s/comment=''/'use /need/ over /want'/'
and then of course with the potential for both malicious but also unintended things like:
# Remove tmp files by: ' rm -r *;' => comment='Remove tmp files by: ' rm -r *;''
--- ## Would this be enough to battle the issue? Add this before the sed -i command:
new_comment=$(
    sed \
    -e "s/'/'\"'\"'/g" \
    -e 's/[&\\/]/\\&/g; s/$/\\/; $s/\\$//'<<< "$new_comment"
)
For bash: 1) Replace ' with '"'"'. For sed: 1) Escape &, \, / and line-terminators. or what would be the faults? ---- Ideally this would not be done at all but curious to know. ### *Side comment:* Another solution, *to keep it in one file*, could be to add an exit in the script and add the text after that, then use sed or the like to print it. But that is beside my question.
#!/bin/bash

code
code
code

# When in need of the comment:
sed -n '/^exit # EOF Script$/$ {/start_xyz/,/end_xyz/ ...}'
# or what ever. Could even record offset and byte-length safely

code
code

exit # EOF Script

start_xyz
Blah blah blah
blaah
end_xyz
And thinking of it I guess something in the realm of:
comment=<<<'SOF'
...
SOF
Where one only need to replace any SOF to not end prematurely. Still my question is the*sanitizing* above. Thanks.
Asked by Err488 (25 rep)
Jun 26, 2023, 06:59 PM
Last activity: Jun 27, 2023, 06:02 AM