Project

General

Profile

1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package eu.dnetlib.espas.pep;
7

    
8
import java.io.File;
9
import java.io.FileOutputStream;
10
import java.rmi.RemoteException;
11
import java.util.Collection;
12
import javax.xml.namespace.QName;
13
import javax.xml.stream.XMLStreamException;
14
import org.apache.axiom.om.OMElement;
15
import org.apache.axiom.om.OMText;
16
import org.apache.axiom.om.impl.llom.util.AXIOMUtil;
17
import org.apache.axis2.client.Options;
18
import org.apache.axis2.client.ServiceClient;
19
import org.apache.axis2.context.ConfigurationContext;
20
import org.apache.axis2.context.ConfigurationContextFactory;
21
import org.apache.axis2.transport.http.HTTPConstants;
22
import org.apache.axis2.transport.http.HttpTransportProperties;
23
import org.apache.commons.io.IOUtils;
24
import org.apache.log4j.Logger;
25
import org.springframework.core.io.Resource;
26
import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceException;
27
import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub;
28

    
29
/**
30
 * The AuthenticationPEP implements a policy enforcement point that is used primarily by the DownloaManager to facilitate the authentication of requested download activities. Submitted requests are
31
 * evaluated against the policies maintained by the ESPAS policy registry and evaluation outcomes are used for checking whether specified actions are permitted or not by the Data Providers. The
32
 * provided implementation is thread safe.
33
 *
34
 * @author gathanas
35
 */
