summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java
blob: da2a3ccbd69c26a6655691aa1f2c3a55d880be29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2010 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.csadmin;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;

import netscape.ldap.LDAPAttribute;
import netscape.ldap.LDAPAttributeSet;
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPEntry;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPSearchResults;
import netscape.ldap.LDAPv2;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISecurityDomainSessionTable;
import com.netscape.cmsutil.password.IPasswordStore;

/**
 * This object stores the values for IP, uid and group based on the cookie id in LDAP.
 * Entries are stored under ou=Security Domain, ou=sessions, $basedn
 */
public class LDAPSecurityDomainSessionTable 
  implements ISecurityDomainSessionTable {

    private long m_timeToLive;

    public LDAPSecurityDomainSessionTable(long timeToLive) {
        m_timeToLive = timeToLive;
    }

    public int addEntry(String sessionId, String ip, 
      String uid, String group) {
        IConfigStore cs = CMS.getConfigStore();
        LDAPConnection conn = null;
        boolean sessions_exists = true;
        int status = FAILURE;

        String basedn = null;
        String sessionsdn = null;
        try {
            basedn = cs.getString("internaldb.basedn");
            sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: addEntry: failed to read basedn" + e);
            return status;
        }

        try {
            // create session entry (if it does not exist)
            conn = getLDAPConn();

            LDAPEntry entry = null;
            LDAPAttributeSet attrs = null;
            attrs = new LDAPAttributeSet();
            attrs.add(new LDAPAttribute("objectclass", "top"));
            attrs.add(new LDAPAttribute("objectclass", "organizationalUnit"));
            attrs.add(new LDAPAttribute("ou", "sessions"));
            entry = new LDAPEntry(sessionsdn, attrs);
            conn.add(entry);
         } catch (Exception e) {
            if ((e instanceof LDAPException) && (((LDAPException) e).getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS)) {
                // continue
            } else {
                CMS.debug("SecurityDomainSessionTable: unable to create ou=sessions:" + e);
                sessions_exists = false;
            }
         }

        // add new entry
        try {
            LDAPEntry entry = null;
            LDAPAttributeSet attrs = null;
            String entrydn = "cn=" + sessionId + "," + sessionsdn;
            attrs = new LDAPAttributeSet();
            attrs.add(new LDAPAttribute("objectclass", "top"));
            attrs.add(new LDAPAttribute("objectclass", "securityDomainSessionEntry"));
            attrs.add(new LDAPAttribute("cn", sessionId));
            attrs.add(new LDAPAttribute("host", ip));
            attrs.add(new LDAPAttribute("uid", uid));
            attrs.add(new LDAPAttribute("cmsUserGroup", group));
            attrs.add(new LDAPAttribute("dateOfCreate", Long.toString((new Date()).getTime())));

            entry = new LDAPEntry(entrydn, attrs);
            if (sessions_exists) {
                conn.add(entry);
                CMS.debug("SecurityDomainSessionTable: added session entry" + sessionId);
                status = SUCCESS;
            }
        } catch(Exception e) {
            CMS.debug("SecurityDomainSessionTable: unable to create session entry" + sessionId + ": " + e);
        } 

        try {
            conn.disconnect();
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable:addEntry: Error in disconnecting from database: " + e);
        }
        return status;
    }

    public int removeEntry(String sessionId) {
        IConfigStore cs = CMS.getConfigStore();
        LDAPConnection conn = null;
        int status = FAILURE;
        try {
            String basedn = cs.getString("internaldb.basedn");
            String dn = "cn=" + sessionId + ",ou=sessions,ou=Security Domain," + basedn;
            conn = getLDAPConn();
            conn.delete(dn);
            status = SUCCESS;
        } catch (Exception e) {
            if ((e instanceof LDAPException) && (((LDAPException) e).getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT)) {
                // continue
            } else {
                CMS.debug("SecurityDomainSessionTable: unable to delete session " + sessionId + ": " + e);
            }
        }
        try {
            conn.disconnect();
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: removeEntry: Error in disconnecting from database: " + e);
        }
        return status;
    }

    public boolean isSessionIdExist(String sessionId) {
        IConfigStore cs = CMS.getConfigStore();
        LDAPConnection conn = null;
        boolean ret = false;
        try {
            String basedn = cs.getString("internaldb.basedn");
            String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
            String filter = "(cn=" + sessionId + ")";
            String[] attrs = { "cn" };

            conn = getLDAPConn();
            LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
            if (res.getCount() > 0) ret = true;
        } catch(Exception e) {
            CMS.debug("SecurityDomainSessionTable: unable to query session " + sessionId + ": " + e);
        }

        try {
            conn.disconnect();
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: isSessionIdExist: Error in disconnecting from database: " + e);
        }
        return ret;
    }


    public Enumeration getSessionIds() {
        IConfigStore cs = CMS.getConfigStore();
        LDAPConnection conn = null;
        Vector ret = new Vector();

        try {
            String basedn = cs.getString("internaldb.basedn");
            String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
            String filter = "(objectclass=securityDomainSessionEntry)";
            String[] attrs = { "cn" };

            conn = getLDAPConn();
            LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
            while (res.hasMoreElements()) {
                LDAPEntry entry = res.next();
                ret.add(entry.getAttribute("cn").getStringValueArray()[0]);
            }
        } catch (LDAPException e) {
            switch (e.getLDAPResultCode()) {
                case LDAPException.NO_SUCH_OBJECT:
                    CMS.debug("SecurityDomainSessionTable: getSessionIds():  no sessions have been created");
                    break;
                default:
                    CMS.debug("SecurityDomainSessionTable: unable to query sessionIds due to ldap exception: " + e);
            }
        } catch(Exception e) {
            CMS.debug("SecurityDomainSessionTable: unable to query sessionIds: " + e);
        }

        try {
            conn.disconnect();
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: getSessionIds: Error in disconnecting from database: " + e);
        }

        return ret.elements();
    }

    private String getStringValue(String sessionId, String attr) {
        IConfigStore cs = CMS.getConfigStore();
        LDAPConnection conn = null;
        String ret = null;
        try { 
            String basedn = cs.getString("internaldb.basedn");
            String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
            String filter = "(cn=" + sessionId + ")";
            String[] attrs = { attr };
            conn = getLDAPConn();
            LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
            if (res.getCount() > 0) { 
                LDAPEntry entry = res.next();
                ret = entry.getAttribute(attr).getStringValueArray()[0];
            }
        } catch(Exception e) {
            CMS.debug("SecurityDomainSessionTable: unable to query session " + sessionId + ": " + e);
        }

        try {
            conn.disconnect();
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: isSessionIdExist: Error in disconnecting from database: " + e);
        }
        return ret;
    }

    public String getIP(String sessionId) {
        return getStringValue(sessionId, "host");
    }

    public String getUID(String sessionId) {
        return getStringValue(sessionId, "uid");
    }

    public String getGroup(String sessionId) {
        return getStringValue(sessionId, "cmsUserGroup");
    }

    public long getBeginTime(String sessionId) {
        String beginStr = getStringValue(sessionId, "dateOfCreate");
        if (beginStr != null) {
            return Long.parseLong(beginStr);
        }
        return -1;
    }

    public long getTimeToLive() {
        return m_timeToLive;
    }

    public int getSize() {
        IConfigStore cs = CMS.getConfigStore();
        LDAPConnection conn = null;
        int ret =0;

        try {
            String basedn = cs.getString("internaldb.basedn");
            String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
            String filter = "(objectclass=securityDomainSessionEntry)";
            String[] attrs = { "cn" };

            conn = getLDAPConn();
            LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
            ret = res.getCount();
        } catch(Exception e) {
            CMS.debug("SecurityDomainSessionTable: unable to query sessionIds: " + e);
        }

        try {
            conn.disconnect();
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: getSessionIds: Error in disconnecting from database: " + e);
        }

        return ret;
    }

    private LDAPConnection getLDAPConn()
            throws IOException
    {
        IConfigStore cs = CMS.getConfigStore();

        String host = "";
        String port = "";
        String pwd = null;
        String binddn = "";
        String security = "";

        IPasswordStore pwdStore = CMS.getPasswordStore();

        if (pwdStore != null) {
            //CMS.debug("SecurityDomainSessionTable: getLDAPConn: password store available");
            pwd = pwdStore.getPassword("internaldb");
        }

        if ( pwd == null) {
           throw new IOException("SecurityDomainSessionTable: Failed to obtain password from password store");
        }

        try {
            host = cs.getString("internaldb.ldapconn.host");
            port = cs.getString("internaldb.ldapconn.port");
            binddn = cs.getString("internaldb.ldapauth.bindDN");
            security = cs.getString("internaldb.ldapconn.secureConn");
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable: getLDAPConn" + e.toString());
            throw new IOException(
                    "Failed to retrieve LDAP information from CS.cfg.");
        }

        int p = -1;

        try {
            p = Integer.parseInt(port);
        } catch (Exception e) {
            CMS.debug("SecurityDomainSessionTable getLDAPConn: " + e.toString());
            throw new IOException("Port is not valid");
        }

        LDAPConnection conn = null;
        if (security.equals("true")) {
          //CMS.debug("SecurityDomainSessionTable getLDAPConn: creating secure (SSL) connection for internal ldap");
          conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
        } else {
          //CMS.debug("SecurityDomainSessionTable getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
          conn = new LDAPConnection();
        }

        //CMS.debug("SecurityDomainSessionTable connecting to " + host + ":" + p);
        try {
            conn.connect(host, p, binddn, pwd);
        } catch (LDAPException e) {
            CMS.debug("SecurityDomainSessionTable getLDAPConn: " + e.toString());
            throw new IOException("Failed to connect to the internal database.");
        }

        return conn;
    }

}