summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
blob: 4142f6abe02db0193111f37ba99f3608a59d1be9 (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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// --- 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) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmscore.security;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.CryptoManager.NotInitializedException;
import org.mozilla.jss.SecretDecoderRing.Decryptor;
import org.mozilla.jss.SecretDecoderRing.Encryptor;
import org.mozilla.jss.SecretDecoderRing.KeyManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.TokenException;
import org.mozilla.jss.util.Base64OutputStream;
import org.mozilla.jss.util.Password;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.cmsutil.util.Utils;

/* 
 * A class for managing passwords in the SDR password cache
 *
 * @author Christina Fu
 * @version $Revision$, $Date$
 */
public class PWsdrCache {
    public static final String PROP_PWC_TOKEN_NAME = "pwcTokenname";
    public static final String PROP_PWC_KEY_ID = "pwcKeyid";
    public static final String PROP_PWC_NICKNAME = "sso_key";

    private ILogger mLogger = null;
    private String mPWcachedb = null;
    // mTool tells if this is called from the PasswordCache tool
    private boolean mIsTool = false;
    private byte[] mKeyID = null;
    private String mTokenName = null;
    private CryptoToken mToken = null;

    // for CMSEngine
    public PWsdrCache() throws EBaseException {
        mLogger = CMS.getLogger();
        try {
            mPWcachedb = CMS.getConfigStore().getString("pwCache");
            CMS.debug("got pwCache file path from configstore");
        } catch (Exception e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_GET_CONFIG"));
            // let it fall through
        }
        initToken();
        initKey();
    }

    private void initToken() throws EBaseException {
        if (mToken == null) {
            CryptoManager cm = null;
            try {
                cm = CryptoManager.getInstance();
                mTokenName = CMS.getConfigStore().getString(PROP_PWC_TOKEN_NAME);
                log(ILogger.LL_DEBUG, "pwcTokenname specified.  Use token for SDR key. tokenname= " + mTokenName);
                mToken = cm.getTokenByName(mTokenName);
            } catch (NotInitializedException e) {
                log(ILogger.LL_FAILURE, e.toString());
                throw new EBaseException(e.toString());
            } catch (Exception e) {
                log(ILogger.LL_DEBUG, "no pwcTokenname specified, use internal token for SDR key");
                mToken = cm.getInternalKeyStorageToken();
            }
        }
    }

    // called from PWCBsdr or CMSEngine only
    private void initKey() throws EBaseException {
        if (mKeyID == null) {
            try {
                String keyID = CMS.getConfigStore().getString(PROP_PWC_KEY_ID);
                log(ILogger.LL_DEBUG, "retrieved PWC SDR key");
                mKeyID = base64Decode(keyID);

            } catch (Exception e) {
                log(ILogger.LL_DEBUG, "no pwcSDRKey specified");
                throw new EBaseException(e.toString());
            }
        }
    }

    // for PasswordCache tool (isTool == true)
    // and installation wizard (isTool == false)
    // Do not use for PWCBsdr, since we don't want to mistakenly
    // generate SDR keys in case of configuration errors
    public PWsdrCache(String pwCache, String pwcTokenname, byte[] keyId,
                      boolean isTool) throws Exception {
        mPWcachedb = pwCache;
        mIsTool = isTool;
        mTokenName = pwcTokenname;
        CryptoManager cm = null;

        if (keyId != null) {
            mKeyID = keyId;
        }

        cm = CryptoManager.getInstance();
        if (mTokenName != null) {
            mToken = cm.getTokenByName(mTokenName);
            mToken = cm.getInternalKeyStorageToken();
            debug("PWsdrCache: mToken = " + mTokenName);
        } else {
            mToken = cm.getInternalKeyStorageToken();
            debug("PWsdrCache: mToken = internal");
        }
    }

    public byte[] getKeyId() {
        return mKeyID;
    }

    public String getTokenName() {
        return mTokenName;
    }

    public void deleteUniqueNamedKey(String nickName)
            throws Exception {
        KeyManager km = new KeyManager(mToken);
        km.deleteUniqueNamedKey(nickName);
    }

    public byte[] generateSDRKey() throws Exception {
        return generateSDRKeyWithNickName(PROP_PWC_NICKNAME);
    }

    public byte[] generateSDRKeyWithNickName(String nickName)
            throws Exception {
        try {

            if (mIsTool != true) {
                // generate SDR key
                KeyManager km = new KeyManager(mToken);
                try {
                    // Bugscape Bug #54838:  Due to the CMS cloning feature,
                    //                       we must check for the presence of
                    //                       a uniquely named symmetric key
                    //                       prior to making an attempt to
                    //                       generate it!
                    //
                    if (!(km.uniqueNamedKeyExists(nickName))) {
                        mKeyID = km.generateUniqueNamedKey(nickName);
                    }
                } catch (TokenException e) {
                    log(0, "generateSDRKey() failed on " + e.toString());
                    throw e;
                }
            }
        } catch (Exception e) {
            log(ILogger.LL_FAILURE, e.toString());
            throw e;
        }
        return mKeyID;
    }

    public byte[] base64Decode(String s) throws IOException {
        byte[] d = com.netscape.osutil.OSUtil.AtoB(s);
        return d;
    }

    public static String base64Encode(byte[] bytes) throws IOException {
        // All this streaming is lame, but Base64OutputStream needs a
        // PrintStream
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(new
                PrintStream(new
                        FilterOutputStream(output)
                )
                );

        b64.write(bytes);
        b64.flush();

        // This is internationally safe because Base64 chars are
        // contained within 8859_1
        return output.toString("8859_1");
    }

    // for PWCBsdr
    public PWsdrCache(String pwCache, ILogger logger) throws
            EBaseException {
        mLogger = logger;
        mPWcachedb = pwCache;
        initToken();
        initKey();
    }

    public void addEntry(String tag, String pwd) throws EBaseException {
        addEntry(tag, pwd, (Hashtable<String, String>) null);
    }

    /*
     * Store passwd in pwcache.
     */
    public void addEntry(Hashtable<String, String> ht) throws EBaseException {
        addEntry((String) null, (String) null, ht);
    }

    /*
     * add passwd in pwcache.
     */
    public void addEntry(String tag, String pwd, Hashtable<String, String> tagPwds) throws EBaseException {

        String stringToAdd = null;
        String bufs = null;

        if (tagPwds == null) {
            stringToAdd = tag + ":" + pwd + "\n";
        } else {
            Enumeration<String> enum1 = tagPwds.keys();

            while (enum1.hasMoreElements()) {
                tag = enum1.nextElement();
                pwd = tagPwds.get(tag);
                debug("password tag: " + tag + " stored in " + mPWcachedb);

                if (stringToAdd == null) {
                    stringToAdd = tag + ":" + pwd + "\n";
                } else {
                    stringToAdd += tag + ":" + pwd + "\n";
                }
            }
        }

        String dcrypts = readPWcache();

        if (dcrypts != null) {
            // converts to Hashtable, replace if tag exists, add
            //                if tag doesn't exist
            Hashtable<String, String> ht = string2Hashtable(dcrypts);

            if (ht.containsKey(tag) == false) {
                debug("adding new tag: " + tag);
                ht.put(tag, pwd);
            } else {
                debug("replacing tag: " + tag);
                ht.put(tag, pwd);
            }
            bufs = hashtable2String(ht);
        } else {
            debug("adding new tag: " + tag);
            bufs = stringToAdd;
        }

        // write update to cache
        writePWcache(bufs);
    }

    /*
     * delete passwd in pwcache.
     */
    public void deleteEntry(String tag) throws EBaseException {
        String bufs = null;

        String dcrypts = readPWcache();

        if (dcrypts != null) {
            // converts to Hashtable, replace if tag exists, add
            //                if tag doesn't exist
            Hashtable<String, String> ht = string2Hashtable(dcrypts);

            if (ht.containsKey(tag) == false) {
                debug("tag: " + tag + " does not exist");
                return;
            } else {
                debug("deleting tag: " + tag);
                ht.remove(tag);
            }
            bufs = hashtable2String(ht);
        } else {
            debug("password cache contains no tags");
            return;
        }

        // write update to cache
        writePWcache(bufs);
    }

    /*
     * reads and decrypts the pwcache.db content
     */
    public String readPWcache() throws EBaseException {
        debug("about to read password cache");
        String dcrypts = null;
        Decryptor sdr = new Decryptor(mToken);

        // not used, but could used for debugging
        int totalRead = 0;
        FileInputStream inputs = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            // for SDR -> read, decrypt, append, and write
            inputs = new FileInputStream(mPWcachedb);
            byte[] readbuf = new byte[2048]; // for now
            int numRead = 0;

            while ((numRead = inputs.read(readbuf)) != -1) {
                bos.write(readbuf, 0, numRead);
                totalRead += numRead;
            }
            inputs.close();
        } catch (FileNotFoundException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
            throw new EBaseException(e.toString() + ": " + mPWcachedb);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
            throw new EBaseException(e.toString() + ": " + mPWcachedb);
        }

        if (totalRead > 0) {
            try {
                // decrypt it first to append
                byte[] dcryptb = sdr.decrypt(bos.toByteArray());

                dcrypts = new String(dcryptb, "UTF-8");
            } catch (Exception e) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_DECRYPT", e.toString()));
                e.printStackTrace();
                throw new EBaseException("password cache decrypt failed");
            }
        }

        return dcrypts;
    }

    /*
     * encrypts and writes the whole String buf into pwcache.db
     */
    public void writePWcache(String bufs) throws EBaseException {
        try {
            Encryptor sdr = new Encryptor(mToken, mKeyID,
                                Encryptor.DEFAULT_ENCRYPTION_ALG);

            byte[] writebuf = null;

            try {
                // now encrypt it again
                writebuf = sdr.encrypt(bufs.getBytes("UTF-8"));
            } catch (Exception e) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_ENCRYPT", e.toString()));
                e.printStackTrace();
                throw new EBaseException("password cache encrypt failed");
            }

            File tmpPWcache = new File(mPWcachedb + ".tmp");

            if (tmpPWcache.exists()) {
                // it wasn't removed?
                tmpPWcache.delete();
                tmpPWcache = new File(mPWcachedb + ".tmp");
            }
            FileOutputStream outstream = new FileOutputStream(mPWcachedb + ".tmp");

            outstream.write(writebuf);
            outstream.close();

            File origFile = new File(mPWcachedb);

            try {
                if (Utils.isNT()) {
                    // NT is very picky on the path
                    Utils.exec("copy " +
                                tmpPWcache.getAbsolutePath().replace('/',
                                                                      '\\') +
                                " " +
                                origFile.getAbsolutePath().replace('/',
                                                                    '\\'));
                } else {
                    // Create a copy of the original file which
                    // preserves the original file permissions.
                    Utils.exec("cp -p " + tmpPWcache.getAbsolutePath() + " " +
                                origFile.getAbsolutePath());
                }

                // Remove the original file if and only if
                // the backup copy was successful.
                if (origFile.exists()) {
                    if (!Utils.isNT()) {
                        try {
                            Utils.exec("chmod 00660 " +
                                        origFile.getCanonicalPath());
                        } catch (IOException e) {
                            CMS.debug("Unable to change file permissions on "
                                     + origFile.toString());
                        }
                    }
                    tmpPWcache.delete();
                    debug("operation completed for " + mPWcachedb);
                }
            } catch (Exception exx) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_CACHE", exx.toString()));
                throw new EBaseException(exx.toString() + ": " + mPWcachedb);
            }
        } catch (FileNotFoundException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
            throw new EBaseException(e.toString() + ": " + mPWcachedb);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
            throw new EBaseException(e.toString() + ": " + mPWcachedb);
        } catch (Exception e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
            throw new EBaseException(e.toString() + ": " + mPWcachedb);
        }
    }

    public String hashtable2String(Hashtable<String, String> ht) {
        Enumeration<String> enum1 = ht.keys();
        String returnString = null;

        while (enum1.hasMoreElements()) {
            String tag = enum1.nextElement();
            String pwd = ht.get(tag);

            if (returnString == null) {
                returnString = tag + ":" + pwd + "\n";
            } else {
                returnString += tag + ":" + pwd + "\n";
            }
        }
        return returnString;
    }

    public Hashtable<String, String> string2Hashtable(String cache) {
        Hashtable<String, String> ht = new Hashtable<String, String>();

        // first, break into lines
        StringTokenizer st = new StringTokenizer(cache, "\n");

        while (st.hasMoreTokens()) {
            String line = (String) st.nextToken();
            // break into tag:password format for each line
            int colonIdx = line.indexOf(":");

            if (colonIdx != -1) {
                String tag = line.substring(0, colonIdx);
                String passwd = line.substring(colonIdx + 1,
                        line.length());

                ht.put(tag.trim(), passwd.trim());
            } else {
                //invalid format...log or throw...later
            }
        }
        return ht;
    }

    /*
     * get password from cache.  This one supplies cache file name
     */
    public Password getEntry(String fileName, String tag) {
        mPWcachedb = fileName;
        return getEntry(tag);
    }

    /*
     * if tag found with pwd, return it
     * if tag not found, return null, which will cause it to give up
     */
    public Password getEntry(String tag) {
        Hashtable<String, String> pwTable = null;
        String pw = null;

        debug("in getEntry, tag=" + tag);

        if (mPWcachedb == null) {
            debug("mPWcachedb file path name is not initialized");
            return null;
        }

        String dcrypts = null;

        try {
            dcrypts = readPWcache();
        } catch (EBaseException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_READ", e.toString()));
            return null;
        }

        if (dcrypts != null) {
            // parse the cache
            String cache = dcrypts;

            // this is created and destroyed at each use
            pwTable = string2Hashtable(cache);
            debug("in getEntry, pw cache parsed");
            pw = (String) pwTable.get(tag);
        }

        if (pw != null) {
            debug("getEntry gotten password for " + tag);
            return new Password(pw.toCharArray());
        } else {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_TAG", tag));
            return null;
        }
    }

    //copied from IOUtil.java
    /**
     * Checks if this is NT.
     */
    public static boolean isNT() {
        return ((File.separator).equals("\\"));
    }

    public static boolean exec(String cmd) throws EBaseException {
        try {
            String cmds[] = null;

            if (isNT()) {
                // NT
                cmds = new String[3];
                cmds[0] = "cmd";
                cmds[1] = "/c";
                cmds[2] = cmd;
            } else {
                // UNIX
                cmds = new String[3];
                cmds[0] = "/bin/sh";
                cmds[1] = "-c";
                cmds[2] = cmd;
            }
            Process process = Runtime.getRuntime().exec(cmds);

            process.waitFor();

            if (process.exitValue() == 0) {

                /**
                 * pOut = new BufferedReader(
                 * new InputStreamReader(process.getInputStream()));
                 * while ((l = pOut.readLine()) != null) {
                 * System.out.println(l);
                 * }
                 **/
                return true;
            } else {

                /**
                 * pOut = new BufferedReader(
                 * new InputStreamReader(process.getErrorStream()));
                 * l = null;
                 * while ((l = pOut.readLine()) != null) {
                 * System.out.println(l);
                 * }
                 **/
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public void debug(String msg) {
        if (mLogger != null) {
            CMS.debug(msg);
        }
    }

    public void log(int level, String msg) {
        if (mLogger != null) {
            mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, level,
                    "PWsdrCache " + msg);
        } else if (mIsTool) {
            System.out.println(msg);
        } // else it's most likely the installation wizard...no logging
    }

    /*
     * list passwds in pwcache.
     */
    public boolean pprint() {
        String dcrypts = null;

        try {
            dcrypts = readPWcache();
        } catch (EBaseException e) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_READ", e.toString()));
            return false;
        }

        debug("----- Password Cache Content -----");

        if (dcrypts != null) {
            // first, break into lines
            StringTokenizer st = new StringTokenizer(dcrypts, "\n");

            while (st.hasMoreTokens()) {
                String line = (String) st.nextToken();
                // break into tag:password format for each line
                int colonIdx = line.indexOf(":");

                if (colonIdx != -1) {
                    String tag = line.substring(0, colonIdx);
                    String passwd = line.substring(colonIdx + 1,
                            line.length());

                    debug(tag.trim() +
                            " : " + passwd.trim());
                } else {
                    //invalid format...log or throw...later
                    debug("invalid format");
                }
            }
        } // else print nothing
        return true;
    }
}