36
public class AuthenticationPEP {
37

    
38
    private static final Logger _logger = Logger.getLogger(AuthenticationPEP.class);
39

    
40
    private EntitlementServiceStub entServiceStub;
41

    
42
    private Resource trustStore = null;
43
    private String trustStorePassword = null;
44
    private String serverUsername = null;
45
    private String serverPassword = null;
46
    private String serverUrl = null;
47
    private long connectionTimeout = 0;
48

    
49
    public void initEntitlementService() throws Exception {
50
        File tempFile = File.createTempFile("trs", null);
51
        FileOutputStream fos = new FileOutputStream(tempFile);
52
        tempFile.deleteOnExit();
53

    
54
        IOUtils.copy(this.trustStore.getInputStream(), fos);
55
        fos.close();
56

    
57
        System.setProperty("javax.net.ssl.trustStore", tempFile.getCanonicalPath());
58
        System.setProperty("javax.net.ssl.trustStorePassword", this.trustStorePassword);
59

    
60
        ConfigurationContext confContx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
61

    
62
        HttpTransportProperties.Authenticator httpAuthenticator = new HttpTransportProperties.Authenticator();
63
        httpAuthenticator.setUsername(this.serverUsername);
64
        httpAuthenticator.setPassword(this.serverPassword);
65

    
66
        entServiceStub = new EntitlementServiceStub(confContx, this.serverUrl);
67
        ServiceClient srv2client = entServiceStub._getServiceClient();
68
        Options _options = srv2client.getOptions();
69

    
70
        _options.setManageSession(true);
71
        _options.setProperty(HTTPConstants.COOKIE_STRING, null);
72
        _options.setProperty(HTTPConstants.AUTHENTICATE, httpAuthenticator);
73
        _options.setManageSession(true);
74
        _options.setTimeOutInMilliSeconds(this.connectionTimeout);
75
        srv2client.setOptions(_options);
76

    
77
        _logger.info("Entitlement service initialized succesfully");
78
    }
79

    
80
    /**
81
     * Checks the conformance of a list of requested objects against the specified policies and returns a list of corresponding responses.
82
     *
83
     */
84
    public synchronized PEPResponseMap isPermitedRequest(Collection<String> requestedObs, String userId, String actionName, String[] environment) throws RemoteException {
85
        _logger.info("Evaluating request for [" + requestedObs.size() + ", " + userId + ", " + actionName + "]");
86
        PEPResponseMap responseMap = new PEPResponseMap();
87
        if (entServiceStub != null)
88
            for (String requestedResource : requestedObs)
89
                try {
90
                    String getDecisionOutcome = entServiceStub.getDecisionByAttributes(userId, requestedResource, actionName, environment);
91
                    _logger.trace("Evaluation of [" + requestedObs.size() + ", " + userId + ", " + actionName + "] returned :" + getDecisionOutcome);
92
                    String[] pepRespopnse = this.getPDPResults(getDecisionOutcome);
93
                    PEPResponse pepResponse = new PEPResponse(requestedResource, pepRespopnse[1], pepRespopnse[0].contains("Permit") ? true : false);
94
                    responseMap.addResponse(requestedResource, pepResponse);
95
                } catch (XMLStreamException ex) {
96
                    _logger.error(null, ex);
97
                    continue;
98
                } catch (EntitlementServiceException ex) {
99
                    _logger.error(null, ex);
100
                    continue;
101
                } catch (Exception ex) {
102
                    _logger.error(null, ex);
103
                    continue;
104
                }
105
        return responseMap;
106
    }
107

    
108
    public synchronized boolean isPermitedRequest(String requestedOb, String userId, String actionName, String[] environment) throws RemoteException, EntitlementServiceException, Exception {
109
        _logger.info("Evaluating request for [" + requestedOb + ", " + userId + ", " + actionName + "]");
110
        if (entServiceStub != null) {
111
            String outcome = entServiceStub.getDecisionByAttributes(userId, requestedOb, actionName, environment);
112
            _logger.info("Evaluation of [" + requestedOb + ", " + userId + ", " + actionName + "] returned :" + outcome);
113
            return outcome.contains("Permit") ? true : false;
114
        }
115
        return false;
116
    }
117

    
118
    public synchronized boolean isPermitedRequest(String request) throws RemoteException, EntitlementServiceException, Exception {
119

    
120
        _logger.info("Evaluating request " + request);
121
        if (entServiceStub != null) {
122
            String outcome = entServiceStub.getDecision(request);
123
            _logger.info("Evaluation of [" + request + "] returned :" + outcome);
124
//            XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(outcome));
125
            return outcome.contains("Permit") ? true : false;
126
        }
127
        return false;
128
    }
129

    
130
    public Resource getTrustStore() {
131
        return trustStore;
132
    }
133

    
134
    public void setTrustStore(Resource trustStore) {
135
        this.trustStore = trustStore;
136
    }
137

    
138
    public String getTrustStorePassword() {
139
        return trustStorePassword;
140
    }
141

    
142
    public void setTrustStorePassword(String trustStorePassword) {
143
        this.trustStorePassword = trustStorePassword;
144
    }
145

    
146
    public String getServerUsername() {
147
        return serverUsername;
148
    }
149

    
150
    public void setServerUsername(String serverUsername) {
151
        this.serverUsername = serverUsername;
152
    }
153

    
154
    public String getServerPassword() {
155
        return serverPassword;
156
    }
157

    
158
    public void setServerPassword(String serverPassword) {
159
        this.serverPassword = serverPassword;
160
    }
161

    
162
    public String getServerUrl() {
163
        return serverUrl;
164
    }
165

    
166
    public void setServerUrl(String serverUrl) {
167
        this.serverUrl = serverUrl;
168
    }
169

    
170
    public long getConnectionTimeout() {
171
        return connectionTimeout;
172
    }
173

    
174
    public void setConnectionTimeout(long connectionTimeout) {
175
        this.connectionTimeout = connectionTimeout;
176
    }
177
    
178
    
179
   /* Parses the PDP response and extracts the returned values
180
     */
181
    protected String[] getPDPResults(String response) throws XMLStreamException{
182
        String[] resultMsg = new String[2];
183
        OMElement omElement= AXIOMUtil.stringToOM(response);
184
        if(omElement!=null && omElement.getChildElements().hasNext()){
185
//            retrieve decision value
186
            OMElement resultOM = ((OMElement)omElement.getFirstChildWithName(new QName("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17","Result")));
187
            
188
            OMElement decisionOM=resultOM.getFirstChildWithName(new QName("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17","Decision"));
189
            resultMsg[0] = decisionOM!=null?((OMText)decisionOM.getFirstOMChild()).getText():"";
190
//            retrieve first advice msg
191
            OMElement advice = (OMElement)resultOM.getFirstChildWithName(new QName("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17","AssociatedAdvice"));
192
            if(advice!=null){
193
                OMElement attributeAssignOM = (OMElement)advice.getFirstElement().getFirstChildWithName(new QName("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17","AttributeAssignment"));
194
                resultMsg[1]=attributeAssignOM!=null?((OMText)attributeAssignOM.getFirstOMChild()).getText():"";
195
            }
196
            else
197
                resultMsg[1]="";
198
           }
199
        return resultMsg;
200
    }
201

    
202
}
(1-1/3)