def pam_conv(auth,query_list,userdata):
	resp = []

	for i in range(len(query_list)):
		query, type = query_list[i]
		if type == PAM.PAM_PROMPT_ECHO_ON:
			val = raw_input(query)
			resp.append((val,0))
		elif type == PAM.PAM_PROMPT_ECHO_OFF:
			challenge = os.urandom(20)
			sha1 = SHA.new(challenge)
			sha1.update(challenge)
			digest = sha1.digest()
			print "PYTHON digest: %s" % digest
			print "PYTHON Encoded digest: %s" % base64.b64encode(digest)
			cc = ccHandler()
			cc.openSession()
			signed = cc.sign(challenge)
			val = base64.b64encode(digest)+'-'+signed

			resp.append((val,0))
		elif type == PAM.PAM_PROMPT_ERROR_MSG or type == PAM.PAM_PROMPT_TEXT_INFO:
			print query
			resp.append(('', 0))
		else:
			return None

	return resp
def loginCC():
	print "Trying to login using your citizen card\n"
	cc = ccHandler()
	err = cc.openSession()
	if not err:
		print 'Unavailable to login by Smartcard, please use your credentials \n'
		return loginPw()
	
	print 'Validating your citizen card'
	if not cc.certificate_chain_verify():
		print 'Your Smartcard certificate could not be verified, please user your credentials \n'
		return loginPw()
	print 'Citizen card validated\n'

	s = requests.Session()
	#prompt = '> '
	#print "What's your username?"
	print 'Getting your cardholder ID\n'
	userid = cc.bi()#raw_input(prompt1)
	resp = s.post('http://localhost:8080/auth/loginCC',headers={'userid':userid})
	if resp.headers['error'] != 'OK':
		return resp.headers['error']
	username = resp.headers['username']
	#print "CLIENT: B64 RECEIVED SEQUENCE %s" % resp.headers['challenge']
	#print "CLIENT: DECODED SEQUENCE %s" % base64.b64decode(resp.headers['challenge'])

	return sendChallenge(username,base64.b64decode(resp.headers['challenge']),cc)
from ccModule import ccHandler
a=ccHandler()
a.openSession()
#a.sign()
#a.verify()
a.certificate_chain_verify()
"""
Verify CRL
"""
#a.revoked_certifications(r'X509v3 CRL Distribution Points:\s+Full Name:\s+URI:([^\s]+)')
"""
Verify Delta CRL
"""
#a.revoked_certifications(r'X509v3 Freshest CRL:\s+Full Name:\s+URI:([^\s]+)')
#print str(result)
#print a.bi()
#print str(a.mx)
#print str(a.ex)
def createPbox():
	prompt = '> '
	s = requests.Session()

	print "To create a Safebox account, make sure you have your citizen card connected to your computer.\nThis can be used later as an authentication method for your Safebox account\n"
	raw_input('Press any key to continue\n')

	a=ccHandler()
	err = a.openSession()
	if not err:
		return 'Smartcard unavailable\n'
		
	"""
	Get from CC
	Modulus, exponent and BI
	"""
	a.sign('1234567890')
	a.verify()
	
	bi = a.bi()
	s.headers = {'userid': bi}
	res = s.post('http://localhost:8080/existingcc')
	if res.headers['existingcc'] == 	'1':
		return 'An account associated with this Citizen Card already exists, you cannot create another one'

	print 'Validating your citizen card'
	if not a.certificate_chain_verify():
		print 'Your Smartcard certificate could not be verified, please user your credentials \n'

	print 'Citizen card validated\n'

	mx = a.mx
	ex = a.ex

	#print "\n\nbi:" + bi
	#print "\n\nmx:" + mx
	#print "\n\nex:" + ex

	print "Username?"
	username = raw_input(prompt)
	s.headers = {'username': username}
	res = s.post('http://localhost:8080/existinguser')
	if res.headers['existinguser'] == 	'1':
		return 'Username has been taken, please choose another one'

	print "Password?"
	while 1:
		os.system("stty -echo")
		password = raw_input(prompt)
		os.system("stty echo")
		if(len(password) < 6):
			print 'Password too short'
		else:
			break
	#TODO validar forca da password

	# Public and Private key - RSA
	rsa = RSA.generate(2048)
	priv = open('private.pem','w')
	priv.write(rsa.exportKey('PEM'))

	pubkey = rsa.publickey().exportKey('PEM').encode('hex')
	
	hashedpw = bcrypt.hashpw(password,bcrypt.gensalt())

	s.headers = {'username': username, 'pwd':hashedpw.encode('hex'), 'pubkey':pubkey, 'bi': bi, 'mx': mx, 'ex' : ex}
	res = s.post('http://localhost:8080/createPbox')
	result = res.headers['result']

	if result == '0': 
	    return 'Registration failed!'
	else:
	    print '\nHi ' + username + '! Welcome to SafeBox! You have created a PBox successfully! ' # (ID: ' + pbox_id + ')'