gluu
公開メンバ関数 | 公開変数類 | 全メンバ一覧
UserCertExternalAuthenticator.PersonAuthentication クラス
UserCertExternalAuthenticator.PersonAuthentication の継承関係図
Inheritance graph
UserCertExternalAuthenticator.PersonAuthentication 連携図
Collaboration graph

公開メンバ関数

def __init__ (self, currentTimeMillis)
 
def init (self, configurationAttributes)
 
def destroy (self, configurationAttributes)
 
def getApiVersion (self)
 
def isValidAuthenticationMethod (self, usageType, configurationAttributes)
 
def getAlternativeAuthenticationMethod (self, usageType, configurationAttributes)
 
def authenticate (self, configurationAttributes, requestParameters, step)
 
def prepareForStep (self, configurationAttributes, requestParameters, step)
 
def getExtraParametersForStep (self, configurationAttributes, step)
 
def getCountAuthenticationSteps (self, configurationAttributes)
 
def getPageForStep (self, configurationAttributes, step)
 
def logout (self, configurationAttributes, requestParameters)
 
def processBasicAuthentication (self, credentials)
 
def getSessionAttribute (self, attribute_name)
 
def calculateCertificateFingerprint (self, x509Certificate)
 
def validateCertificate (self, x509Certificate)
 
def certToString (self, x509Certificate)
 
def certFromString (self, x509CertificateEncoded)
 
def certFromPemString (self, pemCertificate)
 
def initRecaptcha (self, configurationAttributes)
 
def validateRecaptcha (self, recaptcha_response)
 

公開変数類

 currentTimeMillis
 
 chain_certs
 
 validator_types
 
 validators
 
 map_user_cert
 
 enabled_recaptcha
 
 recaptcha_creds
 

詳解

構築子と解体子

◆ __init__()

def UserCertExternalAuthenticator.PersonAuthentication.__init__ (   self,
  currentTimeMillis 
)
32  def __init__(self, currentTimeMillis):
33  self.currentTimeMillis = currentTimeMillis
34 

関数詳解

◆ authenticate()

def UserCertExternalAuthenticator.PersonAuthentication.authenticate (   self,
  configurationAttributes,
  requestParameters,
  step 
)
104  def authenticate(self, configurationAttributes, requestParameters, step):
105  identity = CdiUtil.bean(Identity)
106  credentials = identity.getCredentials()
107 
108  user_name = credentials.getUsername()
109 
110  userService = CdiUtil.bean(UserService)
111  authenticationService = CdiUtil.bean(AuthenticationService)
112 
113  if step == 1:
114  print "Cert. Authenticate for step 1"
115  login_button = ServerUtil.getFirstValue(requestParameters, "loginForm:loginButton")
116  if StringHelper.isEmpty(login_button):
117  print "Cert. Authenticate for step 1. Form were submitted incorrectly"
118  return False
119  if self.enabled_recaptcha:
120  print "Cert. Authenticate for step 1. Validating recaptcha response"
121  recaptcha_response = ServerUtil.getFirstValue(requestParameters, "g-recaptcha-response")
122 
123  recaptcha_result = self.validateRecaptcha(recaptcha_response)
124  print "Cert. Authenticate for step 1. recaptcha_result: '%s'" % recaptcha_result
125 
126  return recaptcha_result
127 
128  return True
129  elif step == 2:
130  print "Cert. Authenticate for step 2"
131 
132  # Validate if user selected certificate
133  cert_x509 = self.getSessionAttribute("cert_x509")
134  if cert_x509 == None:
135  print "Cert. Authenticate for step 2. User not selected any certs"
136  identity.setWorkingParameter("cert_selected", False)
137 
138  # Return True to inform user how to reset workflow
139  return True
140  else:
141  identity.setWorkingParameter("cert_selected", True)
142  x509Certificate = self.certFromString(cert_x509)
143 
144  subjectX500Principal = x509Certificate.getSubjectX500Principal()
145  print "Cert. Authenticate for step 2. User selected certificate with DN '%s'" % subjectX500Principal
146 
147  # Validate certificates which user selected
148  valid = self.validateCertificate(x509Certificate)
149  if not valid:
150  print "Cert. Authenticate for step 2. Certificate DN '%s' is not valid" % subjectX500Principal
151  identity.setWorkingParameter("cert_valid", False)
152 
153  # Return True to inform user how to reset workflow
154  return True
155 
156  identity.setWorkingParameter("cert_valid", True)
157 
158  # Calculate certificate fingerprint
159  x509CertificateFingerprint = self.calculateCertificateFingerprint(x509Certificate)
160  identity.setWorkingParameter("cert_x509_fingerprint", x509CertificateFingerprint)
161  print "Cert. Authenticate for step 2. Fingerprint is '%s' of certificate with DN '%s'" % (x509CertificateFingerprint, subjectX500Principal)
162 
163  # Attempt to find user by certificate fingerprint
164  cert_user_external_uid = "cert:%s" % x509CertificateFingerprint
165  print "Cert. Authenticate for step 2. Attempting to find user by oxExternalUid attribute value %s" % cert_user_external_uid
166 
167  find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", cert_user_external_uid)
168  if find_user_by_external_uid == None:
169  print "Cert. Authenticate for step 2. Failed to find user"
170 
171  if self.map_user_cert:
172  print "Cert. Authenticate for step 2. Storing cert_user_external_uid for step 3"
173  identity.setWorkingParameter("cert_user_external_uid", cert_user_external_uid)
174  return True
175  else:
176  print "Cert. Authenticate for step 2. Mapping cert to user account is not allowed"
177  identity.setWorkingParameter("cert_count_login_steps", 2)
178  return False
179 
180  foundUserName = find_user_by_external_uid.getUserId()
181  print "Cert. Authenticate for step 2. foundUserName: " + foundUserName
182 
183  logged_in = False
184  userService = CdiUtil.bean(UserService)
185  logged_in = authenticationService.authenticate(foundUserName)
186 
187  print "Cert. Authenticate for step 2. Setting count steps to 2"
188  identity.setWorkingParameter("cert_count_login_steps", 2)
189 
190  return logged_in
191  elif step == 3:
192  print "Cert. Authenticate for step 3"
193 
194  cert_user_external_uid = self.getSessionAttribute("cert_user_external_uid")
195  if cert_user_external_uid == None:
196  print "Cert. Authenticate for step 3. cert_user_external_uid is empty"
197  return False
198 
199  user_password = credentials.getPassword()
200 
201  logged_in = False
202  if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
203  logged_in = authenticationService.authenticate(user_name, user_password)
204 
205  if (not logged_in):
206  return False
207 
208  # Double check just to make sure. We did checking in previous step
209  # Check if there is user which has cert_user_external_uid
210  # Avoid mapping user cert to more than one IDP account
211  find_user_by_external_uid = userService.getUserByAttribute("oxExternalUid", cert_user_external_uid)
212  if find_user_by_external_uid == None:
213  # Add cert_user_external_uid to user's external GUID list
214  find_user_by_external_uid = userService.addUserAttribute(user_name, "oxExternalUid", cert_user_external_uid)
215  if find_user_by_external_uid == None:
216  print "Cert. Authenticate for step 3. Failed to update current user"
217  return False
218 
219  return True
220 
221  return True
222  else:
223  return False
224 

◆ calculateCertificateFingerprint()

def UserCertExternalAuthenticator.PersonAuthentication.calculateCertificateFingerprint (   self,
  x509Certificate 
)
331  def calculateCertificateFingerprint(self, x509Certificate):
332  print "Cert. Calculate fingerprint for certificate DN '%s'" % x509Certificate.getSubjectX500Principal()
333 
334  publicKey = x509Certificate.getPublicKey()
335 
336  # Use oxAuth implementation
337  fingerprint = FingerprintHelper.getPublicKeySshFingerprint(publicKey)
338 
339  return fingerprint
340 

◆ certFromPemString()

def UserCertExternalAuthenticator.PersonAuthentication.certFromPemString (   self,
  pemCertificate 
)
368  def certFromPemString(self, pemCertificate):
369  x509CertificateEncoded = pemCertificate.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").strip()
370  return self.certFromString(x509CertificateEncoded)
371 

◆ certFromString()

def UserCertExternalAuthenticator.PersonAuthentication.certFromString (   self,
  x509CertificateEncoded 
)
364  def certFromString(self, x509CertificateEncoded):
365  x509CertificateDecoded = base64.b64decode(x509CertificateEncoded)
366  return CertUtil.x509CertificateFromBytes(x509CertificateDecoded)
367 

◆ certToString()

def UserCertExternalAuthenticator.PersonAuthentication.certToString (   self,
  x509Certificate 
)
359  def certToString(self, x509Certificate):
360  if x509Certificate == None:
361  return None
362  return base64.b64encode(x509Certificate.getEncoded())
363 

◆ destroy()

def UserCertExternalAuthenticator.PersonAuthentication.destroy (   self,
  configurationAttributes 
)
85  def destroy(self, configurationAttributes):
86  print "Cert. Destroy"
87 
88  for type in self.validator_types:
89  self.validators[type][0].destroy()
90 
91  print "Cert. Destroyed successfully"
92 
93  return True
94 

◆ getAlternativeAuthenticationMethod()

def UserCertExternalAuthenticator.PersonAuthentication.getAlternativeAuthenticationMethod (   self,
  usageType,
  configurationAttributes 
)
101  def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes):
102  return None
103 

◆ getApiVersion()

def UserCertExternalAuthenticator.PersonAuthentication.getApiVersion (   self)
95  def getApiVersion(self):
96  return 1
97 

◆ getCountAuthenticationSteps()

def UserCertExternalAuthenticator.PersonAuthentication.getCountAuthenticationSteps (   self,
  configurationAttributes 
)
261  def getCountAuthenticationSteps(self, configurationAttributes):
262  cert_count_login_steps = self.getSessionAttribute("cert_count_login_steps")
263  if cert_count_login_steps != None:
264  return cert_count_login_steps
265  else:
266  return 3
267 

◆ getExtraParametersForStep()

def UserCertExternalAuthenticator.PersonAuthentication.getExtraParametersForStep (   self,
  configurationAttributes,
  step 
)
258  def getExtraParametersForStep(self, configurationAttributes, step):
259  return Arrays.asList("cert_selected", "cert_valid", "cert_x509", "cert_x509_fingerprint", "cert_count_login_steps", "cert_user_external_uid")
260 

◆ getPageForStep()

def UserCertExternalAuthenticator.PersonAuthentication.getPageForStep (   self,
  configurationAttributes,
  step 
)
268  def getPageForStep(self, configurationAttributes, step):
269  if step == 1:
270  return "/auth/cert/login.xhtml"
271  if step == 2:
272  return "/auth/cert/cert-login.xhtml"
273  elif step == 3:
274  cert_selected = self.getSessionAttribute("cert_selected")
275  if True != cert_selected:
276  return "/auth/cert/cert-not-selected.xhtml"
277 
278  cert_valid = self.getSessionAttribute("cert_valid")
279  if True != cert_valid:
280  return "/auth/cert/cert-invalid.xhtml"
281 
282  return "/login.xhtml"
283 
284  return ""
285 

◆ getSessionAttribute()

def UserCertExternalAuthenticator.PersonAuthentication.getSessionAttribute (   self,
  attribute_name 
)
310  def getSessionAttribute(self, attribute_name):
311  identity = CdiUtil.bean(Identity)
312 
313  # Try to get attribute value from Seam event context
314  if identity.isSetWorkingParameter(attribute_name):
315  return identity.getWorkingParameter(attribute_name)
316 
317  # Try to get attribute from persistent session
318  session_id = identity.getSessionId()
319  if session_id == None:
320  return None
321 
322  session_attributes = session_id.getSessionAttributes()
323  if session_attributes == None:
324  return None
325 
326  if session_attributes.containsKey(attribute_name):
327  return session_attributes.get(attribute_name)
328 
329  return None
330 

◆ init()

def UserCertExternalAuthenticator.PersonAuthentication.init (   self,
  configurationAttributes 
)
35  def init(self, configurationAttributes):
36  print "Cert. Initialization"
37 
38  if not (configurationAttributes.containsKey("chain_cert_file_path")):
39  print "Cert. Initialization. Property chain_cert_file_path is mandatory"
40  return False
41 
42  if not (configurationAttributes.containsKey("map_user_cert")):
43  print "Cert. Initialization. Property map_user_cert is mandatory"
44  return False
45 
46  chain_cert_file_path = configurationAttributes.get("chain_cert_file_path").getValue2()
47 
48  self.chain_certs = CertUtil.loadX509CertificateFromFile(chain_cert_file_path)
49  if self.chain_certs == None:
50  print "Cert. Initialization. Failed to load chain certificates from '%s'" % chain_cert_file_path
51  return False
52 
53  print "Cert. Initialization. Loaded '%d' chain certificates" % self.chain_certs.size()
54 
55  crl_max_response_size = 5 * 1024 * 1024 # 10Mb
56  if configurationAttributes.containsKey("crl_max_response_size"):
57  crl_max_response_size = StringHelper.toInteger(configurationAttributes.get("crl_max_response_size").getValue2(), crl_max_response_size)
58  print "Cert. Initialization. CRL max response size is '%d'" % crl_max_response_size
59 
60  # Define array to order methods correctly
61  self.validator_types = [ 'generic', 'path', 'ocsp', 'crl']
62  self.validators = { 'generic' : [GenericCertificateVerifier(), False],
63  'path' : [PathCertificateVerifier(False), False],
64  'ocsp' : [OCSPCertificateVerifier(), False],
65  'crl' : [CRLCertificateVerifier(crl_max_response_size), False] }
66 
67  for type in self.validator_types:
68  validator_param_name = "use_%s_validator" % type
69  if configurationAttributes.containsKey(validator_param_name):
70  validator_status = StringHelper.toBoolean(configurationAttributes.get(validator_param_name).getValue2(), False)
71  self.validators[type][1] = validator_status
72 
73  print "Cert. Initialization. Validation method '%s' status: '%s'" % (type, self.validators[type][1])
74 
75  self.map_user_cert = StringHelper.toBoolean(configurationAttributes.get("map_user_cert").getValue2(), False)
76  print "Cert. Initialization. map_user_cert: '%s'" % self.map_user_cert
77 
78  self.enabled_recaptcha = self.initRecaptcha(configurationAttributes)
79  print "Cert. Initialization. enabled_recaptcha: '%s'" % self.enabled_recaptcha
80 
81  print "Cert. Initialized successfully"
82 
83  return True
84 

◆ initRecaptcha()

def UserCertExternalAuthenticator.PersonAuthentication.initRecaptcha (   self,
  configurationAttributes 
)
372  def initRecaptcha(self, configurationAttributes):
373  print "Cert. Initialize recaptcha"
374  if not configurationAttributes.containsKey("credentials_file"):
375  return False
376 
377  cert_creds_file = configurationAttributes.get("credentials_file").getValue2()
378 
379  # Load credentials from file
380  f = open(cert_creds_file, 'r')
381  try:
382  creds = json.loads(f.read())
383  except:
384  print "Cert. Initialize recaptcha. Failed to load credentials from file: %s" % cert_creds_file
385  return False
386  finally:
387  f.close()
388 
389  try:
390  recaptcha_creds = creds["recaptcha"]
391  except:
392  print "Cert. Initialize recaptcha. Invalid credentials file '%s' format:" % cert_creds_file
393  return False
394 
395  self.recaptcha_creds = None
396  if recaptcha_creds["enabled"]:
397  print "Cert. Initialize recaptcha. Recaptcha is enabled"
398 
399  encryptionService = CdiUtil.bean(EncryptionService)
400 
401  site_key = recaptcha_creds["site_key"]
402  secret_key = recaptcha_creds["secret_key"]
403 
404  try:
405  site_key = encryptionService.decrypt(site_key)
406  except:
407  # Ignore exception. Value is not encrypted
408  print "Cert. Initialize recaptcha. Assuming that 'site_key' in not encrypted"
409 
410  try:
411  secret_key = encryptionService.decrypt(secret_key)
412  except:
413  # Ignore exception. Value is not encrypted
414  print "Cert. Initialize recaptcha. Assuming that 'secret_key' in not encrypted"
415 
416 
417  self.recaptcha_creds = { 'site_key' : site_key, "secret_key" : secret_key }
418  print "Cert. Initialize recaptcha. Recaptcha is configured correctly"
419 
420  return True
421  else:
422  print "Cert. Initialize recaptcha. Recaptcha is disabled"
423 
424  return False
425 

◆ isValidAuthenticationMethod()

def UserCertExternalAuthenticator.PersonAuthentication.isValidAuthenticationMethod (   self,
  usageType,
  configurationAttributes 
)
98  def isValidAuthenticationMethod(self, usageType, configurationAttributes):
99  return True
100 

◆ logout()

def UserCertExternalAuthenticator.PersonAuthentication.logout (   self,
  configurationAttributes,
  requestParameters 
)
286  def logout(self, configurationAttributes, requestParameters):
287  return True
288 

◆ prepareForStep()

def UserCertExternalAuthenticator.PersonAuthentication.prepareForStep (   self,
  configurationAttributes,
  requestParameters,
  step 
)
225  def prepareForStep(self, configurationAttributes, requestParameters, step):
226  print "Cert. Prepare for step %d" % step
227  identity = CdiUtil.bean(Identity)
228 
229  if step == 1:
230  if self.enabled_recaptcha:
231  identity.setWorkingParameter("recaptcha_site_key", self.recaptcha_creds['site_key'])
232  elif step == 2:
233  # Store certificate in session
234  facesContext = CdiUtil.bean(FacesContext)
235  externalContext = facesContext.getExternalContext()
236  request = externalContext.getRequest()
237 
238  # Try to get certificate from header X-ClientCert
239  clientCertificate = externalContext.getRequestHeaderMap().get("X-ClientCert")
240  if clientCertificate != None:
241  x509Certificate = self.certFromPemString(clientCertificate)
242  identity.setWorkingParameter("cert_x509", self.certToString(x509Certificate))
243  print "Cert. Prepare for step 2. Storing user certificate obtained from 'X-ClientCert' header"
244  return True
245 
246  # Try to get certificate from attribute javax.servlet.request.X509Certificate
247  x509Certificates = request.getAttribute('javax.servlet.request.X509Certificate')
248  if (x509Certificates != None) and (len(x509Certificates) > 0):
249  identity.setWorkingParameter("cert_x509", self.certToString(x509Certificates[0]))
250  print "Cert. Prepare for step 2. Storing user certificate obtained from 'javax.servlet.request.X509Certificate' attribute"
251  return True
252 
253  if step < 4:
254  return True
255  else:
256  return False
257 

◆ processBasicAuthentication()

def UserCertExternalAuthenticator.PersonAuthentication.processBasicAuthentication (   self,
  credentials 
)
289  def processBasicAuthentication(self, credentials):
290  userService = CdiUtil.bean(UserService)
291  authenticationService = CdiUtil.bean(AuthenticationService)
292 
293  user_name = credentials.getUsername()
294  user_password = credentials.getPassword()
295 
296  logged_in = False
297  if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
298  logged_in = authenticationService.authenticate(user_name, user_password)
299 
300  if (not logged_in):
301  return None
302 
303  find_user_by_uid = authenticationService.getAuthenticatedUser()
304  if (find_user_by_uid == None):
305  print "Cert. Process basic authentication. Failed to find user '%s'" % user_name
306  return None
307 
308  return find_user_by_uid
309 

