Tuesday, December 04, 2007

Tech: Using Curl to Generate a Pubcookie for Programatic SSO Access

A pubcookie login server is a handy way to create SSO authorization accross internal resources deployed to many different application servers. However, this may create a challenge for programatic access to these same resources. Rather than attempting to hunt down and re-use the auth cookie out of your browser cookie cache, curl's cookie engine may be a better automated solution. Pubcookie's behavior is detailed at: http://www.pubcookie.org/docs/how-pubcookie-works.html . The simple script below will provide you with a re-usable token for programatic access to pubcookie protected resources.



#!/bin/bash



###########################################
# getPubcookie
# v2 - robaker
# Fetches a web resource from a server
# that is pubcookie-enabled and stores the
# SSO token locally for future requests
# as long as the token remains valid.
#
# Usage: getPubcookie [App URL ]
#
# App URL must be a pubcookie-enabled
# server. Before initial use, USERNAME
# and PASSWORD need to be changed to
# your own login credentials. As such,
# this file should retain 700 unix
# permission leveling and should not be
# stored on a system with shared-level
# administrative access
###########################################


APPURL=$1
LOGINURL='https://login.com'
USERNAME='yourUsername'
PASSWORD='yourPassword'
PROGRAM_NAME=${0##*/}

usage()
{
echo "usage: ${PROGRAM_NAME} [App URL]"
echo "e.g: ${PROGRAM_NAME} https://wiki.com/wiki/User:Robaker"
exit 2
}

[ $# -ge 1 ] || \
usage

if [ -f pubcookie_s ]; then
# Verify session remains valid
curl -k -b pubcookie_s -s $LOGINURL | grep "You are still logged in" > /dev/null 2>&1;
if [ $? -eq 0 ]; then
# Session is valid, fetch the App URL
curl -k -b pubcookie_s $APPURL;
exit;
fi
fi
# Request pre-session and granting request cookies from pubcookie auth-controlled App Server
curl -k -c pubcookie_pre_s -s -o /dev/null $APPURL
# Parse login form hidden fields... Admittedly a bit hacky
opts=`curl -k -b pubcookie_pre_s -s -c pubcookie_l $LOGINURL | grep hidden | grep -v "<\!--" | sed -e 's/^.*name=\"//' -e 's/\" value/ /' -e 's/ //' -e 's/>//' -e 's/\"//g' | tr '\n' '&'`
# Append login credentials
opts=$opts"user=${USERNAME}&pass=${PASSWORD}"
# Send POST request to the Login Server to get granting cookie
curl -k -b pubcookie_l -c pubcookie_g -d "$opts" -s -o /dev/null $LOGINURL
# Re-request initial App URL and establish valid session
curl -k -b pubcookie_g -c pubcookie_s -L $APPURL
# Remove temporary cookie files
rm pubcookie_pre_s pubcookie_l pubcookie_g
exit;