import commands
import urllib

# Get a file-like object for the crl, this is a URL for the CRL
f = urllib.urlopen("http://devca.wijis.state.wi.us/certenroll/devca.wijis.state.wi.us.crl")

# Read from the object, storing the page's contents in 's'.
s = f.read()
f.close()
	
#Write the CRL in DER format to a file	 
outFile = open('./tempCerts/crlDER.crl', 'w')
outFile.write(s)
outFile.close()

#Convert the CRL using openssl to a PEM file
commands.getoutput('openssl crl -in ./tempCerts/crlDER.crl -out ./tempCerts/crlPEM.crl -inform DER ')	
	
#Store the root and intermediary of the server cert in a file
#called yourChain.cer, here it is WijisChain.cer
#Copy your CRL and your chair to tempCertChain.cer	 
outFile = open('./tempCerts/tempCertChain.cer', 'w')
outFilePermCer = open('./tempCerts/WijisChain.cer', 'r')	
outFileCRL = open('./tempCerts/crlPEM.crl', 'r')	

outFile.write(outFilePermCer.read())
outFile.write(outFileCRL.read())	
outFile.close()
outFilePermCer.close()
outFileCRL.close()	
	 
#Now actually get the server cert, dont know if this work on windows
#You must pass in your client cert and private key
#enter server port
bigString =  commands.getoutput('echo | openssl s_client -connect SERVER:PORT  -key myserver.key  -cert Yogesh02.cer')
	
#Get the server cert out by parsing the output of the above openSSL command
blockBegin = '-----BEGIN CERTIFICATE-----'
blockEnd = '-----END CERTIFICATE-----'

beginOuter = bigString.find(blockBegin) 
if beginOuter < 0:
	print 'Unable to continue: block begin string not found'
	
	
beginInner = beginOuter + len(blockBegin)

endInner = bigString.find(blockEnd)
if endInner < 0:
	print 'Unable to continue: block end string not found'
	
	
endOuter = endInner + len(blockEnd)

blockWithDelims = bigString[beginOuter:endOuter]
blockWithoutDelims = bigString[beginInner:endInner]

#Write the server cert to a file
outFile = open('./tempCerts/server.cer', 'w')
outFile.write(blockWithDelims)
outFile.write('\n')

outFile.close()	

#Verify the server cert and check it against the CRL as well
statusOutput = commands.getstatusoutput('openssl verify  -CAfile ./tempCerts/tempCertChain.cer -purpose sslserver -crl_check  ./tempCerts/server.cer')

#Look at the output and cry or rejoice, drink beer here/repeat
print statusOutput
