On 04/04/2013 07:34 AM, Greg Wooledge wrote: > # Sanitize user before feeding it to eval. > # You must adjust this code based on what characters are legal in your > # system's usernames. If your system allows shell metacharacters in > # usernames, you are screwed. Just give up now (switch to perl). > user=${user#\~} > user2=${user//[^[:alnum:]._-]/}
Even if your system allows shell metacharacters in usernames, tilde expansion does not. Remember, to express a shell metacharacter on the command line, you HAVE to use quoting; and once there is anything quoted between the ~ and /, that word is no longer subject to tilde expansion. Don't error out, just echo the string back as-is (the correct tilde expansion of any shell metacharacter is no expansion at all, regardless of whether the system allows for a username containing a shell metacharacter). > if [[ $user != "$user2" ]]; then > echo "Error: invalid characters in username" >&2 > exit 1 > fi > eval "home=~$user2" > case $1 in > */* ) printf '%s\n' "$home/$path" ;; > * ) printf '%s\n' "$home" ;; > esac ;; > * ) > printf '%s\n' "$1" ;; > esac > > As I said on the other list, this code must be adjusted based on your > local system's definition of what constitutes a valid username. Not > all valid usernames can be accomodated by this approach -- particularly, > user accounts with dollar signs in them are NOT going to be manageable > without a second pass to escape those. Systems that allow usernames with a $ are still not going to be able to tilde-expand such user names, ever. A second pass to escape them won't help you, because the escaped form WON'T be tilde-expanded during the eval. For example: $ echo ~eblake /home/eblake $ echo ~eblak\e ~eblake > > If you need more flexibility than this provides, consider switching to > some other language that has support for calling getpwnam() directly. > > (There was also some ambiguity in the stated goals in the request that > appeared on the other mailing list. The code presented here was written > under the interpretation that the input should be tilde-expanded in the > same way that bash performs tilde expansions, and that it was safe to > ignore tilde expansions in inputs of the form "hostname:~username/pathname" > and "variable=~username/pathname".) But those more complex problems should still be solvable (as an exercise for the reader); it is possible to dissect a string after : or = to determine if tilde expansion would occur on a ~ occuring next. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature