incubator-ambari-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From maha...@apache.org
Subject svn commit: r1390838 [1/2] - in /incubator/ambari/branches/AMBARI-666: ./ ambari-agent/src/main/python/ambari_agent/ ambari-agent/src/test/python/ ambari-project/ ambari-server/ ambari-server/src/main/assemblies/ ambari-server/src/main/java/org/apache/...
Date Thu, 27 Sep 2012 04:42:25 GMT
Author: mahadev
Date: Thu Sep 27 04:42:23 2012
New Revision: 1390838

URL: http://svn.apache.org/viewvc?rev=1390838&view=rev
Log:
AMBARI-771. Add security between the server and agent and authentication for the API. (mahadev)

Added:
    incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/TestCertGeneration.py
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntityPK.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SecurityFilter.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignCertResponse.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignMessage.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProvider.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/LdapServerProperties.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/unsecured/rest/CertificateSign.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/resources/ca.config
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/resources/db/
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/resources/db/serial
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/CertGenerationTest.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsServiceTest.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationHelperTest.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AuthorizationTestModule.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/LdapServerPropertiesTest.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/resources/users.ldif
Removed:
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/AmbariUserDetailsService.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/resources/users.ldif
Modified:
    incubator/ambari/branches/AMBARI-666/AMBARI-666-CHANGES.txt
    incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/Controller.py
    incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/main.py
    incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/security.py
    incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/unitTests.py
    incubator/ambari/branches/AMBARI-666/ambari-project/pom.xml
    incubator/ambari/branches/AMBARI-666/ambari-server/pom.xml
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/assemblies/server.xml
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ClusterDAO.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/CertificateManager.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/ClientSecurityType.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/unsecured/rest/CertificateDownload.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/main/resources/webapp/WEB-INF/spring-security.xml
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/bootstrap/BootStrapTest.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/java/org/apache/ambari/server/orm/OrmTestHelper.java
    incubator/ambari/branches/AMBARI-666/ambari-server/src/test/resources/log4j.properties

Modified: incubator/ambari/branches/AMBARI-666/AMBARI-666-CHANGES.txt
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/AMBARI-666-CHANGES.txt?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/AMBARI-666-CHANGES.txt (original)
+++ incubator/ambari/branches/AMBARI-666/AMBARI-666-CHANGES.txt Thu Sep 27 04:42:23 2012
@@ -12,6 +12,9 @@ AMBARI-666 branch (unreleased changes)
 
   NEW FEATURES
 
+  AMBARI-771. Add security between the server and agent and authentication for
+  the API. (mahadev)
+
   AMBARI-770. Cluster Management pages for Ambari Web. (yusaku)
 
   AMBARI-769. Implement step 9 (Install,start and test) of installer wizard.

