1 /* Security.java --- Java base security class implementation
2 Copyright (C) 1999, 2001, 2002, 2003, 2004, 2005, 2006
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
40 package java
.security
;
42 import gnu
.classpath
.SystemProperties
;
44 import gnu
.classpath
.Configuration
;
45 // GCJ LOCAL - We don't have VMStackWalker yet.
46 // import gnu.classpath.VMStackWalker;
48 import java
.io
.IOException
;
49 import java
.io
.InputStream
;
51 import java
.util
.Collections
;
52 import java
.util
.Enumeration
;
53 import java
.util
.HashMap
;
54 import java
.util
.HashSet
;
55 import java
.util
.Iterator
;
56 import java
.util
.LinkedHashSet
;
58 import java
.util
.Properties
;
60 import java
.util
.Vector
;
63 * This class centralizes all security properties and common security methods.
64 * One of its primary uses is to manage providers.
66 * @author Mark Benvenuto (ivymccough@worldnet.att.net)
68 public final class Security
70 private static final String ALG_ALIAS
= "Alg.Alias.";
72 private static Vector providers
= new Vector();
73 private static Properties secprops
= new Properties();
77 String base
= SystemProperties
.getProperty("gnu.classpath.home.url");
78 String vendor
= SystemProperties
.getProperty("gnu.classpath.vm.shortname");
80 // Try VM specific security file
81 boolean loaded
= loadProviders (base
, vendor
);
83 // Append classpath standard provider if possible
84 if (!loadProviders (base
, "classpath")
86 && providers
.size() == 0)
88 if (Configuration
.DEBUG
)
90 /* No providers found and both security files failed to
91 * load properly. Give a warning in case of DEBUG is
92 * enabled. Could be done with java.util.logging later.
95 ("WARNING: could not properly read security provider files:");
97 (" " + base
+ "/security/" + vendor
100 (" " + base
+ "/security/" + "classpath"
103 (" Falling back to standard GNU security provider");
105 providers
.addElement (new gnu
.java
.security
.provider
.Gnu());
108 // This class can't be instantiated.
114 * Tries to load the vender specific security providers from the given
115 * base URL. Returns true if the resource could be read and completely
116 * parsed successfully, false otherwise.
118 private static boolean loadProviders(String baseUrl
, String vendor
)
120 if (baseUrl
== null || vendor
== null)
123 boolean result
= true;
124 String secfilestr
= baseUrl
+ "/security/" + vendor
+ ".security";
127 InputStream fin
= new URL(secfilestr
).openStream();
132 while ((name
= secprops
.getProperty("security.provider." + i
)) != null)
134 Exception exception
= null;
137 providers
.addElement(Class
.forName(name
).newInstance());
139 catch (ClassNotFoundException x
)
143 catch (InstantiationException x
)
147 catch (IllegalAccessException x
)
152 if (exception
!= null)
154 System
.err
.println ("WARNING: Error loading security provider "
155 + name
+ ": " + exception
);
161 catch (IOException ignored
)
170 * Gets a specified property for an algorithm. The algorithm name should be a
171 * standard name. See Appendix A in the Java Cryptography Architecture API
172 * Specification & Reference for information about standard algorithm
173 * names. One possible use is by specialized algorithm parsers, which may map
174 * classes to algorithms which they understand (much like {@link Key} parsers
177 * @param algName the algorithm name.
178 * @param propName the name of the property to get.
179 * @return the value of the specified property.
180 * @deprecated This method used to return the value of a proprietary property
181 * in the master file of the "SUN" Cryptographic Service Provider in order to
182 * determine how to parse algorithm-specific parameters. Use the new
183 * provider-based and algorithm-independent {@link AlgorithmParameters} and
184 * {@link KeyFactory} engine classes (introduced in the Java 2 platform)
187 public static String
getAlgorithmProperty(String algName
, String propName
)
189 if (algName
== null || propName
== null)
192 String property
= String
.valueOf(propName
) + "." + String
.valueOf(algName
);
194 for (Iterator i
= providers
.iterator(); i
.hasNext(); )
196 p
= (Provider
) i
.next();
197 for (Iterator j
= p
.keySet().iterator(); j
.hasNext(); )
199 String key
= (String
) j
.next();
200 if (key
.equalsIgnoreCase(property
))
201 return p
.getProperty(key
);
208 * <p>Adds a new provider, at a specified position. The position is the
209 * preference order in which providers are searched for requested algorithms.
210 * Note that it is not guaranteed that this preference will be respected. The
211 * position is 1-based, that is, <code>1</code> is most preferred, followed by
212 * <code>2</code>, and so on.</p>
214 * <p>If the given provider is installed at the requested position, the
215 * provider that used to be at that position, and all providers with a
216 * position greater than position, are shifted up one position (towards the
217 * end of the list of installed providers).</p>
219 * <p>A provider cannot be added if it is already installed.</p>
221 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
222 * </code> method is called with the string <code>"insertProvider."+provider.
223 * getName()</code> to see if it's ok to add a new provider. If the default
224 * implementation of <code>checkSecurityAccess()</code> is used (i.e., that
225 * method is not overriden), then this will result in a call to the security
226 * manager's <code>checkPermission()</code> method with a
227 * <code>SecurityPermission("insertProvider."+provider.getName())</code>
230 * @param provider the provider to be added.
231 * @param position the preference position that the caller would like for
233 * @return the actual preference position in which the provider was added, or
234 * <code>-1</code> if the provider was not added because it is already
236 * @throws SecurityException if a security manager exists and its
237 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
238 * to add a new provider.
239 * @see #getProvider(String)
240 * @see #removeProvider(String)
241 * @see SecurityPermission
243 public static int insertProviderAt(Provider provider
, int position
)
245 SecurityManager sm
= System
.getSecurityManager();
247 sm
.checkSecurityAccess("insertProvider." + provider
.getName());
250 int max
= providers
.size ();
251 for (int i
= 0; i
< max
; i
++)
253 if (((Provider
) providers
.elementAt(i
)).getName().equals(provider
.getName()))
262 providers
.insertElementAt(provider
, position
);
268 * <p>Adds a provider to the next position available.</p>
270 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
271 * </code> method is called with the string <code>"insertProvider."+provider.
272 * getName()</code> to see if it's ok to add a new provider. If the default
273 * implementation of <code>checkSecurityAccess()</code> is used (i.e., that
274 * method is not overriden), then this will result in a call to the security
275 * manager's <code>checkPermission()</code> method with a
276 * <code>SecurityPermission("insertProvider."+provider.getName())</code>
279 * @param provider the provider to be added.
280 * @return the preference position in which the provider was added, or
281 * <code>-1</code> if the provider was not added because it is already
283 * @throws SecurityException if a security manager exists and its
284 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
285 * to add a new provider.
286 * @see #getProvider(String)
287 * @see #removeProvider(String)
288 * @see SecurityPermission
290 public static int addProvider(Provider provider
)
292 return insertProviderAt (provider
, providers
.size () + 1);
296 * <p>Removes the provider with the specified name.</p>
298 * <p>When the specified provider is removed, all providers located at a
299 * position greater than where the specified provider was are shifted down
300 * one position (towards the head of the list of installed providers).</p>
302 * <p>This method returns silently if the provider is not installed.</p>
304 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
305 * </code> method is called with the string <code>"removeProvider."+name</code>
306 * to see if it's ok to remove the provider. If the default implementation of
307 * <code>checkSecurityAccess()</code> is used (i.e., that method is not
308 * overriden), then this will result in a call to the security manager's
309 * <code>checkPermission()</code> method with a <code>SecurityPermission(
310 * "removeProvider."+name)</code> permission.</p>
312 * @param name the name of the provider to remove.
313 * @throws SecurityException if a security manager exists and its
314 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
315 * to remove the provider.
316 * @see #getProvider(String)
317 * @see #addProvider(Provider)
319 public static void removeProvider(String name
)
321 SecurityManager sm
= System
.getSecurityManager();
323 sm
.checkSecurityAccess("removeProvider." + name
);
325 int max
= providers
.size ();
326 for (int i
= 0; i
< max
; i
++)
328 if (((Provider
) providers
.elementAt(i
)).getName().equals(name
))
337 * Returns an array containing all the installed providers. The order of the
338 * providers in the array is their preference order.
340 * @return an array of all the installed providers.
342 public static Provider
[] getProviders()
344 Provider
[] array
= new Provider
[providers
.size ()];
345 providers
.copyInto (array
);
350 * Returns the provider installed with the specified name, if any. Returns
351 * <code>null</code> if no provider with the specified name is installed.
353 * @param name the name of the provider to get.
354 * @return the provider of the specified name.
355 * @see #removeProvider(String)
356 * @see #addProvider(Provider)
358 public static Provider
getProvider(String name
)
365 if (name
.length() == 0)
369 int max
= providers
.size ();
370 for (int i
= 0; i
< max
; i
++)
372 p
= (Provider
) providers
.elementAt(i
);
373 if (p
.getName().equals(name
))
380 * <p>Gets a security property value.</p>
382 * <p>First, if there is a security manager, its <code>checkPermission()</code>
383 * method is called with a <code>SecurityPermission("getProperty."+key)</code>
384 * permission to see if it's ok to retrieve the specified security property
387 * @param key the key of the property being retrieved.
388 * @return the value of the security property corresponding to key.
389 * @throws SecurityException if a security manager exists and its
390 * {@link SecurityManager#checkPermission(Permission)} method denies access
391 * to retrieve the specified security property value.
392 * @see #setProperty(String, String)
393 * @see SecurityPermission
395 public static String
getProperty(String key
)
397 // GCJ LOCAL - We don't have VMStackWalker yet.
398 // XXX To prevent infinite recursion when the SecurityManager calls us,
399 // don't do a security check if the caller is trusted (by virtue of having
400 // been loaded by the bootstrap class loader).
401 SecurityManager sm
= System
.getSecurityManager();
402 // if (sm != null && VMStackWalker.getCallingClassLoader() != null)
404 sm
.checkSecurityAccess("getProperty." + key
);
406 return secprops
.getProperty(key
);
410 * <p>Sets a security property value.</p>
412 * <p>First, if there is a security manager, its <code>checkPermission()</code>
413 * method is called with a <code>SecurityPermission("setProperty."+key)</code>
414 * permission to see if it's ok to set the specified security property value.
417 * @param key the name of the property to be set.
418 * @param datum the value of the property to be set.
419 * @throws SecurityException if a security manager exists and its
420 * {@link SecurityManager#checkPermission(Permission)} method denies access
421 * to set the specified security property value.
422 * @see #getProperty(String)
423 * @see SecurityPermission
425 public static void setProperty(String key
, String datum
)
427 SecurityManager sm
= System
.getSecurityManager();
429 sm
.checkSecurityAccess("setProperty." + key
);
432 secprops
.remove(key
);
434 secprops
.put(key
, datum
);
438 * Returns a Set of Strings containing the names of all available algorithms
439 * or types for the specified Java cryptographic service (e.g., Signature,
440 * MessageDigest, Cipher, Mac, KeyStore). Returns an empty Set if there is no
441 * provider that supports the specified service. For a complete list of Java
442 * cryptographic services, please see the Java Cryptography Architecture API
443 * Specification & Reference. Note: the returned set is immutable.
445 * @param serviceName the name of the Java cryptographic service (e.g.,
446 * Signature, MessageDigest, Cipher, Mac, KeyStore). Note: this parameter is
448 * @return a Set of Strings containing the names of all available algorithms
449 * or types for the specified Java cryptographic service or an empty set if
450 * no provider supports the specified service.
453 public static Set
getAlgorithms(String serviceName
)
455 HashSet result
= new HashSet();
456 if (serviceName
== null || serviceName
.length() == 0)
459 serviceName
= serviceName
.trim();
460 if (serviceName
.length() == 0)
463 serviceName
= serviceName
.toUpperCase()+".";
464 Provider
[] providers
= getProviders();
466 for (int i
= 0; i
< providers
.length
; i
++)
467 for (Enumeration e
= providers
[i
].propertyNames(); e
.hasMoreElements(); )
469 String service
= ((String
) e
.nextElement()).trim();
470 if (service
.toUpperCase().startsWith(serviceName
))
472 service
= service
.substring(serviceName
.length()).trim();
473 ndx
= service
.indexOf(' '); // get rid of attributes
475 service
= service
.substring(0, ndx
);
479 return Collections
.unmodifiableSet(result
);
483 * <p>Returns an array containing all installed providers that satisfy the
484 * specified selection criterion, or <code>null</code> if no such providers
485 * have been installed. The returned providers are ordered according to their
486 * preference order.</p>
488 * <p>A cryptographic service is always associated with a particular
489 * algorithm or type. For example, a digital signature service is always
490 * associated with a particular algorithm (e.g., <i>DSA</i>), and a
491 * CertificateFactory service is always associated with a particular
492 * certificate type (e.g., <i>X.509</i>).</p>
494 * <p>The selection criterion must be specified in one of the following two
498 * <li><p><crypto_service>.<algorithm_or_type></p>
499 * <p>The cryptographic service name must not contain any dots.</p>
500 * <p>A provider satisfies the specified selection criterion iff the
501 * provider implements the specified algorithm or type for the specified
502 * cryptographic service.</p>
503 * <p>For example, "CertificateFactory.X.509" would be satisfied by any
504 * provider that supplied a CertificateFactory implementation for X.509
505 * certificates.</p></li>
507 * <li><p><crypto_service>.<algorithm_or_type> <attribute_name>:<attribute_value></p>
508 * <p>The cryptographic service name must not contain any dots. There must
509 * be one or more space charaters between the the <algorithm_or_type>
510 * and the <attribute_name>.</p>
511 * <p>A provider satisfies this selection criterion iff the provider
512 * implements the specified algorithm or type for the specified
513 * cryptographic service and its implementation meets the constraint
514 * expressed by the specified attribute name/value pair.</p>
515 * <p>For example, "Signature.SHA1withDSA KeySize:1024" would be satisfied
516 * by any provider that implemented the SHA1withDSA signature algorithm
517 * with a keysize of 1024 (or larger).</p></li>
520 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
521 * & Reference for information about standard cryptographic service names,
522 * standard algorithm names and standard attribute names.</p>
524 * @param filter the criterion for selecting providers. The filter is case-
526 * @return all the installed providers that satisfy the selection criterion,
527 * or null if no such providers have been installed.
528 * @throws InvalidParameterException if the filter is not in the required
530 * @see #getProviders(Map)
532 public static Provider
[] getProviders(String filter
)
534 if (providers
== null || providers
.isEmpty())
537 if (filter
== null || filter
.length() == 0)
538 return getProviders();
540 HashMap map
= new HashMap(1);
541 int i
= filter
.indexOf(':');
542 if (i
== -1) // <service>.<algorithm>
544 else // <service>.<algorithm> <attribute>:<value>
545 map
.put(filter
.substring(0, i
), filter
.substring(i
+1));
547 return getProviders(map
);
551 * <p>Returns an array containing all installed providers that satisfy the
552 * specified selection criteria, or <code>null</code> if no such providers
553 * have been installed. The returned providers are ordered according to their
554 * preference order.</p>
556 * <p>The selection criteria are represented by a map. Each map entry
557 * represents a selection criterion. A provider is selected iff it satisfies
558 * all selection criteria. The key for any entry in such a map must be in one
559 * of the following two formats:</p>
562 * <li><p><crypto_service>.<algorithm_or_type></p>
563 * <p>The cryptographic service name must not contain any dots.</p>
564 * <p>The value associated with the key must be an empty string.</p>
565 * <p>A provider satisfies this selection criterion iff the provider
566 * implements the specified algorithm or type for the specified
567 * cryptographic service.</p></li>
569 * <li><p><crypto_service>.<algorithm_or_type> <attribute_name></p>
570 * <p>The cryptographic service name must not contain any dots. There must
571 * be one or more space charaters between the <algorithm_or_type> and
572 * the <attribute_name>.</p>
573 * <p>The value associated with the key must be a non-empty string. A
574 * provider satisfies this selection criterion iff the provider implements
575 * the specified algorithm or type for the specified cryptographic service
576 * and its implementation meets the constraint expressed by the specified
577 * attribute name/value pair.</p></li>
580 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
581 * & Reference for information about standard cryptographic service names,
582 * standard algorithm names and standard attribute names.</p>
584 * @param filter the criteria for selecting providers. The filter is case-
586 * @return all the installed providers that satisfy the selection criteria,
587 * or <code>null</code> if no such providers have been installed.
588 * @throws InvalidParameterException if the filter is not in the required
590 * @see #getProviders(String)
592 public static Provider
[] getProviders(Map filter
)
594 if (providers
== null || providers
.isEmpty())
598 return getProviders();
600 Set querries
= filter
.keySet();
601 if (querries
== null || querries
.isEmpty())
602 return getProviders();
604 LinkedHashSet result
= new LinkedHashSet(providers
); // assume all
606 String querry
, service
, algorithm
, attribute
, value
;
607 LinkedHashSet serviceProviders
= new LinkedHashSet(); // preserve insertion order
608 for (Iterator i
= querries
.iterator(); i
.hasNext(); )
610 querry
= (String
) i
.next();
611 if (querry
== null) // all providers
614 querry
= querry
.trim();
615 if (querry
.length() == 0) // all providers
618 dot
= querry
.indexOf('.');
619 if (dot
== -1) // syntax error
620 throw new InvalidParameterException(
621 "missing dot in '" + String
.valueOf(querry
)+"'");
623 value
= (String
) filter
.get(querry
);
624 // deconstruct querry into [service, algorithm, attribute]
625 if (value
== null || value
.trim().length() == 0) // <service>.<algorithm>
629 service
= querry
.substring(0, dot
).trim();
630 algorithm
= querry
.substring(dot
+1).trim();
632 else // <service>.<algorithm> <attribute>
634 ws
= querry
.indexOf(' ');
636 throw new InvalidParameterException(
637 "value (" + String
.valueOf(value
) +
638 ") is not empty, but querry (" + String
.valueOf(querry
) +
639 ") is missing at least one space character");
640 value
= value
.trim();
641 attribute
= querry
.substring(ws
+1).trim();
642 // was the dot in the attribute?
643 if (attribute
.indexOf('.') != -1)
644 throw new InvalidParameterException(
645 "attribute_name (" + String
.valueOf(attribute
) +
646 ") in querry (" + String
.valueOf(querry
) + ") contains a dot");
648 querry
= querry
.substring(0, ws
).trim();
649 service
= querry
.substring(0, dot
).trim();
650 algorithm
= querry
.substring(dot
+1).trim();
653 // service and algorithm must not be empty
654 if (service
.length() == 0)
655 throw new InvalidParameterException(
656 "<crypto_service> in querry (" + String
.valueOf(querry
) +
659 if (algorithm
.length() == 0)
660 throw new InvalidParameterException(
661 "<algorithm_or_type> in querry (" + String
.valueOf(querry
) +
664 selectProviders(service
, algorithm
, attribute
, value
, result
, serviceProviders
);
665 result
.retainAll(serviceProviders
); // eval next retaining found providers
666 if (result
.isEmpty()) // no point continuing
670 if (result
.isEmpty())
673 return (Provider
[]) result
.toArray(new Provider
[result
.size()]);
676 private static void selectProviders(String svc
, String algo
, String attr
,
677 String val
, LinkedHashSet providerSet
,
678 LinkedHashSet result
)
680 result
.clear(); // ensure we start with an empty result set
681 for (Iterator i
= providerSet
.iterator(); i
.hasNext(); )
683 Provider p
= (Provider
) i
.next();
684 if (provides(p
, svc
, algo
, attr
, val
))
689 private static boolean provides(Provider p
, String svc
, String algo
,
690 String attr
, String val
)
693 String serviceDotAlgorithm
= null;
696 boolean found
= false;
697 // if <svc>.<algo> <attr> is in the set then so is <svc>.<algo>
698 // but it may be stored under an alias <algo>. resolve
699 outer
: for (int r
= 0; r
< 3; r
++) // guard against circularity
701 serviceDotAlgorithm
= (svc
+"."+String
.valueOf(algo
)).trim();
702 for (it
= p
.keySet().iterator(); it
.hasNext(); )
704 key
= (String
) it
.next();
705 if (key
.equalsIgnoreCase(serviceDotAlgorithm
)) // eureka
710 // it may be there but as an alias
711 if (key
.equalsIgnoreCase(ALG_ALIAS
+ serviceDotAlgorithm
))
713 algo
= p
.getProperty(key
);
716 // else continue inner
723 // found a candidate for the querry. do we have an attr to match?
724 if (val
== null) // <service>.<algorithm> querry
727 // <service>.<algorithm> <attribute>; find the key entry that match
729 int limit
= serviceDotAlgorithm
.length() + 1;
730 for (it
= p
.keySet().iterator(); it
.hasNext(); )
732 key
= (String
) it
.next();
733 if (key
.length() <= limit
)
736 if (key
.substring(0, limit
).equalsIgnoreCase(serviceDotAlgorithm
+" "))
738 realAttr
= key
.substring(limit
).trim();
739 if (! realAttr
.equalsIgnoreCase(attr
))
742 // eveything matches so far. do the value
743 realVal
= p
.getProperty(key
);
747 realVal
= realVal
.trim();
748 // is it a string value?
749 if (val
.equalsIgnoreCase(realVal
))
752 // assume value is a number. cehck for greater-than-or-equal
753 return (new Integer(val
).intValue() >= new Integer(realVal
).intValue());