summaryrefslogtreecommitdiff
path: root/usr/src/lib/libslp/javalib/com/sun/slp/AuthBlock.java
blob: 94cc7130a6fccc66b6ab124e0f24eb1e333eaa5b (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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * ident	"%Z%%M%	%I%	%E% SMI"
 *
 * Copyright (c) 1999 by Sun Microsystems, Inc.
 * All rights reserved.
 *
 */

package com.sun.slp;

import java.util.*;
import java.io.*;
import java.security.*;
import java.security.cert.*;

/**
 * The AuthBlock class models both the client and server side
 * authentication blocks.
 *<p>
 * AuthBlocks are agnostic as to which components from a given
 * message should be used in authentication. Thus each message
 * must provide the correct components in the correct order.
 *<p>
 * These components are passed via Object[]s. The Object[] elements
 * should be in externalized form, and should be ordered as stated
 * in the protocol specification for auth blocks. AuthBlocks will
 * add the externalized SPI string before the Object[] and the
 * externalized timestamp after the vector.
 *<p>
 * The AuthBlock class provides a number of static convenience
 * methods which operate on sets of AuthBlocks. The sets of
 * AuthBlocks are stored in Hashtables, keyed by SPIs.
 */

class AuthBlock {

    static private String SPI_PROPERTY = "sun.net.slp.SPIs";

    /**
     * A convenience method for creating a set of auth blocks
     * from internal data structures.
     *
     * @param message The ordered components of the SLP message
     *			over which the signature should be computed,
     *			in externalized (byte[]) form.
     * @param lifetime The lifetime for this message, in seconds.
     * @return A Hashtable of AuthBlocks, one for each SPI, null if no
     *		SPIs have been configured.
     * @exception ServiceLocationException If a key management or crypto
     *					algorithm provider cannot be
     *					instantiated, a SYSTEM_ERROR exception
     *					is thrown.
     * @exception IllegalArgumentException If any of the parameters are null
     *					or empty.
     */
    static Hashtable makeAuthBlocks(Object[] message, int lifetime)
	throws ServiceLocationException, IllegalArgumentException {

	Hashtable spis = getSignAs();
	if (spis == null) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"cant_sign", new Object[0]);
	}

	Hashtable blocks = new Hashtable();
	Enumeration spisEnum = spis.keys();
	while (spisEnum.hasMoreElements()) {
	    String spi = (String) spisEnum.nextElement();
	    int bsd = ((Integer)(spis.get(spi))).intValue();
	    blocks.put(spi, new AuthBlock(message, spi, bsd, lifetime));
	}
	return blocks;
    }

    /**
     * A convenience method which creates a Hashtable of auth blocks
     * from an input stream.
     *
     * @param hdr Header of message being parsed out.
     * @param message The ordered components of the SLP message
     *			over which the signature should have been computed,
     *			in externalized (byte[]) form.
     * @param dis Input stream with the auth block bytes queued up as the
     *			next thing.
     * @param nBlocks Number of auth blocks to read.
     * @return A Hashtable of AuthBlocks.
     * @exception ServiceLocationException If anything goes wrong during
     *					parsing. If nBlocks is 0, the
     *					error code is AUTHENTICATION_ABSENT.
     * @exception IllegalArgumentException If any of the parameters are null
     *					or empty.
     * @exception IOException If DataInputStream throws it.
     */
    static Hashtable makeAuthBlocks(SrvLocHeader hdr,
				    Object[] message,
				    DataInputStream dis,
				    byte nBlocks)
	throws ServiceLocationException,
	       IllegalArgumentException,
	       IOException {

	Hashtable blocks = new Hashtable();

	for (byte cnt = 0; cnt < nBlocks; cnt++) {
	    AuthBlock ab = new AuthBlock(hdr, message, dis);
	    blocks.put(ab.getSPI(), ab);
	}

	return blocks;
    }

    /**
     * A convenience method which verifies all auth blocks in the
     * input Hashtable.
     *
     * @param authBlocks A Hashtable containing AuthBlocks.
     * @exception ServiceLocationException Thrown if authentication fails,
     *            with the error code
     *            ServiceLocationException.AUTHENTICATION_FAILED. If any
     *            other error occurs during authentication, the
     *            error code is ServiceLocationException.SYSTEM_ERROR.
     *            If the signature hasn't been calculated the
     *		   authentication fails.
     * @exception IllegalArgumentException If authBlocks is null or empty.
     */
    static void verifyAll(Hashtable authBlocks)
	throws ServiceLocationException, IllegalArgumentException {

	ensureNonEmpty(authBlocks, "authBlocks");

	Enumeration blocks = authBlocks.elements();

	while (blocks.hasMoreElements()) {
	    AuthBlock ab = (AuthBlock) blocks.nextElement();
	    ab.verify();
	}
    }

    /**
     * A convenience method which finds the shortest lifetime in a
     * set of AuthBlocks.
     *
     * @param authBlocks A Hashtable containing AuthBlocks.
     * @return The shortest lifetime found.
     * @exception IllegalArgumentException If authBlocks is null or empty.
     */
    static int getShortestLifetime(Hashtable authBlocks)
	    throws IllegalArgumentException {

	ensureNonEmpty(authBlocks, "authBlocks");

	Enumeration blocks = authBlocks.elements();
	int lifetime = Integer.MAX_VALUE;

	while (blocks.hasMoreElements()) {
	    AuthBlock ab = (AuthBlock) blocks.nextElement();
	    int abLife = ab.getLifetime();
	    lifetime = (lifetime < abLife) ? lifetime : abLife;
	}

	return lifetime;
    }

    /**
     * A convenience method which externalizes a set of AuthBlocks
     * into a ByteArrayOutputStream. The number of blocks is NOT
     * written onto the stream.
     *
     * @param hdr Header of message being externalized.
     * @param authBlocks A Hashtable containing AuthBlocks.
     * @param baos The output stream into which to write.
     * @exception ServiceLocationException Thrown if an error occurs during
     *					  output, with PARSE_ERROR error code.
     * @exception IllegalArgumentException If any parameters are null, or
     *					  if authBlocks is empty.
     */
    static void externalizeAll(SrvLocHeader hdr,
			       Hashtable authBlocks,
			       ByteArrayOutputStream baos)
	throws ServiceLocationException, IllegalArgumentException {

	ensureNonEmpty(authBlocks, "authBlocks");

	Enumeration blocks = authBlocks.elements();

	while (blocks.hasMoreElements()) {
	    AuthBlock ab = (AuthBlock) blocks.nextElement();
	    ab.externalize(hdr, baos);
	}
    }

    /**
     * Returns the message parts obtained from the AuthBlock contructor.
     * The Object[] will not have been altered. Note that all AuthBlocks
     * contain the same message Object[] Object.
     *
     * @param authBlocks A Hashtable containing AuthBlocks.
     * @return This auth block's message components Object[].
     * @exception IllegalArgumentException If authBlocks is null or empty.
     */
    static Object[] getContents(Hashtable authBlocks)
	throws IllegalArgumentException {

	ensureNonEmpty(authBlocks, "authBlocks");

	Enumeration blocks = authBlocks.elements();
	AuthBlock ab = (AuthBlock) blocks.nextElement();
	return ab.getMessageParts();
    }

    /**
     * Creates a String describing all auth blocks in authBlocks.
     * We dont't use toString() since that would get Hashtable.toString(),
     * and we can format it a little prettier.
     *
     * @param authBlocks A Hashtable containing AuthBlocks.
     * @return A String description of all AuthBlocks in this Hashtable
     */
    static String desc(Hashtable authBlocks) {

	if (authBlocks == null) {
	    return "null";
	}

	Enumeration blocks = authBlocks.elements();
	int size = authBlocks.size();
	String desc = size == 1 ? "1 Auth Block:\n" : size + " Auth Blocks:\n";
	int cnt = 0;

	while (blocks.hasMoreElements()) {
	    AuthBlock ab = (AuthBlock) blocks.nextElement();
	    desc = desc + "             " + (cnt++) + ": " + ab.toString();
	}

	return desc;
    }

    /**
     * Returns the list of SPIs configured with this 'prop', or null
     * if the property hasn't been set.
     */
    static LinkedList getSPIList(String prop) {
	String spiProp = System.getProperty(prop);
	if (spiProp == null) {
	    return null;
	}

	return commaSeparatedListToLinkedList(spiProp);
    }

    /**
     * Converts a comma-separaterd list in a String to a LinkedList.
     */
    static LinkedList commaSeparatedListToLinkedList(String listStr) {
	StringTokenizer stk_comma = new StringTokenizer(listStr, ",");
	LinkedList answer = new LinkedList();
	while (stk_comma.hasMoreTokens()) {
	    String spi = stk_comma.nextToken();
	    answer.add(spi);
	}

	return answer;
    }

    /**
     * Returns true if this principal is someDH, or if this principal's
     * cert has been signed by someDN.
     */
    static boolean canSignAs(String someDN) throws ServiceLocationException {
	X509Certificate myCert = getSignAsCert();
	if (myCert == null) {
	    return false;
	}

	KeyStore ks = getKeyStore();
	if (ks == null) {
	    return false;
	}

	X509Certificate cert = getCert(someDN, ks);

	return onCertChain(
		myCert.getSubjectDN().toString(), cert.getSubjectDN());
    }

    /**
     * Checks if caDN is in ab's equivalency set, i.e. if caDN
     * is in ab's cert chain.
     */
    static boolean checkEquiv(String caDN, AuthBlock ab) {
	// Get cert for input DN
	X509Certificate caCert;
	try {
	    KeyStore ks = getKeyStore();

	    caCert = getCert(caDN, ks);
	} catch (Exception e) {
	    SLPConfig.getSLPConfig().writeLog(
		"cant_get_equivalency",
		new Object[] {caDN, e.getMessage()});
	    return false;
	}

	return ab.inEqSet(caCert.getSubjectDN());
    }

    /**
     * Filters out from auths all auth blocks which have not been
     * signed by DNs equivalent to caDN.
     */
    static AuthBlock getEquivalentAuth(String caDN, Hashtable authBlocks) {
	if (authBlocks.size() == 0) {
	    return null;
	}

	// Get cert for input DN
	X509Certificate caCert;
	try {
	    KeyStore ks = getKeyStore();

	    caCert = getCert(caDN, ks);
	} catch (Exception e) {
	    SLPConfig.getSLPConfig().writeLog(
		"cant_get_equivalency",
		new Object[] { caDN, e.getMessage()});
	    return null;
	}

	Enumeration blocks = authBlocks.elements();

	while (blocks.hasMoreElements()) {
	    AuthBlock ab = (AuthBlock) blocks.nextElement();
	    if (ab.inEqSet(caCert.getSubjectDN())) {
		return ab;
	    }
	}

	return null;
    }


    /**
     * Gets a list of signing identities. Returns a Hashtable of
     * which the keys are SPI strings (DNs) and the values
     * are BSD Integers.
     */
    static Hashtable getSignAs() throws ServiceLocationException {
	X509Certificate cert = getSignAsCert();
	Hashtable answer = new Hashtable();

	if (cert == null) {
	    return null;
	}

	/* derive DN from alias */
	String DN = cert.getSubjectDN().toString();
	String e_DN = null;
	// escape DN
	try {
	    e_DN = ServiceLocationAttribute.escapeAttributeString(DN, false);
	} catch (ServiceLocationException e) {
	    // Shouldn't get here if badTag == false
	    e_DN = DN;
	}
	DN = e_DN;

	String alg = cert.getPublicKey().getAlgorithm();
	int ibsd;
	if (alg.equals("DSA")) {
	    ibsd = 2;
	} else if (alg.equals("RSA")) {
	    ibsd = 1;
	} else {
	    SLPConfig.getSLPConfig().writeLog("bad_alg_for_alias",
					      new Object[] {alg});
	    return null;
	}

	answer.put(DN, new Integer(ibsd));

	return answer;
    }

    /**
     * Returns the cert corresponding to our signing alias.
     * @@@ change this when AMI goes in to use private AMI interface.
     */
    static X509Certificate getSignAsCert() throws ServiceLocationException {
	String spiProp = System.getProperty("sun.net.slp.signAs");
	if (spiProp == null) {
	    SLPConfig.getSLPConfig().writeLog(
		"no_spis_given", new Object[0]);
	    return null;
	}

	/* load key store */
	KeyStore ks = getKeyPkg();

	StringTokenizer stk_comma = new StringTokenizer(spiProp, ",");
	X509Certificate cert = null;

	// Can only sign with one alias, so ignore any extras
	if (stk_comma.hasMoreTokens()) {
	    String alias = stk_comma.nextToken();

	    /* get keypkg for this alias */
	    cert = getCert(alias, ks);
	}

	return cert;
    }

    /**
     * Creates a new AuthBlock based on the SPI and message parts.
     *
     * @param message The ordered components of the SLP message
     *			over which the signature should be computed,
     *			in externalized (byte[]) form.
     * @param spi The SLP SPI for which to create the auth block.
     * @param lifetime The lifetime for this message, in seconds.
     * @exception ServiceLocationException If a key management or crypto
     *					algorithm provider cannot be
     *					instantiated, a SYSTEM_ERROR exception
     *					is thrown.
     * @exception IllegalArgumentException If any of the parameters are null
     *					or empty.
     */
    AuthBlock(Object[] message, String spi, int bsd, int lifetime)
	throws ServiceLocationException, IllegalArgumentException {

	ensureNonEmpty(message, "message");
	Assert.nonNullParameter(spi, "spi");

	// init crypto provider associated with bsd
	this.bsd = bsd;
	getSecurityProvider(bsd);

	this.message = message;
	this.spi = spi;
	this.lifetime = lifetime;
	this.timeStamp = SLPConfig.currentSLPTime() + lifetime;

	// Create the signature: create and sign the hash

	try {
	    // @@@ how to sign for different aliases?
	    sig.initSign(null);
	    computeHash();
	    abBytes = sig.sign();
	} catch (InvalidKeyException e) {	// @@@ will change for AMI
	  SLPConfig conf = SLPConfig.getSLPConfig();
	    throw 
		new IllegalArgumentException(
				conf.formatMessage(
					"cant_sign_for_spi",
					new Object[] { 
						spi, 
						e.getMessage() }));
	} catch (SignatureException e) {
	  SLPConfig conf = SLPConfig.getSLPConfig();
	    throw 
		new IllegalArgumentException(
				conf.formatMessage(
					"cant_sign_for_spi",
					new Object[] { 
						spi, 
						e.getMessage() }));
	}

	// calculate the length
	abLength =
		2 + // bsd
		2 + // length
		4 + // timestamp
		spiBytes.length + // externalized SPI string, with length
		abBytes.length; // structured auth block
    }

    /**
     * Creates a new AuthBlock from an input stream.
     *
     * @param hdr The header of the message being parsed.
     * @param message The ordered components of the SLP message
     *			over which the signature should have been computed,
     *			in externalized (byte[]) form.
     * @param dis Input stream with the auth block bytes queued up as the
     *			next thing.
     * @exception ServiceLocationException If anything goes wrong during
     *					parsing. If nBlocks is 0, the
     *					error code is AUTHENTICATION_ABSENT.
     * @exception IllegalArgumentException If any of the parameters are null
     *					or empty.
     * @exception IOException If DataInputStream throws it.
     */
    AuthBlock(SrvLocHeader hdr, Object[] message, DataInputStream dis)
	throws ServiceLocationException,
	       IllegalArgumentException,
	       IOException {

	Assert.nonNullParameter(hdr, "hdr");
	ensureNonEmpty(message, "message");
	Assert.nonNullParameter(dis, "dis");

	this.message = message;
	this.eqSet = new HashSet();

	// parse in the auth block from the input stream;
	// first get the BSD and length
	bsd = hdr.getInt(dis);
	abLength = hdr.getInt(dis);

	int pos = 4;	// bsd and length have already been consumed

	// get the timestamp
	timeStamp = getInt32(dis);
	pos += 4;
	hdr.nbytes += 4;

	// get the SPI
	StringBuffer buf = new StringBuffer();
	hdr.getString(buf, dis);
	spi = buf.toString();
	if (spi.length() == 0) {
		throw new ServiceLocationException(
		    ServiceLocationException.PARSE_ERROR,
		    "no_spi_string",
		    new Object[0]);
	}
	pos += (2 + spi.length());

	// get the structured auth block
	abBytes = new byte[abLength - pos];
	dis.readFully(abBytes, 0, abLength - pos);
	hdr.nbytes += abBytes.length;

	// calculate remaining lifetime from timestamp
	long time = timeStamp - SLPConfig.currentSLPTime();
	time = time <= Integer.MAX_VALUE ? time : 0;	// no crazy values
	lifetime = (int) time;
	lifetime = lifetime < 0 ? 0 : lifetime;

	// Initialize the crypto provider
	getSecurityProvider(bsd);
    }

    /**
     * Gets the size of this auth block, after externalization, in bytes.
     *
     * @return The number of bytes in this auth block.
     */
    int nBytes() {
	return abLength;
    }

    /**
     * Returns the message parts obtained from the AuthBlock contructor.
     * The Object[] will not have been altered.
     *
     * @return This auth block's message components Object[].
     */
    Object[] getMessageParts() {
	return message;
    }

    /**
     * Verifies the signature on this auth block.
     *
     * @exception ServiceLocationException Thrown if authentication fails,
     *            with the error code
     *            ServiceLocationException.AUTHENTICATION_FAILED. If any
     *            other error occurs during authentication, the
     *            error code is ServiceLocationException.SYSTEM_ERROR.
     *            If the signature hasn't been calculated, the
     *		   fails.
     */
    void verify() throws ServiceLocationException {
	// Load the keystore
	KeyStore ks = null;
	try {
	    ks = KeyStore.getInstance("amicerts", "SunAMI");
	    ks.load(null, null);
	} catch (Exception e) {
	    throw 
		new ServiceLocationException(
			ServiceLocationException.AUTHENTICATION_FAILED,
			"no_keystore",
			new Object[] {e.getMessage()});
	}

	// Unescape the SPI for cleaner logging
	String u_DN = null;
	try {
	    u_DN =
		ServiceLocationAttribute.unescapeAttributeString(spi, false);
	} catch (ServiceLocationException e) {
	    u_DN = spi;
	}

	// get cert for this spi
	X509Certificate cert = getCert(spi, ks);

	// check cert validity
	try {
	    cert.checkValidity();
	} catch (CertificateException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"invalid_cert",
		new Object[] {u_DN, e.getMessage()});
	}

	// check the lifetime
	if (lifetime == 0) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"timestamp_failure",
		new Object[] {u_DN});
	}

	// make sure this SPI matches up with configured SPIs
	try {
	    checkSPIs(cert, ks);
	} catch (GeneralSecurityException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"cant_match_spis",
		new Object[] {cert.getSubjectDN(), e.getMessage()});
	}


	// check the signature
	try {
	    sig.initVerify(cert.getPublicKey());
	} catch (InvalidKeyException ex) {
	    throw 
		new ServiceLocationException(
			ServiceLocationException.INTERNAL_SYSTEM_ERROR,
			"init_verify_failure",
			new Object[] {
				u_DN,
				    ex.getMessage()});
	}

	computeHash();

	ServiceLocationException vex =
	    new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"verify_failure",
		new Object[] {u_DN});

	try {
	    if (!sig.verify(abBytes))
		throw vex;
	} catch (SignatureException ex) {
	    throw vex;
	}
    }

    /**
     * Convert the auth block into its on-the-wire format.
     *
     * @param hdr The header of the message being parsed out.
     * @param baos The output stream into which to write.
     * @exception ServiceLocationException Thrown if an error occurs during
     *					  output, with PARSE_ERROR error code.
     * @exception IllegalArgumentException If any baos is null.
     */
    void externalize(SrvLocHeader hdr, ByteArrayOutputStream baos)
	throws ServiceLocationException, IllegalArgumentException {

	Assert.nonNullParameter(hdr, "hdr");
	Assert.nonNullParameter(baos, "baos");

	// Lay out the auth block, starting with the BSD
	hdr.putInt(bsd, baos);

	// write out the length
	hdr.putInt(abLength, baos);

	// calculate and write out the timestamp
	putInt32(timeStamp, baos);
	hdr.nbytes += 4;

	// write the SPI string
	hdr.putString(spi, baos);

	// Finish by writting the structured auth block
	baos.write(abBytes, 0, abBytes.length);
	hdr.nbytes += abBytes.length;
    }

    /**
     * Returns the SPI associated with this auth block.
     *
     * @return The SLP SPI for this auth block.
     */
    String getSPI() {
	return spi;
    }

    /**
     * Returns the lifetime computed from this auth block.
     *
     * @return The lifetime from this auth block.
     */
    int getLifetime() {
	return lifetime;
    }

    /**
     * Given a BSD, sets this AuthBlock's Signature to the
     * right algorithm.
     */
    private void getSecurityProvider(int bsd)
	throws ServiceLocationException {

	String algo = "Unknown BSD";
	try {
	    if (bsd == 2) {
		// get DSA/SHA1 provider
		algo = "DSA";
		sig = Signature.getInstance("SHA/DSA", "SunAMI");
		return;
	    } else if (bsd == 1) {
		algo = "MD5/RSA";
		sig = Signature.getInstance("MD5/RSA", "SunAMI");
		return;
	    } else if (bsd == 3) {
		algo = "Keyed HMAC with MD5";
	    }
	} catch (GeneralSecurityException e) {
	    // system error -- no such provider
	    throw new ServiceLocationException(
		ServiceLocationException.INTERNAL_SYSTEM_ERROR,
		"cant_get_security_provider",
		new Object[] {
			new Integer(bsd),
			algo,
			e.getMessage()});
	}

	// Unknown or unsupported BSD
	throw new ServiceLocationException(
	    ServiceLocationException.INTERNAL_SYSTEM_ERROR,
	    "cant_get_security_provider",
	    new Object[] {
		new Integer(bsd),
		algo,
		"Unknown or unsupported BSD"});
    }

    /**
     * throws an IllegalArgumentException if v is null or empty.
     * v can be either a Hashtable or a Object[].
     */
    static private void ensureNonEmpty(Object v, String param)
	throws IllegalArgumentException {

	int size = 0;
	if (v != null) {
	    if (v instanceof Object[]) {
		size = ((Object[]) v).length;
	    } else {
		// this will force a class cast exception if not a Hashtable
		size = ((Hashtable) v).size();
	    }
	}

	if (v == null || size == 0) {
	    SLPConfig conf = SLPConfig.getSLPConfig();
	    String msg = 
		conf.formatMessage("null_or_empty_vector",
				   new Object[] {param});
	    throw
		new IllegalArgumentException(msg);
	}
    }

    /**
     * Computes a hash over the SPI String, message componenets,
     * and timstamp. Which hash is used depends on which crypto
     * provider was installed.
     *
     * This method assumes that the class variables spi, sig,
     * message, and timeStamp have all been initialized. As a side
     * effect, it places the externalized SPI String into spiBytes.
     */
    private void computeHash() throws ServiceLocationException {
	try {
	    // get the SPI String bytes
	    ByteArrayOutputStream baosT = new ByteArrayOutputStream();
	    SrvLocHeader.putStringField(spi, baosT, Defaults.UTF8);
	    spiBytes = baosT.toByteArray();
	    sig.update(spiBytes);

	    // Add each message component
	    int mSize = message.length;
	    for (int i = 0; i < mSize; i++) {
		sig.update((byte[]) message[i]);
	    }

	    // end by adding the timestamp
	    baosT = new ByteArrayOutputStream();
	    putInt32(timeStamp, baosT);
	    sig.update(baosT.toByteArray());
	} catch (SignatureException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.INTERNAL_SYSTEM_ERROR,
		"cant_compute_hash",
		new Object[] {e.getMessage()});
	}
    }

    static private long getInt32(DataInputStream dis) throws IOException {
	byte[] bytes = new byte[4];

	dis.readFully(bytes, 0, 4);

	long a = (long)(bytes[0] & 0xFF);
	long b = (long)(bytes[1] & 0xFF);
	long c = (long)(bytes[2] & 0xFF);
	long d = (long)(bytes[3] & 0xFF);

	long i = a << 24;
	i += b << 16;
	i += c << 8;
	i += d;

	return i;
    }

    static private void putInt32(long i, ByteArrayOutputStream baos) {
	baos.write((byte) ((i >> 24) & 0xFF));
	baos.write((byte) ((i >> 16) & 0xFF));
	baos.write((byte) ((i >> 8)  & 0xFF));
	baos.write((byte) (i & 0XFF));
    }

    /**
     * Determines if this process' SPI configuration allows
     * messages signed by 'cert' to be verified. This method
     * also verifies and validates 'cert's cert chain.
     */
    private void checkSPIs(X509Certificate cert, KeyStore ks)
	throws ServiceLocationException, GeneralSecurityException {

	// get the list of configured SPIs
	String conf_spis = System.getProperty("sun.net.slp.SPIs");
	if (conf_spis == null) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"no_spis_configured", new Object[0]);
	}

	// Get cert chain
	java.security.cert.Certificate[] chain =
	    ks.getCertificateChain(cert.getSubjectDN().toString());
	if (chain == null) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"no_cert_chain",
		new Object[] {cert.getSubjectDN().toString()});
	}

	// validate all links in chain
	int i = 0;
	try {
	    // Add cert's own subjec to equiv set
	    eqSet.add(((X509Certificate)chain[0]).getSubjectDN());

	    for (i = 1; i < chain.length; i++) {
		((X509Certificate)chain[i]).checkValidity();
		chain[i-1].verify(chain[i].getPublicKey(), "SunAMI");

		// OK, so add to equivalency set
		eqSet.add(((X509Certificate)chain[i]).getSubjectDN());
	    }
	} catch (ClassCastException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"not_x509cert",
		new Object[] { chain[i].getType(), e.getMessage() });
	}

	if (configuredToVerify(chain, conf_spis, ks)) {
	    return;
	}

	// if we get here, no SPIs matched, so the authentication fails
	throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"cant_match_spis",
		new Object[] {cert.getSubjectDN().toString(), ""});
    }

    /**
     * Determines if, given a set of SPIs 'conf_spis', we can
     * verify a message signed by the Principal named by 'cert'.
     */
    static private boolean configuredToVerify(
				java.security.cert.Certificate[] chain,
				String conf_spis,
				KeyStore ks) {

	StringTokenizer stk = new StringTokenizer(conf_spis, ",");
	while (stk.hasMoreTokens()) {
	    String spi;

	    try {
		spi = stk.nextToken();
	    } catch (NoSuchElementException e) {
		break;
	    }

	    // get CA cert to get CA Principal
	    Principal ca;
	    try {
		X509Certificate cacert = getCert(spi, ks);
		ca = cacert.getSubjectDN();
	    } catch (ServiceLocationException e) {
		SLPConfig.getSLPConfig().writeLog(
			"cant_process_spi",
			new Object[] {spi, e.getMessage()});
		continue;
	    }

	    if (onCertChain(ca, chain)) {
		return true;
	    }
	}

	return false;
    }

    /**
     * Determines if sub if equivalent to ca by getting sub's cert
     * chain and walking the chain looking for ca.
     * This routine does not verify the cert chain.
     */
    private static boolean onCertChain(String sub, Principal ca)
	throws ServiceLocationException {

	java.security.cert.Certificate[] chain;

	ServiceLocationException ex = new ServiceLocationException(
			ServiceLocationException.AUTHENTICATION_UNKNOWN,
			"no_cert_chain",
			new Object[] {sub});

	try {
	    // Get cert keystore
	    KeyStore ks = getKeyStore();

	    // Get cert chain for subject
	    chain = ks.getCertificateChain(sub);
	} catch (KeyStoreException e) {
	    throw ex;
	}

	if (chain == null) {
	    throw ex;
	}

	// walk the cert chain
	return onCertChain(ca, chain);
    }

    /**
     * Operates the same as above, but rather than getting the cert
     * chain for sub, uses a given cert chain.
     */
    private static boolean onCertChain(Principal ca,
				       java.security.cert.Certificate[] chain)
    {
	// walk the cert chain
	for (int i = 0; i < chain.length; i++) {
	    Principal sub = ((X509Certificate)chain[i]).getSubjectDN();
	    if (ca.equals(sub)) {
		return true;
	    }
	}

	return false;
    }

    /**
     * Returns true if someDN is in this AuthBlock's equivalence set.
     */
    private boolean inEqSet(Principal someDN) {
	return eqSet.contains(someDN);
    }

    /**
     * Retrieves from the KeyStore 'ks' the X509Certificate named
     * by DN.
     */
    static private X509Certificate getCert(String DN, KeyStore ks)
	throws ServiceLocationException {

	X509Certificate cert = null;

	// Unescape DN
	try {
	    DN = ServiceLocationAttribute.unescapeAttributeString(DN, false);
	} catch (ServiceLocationException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.PARSE_ERROR,
		"spi_parse_error",
		new Object[] {DN, e.getMessage()});
	}

	try {
	    cert = (X509Certificate)ks.getCertificate(DN);
	} catch (ClassCastException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"not_x509cert",
		new Object[] {cert.getType(), e.getMessage()});
	} catch (KeyStoreException e) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"no_cert",
		new Object[] {DN, e.getMessage()});
	}

	if (cert == null) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"no_cert",
		new Object[] {DN, "" });
	}

	return cert;
    }

    /**
     * Gets a handle to the trusted key package for this process.
     */
    static private synchronized KeyStore getKeyPkg()
	throws ServiceLocationException {

	if (keypkg != null) {
	    return keypkg;
	}

	/* else load key store */
	try {
	    keypkg = KeyStore.getInstance("amiks", "SunAMI");
	    keypkg.load(null, null);
	} catch (Exception e) {
	    throw new ServiceLocationException(
		ServiceLocationException.AUTHENTICATION_FAILED,
		"no_keystore",
		new Object[] {e.getMessage()});
	}

	return keypkg;
    }

    /**
     * Gets a handle to a certificate repository.
     */
    static private synchronized KeyStore getKeyStore()
	throws ServiceLocationException {

	if (keystore != null) {
	    return keystore;
	}

	try {
	    keystore = KeyStore.getInstance("amicerts", "SunAMI");
	    keystore.load(null, null);
	} catch (Exception e) {
	    throw 
		new ServiceLocationException(
			ServiceLocationException.AUTHENTICATION_FAILED,
			"no_keystore",
			new Object[] {e.getMessage()});
	}

	return keystore;
    }

    public String toString() {
	return  "SPI=``" + spi + "''\n" +
		"                BSD=``" + bsd + "''\n" +
		"                timeStamp=``" + timeStamp + "''\n" +
		"                AuthBlock bytes=" + abLength + " bytes\n";
    }


    // Instance variables
    int bsd;
    String spi;
    Object[] message;
    int lifetime;	// need both: lifetime is for optimization,
    long timeStamp;	// timeStamp is needed to compute the hash
    SrvLocHeader hdr;
    Signature sig;
    int abLength;
    byte[] abBytes;
    byte[] spiBytes;
    HashSet eqSet;	// built only during authblock verification

    // cached per process
    static private KeyStore keystore;	// Certificate repository
    static private KeyStore keypkg;	// My own keypkg
}