Modified: incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/Controller.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/Controller.py?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/Controller.py (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/Controller.py Thu Sep 27 04:42:23 2012
@@ -28,6 +28,8 @@ import time
 import threading
 import urllib2
 from urllib2 import Request, urlopen, URLError
+import httplib
+import ssl
 import AmbariConfig
 import pprint
 from Heartbeat import Heartbeat
@@ -35,9 +37,11 @@ from Register import Register
 from ActionQueue import ActionQueue
 from optparse import OptionParser
 from wsgiref.simple_server import ServerHandler
+import security
 
 logger = logging.getLogger()
 
+
 class Controller(threading.Thread):
 
   def __init__(self, config):
@@ -53,9 +57,9 @@ class Controller(threading.Thread):
     #                      'password' : config.get('controller', 'password')
     #  }
     self.hostname = socket.gethostname()
-    self.registerUrl = config.get('server', 'url') + \
+    self.registerUrl = config.get('server', 'secured_url') + \
       '/agent/register/' + self.hostname
-    self.heartbeatUrl = config.get('server', 'url') + \
+    self.heartbeatUrl = config.get('server', 'secured_url') + \
        '/agent/heartbeat/' + self.hostname
      
   def start(self):
@@ -80,7 +84,7 @@ class Controller(threading.Thread):
         data = json.dumps(self.register.build(id))
         req = urllib2.Request(self.registerUrl, data, {'Content-Type': 
                                                       'application/json'})
-        stream = urllib2.urlopen(req)
+        stream = security.secured_url_open(req)
         response = stream.read()
         stream.close()
         ret = json.loads(response)
@@ -103,8 +107,12 @@ class Controller(threading.Thread):
       try:
         if retry==False:
           data = json.dumps(self.heartbeat.build(id))
+
         req = urllib2.Request(self.heartbeatUrl, data, {'Content-Type': 'application/json'})
-        f = urllib2.urlopen(req)
+        
+        logger.info(data)
+        
+        f = security.secured_url_open(req)
         response = f.read()
         f.close()
         data = json.loads(response)

Modified: incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/main.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/main.py?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/main.py (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/main.py Thu Sep 27 04:42:23 2012
@@ -31,6 +31,7 @@ from Controller import Controller
 from shell import getTempFiles
 from shell import killstaleprocesses 
 import AmbariConfig
+from security import CertificateManager
 
 logger = logging.getLogger()
 agentPid = os.getpid()
@@ -133,6 +134,13 @@ def main():
   killstaleprocesses()
   logger.info("Connecting to Server at: "+config.get('server', 'url'))
 
+
+  #Initiate security
+  
+  certMan = CertificateManager(config)
+  
+  certMan.initSecurity()
+
   # Launch Controller communication
   controller = Controller(config) 
   controller.start()

Modified: incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/security.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/security.py?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/security.py (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-agent/src/main/python/ambari_agent/security.py Thu Sep 27 04:42:23 2012
@@ -1,3 +1,5 @@
+#!/usr/bin/env python2.6
+
 import httplib
 import urllib2
 from urllib2 import Request
@@ -7,59 +9,126 @@ import os
 import logging
 from subprocess import Popen, PIPE
 import AmbariConfig
-
+import json
+import pprint
 logger = logging.getLogger()
 
 GEN_AGENT_KEY="openssl req -new -newkey rsa:1024 -nodes -keyout %(keysdir)s/%(hostname)s.key\
 	-subj /OU=%(hostname)s/\
         -out %(keysdir)s/%(hostname)s.csr"
 
+
+class VerifiedHTTPSConnection(httplib.HTTPSConnection):
+  def connect(self):
+    sock = socket.create_connection((self.host, self.port), self.timeout)
+    if self._tunnel_host:
+      self.sock = sock
+      self._tunnel()
+    agent_key = AmbariConfig.config.get('security', 'keysdir') + os.sep + socket.gethostname() + ".key"
+    agent_crt = AmbariConfig.config.get('security', 'keysdir') + os.sep + socket.gethostname() + ".crt"
+    server_crt = AmbariConfig.config.get('security', 'keysdir') + os.sep + "ca.crt"
+    self.sock = ssl.wrap_socket(sock,
+                                keyfile=agent_key,
+                                certfile=agent_crt,
+                                cert_reqs=ssl.CERT_REQUIRED,
+                                ca_certs=server_crt)
+class VerifiedHTTPSHandler(urllib2.HTTPSHandler):
+  def __init__(self, connection_class = VerifiedHTTPSConnection):
+    self.specialized_conn_class = connection_class
+    urllib2.HTTPSHandler.__init__(self)
+  def https_open(self, req):
+    return self.do_open(self.specialized_conn_class, req)
+
+def secured_url_open(req):
+  logger.info("Secured url open")
+  https_handler = VerifiedHTTPSHandler()
+  url_opener = urllib2.build_opener(https_handler)
+  stream = url_opener.open(req)
+  return stream
 class CertificateManager():
-    def __init__(self, config):
-        self.config = config
-        self.keysdir = self.config.get('security', 'keysdir')
-        self.server_crt=self.config.get('security', 'server_crt')
-    def getAgentKeyName(self):
-        return self.keysdir + os.sep + socket.gethostname() + ".key"
-    def getAgentCrtName(self):
-        return self.keysdir + os.sep + socket.gethostname() + ".key"
-    def getSrvrCrtName(self):
-        return self.keysdir + os.sep + "ca.crt"
-        
-    def checkCertExists(self):
-        
-        server_crt_exists = os.path.exists(self.getSrvrCrtName())
-        
-        if not server_crt_exists:
-            logger.info("Server certicate not exists, downloading")
-            self.loadSrvrCrt()
-        else:
-            logger.info("Server certicate exists, ok")
-            
-        agent_crt_exists = os.path.exists(self.getAgentCrtName())
-        
-        logger.info(self.getAgentCrtName())
-        
-        if not agent_crt_exists:
-            logger.info("Agent certicate not exists, generating request")
-            self.genAgentCrtReq()
-        else:
-            logger.info("Agent certicate exists, ok")
+  def __init__(self, config):
+    self.config = config
+    self.keysdir = self.config.get('security', 'keysdir')
+    self.server_crt=self.config.get('security', 'server_crt')
+    
+  def getAgentKeyName(self):
+    keysdir = self.config.get('security', 'keysdir')
+    return keysdir + os.sep + socket.gethostname() + ".key"
+  def getAgentCrtName(self):
+    keysdir = self.config.get('security', 'keysdir')
+    return keysdir + os.sep + socket.gethostname() + ".crt"
+  def getAgentCrtReqName(self):
+    keysdir = self.config.get('security', 'keysdir')
+    return keysdir + os.sep + socket.gethostname() + ".csr"
+  def getSrvrCrtName(self):
+    keysdir = self.config.get('security', 'keysdir')
+    return keysdir + os.sep + "ca.crt"
+    
+  def checkCertExists(self):
+    
+    s = self.config.get('security', 'keysdir') + os.sep + "ca.crt"
+
+    server_crt_exists = os.path.exists(s)
+    
+    if not server_crt_exists:
+      logger.info("Server certicate not exists, downloading")
+      self.loadSrvrCrt()
+    else:
+      logger.info("Server certicate exists, ok")
+      
+    agent_key_exists = os.path.exists(self.getAgentKeyName())
+    
+    if not agent_key_exists:
+      logger.info("Agent key not exists, generating request")
+      self.genAgentCrtReq()
+    else:
+      logger.info("Agent key exists, ok")
+      
+    agent_crt_exists = os.path.exists(self.getAgentCrtName())
+    
+    if not agent_crt_exists:
+        logger.info("Agent certificate not exists, sending sign request")
+        self.reqSignCrt()
+    else:
+        logger.info("Agent certificate exists, ok")
             
-        
-    def loadSrvrCrt(self):
-      get_ca_url = self.config.get('server', 'url') + '/cert/ca/'
-      stream = urllib2.urlopen(get_ca_url)
-      response = stream.read()
-      stream.close()
-      srvr_crt_f = open(self.getSrvrCrtName(), 'w+')
-      srvr_crt_f.write(response)
+  def loadSrvrCrt(self):
+    get_ca_url = self.config.get('server', 'url') + '/cert/ca/'
+    stream = urllib2.urlopen(get_ca_url)
+    response = stream.read()
+    stream.close()
+    srvr_crt_f = open(self.getSrvrCrtName(), 'w+')
+    srvr_crt_f.write(response)
       
-    def genAgentCrtReq(self):
-        generate_script = GEN_AGENT_KEY % {'hostname': socket.gethostname(),
-                                           'keysdir' : self.config.get('security', 'keysdir')}
-        logger.info(generate_script)
-        pp = Popen([generate_script], shell=True, stdout=PIPE)
+  def reqSignCrt(self):
+    sign_crt_req_url = self.config.get('server', 'url') + '/certs/' + socket.gethostname()
+    agent_crt_req_f = open(self.getAgentCrtReqName())
+    agent_crt_req_content = agent_crt_req_f.read()
+    passphrase_env_var = self.config.get('security', 'passphrase_env_var_name')
+    passphrase = os.environ[passphrase_env_var]
+    register_data = {'csr'       : agent_crt_req_content,
+                    'passphrase' : passphrase}
+    data = json.dumps(register_data)
+    req = urllib2.Request(sign_crt_req_url, data, {'Content-Type': 'application/json'})
+    f = urllib2.urlopen(req)
+    response = f.read()
+    f.close()
+    data = json.loads(response)
+    logger.info("Sign response from Server: \n" + pprint.pformat(data))
+    result=data['result']
+    if result == 'OK':
+      agentCrtContent=data['signedCa']
+      agentCrtF = open(self.getAgentCrtName(), "w")
+      agentCrtF.write(agentCrtContent)
+    else:
+      logger.error("Certificate signing failed")
 
-    def initSecurity(self):
-        self.checkCertExists()
\ No newline at end of file
+  def genAgentCrtReq(self):
+    generate_script = GEN_AGENT_KEY % {'hostname': socket.gethostname(),
+                                     'keysdir' : self.config.get('security', 'keysdir')}
+    logger.info(generate_script)
+    p = Popen([generate_script], shell=True, stdout=PIPE)
+    p.wait()
+      
+  def initSecurity(self):
+    self.checkCertExists()
\ No newline at end of file

Added: incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/TestCertGeneration.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/TestCertGeneration.py?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/TestCertGeneration.py (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/TestCertGeneration.py Thu Sep 27 04:42:23 2012
@@ -0,0 +1,45 @@
+#!/usr/bin/env python2.6
+
+'''
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+'''
+import os
+import tempfile
+import shutil
+from unittest import TestCase
+import ConfigParser
+import security
+from security import CertificateManager
+from ambari_agent import AmbariConfig
+
+class TestCertGeneration(TestCase):
+  def setUp(self):
+    self.tmpdir = tempfile.mkdtemp()
+    config = ConfigParser.RawConfigParser()
+    config.add_section('security')
+    config.set('security', 'keysdir', self.tmpdir)
+    config.set('security', 'server_crt', 'ca.crt')
+    self.certMan = CertificateManager(config)
+    
+  def test_generation(self):
+    self.certMan.genAgentCrtReq()
+    self.assertTrue(os.path.exists(self.certMan.getAgentKeyName()))
+    self.assertTrue(os.path.exists(self.certMan.getAgentCrtReqName()))
+  def tearDown(self):
+    shutil.rmtree(self.tmpdir)
+    
+

Modified: incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/unitTests.py
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/unitTests.py?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/unitTests.py (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-agent/src/test/python/unitTests.py Thu Sep 27 04:42:23 2012
@@ -21,6 +21,8 @@ limitations under the License.
 import unittest
 import doctest
 
+
+
 class TestAgent(unittest.TestSuite):
   def run(self, result):
     run = unittest.TestSuite.run
@@ -34,8 +36,9 @@ def all_tests_suite():
     'TestServerStatus',
     'TestFileUtil',
     'TestActionQueue',
-    'TestAmbariComponent',
-    'TestAgentActions'
+    #'TestAmbariComponent',
+    'TestAgentActions',
+    'TestCertGeneration'
   ])
   return TestAgent([suite])
 
@@ -48,4 +51,6 @@ if __name__ == '__main__':
   import os
   import sys
   sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + os.sep + 'main' + os.sep + 'python')
+  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + os.sep + 'main' + os.sep + 'python' + os.sep + 'ambari_agent')
   main()

Modified: incubator/ambari/branches/AMBARI-666/ambari-project/pom.xml
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-project/pom.xml?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-project/pom.xml (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-project/pom.xml Thu Sep 27 04:42:23 2012
@@ -152,7 +152,7 @@
       <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-log4j12</artifactId>
-        <version>1.0.1</version>
+        <version>1.5.5</version>
       </dependency>
       <dependency>
         <groupId>org.eclipse.persistence</groupId>

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/pom.xml
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/pom.xml?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/pom.xml (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/pom.xml Thu Sep 27 04:42:23 2012
@@ -104,10 +104,6 @@
       <groupId>org.apache.directory.server</groupId>
       <artifactId>apacheds-all</artifactId>
     </dependency>
-    <!--<dependency>-->
-      <!--<groupId>org.apache.directory.shared</groupId>-->
-      <!--<artifactId>shared-ldap</artifactId>-->
-    <!--</dependency>-->
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/assemblies/server.xml
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/assemblies/server.xml?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/assemblies/server.xml (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/assemblies/server.xml Thu Sep 27 04:42:23 2012
@@ -29,11 +29,6 @@
       <outputDirectory>ambari-server-${project.version}/lib</outputDirectory>
     </file>
 
-    <file>
-      <source>${basedir}/src/main/resources/pass.txt</source>
-      <outputDirectory>/ambari-server-${project.version}</outputDirectory>
-    </file>
-
   </files>
   <fileSets>
     <!-- Distro files, readme, licenses, etc -->
@@ -54,6 +49,17 @@
       <fileMode>0755</fileMode>
     </fileSet>
     -->
+
+    <fileSet>
+      <directory>${basedir}/src/main/resources/</directory>
+      <outputDirectory>/ambari-server-${project.version}/keystore</outputDirectory>
+      <includes>
+        <include>db/*</include>
+        <include>ca.config</include>
+	<include>pass.txt</include>
+      </includes>
+    </fileSet>
+
   </fileSets>
   <dependencySets>
     <dependencySet>

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java Thu Sep 27 04:42:23 2012
@@ -21,13 +21,12 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
+import java.util.*;
 
+import org.apache.ambari.server.security.ClientSecurityType;
+import org.apache.ambari.server.security.authorization.LdapServerProperties;
 import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
@@ -41,8 +40,8 @@ import com.google.inject.Singleton;
 @Singleton
 public class Configuration {
 
-  private static final String AMBARI_CONF_VAR = "AMBARI_CONF_DIR";
-  private static final String CONFIG_FILE = "ambari.properties";
+  public static final String AMBARI_CONF_VAR = "AMBARI_CONF_DIR";
+  public static final String CONFIG_FILE = "ambari.properties";
   public static final String BOOTSTRAP_DIR = "bootstrap.dir";
   public static final String BOOTSTRAP_SCRIPT = "bootstrap.script";
   public static final String SRVR_KSTR_DIR_KEY = "security.server.keys_dir";
@@ -51,14 +50,39 @@ public class Configuration {
   public static final String KSTR_NAME_KEY = "security.server.keystore_name";
   public static final String SRVR_CRT_PASS_FILE_KEY = "security.server.crt_pass_file";
   public static final String SRVR_CRT_PASS_KEY = "security.server.crt_pass";
+  public static final String PASSPHRASE_ENV_KEY = "security.server.passphrase_env_var";
+  public static final String PASSPHRASE_KEY = "security.server.passphrase";
+ 
   public static final String CLIENT_SECURITY_KEY = "client.security";
+  public static final String LDAP_USE_SSL_KEY = "authorization.ldap.useSSL";
+  public static final String LDAP_PRIMARY_URL_KEY = "authorization.ldap.primaryUrl";
+  public static final String LDAP_SECONDARY_URL_KEY = "authorization.ldap.secondaryUrl";
+  public static final String LDAP_BASE_DN_KEY = "authorization.ldap.baseDn";
+  public static final String LDAP_BIND_ANONYMOUSLY_KEY = "authorization.ldap.bindAnonymously";
+  public static final String LDAP_MANAGER_DN_KEY = "authorization.ldap.managerDn";
+  public static final String LDAP_MANAGER_PASSWORD_KEY = "authorization.ldap.managerPassword";
+  public static final String LDAP_USERNAME_ATTRIBUTE_KEY = "authorization.ldap.usernameAttribute";
+  public static final String LDAP_USER_DEFAULT_ROLE_KEY = "authorization.ldap.userDefaultRole";
+
   private static final String SRVR_KSTR_DIR_DEFAULT = ".";
-  private static final String SRVR_CRT_NAME_DEFAULT = "ca.crt";
-  private static final String SRVR_KEY_NAME_DEFAULT = "ca.key";
-  private static final String KSTR_NAME_DEFAULT = "keystore.p12";
+  public static final String SRVR_CRT_NAME_DEFAULT = "ca.crt";
+  public static final String SRVR_KEY_NAME_DEFAULT = "ca.key";
+  public static final String KSTR_NAME_DEFAULT = "keystore.p12";
   private static final String SRVR_CRT_PASS_FILE_DEFAULT ="pass.txt";
+  private static final String PASSPHRASE_ENV_DEFAULT = "AMBARI_PASSPHRASE";
+  
+  
   private static final String CLIENT_SECURITY_DEFAULT = "local";
 
+  private static final String LDAP_USER_SEARCH_FILTER_DEFAULT = "({attribute}={0})";
+  private static final String LDAP_USER_DEFAULT_ROLE_DEFAULT = "user";
+  private static final String LDAP_BIND_ANONYMOUSLY_DEFAULT = "true";
+
+  //For embedded server only - should be removed later
+  private static final String LDAP_PRIMARY_URL_DEFAULT = "localhost:33389";
+  private static final String LDAP_BASE_DN_DEFAULT = "dc=ambari,dc=apache,dc=org";
+  private static final String LDAP_USERNAME_ATTRIBUTE_DEFAULT = "uid";
+
 
 
   
@@ -91,7 +115,11 @@ public class Configuration {
     configsMap.put(SRVR_KEY_NAME_KEY, properties.getProperty(SRVR_KEY_NAME_KEY, SRVR_KEY_NAME_DEFAULT));
     configsMap.put(KSTR_NAME_KEY, properties.getProperty(KSTR_NAME_KEY, KSTR_NAME_DEFAULT));
     configsMap.put(SRVR_CRT_PASS_FILE_KEY, properties.getProperty(SRVR_CRT_PASS_FILE_KEY, SRVR_CRT_PASS_FILE_DEFAULT));
+
+    configsMap.put(PASSPHRASE_ENV_KEY, properties.getProperty(PASSPHRASE_ENV_KEY, PASSPHRASE_ENV_DEFAULT));
+	configsMap.put(PASSPHRASE_KEY, System.getenv(configsMap.get(PASSPHRASE_ENV_KEY)));
     configsMap.put(CLIENT_SECURITY_KEY, properties.getProperty(CLIENT_SECURITY_KEY, CLIENT_SECURITY_DEFAULT));
+    configsMap.put(LDAP_USER_DEFAULT_ROLE_KEY, properties.getProperty(LDAP_USER_DEFAULT_ROLE_KEY, LDAP_USER_DEFAULT_ROLE_DEFAULT));
 
     try {
         File passFile = new File(configsMap.get(SRVR_KSTR_DIR_KEY) + File.separator 
@@ -116,7 +144,10 @@ public class Configuration {
     Properties properties = new Properties();
 
     // get the configuration directory and filename
-    String confDir = System.getenv(AMBARI_CONF_VAR);
+
+    String confDir = System.getProperty(AMBARI_CONF_VAR);
+    if (confDir == null)
+      confDir = System.getenv(AMBARI_CONF_VAR);
     if (confDir == null) {
       confDir = "/etc/ambari";
     }
@@ -159,4 +190,35 @@ public class Configuration {
     return configsMap;
   }
 
+  /**
+   * Gets client security type
+   * @return appropriate ClientSecurityType
+   */
+  public ClientSecurityType getClientSecurityType() {
+    return ClientSecurityType.fromString(properties.getProperty(CLIENT_SECURITY_KEY));
+  }
+
+  public void setClientSecurityType(ClientSecurityType type) {
+    properties.setProperty(CLIENT_SECURITY_KEY, type.toString());
+  }
+
+  /**
+   * Gets parameters of LDAP server to connect to
+   * @return LdapServerProperties object representing connection parameters
+   */
+  public LdapServerProperties getLdapServerProperties() {
+    LdapServerProperties ldapServerProperties = new LdapServerProperties();
+
+    ldapServerProperties.setPrimaryUrl(properties.getProperty(LDAP_PRIMARY_URL_KEY, LDAP_PRIMARY_URL_DEFAULT));
+    ldapServerProperties.setSecondaryUrl(properties.getProperty(LDAP_SECONDARY_URL_KEY));
+    ldapServerProperties.setUseSsl("true".equalsIgnoreCase(properties.getProperty(LDAP_USE_SSL_KEY)));
+    ldapServerProperties.setAnonymousBind("true".equalsIgnoreCase(properties.getProperty(LDAP_BIND_ANONYMOUSLY_KEY, LDAP_BIND_ANONYMOUSLY_DEFAULT)));
+    ldapServerProperties.setManagerDn(properties.getProperty(LDAP_MANAGER_DN_KEY));
+    ldapServerProperties.setManagerPassword(properties.getProperty(LDAP_MANAGER_PASSWORD_KEY));
+    ldapServerProperties.setBaseDN(properties.getProperty(LDAP_BASE_DN_KEY, LDAP_BASE_DN_DEFAULT));
+    ldapServerProperties.setUsernameAttribute(properties.getProperty(LDAP_USERNAME_ATTRIBUTE_KEY, LDAP_USERNAME_ATTRIBUTE_DEFAULT));
+
+    return ldapServerProperties;
+  }
+
 }

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java Thu Sep 27 04:42:23 2012
@@ -28,6 +28,7 @@ import com.sun.jersey.spi.container.serv
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.GuiceJpaInitializer;
 import org.apache.ambari.server.security.CertificateManager;
+import org.apache.ambari.server.security.SecurityFilter;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.mortbay.jetty.Server;
@@ -52,8 +53,8 @@ import java.util.Map;
 public class AmbariServer {
   public static final String PERSISTENCE_PROVIDER = "ambari-postgres";
   private static Log LOG = LogFactory.getLog(AmbariServer.class);
-  public static int CLIENT_PORT = 4080;
-  public static int CLIENT_SECURED_PORT = 8443;
+  public static int CLIENT_ONE_WAY = 4080;
+  public static int CLIENT_TWO_WAY = 8443;
   private Server server = null;
   public volatile boolean running = true; // true while controller runs
 
@@ -71,7 +72,7 @@ public class AmbariServer {
   Injector injector;
 
   public void run() {
-    server = new Server(CLIENT_PORT);
+    server = new Server();
 
     try {
       ClassPathXmlApplicationContext parentSpringAppContext = new ClassPathXmlApplicationContext();
@@ -90,6 +91,7 @@ public class AmbariServer {
 
       webAppContext.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, springWebAppContext);
 
+      
       server.setHandler(webAppContext);
 
       certMan.initRootCert();
@@ -99,26 +101,42 @@ public class AmbariServer {
 
       ServletHolder rootServlet = root.addServlet(DefaultServlet.class, "/");
       rootServlet.setInitOrder(1);
-
-
+    
+      root.addFilter(SecurityFilter.class, "/*", 1);
       //Secured connector for 2-way auth
-      SslSocketConnector sslConnector = new SslSocketConnector();
-      sslConnector.setPort(CLIENT_SECURED_PORT);
+      SslSocketConnector sslConnectorTwoWay = new SslSocketConnector();
+      sslConnectorTwoWay.setPort(CLIENT_TWO_WAY);
 
       Map<String, String> configsMap = configs.getConfigsMap();
       String keystore = configsMap.get(Configuration.SRVR_KSTR_DIR_KEY) + File.separator + configsMap.get(Configuration.KSTR_NAME_KEY);
       String srvrCrtPass = configsMap.get(Configuration.SRVR_CRT_PASS_KEY);
 
-      sslConnector.setKeystore(keystore);
-      sslConnector.setTruststore(keystore);
-      sslConnector.setPassword(srvrCrtPass);
-      sslConnector.setKeyPassword(srvrCrtPass);
-      sslConnector.setTrustPassword(srvrCrtPass);
-      sslConnector.setKeystoreType("PKCS12");
-      sslConnector.setTruststoreType("PKCS12");
-      sslConnector.setNeedClientAuth(true);
+      sslConnectorTwoWay.setKeystore(keystore);
+      sslConnectorTwoWay.setTruststore(keystore);
+      sslConnectorTwoWay.setPassword(srvrCrtPass);
+      sslConnectorTwoWay.setKeyPassword(srvrCrtPass);
+      sslConnectorTwoWay.setTrustPassword(srvrCrtPass);
+      sslConnectorTwoWay.setKeystoreType("PKCS12");
+      sslConnectorTwoWay.setTruststoreType("PKCS12");
+      sslConnectorTwoWay.setNeedClientAuth(true);
+      
+      //Secured connector for 1-way auth
+      SslSocketConnector sslConnectorOneWay = new SslSocketConnector();
+      sslConnectorOneWay.setPort(CLIENT_ONE_WAY);
+      
+      sslConnectorOneWay.setKeystore(keystore);
+      sslConnectorOneWay.setTruststore(keystore);
+      sslConnectorOneWay.setPassword(srvrCrtPass);
+      sslConnectorOneWay.setKeyPassword(srvrCrtPass);
+      sslConnectorOneWay.setTrustPassword(srvrCrtPass);
+      sslConnectorOneWay.setKeystoreType("PKCS12");
+      sslConnectorOneWay.setTruststoreType("PKCS12");
+      sslConnectorOneWay.setNeedClientAuth(false);
+      
+      
 
-      server.addConnector(sslConnector);
+      server.addConnector(sslConnectorOneWay);
+      server.addConnector(sslConnectorTwoWay);
 
       ServletHolder sh = new ServletHolder(ServletContainer.class);
       sh.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
@@ -143,6 +161,14 @@ public class AmbariServer {
               "org.apache.ambari.server.security.unsecured.rest");
       root.addServlet(cert, "/cert/*");
       cert.setInitOrder(4);
+      
+      ServletHolder certs = new ServletHolder(ServletContainer.class);
+      certs.setInitParameter("com.sun.jersey.config.property.resourceConfigClass",
+        "com.sun.jersey.api.core.PackagesResourceConfig");
+      certs.setInitParameter("com.sun.jersey.config.property.packages",
+        "org.apache.ambari.server.security.unsecured.rest");
+      root.addServlet(cert, "/certs/*");
+      certs.setInitOrder(5);
 
       server.setStopAtShutdown(true);
 
@@ -183,4 +209,4 @@ public class AmbariServer {
       LOG.error("Failed to run the Ambari Server", t);
     }
   }
-}
+}
\ No newline at end of file

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java Thu Sep 27 04:42:23 2012
@@ -18,6 +18,7 @@
 package org.apache.ambari.server.controller;
 import org.apache.ambari.server.agent.rest.AgentResource;
 import org.apache.ambari.server.security.unsecured.rest.CertificateDownload;
+import org.apache.ambari.server.security.unsecured.rest.CertificateSign;
 
 import com.google.inject.AbstractModule;
 
@@ -31,5 +32,6 @@ public class ControllerModule extends Ab
   protected void configure() {
     requestStaticInjection(AgentResource.class);
     requestStaticInjection(CertificateDownload.class);
+    requestStaticInjection(CertificateSign.class);
   }
 }

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ClusterDAO.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ClusterDAO.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ClusterDAO.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ClusterDAO.java Thu Sep 27 04:42:23 2012
@@ -37,6 +37,7 @@ public class ClusterDAO {
     return entityManagerProvider.get().find(ClusterEntity.class, clusterName);
   }
 
+  @Transactional
   public void create(ClusterEntity clusterEntity) {
     entityManagerProvider.get().persist(clusterEntity);
   }

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java Thu Sep 27 04:42:23 2012
@@ -33,6 +33,7 @@ public class RoleDAO {
     return entityManagerProvider.get().find(RoleEntity.class, roleName);
   }
 
+  @Transactional
   public void create(RoleEntity roleName) {
     entityManagerProvider.get().persist(roleName);
   }

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java Thu Sep 27 04:42:23 2012
@@ -21,18 +21,44 @@ import com.google.inject.Inject;
 import com.google.inject.Provider;
 import com.google.inject.persist.Transactional;
 import org.apache.ambari.server.orm.entities.UserEntity;
+import org.apache.ambari.server.orm.entities.UserEntityPK;
 
 import javax.persistence.EntityManager;
+import javax.persistence.NoResultException;
+import javax.persistence.TypedQuery;
 
 public class UserDAO {
 
   @Inject
   Provider<EntityManager> entityManagerProvider;
 
-  public UserEntity findByName(String userName) {
-    return entityManagerProvider.get().find(UserEntity.class, userName);
+  @Transactional
+  public UserEntity findByPK(UserEntityPK userPK) {
+    return entityManagerProvider.get().find(UserEntity.class, userPK);
+  }
+
+  @Transactional
+  public UserEntity findLocalUserByName(String userName) {
+    TypedQuery<UserEntity> query = entityManagerProvider.get().createNamedQuery("localUserByName", UserEntity.class);
+    query.setParameter("username", userName);
+    try {
+      return query.getSingleResult();
+    } catch (NoResultException e) {
+      return null;
+    }
   }
 
+  public UserEntity findLdapUserByName(String userName) {
+    TypedQuery<UserEntity> query = entityManagerProvider.get().createNamedQuery("ldapUserByName", UserEntity.class);
+    query.setParameter("username", userName);
+    try {
+      return query.getSingleResult();
+    } catch (NoResultException e) {
+      return null;
+    }
+  }
+
+  @Transactional
   public void create(UserEntity userName) {
     entityManagerProvider.get().persist(userName);
   }
@@ -48,8 +74,8 @@ public class UserDAO {
   }
 
   @Transactional
-  public void removeByName(String userName) {
-    remove(findByName(userName));
+  public void removeByPK(UserEntityPK userPK) {
+    remove(findByPK(userPK));
   }
 
 }

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java Thu Sep 27 04:42:23 2012
@@ -2,10 +2,16 @@ package org.apache.ambari.server.orm.ent
 
 import javax.persistence.*;
 import java.sql.Timestamp;
+import java.util.Date;
 import java.util.Set;
 
+@IdClass(UserEntityPK.class)
 @javax.persistence.Table(name = "users", schema = "ambari", catalog = "")
 @Entity
+@NamedQueries({
+        @NamedQuery(name = "localUserByName", query = "SELECT user FROM UserEntity user where user.userName=:username AND user.ldapUser=false"),
+        @NamedQuery(name = "ldapUserByName", query = "SELECT user FROM UserEntity user where user.userName=:username AND user.ldapUser=true")
+})
 public class UserEntity {
 
   private String userName;
@@ -20,6 +26,18 @@ public class UserEntity {
     this.userName = userName;
   }
 
+  private Boolean ldapUser = false;
+
+  @javax.persistence.Column(name = "ldap_user")
+  @Id
+  public Boolean getLdapUser() {
+    return ldapUser;
+  }
+
+  public void setLdapUser(Boolean ldapUser) {
+    this.ldapUser = ldapUser;
+  }
+
   private String userPassword;
 
   @javax.persistence.Column(name = "user_password")
@@ -32,27 +50,16 @@ public class UserEntity {
     this.userPassword = userPassword;
   }
 
-  private Boolean ldapUser;
-
-  @javax.persistence.Column(name = "ldap_user")
-  @Basic
-  public Boolean getLdapUser() {
-    return ldapUser;
-  }
-
-  public void setLdapUser(Boolean ldapUser) {
-    this.ldapUser = ldapUser;
-  }
-
-  private Timestamp createTime;
+  private Date createTime = new Date();
 
   @javax.persistence.Column(name = "create_time")
   @Basic
-  public Timestamp getCreateTime() {
+  @Temporal(value = TemporalType.TIMESTAMP)
+  public Date getCreateTime() {
     return createTime;
   }
 
-  public void setCreateTime(Timestamp createTime) {
+  public void setCreateTime(Date createTime) {
     this.createTime = createTime;
   }
 
@@ -82,7 +89,10 @@ public class UserEntity {
 
   private Set<RoleEntity> roleEntities;
 
-  @javax.persistence.JoinTable(name = "user_roles", catalog = "", schema = "ambari", joinColumns = {@JoinColumn(name = "user_name")}, inverseJoinColumns = {@JoinColumn(name = "user_name")})
+  @javax.persistence.JoinTable(name = "user_roles", catalog = "", schema = "ambari",
+          joinColumns = {@JoinColumn(name = "user_name", referencedColumnName = "user_name"),
+                  @JoinColumn(name = "ldap_user", referencedColumnName = "ldap_user")},
+          inverseJoinColumns = {@JoinColumn(name = "role_name", referencedColumnName = "role_name")})
   @ManyToMany
   public Set<RoleEntity> getRoleEntities() {
     return roleEntities;

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntityPK.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntityPK.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntityPK.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntityPK.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,69 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.orm.entities;
+
+import javax.persistence.Id;
+import java.io.Serializable;
+
+public class UserEntityPK implements Serializable {
+
+  private String userName;
+
+  @javax.persistence.Column(name = "user_name")
+  @Id
+  public String getUserName() {
+    return userName;
+  }
+
+  public void setUserName(String userName) {
+    this.userName = userName;
+  }
+
+  private Boolean ldapUser;
+
+  @javax.persistence.Column(name = "ldap_user")
+  @Id
+  public Boolean getLdapUser() {
+    return ldapUser;
+  }
+
+  public void setLdapUser(Boolean ldapUser) {
+    this.ldapUser = ldapUser;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    UserEntityPK that = (UserEntityPK) o;
+
+    if (userName != null ? !userName.equals(that.userName) : that.userName != null) return false;
+    if (ldapUser != null ? !ldapUser.equals(that.ldapUser) : that.ldapUser != null) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    int result = userName != null ? userName.hashCode() : 0;
+    result = 31 * result + (ldapUser != null ? ldapUser.hashCode() : 0);
+    return result;
+  }
+
+}

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/CertificateManager.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/CertificateManager.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/CertificateManager.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/CertificateManager.java Thu Sep 27 04:42:23 2012
@@ -48,8 +48,7 @@ public class CertificateManager {
   private static final String GEN_SRVR_REQ = "openssl req -passin pass:{0} -new -key {1}/{2} -out {1}/{3} -batch";
   private static final String SIGN_SRVR_CRT = "openssl x509 -passin pass:{0} -req -days 365 -in {1}/{3} -signkey {1}/{2} -out {1}/{3} \n";
   private static final String EXPRT_KSTR = "openssl pkcs12 -export -in {1}/{3} -inkey {1}/{2} -certfile {1}/{3} -out {1}/{4} -password pass:{0} -passin pass:{0} \n";
-	
-  /**
+  private static final String SIGN_AGENT_CRT = "openssl ca -config {0}/ca.config -in {0}/{1} -out {0}/{2} -batch -passin pass:{3} -keyfile {0}/{4} -cert {0}/{5}"; /**
    * Verify that root certificate exists, generate it otherwise.
    */
   public void initRootCert() {
@@ -83,7 +82,7 @@ public class CertificateManager {
    * Runs os command
    */
   private void runCommand(String command) {
-	  
+	  LOG.info("Executing command:" + command);
 	  String line = null;
       Process process = null;
       try {
@@ -121,27 +120,15 @@ public class CertificateManager {
 			               srvrCrtName, kstrName};
 
     String command = MessageFormat.format(GEN_SRVR_KEY,scriptArgs);
-
-    LOG.info("Executing command:" + command);
-    
 	runCommand(command);
 	
     command = MessageFormat.format(GEN_SRVR_REQ,scriptArgs);
-    
-    LOG.info("Executing command:" + command);
-    
 	runCommand(command);
 	
     command = MessageFormat.format(SIGN_SRVR_CRT,scriptArgs);
-    
-    LOG.info("Executing command:" + command);
-    
 	runCommand(command);
 	
     command = MessageFormat.format(EXPRT_KSTR,scriptArgs);
-    
-    LOG.info("Executing command:" + command);
-    
 	runCommand(command);
 	
 	}
@@ -161,4 +148,62 @@ public class CertificateManager {
 	}   
     return srvrCrtContent;
 	}
+  
+  /**
+   * Signs agent certificate
+   * Adds agent certificate to server keystore
+   * @return string with agent signed certificate content
+   */
+  public String signAgentCrt(String agentHostname, String agentCrtReqContent, String passphraseAgent) {
+    LOG.info("Signing of agent certificate");
+    LOG.info("Verifying passphrase");
+    
+    
+    
+    String passphraseSrvr = configs.getConfigsMap().get(Configuration.PASSPHRASE_KEY);
+    
+    System.out.println(passphraseSrvr);
+    System.out.println(passphraseAgent);
+    
+    if (!passphraseAgent.equals(passphraseSrvr)) {
+      LOG.warn("Incorrect passphrase from agent");
+      return "";
+    }
+    
+    Map<String, String> configsMap = configs.getConfigsMap();
+    String srvrKstrDir = configsMap.get(Configuration.SRVR_KSTR_DIR_KEY);
+    String srvrCrtPass = configsMap.get(Configuration.SRVR_CRT_PASS_KEY);
+    String srvrCrtName = configsMap.get(Configuration.SRVR_CRT_NAME_KEY);
+    String srvrKeyName = configsMap.get(Configuration.SRVR_KEY_NAME_KEY);
+    String agentCrtReqName = agentHostname + ".csr";
+    String agentCrtName = agentHostname + ".crt";
+    
+    
+    File agentCrtReqFile = new File(srvrKstrDir + File.separator + agentCrtReqName);
+    try {
+		FileUtils.writeStringToFile(agentCrtReqFile, agentCrtReqContent);
+	} catch (IOException e1) {
+		// TODO Auto-generated catch block
+		e1.printStackTrace();
+	}
+    Object[] scriptArgs = {srvrKstrDir,agentCrtReqName,agentCrtName,
+    					   srvrCrtPass,srvrKeyName,srvrCrtName};
+
+    String command = MessageFormat.format(SIGN_AGENT_CRT,scriptArgs);
+    
+    LOG.error(command);
+    
+	runCommand(command);
+	
+	File agentCrtFile = new File(srvrKstrDir + File.separator + agentCrtName);
+	String agentCrtContent = "";
+	try {
+		agentCrtContent = FileUtils.readFileToString(agentCrtFile);
+	} catch (IOException e) {
+		e.printStackTrace();
+		LOG.error("Error reading signed agent certificate");
+	}
+    
+    return agentCrtContent;
+	}
 }

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/ClientSecurityType.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/ClientSecurityType.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/ClientSecurityType.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/ClientSecurityType.java Thu Sep 27 04:42:23 2012
@@ -1,3 +1,20 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.ambari.server.security;
 
 public enum ClientSecurityType {
@@ -9,13 +26,18 @@ public enum ClientSecurityType {
     this.value = value;
   }
 
+  /**
+   * Constructs enum object from string representation
+   * @param value string representation of client security type
+   * @return ClientSecurityType (defaults to LOCAL if not recognized)
+   */
   public static ClientSecurityType fromString(String value) {
     for (ClientSecurityType securityType : ClientSecurityType.values()) {
-      if (securityType.toString().equals(value)) {
+      if (securityType.toString().equalsIgnoreCase(value)) {
         return securityType;
       }
     }
-    return null;
+    return LOCAL;
   }
 
 

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SecurityFilter.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SecurityFilter.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SecurityFilter.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SecurityFilter.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,85 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements.  See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership.  The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License.  You may obtain a copy of the License at
+*
+*     http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+
+package org.apache.ambari.server.security;
+
+import java.io.IOException;
+import java.util.regex.Pattern;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.ambari.server.controller.AmbariServer;
+
+public class SecurityFilter implements Filter {
+	
+  //Allowed pathes for one way auth https
+  private static String CA = "/ca";
+
+  @Override
+  public void destroy() {
+  }
+
+  @Override
+  public void doFilter(ServletRequest serReq, ServletResponse serResp,
+		FilterChain filtCh) throws IOException, ServletException {
+
+    HttpServletRequest req = (HttpServletRequest) serReq;
+    String reqUrl = req.getRequestURL().toString();
+    
+    System.out.println("req url:" + reqUrl);
+    
+    //req.getC
+	
+    if (serReq.getLocalPort() == AmbariServer.CLIENT_ONE_WAY) {
+      if (isRequestAllowed(reqUrl))
+        filtCh.doFilter(serReq, serResp);
+      else
+        System.out.println("Such request is not allowed on this port");
+
+	}
+	else
+      filtCh.doFilter(serReq, serResp);
+  }
+
+  @Override
+  public void init(FilterConfig arg0) throws ServletException {
+  }
+
+  private boolean isRequestAllowed(String reqUrl) {
+	try {
+      boolean isMatch = Pattern.matches("https://[A-z]*:[0-9]*/cert/ca[/]*", reqUrl);
+		 
+      if (isMatch)
+    	  return true;
+		 
+		 isMatch = Pattern.matches("https://[A-z]*:[0-9]*/certs/[A-z0-9-]*", reqUrl);
+		 
+		 if (isMatch)
+			 return true;
+		
+	} catch (Exception e) {
+	}
+	return false;
+  }
+}
\ No newline at end of file

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignCertResponse.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignCertResponse.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignCertResponse.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignCertResponse.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.security;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+import org.apache.commons.logging.Log;
+
+
+
+/**
+ *
+ * Sign certificate response data model.
+ *
+ */
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "", propOrder = {})
+public class SignCertResponse {
+	
+  public static final String ERROR_STATUS = "ERROR";
+  public static final String OK_STATUS = "OK";
+
+  @XmlElement
+  private String result;
+  @XmlElement
+  private String signedCa;
+  
+  public String getResult() {
+    return result;
+  }
+  public void setResult(String result) {
+    this.result = result;
+  }
+  public String getSignedCa() {
+    return signedCa;
+  }
+  public void setSignedCa(String signedCa) {
+    this.signedCa = signedCa;
+  }
+}
+

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignMessage.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignMessage.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignMessage.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/SignMessage.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,56 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.security;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+
+
+/**
+ *
+ * Sign certificate request data model.
+ *
+ */
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlType(name = "", propOrder = {})
+public class SignMessage {
+
+  @XmlElement
+  private String csr;
+  @XmlElement
+  private String passphrase;
+  public String getCsr() {
+    return csr;
+  }
+  public void setCsr(String csr) {
+    this.csr = csr;
+  }
+  public String getPassphrase() {
+    return passphrase;
+  }
+  public void setPassphrase(String passphrase) {
+    this.passphrase = passphrase;
+  }
+}
+

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProvider.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProvider.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProvider.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProvider.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,135 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.security.authorization;
+
+import com.google.inject.Inject;
+import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.security.ClientSecurityType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
+import org.springframework.security.ldap.authentication.BindAuthenticator;
+import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
+import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
+
+
+/**
+ * Provides LDAP user authorization logic for Ambari Server
+ */
+public class AmbariLdapAuthenticationProvider implements AuthenticationProvider {
+  private static final Logger log = LoggerFactory.getLogger(AmbariLdapAuthenticationProvider.class);
+
+  Configuration configuration;
+
+  private AmbariLdapAuthoritiesPopulator authoritiesPopulator;
+
+  private ThreadLocal<LdapServerProperties> ldapServerProperties = new ThreadLocal<LdapServerProperties>();
+  private ThreadLocal<LdapAuthenticationProvider> providerThreadLocal = new ThreadLocal<LdapAuthenticationProvider>();
+
+  @Inject
+  public AmbariLdapAuthenticationProvider(Configuration configuration, AmbariLdapAuthoritiesPopulator authoritiesPopulator) {
+    this.configuration = configuration;
+    this.authoritiesPopulator = authoritiesPopulator;
+  }
+
+  @Override
+  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+
+    if (isLdapEnabled()) {
+
+      return loadLdapAuthenticationProvider().authenticate(authentication);
+
+    } else {
+      throw new UsernameNotFoundException("LDAP authorization is not enabled");
+    }
+
+  }
+
+  @Override
+  public boolean supports(Class<?> authentication) {
+    return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
+  }
+
+  /**
+   * Reloads LDAP Context Source and depending objects if properties were changed
+   * @return corresponding LDAP authentication provider
+   */
+  private LdapAuthenticationProvider loadLdapAuthenticationProvider() {
+    if (reloadLdapServerProperties()) {
+      log.info("LDAP Properties changed - rebuilding Context");
+      DefaultSpringSecurityContextSource springSecurityContextSource =
+              new DefaultSpringSecurityContextSource(ldapServerProperties.get().getLdapUrls(), ldapServerProperties.get().getBaseDN());
+
+      if (!ldapServerProperties.get().isAnonymousBind()) {
+        springSecurityContextSource.setUserDn(ldapServerProperties.get().getManagerDn());
+        springSecurityContextSource.setPassword(ldapServerProperties.get().getManagerPassword());
+      }
+
+      try {
+        springSecurityContextSource.afterPropertiesSet();
+      } catch (Exception e) {
+        log.error("LDAP Context Source not loaded ", e);
+        throw new UsernameNotFoundException("LDAP Context Source not loaded", e);
+      }
+
+      //TODO change properties
+      String userSearchBase = ldapServerProperties.get().getUserSearchBase();
+      String userSearchFilter = ldapServerProperties.get().getUserSearchFilter();
+
+      FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(userSearchBase, userSearchFilter, springSecurityContextSource);
+
+      BindAuthenticator bindAuthenticator = new BindAuthenticator(springSecurityContextSource);
+      bindAuthenticator.setUserSearch(userSearch);
+
+      LdapAuthenticationProvider authenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, authoritiesPopulator);
+
+      providerThreadLocal.set(authenticationProvider);
+    }
+
+    return providerThreadLocal.get();
+  }
+
+
+  /**
+   * Check if LDAP authentication is enabled in server properties
+   * @return true if enabled
+   */
+  private boolean isLdapEnabled() {
+    return configuration.getClientSecurityType() == ClientSecurityType.LDAP;
+  }
+
+  /**
+   * Reloads LDAP Server properties from configuration
+   *
+   * @return true if properties were reloaded
+   */
+  private boolean reloadLdapServerProperties() {
+    LdapServerProperties properties = configuration.getLdapServerProperties();
+    if (!properties.equals(ldapServerProperties.get())) {
+      log.info("Reloading properties");
+      ldapServerProperties.set(properties);
+      return true;
+    }
+    return false;
+  }
+}

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.security.authorization;
+
+import com.google.inject.Inject;
+import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.orm.dao.RoleDAO;
+import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.RoleEntity;
+import org.apache.ambari.server.orm.entities.UserEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.ldap.core.DirContextOperations;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
+
+import javax.persistence.NoResultException;
+import java.util.Collection;
+
+/**
+ * Provides authorities population for LDAP user from local DB
+ */
+public class AmbariLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
+  private static final Logger log = LoggerFactory.getLogger(AmbariLdapAuthoritiesPopulator.class);
+
+  Configuration configuration;
+  private AuthorizationHelper authorizationHelper;
+  UserDAO userDAO;
+  RoleDAO roleDAO;
+
+  @Inject
+  public AmbariLdapAuthoritiesPopulator(Configuration configuration, AuthorizationHelper authorizationHelper,
+                                        UserDAO userDAO, RoleDAO roleDAO) {
+    this.configuration = configuration;
+    this.authorizationHelper = authorizationHelper;
+    this.userDAO = userDAO;
+    this.roleDAO = roleDAO;
+  }
+
+  @Override
+  @Transactional
+  public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
+    log.info("Get roles for user " + username + " from local DB");
+
+    UserEntity user = null;
+
+    user = userDAO.findLdapUserByName(username);
+
+    if (user == null) {
+      log.info("User " + username + " not present in local DB - creating");
+
+      UserEntity newUser = new UserEntity();
+      newUser.setLdapUser(true);
+      newUser.setUserName(username);
+
+      String roleName = (configuration.getConfigsMap().get(Configuration.LDAP_USER_DEFAULT_ROLE_KEY));
+      log.info("Using default role name " + roleName);
+
+      RoleEntity role = roleDAO.findByName(roleName);
+
+      if (role == null) {
+        log.info("Role " + roleName + " not present in local DB - creating");
+        role = new RoleEntity();
+        role.setRoleName(roleName);
+        roleDAO.create(role);
+        role = roleDAO.findByName(role.getRoleName());
+      }
+
+      userDAO.create(newUser);
+
+      user = userDAO.findLdapUserByName(newUser.getUserName());
+
+      user.getRoleEntities().add(role);
+      role.getUserEntities().add(user);
+      roleDAO.merge(role);
+      userDAO.merge(user);
+    }
+
+    return authorizationHelper.convertRolesToAuthorities(user.getRoleEntities());
+  }
+}

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.security.authorization;
+
+import com.google.inject.Inject;
+import com.google.inject.Injector;
+import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.orm.dao.RoleDAO;
+import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.RoleEntity;
+import org.apache.ambari.server.orm.entities.UserEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.security.ldap.userdetails.LdapUserDetailsService;
+
+import javax.persistence.NoResultException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class AmbariLocalUserDetailsService implements UserDetailsService {
+  private static final Logger log = LoggerFactory.getLogger(AmbariLocalUserDetailsService.class);
+
+  Injector injector;
+  Configuration configuration;
+  private AuthorizationHelper authorizationHelper;
+  UserDAO userDAO;
+  RoleDAO roleDAO;
+
+  @Inject
+  public AmbariLocalUserDetailsService(Injector injector, Configuration configuration,
+                                       AuthorizationHelper authorizationHelper, UserDAO userDAO, RoleDAO roleDAO) {
+    this.injector = injector;
+    this.configuration = configuration;
+    this.authorizationHelper = authorizationHelper;
+    this.userDAO = userDAO;
+    this.roleDAO = roleDAO;
+  }
+
+  /**
+   * Loads Spring Security UserDetails from identity storage according to Configuration
+   *
+   * @param username username
+   * @return UserDetails
+   * @throws UsernameNotFoundException when user not found or have empty roles
+   */
+  @Override
+  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
+    log.info("Loading user by name: " + username);
+
+    UserEntity user = userDAO.findLocalUserByName(username);
+
+    if (user == null) {
+      log.info("user not found ");
+      throw new UsernameNotFoundException("Username " + username + " not found");
+    } else if (user.getRoleEntities().isEmpty()) {
+      log.info("No authorities for user");
+      throw new UsernameNotFoundException("Username " + username + " has no roles");
+    }
+
+    return new User(user.getUserName(), user.getUserPassword(),
+            authorizationHelper.convertRolesToAuthorities(user.getRoleEntities()));
+  }
+
+}

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.security.authorization;
+
+import com.google.inject.Singleton;
+import org.apache.ambari.server.orm.entities.RoleEntity;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Set;
+
+@Singleton
+/**
+ * Provides utility methods for authentication functionality
+ */
+public class AuthorizationHelper {
+
+  /**
+   * Converts collection of RoleEntities to collection of GrantedAuthorities
+   */
+  public Collection<GrantedAuthority> convertRolesToAuthorities(Collection<RoleEntity> roleEntities) {
+    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(roleEntities.size());
+
+    for (RoleEntity roleEntity : roleEntities) {
+      authorities.add(new SimpleGrantedAuthority(roleEntity.getRoleName().toUpperCase()));
+    }
+
+    return authorities;
+  }
+}

Added: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/LdapServerProperties.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/LdapServerProperties.java?rev=1390838&view=auto
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/LdapServerProperties.java (added)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/LdapServerProperties.java Thu Sep 27 04:42:23 2012
@@ -0,0 +1,171 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.security.authorization;
+
+import org.apache.commons.lang.StringUtils;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Describes LDAP Server connection parameters
+ */
+public class LdapServerProperties {
+
+  private String primaryUrl;
+  private String secondaryUrl;
+  private boolean useSsl;
+  private boolean anonymousBind;
+  private String managerDn;
+  private String managerPassword;
+  private String baseDN;
+  private String userSearchBase = "";
+  private String usernameAttribute;
+
+  private static final String userSearchFilter = "({attribute}={0})";
+
+  public List<String> getLdapUrls() {
+    String protocol = useSsl ? "ldaps://" : "ldap://";
+
+    if (StringUtils.isEmpty(primaryUrl)) {
+      return Collections.emptyList();
+    } else {
+      List<String> list = new ArrayList<String>();
+      list.add(protocol + primaryUrl);
+      if (!StringUtils.isEmpty(secondaryUrl)) {
+        list.add(protocol + secondaryUrl);
+      }
+      return list;
+    }
+  }
+
+  public String getPrimaryUrl() {
+    return primaryUrl;
+  }
+
+  public void setPrimaryUrl(String primaryUrl) {
+    this.primaryUrl = primaryUrl;
+  }
+
+  public String getSecondaryUrl() {
+    return secondaryUrl;
+  }
+
+  public void setSecondaryUrl(String secondaryUrl) {
+    this.secondaryUrl = secondaryUrl;
+  }
+
+  public boolean isUseSsl() {
+    return useSsl;
+  }
+
+  public void setUseSsl(boolean useSsl) {
+    this.useSsl = useSsl;
+  }
+
+  public boolean isAnonymousBind() {
+    return anonymousBind;
+  }
+
+  public void setAnonymousBind(boolean anonymousBind) {
+    this.anonymousBind = anonymousBind;
+  }
+
+  public String getManagerDn() {
+    return managerDn;
+  }
+
+  public void setManagerDn(String managerDn) {
+    this.managerDn = managerDn;
+  }
+
+  public String getManagerPassword() {
+    return managerPassword;
+  }
+
+  public void setManagerPassword(String managerPassword) {
+    this.managerPassword = managerPassword;
+  }
+
+  public String getBaseDN() {
+    return baseDN;
+  }
+
+  public void setBaseDN(String baseDN) {
+    this.baseDN = baseDN;
+  }
+
+  public String getUserSearchBase() {
+    return userSearchBase;
+  }
+
+  public void setUserSearchBase(String userSearchBase) {
+    this.userSearchBase = userSearchBase;
+  }
+
+  public String getUserSearchFilter() {
+    return userSearchFilter.replace("{attribute}", usernameAttribute);
+  }
+
+  public String getUsernameAttribute() {
+    return usernameAttribute;
+  }
+
+  public void setUsernameAttribute(String usernameAttribute) {
+    this.usernameAttribute = usernameAttribute;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) return true;
+    if (obj == null || getClass() != obj.getClass()) return false;
+
+    LdapServerProperties that = (LdapServerProperties) obj;
+
+    if (primaryUrl != null ? !primaryUrl.equals(that.primaryUrl) : that.primaryUrl != null) return false;
+    if (secondaryUrl != null ? !secondaryUrl.equals(that.secondaryUrl) : that.secondaryUrl != null) return false;
+    if (useSsl!=that.useSsl) return false;
+    if (anonymousBind!=that.anonymousBind) return false;
+    if (managerDn != null ? !managerDn.equals(that.managerDn) : that.managerDn != null) return false;
+    if (managerPassword != null ? !managerPassword.equals(that.managerPassword) : that.managerPassword != null)
+      return false;
+    if (baseDN != null ? !baseDN.equals(that.baseDN) : that.baseDN != null) return false;
+    if (userSearchBase != null ? !userSearchBase.equals(that.userSearchBase) : that.userSearchBase != null)
+      return false;
+    if (usernameAttribute != null ? !usernameAttribute.equals(that.usernameAttribute) : that.usernameAttribute != null)
+      return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    int result = primaryUrl != null ? primaryUrl.hashCode() : 0;
+    result = 31 * result + (secondaryUrl != null ? secondaryUrl.hashCode() : 0);
+    result = 31 * result + (useSsl ? 1 : 0);
+    result = 31 * result + (anonymousBind ? 1 : 0);
+    result = 31 * result + (managerDn != null ? managerDn.hashCode() : 0);
+    result = 31 * result + (managerPassword != null ? managerPassword.hashCode() : 0);
+    result = 31 * result + (baseDN != null ? baseDN.hashCode() : 0);
+    result = 31 * result + (userSearchBase != null ? userSearchBase.hashCode() : 0);
+    result = 31 * result + (usernameAttribute != null ? usernameAttribute.hashCode() : 0);
+    return result;
+  }
+
+}

Modified: incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/unsecured/rest/CertificateDownload.java
URL: http://svn.apache.org/viewvc/incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/unsecured/rest/CertificateDownload.java?rev=1390838&r1=1390837&r2=1390838&view=diff
==============================================================================
--- incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/unsecured/rest/CertificateDownload.java (original)
+++ incubator/ambari/branches/AMBARI-666/ambari-server/src/main/java/org/apache/ambari/server/security/unsecured/rest/CertificateDownload.java Thu Sep 27 04:42:23 2012
@@ -44,4 +44,6 @@ public class CertificateDownload {
   public String downloadSrvrCrt() {
     return certMan.getServerCert();
   }
+  
+  
 }



Mime
View raw message