You are not logged in.

#1 2009-02-27 13:00:51

Bralkein
Member
Registered: 2004-10-26
Posts: 354

Avoiding symlink attacks in shell scripts

Hi,

I'm doing a CS course at University and in one of my modules I have to do some shell scripting. For one of the first assignments I have to write a shell script that swaps the contents of two files by moving one to a new temporary location and then swapping them over. I completed this task without any problems, but I had an interesting thought about manipulating files in shell scripts. It seems that it is very common to test to see if a file exists with [ -e filename ] and then proceed on the information gained. However, as every good programmer knows this method is possibly susceptible to at best an annoying bug and at worst a symlink attack, because the operation is not atomic and the file could be created, destroyed, changed to a symlink etc. in between the test and the operation based on that test.

Now I know this is probably overkill for my lame university assignment, but I thought it would be fun to try and find a safe way to do this smile

In my case, since I am moving to a temporary file I thought it would be good to use the -n option on cp or mv to avoid clobbering the target. Unfortunately, cp/mv still return 0 if the transaction fails due to exisiting file so it takes a bit more work. If you use the -v argument then the utility will print one line of output per file copied/moved, so one solution would be

cp -nv source dest | wc | awk '{print $1}'

which would be 0 if the destination already exists or 1 if one file copied successfully.

Obviously that's a bit long-winded though. Has anyone got a cooler way to do it?

Offline

#2 2009-02-27 13:12:17

Dieter@be
Forum Fellow
From: Belgium
Registered: 2006-11-05
Posts: 2,001
Website

Re: Avoiding symlink attacks in shell scripts

sure you can have race conditions, that's why you should also check if the copy/move/.. completed successfully.

As for the symlink/move different file/.. "attack".  this is just a matter of security (eg permissions/ACL's). if you don't want people to mess/put/move/... files you should just use appropriate acl's.


< Daenyth> and he works prolifically
4 8 15 16 23 42

Offline

#3 2009-02-27 13:24:42

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Avoiding symlink attacks in shell scripts

-n is non-standard. I don't have it.

If you use an alternative like yes n | cp -i, that script won't work.

Offline

#4 2009-02-27 14:53:10

Bralkein
Member
Registered: 2004-10-26
Posts: 354

Re: Avoiding symlink attacks in shell scripts

Hmmm I've confused myself now, time to do some reading!

Last edited by Bralkein (2009-02-27 15:10:37)

Offline

Board footer

Powered by FluxBB