◆ validateCertificate()

def UserCertExternalAuthenticator.PersonAuthentication.validateCertificate (   self,
  x509Certificate 
)
341  def validateCertificate(self, x509Certificate):
342  subjectX500Principal = x509Certificate.getSubjectX500Principal()
343 
344  print "Cert. Validating certificate with DN '%s'" % subjectX500Principal
345 
346  validation_date = java.util.Date()
347 
348  for type in self.validator_types:
349  if self.validators[type][1]:
350  result = self.validators[type][0].validate(x509Certificate, self.chain_certs, validation_date)
351  print "Cert. Validate certificate: '%s'. Validation method '%s' result: '%s'" % (subjectX500Principal, type, result)
352 
353  if (result.getValidity() != ValidationStatus.CertificateValidity.VALID):
354  print "Cert. Certificate: '%s' is invalid" % subjectX500Principal
355  return False
356 
357  return True
358 

◆ validateRecaptcha()

def UserCertExternalAuthenticator.PersonAuthentication.validateRecaptcha (   self,
  recaptcha_response 
)
426  def validateRecaptcha(self, recaptcha_response):
427  print "Cert. Validate recaptcha response"
428 
429  facesContext = CdiUtil.bean(FacesContext)
430  request = facesContext.getExternalContext().getRequest()
431 
432  remoteip = ServerUtil.getIpAddress(request)
433  print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip
434 
435  httpService = CdiUtil.bean(HttpService)
436 
437  http_client = httpService.getHttpsClient()
438  http_client_params = http_client.getParams()
439  http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)
440 
441  recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
442  recaptcha_validation_request = urllib.urlencode({ "secret" : self.recaptcha_creds['secret_key'], "response" : recaptcha_response, "remoteip" : remoteip })
443  recaptcha_validation_headers = { "Content-type" : "application/x-www-form-urlencoded", "Accept" : "application/json" }
444 
445  try:
446  http_service_response = httpService.executePost(http_client, recaptcha_validation_url, None, recaptcha_validation_headers, recaptcha_validation_request)
447  http_response = http_service_response.getHttpResponse()
448  except:
449  print "Cert. Validate recaptcha response. Exception: ", sys.exc_info()[1]
450  return False
451 
452  try:
453  if not httpService.isResponseStastusCodeOk(http_response):
454  print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(http_response.getStatusLine().getStatusCode())
455  httpService.consume(http_response)
456  return False
457 
458  response_bytes = httpService.getResponseContent(http_response)
459  response_string = httpService.convertEntityToString(response_bytes)
460  httpService.consume(http_response)
461  finally:
462  http_service_response.closeConnection()
463 
464  if response_string == None:
465  print "Cert. Validate recaptcha response. Get empty response from validation server"
466  return False
467 
468  response = json.loads(response_string)
469 
470  return response["success"]
471 

メンバ詳解

◆ chain_certs

UserCertExternalAuthenticator.PersonAuthentication.chain_certs

◆ currentTimeMillis

UserCertExternalAuthenticator.PersonAuthentication.currentTimeMillis

◆ enabled_recaptcha

UserCertExternalAuthenticator.PersonAuthentication.enabled_recaptcha

◆ map_user_cert

UserCertExternalAuthenticator.PersonAuthentication.map_user_cert

◆ recaptcha_creds

UserCertExternalAuthenticator.PersonAuthentication.recaptcha_creds

◆ validator_types

UserCertExternalAuthenticator.PersonAuthentication.validator_types

◆ validators

UserCertExternalAuthenticator.PersonAuthentication.validators

このクラス詳解は次のファイルから抽出されました: