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
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?

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.

Similar Messages

  • How to avoid password prompt in shell script for zip password protection

    Hi
    I am trying to set password protection to my oracle database export backup. Once the backup completed, it should compress with a password protection. Thats the plan. Initialy we were using the gzip for the compression. Then realized that there is no password protection for the gzip. Started using zip option. I tried using
    zip -P <password> filename
    But it was throwing below error.
    -bash-3.2$ zip -P expreports REPORTS_2013FEB14.dmp
    zip warning: missing end signature--probably not a zip file (did you
    zip warning: remember to use binary mode when you transferred it?)
    zip warning: (if you are trying to read a damaged archive try -F)
    zip error: Zip file structure invalid (REPORTS_2013FEB14.dmp)
    Not quite sure why.
    Then I used zip -e REPORTS_2013FEB14.dmp.zip REPORTS_2013FEB14.dmp
    But this prompting for the password. As I am trying to put the command in the script. It will be tough if it prompts for the password.
    I would like to know how to avoid the password prompting by saving somewhere or how the code should be written. Tried using expect feature of shell script. Below was the code I tried. It didnt work.
    [oracle@SF40V6636 test]$ cat repexp.sh
    zip -e REPORTS_imp.log.zip REPORTS_imp.log
    expect "Enter password:"
    send "imprep"
    expect "Verify password:"
    send "imprep"
    So please help in avoiding this password prompt or let me know how to change the code.
    Thanks
    SHIYAS M

    How about using gpg and adding a secret key to the requirement of a password? No one should be able to decrypt your file, not by knowing only the password.
    1. Generate a public and private key pair:
    $ gpg --gen-key
    When it shows "We need to generate a lot of random bytes…" open another terminal session and type "dd if=/dev/sda of=/dev/null" to create traffic. When the public and secret key created and signed you can Ctrl-C the dd command.
    To see what you have created:
    $ gpg --list-keys
    2. Encrypt and gzip your stuff:
    $ tar zcf stuff.tgz file_or_folder
    $ gpg recipient "Some Name" encrypt stuff.tgz
    $ rm -f stuff.tgz
    3. Decrypt and extract the archive:
    $ gpg batch yes --passphrase "password" -d stuff.tgz.gpg > stuff.tgz
    $ tar zxvf stuff.tgz
    Again, knowing the password alone will not let anybody decrypt your stuff.

  • Shell script for RMAN backup

    Hi,
    on 10G R2 in AIX 6.1
    I'm looking for Shell script for RMAN backup.
    Moreover , if we should connect like this :
    rman nocatalog target sys/password@myDB << EOF
    backup as compressed backupset format '$savdir/ctl_%d_%T_%s_%p' current controlfile;
    exit
    EOFHow to avoid writting password in shell script ?
    Thank you.

    user522961 wrote:
    Can you please tell me in case of having a catalog , how to connect to catalog without writting password in script ? I mean , how to write the following in a way without password :
    #!/usr/bin/ksh
    export ORACLE_SID=myDB
    ORACLE_ENV_ASK=NO
    . /usr/local/bin/oraenv
    export savedir=/backups/myDB
    rman target /  << EOF
    connect catalog rman/password@myrepository
    backup as compressed backupset
        format '$savdir/ctl_%d_%T_%s_%p'
        include current controlfile;
    exit
    EOF:p

  • Shell script called from .sql fie in oracle concurrent manager

    Hi
    I am running a request set through Oracle concurrent manager.
    The manager calls a .sql file. The sql file internally calls a unix shell script.
    v_body VARCHAR2(10000);
    v_body is set as followed in the sql program.
    v_body := 'ATTENTION :' || CHR(10) || CHR(10) ||
    'Your invoice number ' || r_error_rec.invoice_num || ' cannot be paid at present due ' ||
              'to one of the following reasons:' || CHR(10) || CHR(10) ||
              ' - The Purchase Order number quoted on the invoice is invalid ' || CHR(10) ||
              ' - The Purchase Order number has not been quoted at all on the invoice' || CHR(10) ||
              ' - The Purchase Order number is missing on one or more of the lines on the invoice' ||
              CHR(10) || CHR(10) ||
              'To avoid any further payment delays, please advise us of the correct Purchase ' ||
              'Order number(s) by emailing ' || r_error_rec.sender || '. Please note that it is not ' ||
              'necessary to re-submit the invoice.' || CHR(10) || CHR(10) ||
              'If you do not know the Purchase Order number, please contact the employee ' ||
              'who ordered your goods/services for this number. For future reference please note that ' ||
              'it is the responsibility of the vendor to ensure that an approved Purchase Order ' ||
              'number is received before supplying goods/services to . The purchase order is ' ||
              'evidence that the order has been approved by management.' || CHR(10) || CHR(10) ||
              'This invoice will be held as pending until the valid Purchase Order number can be provided.' || CHR(10) || CHR(10) ||
              'Thank you,' || CHR(10) || CHR(10) || ' Accounts Payable' || CHR(10);
    The sql now calls a unix shell script as shown below.
              l_request_id := fnd_request.submit_request (
                                            'CFI',                                   'CFIECAPEMLSH',                         NULL,                              NULL,                              FALSE,                              r_error_rec.sender,                          v_recipient,                              v_ccrecipient,                          v_bccrecipient,                          v_subject,                                   v_body,                                   v_attachment     
    So here the problem i am facing is that the shell script is not getting called.
    If i keep v_body= 'Test' the shell script is called and program is working fine.
    Is it a problem with CHR(10) or the size limitation of v_body i dont know.
    I tried to keep v_body VARCHAR2(10000).
    Still it did not work.
    Plz help me if u know about this.

    You cannot have varchar2 > 4000.

  • Encrypting password in shell script on Solaris 10.

    Hi,
    I have a shell script & in that the username & password is specified. I can see the password. Is there any way to encrpyt password in Unix scripts on solaris 10 box.
    Please suggest.
    Thanks & Regards,
    Tejas

    Here are some examples of avoiding passwords in scripts.
    First, if it's a script that needs to use remote login, you could set up ssh keys in the authorized_keys file of the remote system to allow auto-authentication.
    As a more general example, you could create a shell function that prompts for the password and stores it in an environment variable to be used by the script or utility that you want to use. Here is an example that we use in our Red Hat systems to allow yum to tunnel through our http proxy:
    function yumproxy(){
        echo -n "Enter Proxy Username: "
        read -e username
        echo -n "Enter Proxy Password: "
        read -es password
        echo
        export http_proxy="http://$username:$password@ourproxyserver:8080/"
    }This is in .bashrc so that we can run it once just before running any yum commands (not that this means anything in a Solaris forum!)

  • Add Password to Shell Script for ssh

    Hi I'm trying to avoid creating ssh keys for this I was hoping to write it all in to applescript.
    This is what I have.
    I've done lots of searches, but not quite getting the right outcome.
    Matt
    set ShellS to "rsync -aE --progress --delete --exclude=\"._*\" /Volumes/Images/2014-2015 [email protected]:/Volumes/ImagesB/ "
    do shell script ShellS

    Thanks, that did help, I wondered what all those extra files were,
    Now searching the net this is where I am at., But I get the error
    error "invalid command name \"rsync\"
        while executing
    \"rsync -a --progress --delete --exclude=\"._*\" -e ssh /Volumes/Images/2014-2015 [email protected]:/Volumes/ImagesB/ \"" number 1
    set sshPasswd to "PSW"
    set ShellS to "rsync -a --progress --delete --exclude=\"._*\" -e ssh /Volumes/Images/2014-2015 [email protected]:/Volumes/ImagesB/
    expect {
      \"Password:\" {
          send \"" & sshPasswd & "\\r\"
          exp_continue
        \"yes/no?\" {
          send \"yes\\r\"
          exp_continue
    do shell script "expect <<<" & quoted form of ShellS

  • Echo colored text in a shell script?

    As part of a shell script I'm working on, I want to be able to print colored (preferably red) text to the Terminal window, to provide warnings to the user.
    How can I code in echoing colored text?
    (I did some googling and couldn't find anything that seemed to apply to what I want to do.)
    Any help would be appreciated!
    Thanks in advance!

    The following is a shell script that displays the terminal colors and the escape sequences used to generate them:
    #!/bin/sh
    # colors.esc - display the terminal colors and the escape sequences that
    # generate them. "Blink" is _NOT_ shown, as it is a very
    # annoying effect, and should be avoided at all costs in normal
    # daily uses.
    # Usage: colors.esc [12 character or less display string]
    # Bob Harris
    E=$(printf ' ') # escape <E>
    R="${E}[0m" # reset <E>[0m
    typeset dsp_str=""
    typeset dsp_txt
    typeset fg_text
    typeset bg_text
    if [[ $# != 0 ]]; then
    dsp_str=$(printf "%12.12s" "$*")
    fi
    color=(Black Red Green Yellow Blue Magenta Cyan White)
    for bg in "" 0 1 2 3 4 5 6 7 # for each background color
    do
    b=$bg && [[ X$b != X ]] && b="4$b;" # deal with no background color ""
    echo " ------------ ----bold---- -underline-- --reverse---"
    for fg in 0 1 2 3 4 5 6 7 # for each foreground color
    do
    f="3$fg" # setup foreground color
    line=""
    for a in "" 1 4 7 # for each attribute
    do
    [[ X$a != X ]] && a=";$a" # deal with no attribute ""
    if [[ -z "$dsp_str" ]]; then
    dsp_txt=$(printf "%12s" "<E>[${b}${f}${a}m") # build esc text
    else
    dsp_txt="$dsp_str" # use supplied text
    fi
    line="${line}${E}[${b}${f}${a}m${dsp_txt}${R} " # build entry
    done
    fg_text=$(printf "%-7s" ${color[$fg]}) # translate foreground color
    bg_text=$(printf "%-9s" "Bg${color[$bg]}") # translate background color
    [[ X$b = X ]] && bg_text=$(printf "%-9s" " ") # no bckgnd color
    line="$bg_text $fg_text $line" # build final display line
    echo "${line% }" # display the colorized line
    done
    done
    echo " ------------ ----bold---- -underline-- --reverse---"
    bg_text=$(printf "%-9s" " ")
    fg_text=$(printf "%-7s" "Reset")
    dsp_txt=$(printf "%12s" "<E>[0m")
    line="$bg_text $fg_text $dsp_txt" # build final display line
    echo "${line% }"

  • Shell Script Authentication

    How do you make like a dialogue box appear when I am using sudo scripts?

    It might be helpful if you could provide a bit more detail about the goal. Your original question asked about an actual password dialogue, but if there is someone there to enter an "admin" password, why can't they use the "Accounts" pref pane? For example, I could see this being the case if the current account was "managed" with access to secure pref panes restricted, but a few posts later, your example of 'sudo passwd admin' implies that it is an "admin" account's password that is to be changed. But why would an "admin" want to change their password from a "managed" account... Without knowing what exactly the goal is, it is difficult to provide meaningful suggestions.
    But speaking more generally, changing 'do shell script "sudo ..."' to 'tell application "Terminal" to do script "sudo ..."' should cause a "Terminal" window to open, with a password prompt in a command line interface.
    Alternatively, rather than using 'sudo' in "do shell script" statements, it is possible to use "with administrator privileges" to avoid the need for the interactive password (and don't combine 'sudo' with "with administrative privileges" because it is apparently insecure).
    http://developer.apple.com/technotes/tn2002/tn2065.html
    To incorporate a password dialog into a "do shell script ... with administrative privileges" statement, you could use Tiger's new "hidden answer" option in the standard "display dialog" statement. While this does obscure the password, I don't think it is particularly secure either.
    Finally, 'passwd' also requires an interactive password, whereas 'dscl' doesn't with some options, (nor does 'pwpolicy' but that won't work unless password policy options are enabled), so 'dscl' might be more suitable in a script. However, options where the password is provided in the command are also less secure since theoretically the password could be viewed in plain text by someone running 'ps' at the right time...

  • Directory for shell scripts

    I'm looking for a logical place to save Unix shell scripts. ~/Documents doesn't sound right, nor would ~/bin because the scripts aren't binaries. I know it comes down to personal preference, but what makes the most sense, ~/Library/Scripts? and /Library/Scripts for all users?

    I've been using Unix since '85, and here is what I do:
    ~/local/bin # for my personal scripts and executables
    /usr/local/bin # for my shared scripts and executables
    And I also create a symlink ~/bin that points to ~/local/bin
    cd ~
    ln -s local/bin bin
    Many open source applications are stored by default in /usr/local/bin, but from time to time, I'm on a Unix system I do not own, and I want to install a personal open source program, so I use
    ./configure --prefix=$HOME/local
    which will configure the open source software so it is setup to store things in my home directory, including any support files, man files etc... associated with the program. For example a personal copy of Vim.

  • Dbbackup shell script error

    hi frnds
    i need a help,i want to use a shell script to shutdown the database if the database is not shutdown properly using shutdown immediate.If shutdown immediate hangs it should check whther the database is up then call another script contains shutdown abort and startup and shutdown.
    The problem is it is not go to the next line when the shutdown immediate hangs.I am giving my script how can i fix this
    with regards
    ramya
    ORACLE_SID=CDRD; export ORACLE_SID
    ALERT=/tmp/dbalert
    dbstop.sh
    sleep 300
    ps -ef | grep ora_smon_$ORACLE_SID >$ALERT
    if test -s $ALERT
    then
    dbabort.sh
    sun7start.sh
    sun7stop.sh
    echo "Database Down"
    else
    echo "Database DOwn"
    fi

    I suppose that when you say "shutdown immediate hangs" you mean that it hangs indefinitely. Shutdown immediate could take a long time to complete for some reason (e.g. SMON has to clean up extents which are no longer needed and mark them as freed).
    I don't know a way to exit from an (indefinitely) hanging process, unless you kill it from another session.
    Maybe shutdown abort is not the most advisable way to go normally, but sometimes you can't avoid it, and personally I've never had problem with it (maybe I'm lucky :-)).

  • Help needed in shell script for FTPS

    Hi,
    Im trying to build a script to download files from a secure FTP site.
    When I run the command ftps <host_address> in the unix prompt, it asks username and password, and then prompts the following question.
    Do you want to trust this certificate? y(y):
    From the prompt, I am able to type 'y' and then it is connecting to the FTP site without any issue.
    When i run the shell script which contains the same command ftps <host_address>, it prompts the same question. And then it comes out of the program saying 'Connection aborted'.
    Could anyone tell me how to avoid this prompt?
    Thanks,
    Vidhya

    Ya. It worked for me when i typed the command ftps <host_address> in the command prompt.
    When I type this command, it is asking for username,pwd and after that, it is asking 'Do you want to trust this certificate?'. For this i have typed 'y' (Yes) in the command prompt.
    After i entered 'y', the connection got established properly.
    I have included this command in a shell script, and ran this script.
    When i execute the script, i asks 'Do you want to trust this certificate?'.
    Since i will not be able to type 'y'(Yes) connection is getting aborted.
    So, I want to know how to avoid this question ot how to enter 'y' while executing the script.
    Thanks

  • Cd not changing directory in shell script

    This shell script executes correctly, but... not correctly:
    #!/bin/bash
    cd /var/www/vhosts/mydomain.com/httpdocs
    pwd
    Output is:
    /var/www/vhosts/mydomain.com/httpdocs
    [root bin]#
    However, when I immediately type "pwd", it returns
    /usr/bin
    How can pwd in the script return a path different from the path I am in?

    [Running a script launches a subshell|http://tldp.org/LDP/abs/html/subshells.html], and the subshell does change the default, and that default promptly evaporates when the subshell exits.
    You can invoke the script as dot-space-scriptname or as +source script+ to avoid the subshell.
    . ~/script
    source ~/script
    Or you can switch tactics and use a bash function:
    function cdhttpdocs() {
    cd /var/www/vhosts/mydomain.com/httpdocs
    The easiest for this case is probably something akin to an alias:
    alias cdhttpdocs="cd /var/www/vhosts/mydomain.com/httpdocs"

  • Shell script blog -OR- Give me tips on how to write better scripts!

    Hi folks,
    I don't write a lot of shell scripts, and the ones that I do write are usually quite short, so as a learning exercise I made a shell/CGI blog script.. And I was hoping that some of the shell scripting experts in the community could give me some pointers on form, style, etc! The script works just fine, but maybe I haven't coded it very elegantly. Or maybe in some places I haven't necessarily used the right (or most appropriate?) commands to accomplish what I want.
    It's a simple blog. It can either:
    - Display a blog post (by default the newest, unless the name of a post is given)
    - Display a listing of posts for a certain tag
    Posts are saved in normal files in markdown format. Tagging is accomplished by putting the name of the tag(s) into the filename, separated by hyphens. For example: the file "wonderful_blog_post-whining-computers-archlinux.md" would be a post named "wonderful blog post", and it would have three tags ("whining", "computers", "archlinux"). Maybe it's not the best idea in the world... but I went with it anyhow
    I put the script on pastebin for you all to see: http://pastebin.com/L8nMpUjT
    Please do take a look and let me know if I've done something badly! Hopefully I can learn a thing or two from your comments.
    And there's a working example of it here: http://www.ynnhoj.net/thedump/s.cgi

    falconindy wrote:
    To sort files by modification time (safely) requires GNU stat and some bash:
    declare -a files
    while IFS=$'\t' read -r -d '' ts file; do
    files+=("$file")
    done < <(stat --printf '%Y\t%n\0' * | sort -zn)
    printf "%s\n" "${files[@]}"
    The array is of course unnecessary as you could print inside the loop, but I see no way around the usage of null delimiters and bashisms (read's -d flag in particular) to be 100% safe.
    Thanks for the example, though I'm trying to avoid bash and write my script in posix shell. So after some tinkering, this is what I've come up with to make a simple list of blog post file names:
    #!/bin/sh
    cd posts
    while IFS=$'\t' read -r ts file; do
    ALLPOSTS="$ALLPOSTS $file"
    done << EOF
    $(stat --printf '%Y\t%n\n' *.md | sort -rn)
    EOF
    echo $ALLPOSTS
    So I suppose that it isn't 100% safe - but could it be acceptable? Is there anything else I could do?
    Edit: as it turns out, my server is running some flavour of BSD, I think FreeBSD. So the above examples don't work with FreeBSD's stat. Ah well..
    Last edited by upsidaisium (2011-02-23 08:26:29)

  • Calling shell script from stored procedure.

    Hi Everybody,
    Could anyone tell me how to call a shell script from a stored procedure.
    Thanks,
    Vasu

    You would need to write a Java stored procedure that calls out to the underlying operating system. Tom Kyte has an example of this here
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:952229840241
    Make sure that you're very aware of the security implications here, however. Your commands will run as the Oracle user on the host operating system, which makes it possible that a coding error and/or an attacker could do something like delete or corrupt Oracle data files, so you'll probably want to harden the code substantially.
    Justin

  • Mxmlc shell script update

    Hey, first time playing around with flex i stumbled over a hickup in the mxmlc shell script undex linux.
    I could not symlink to the mxmlc script to simplify setting up multiple versions/environment.
    The flex SDK I am using is 3.4.1 build 10084.
    I modified the shell script to lookup the java binary using JAVA_HOME instead of relying on PATH, and setup the automatic path resolution to resolve absolute url's using readlink.
    I also decided to use exec to make sure that file descriptors and signals where directly passed to the executed java process.
    I am sure that it isn't perfect, there might be some issues about finding JAVA_BIN under cygwin, but I sure would like to se symlinks resolved properly upstream.
    Hope this is useful!

    Just encountered a problem, the first readlink must be: 'readlink -f $path' in unices, since readlink (only) just gives you the symbolic link, which would be relative to the actual file.
    Fix attached here.

Maybe you are looking for

  • Firefox will not start on homepage. Always starts on last tab(s) open.

    This problem has persisted since version 16. Settings in options are correct. I have tried changing different options and my settings file does save the new settings. I run a current version of Norton 360 and have used a separate malware detector Mic

  • Panorama and Windows 8.1

    Why does panorama no longer function with Windows 8.1

  • SQL Query Data Model Question

    Hi All, I'm new to XMLPublisher so i'll try to explain the best i can the problem i'm having creating a Data Model for my report. I'm using Database XE and have installed XMLPublisher, as XE is extremely flexible in creating apps i'm having huge trou

  • DBAdapter Polling service timing out.

    I have created a composite application which is polling data (sync operation for in order delivery) from a table then making an asynchronous call to another webservice. The other async service can take upto 5 minutes based on the long running BPEL pr

  • How do you remove single click delete from mail?

    I accidentally delete emails when cleaning out my inbox and was wondering if there is anyway to remove this single click delete function. I remember setting up mail and being asked if I wanted to remove the warning popup. Anyone know how to add this