1 /* Security.java --- Java base security class implementation
2 Copyright (C) 1999, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
39 package java.security;
41 import gnu.java.security.action.GetPropertyAction;
43 import java.io.IOException;
44 import java.io.InputStream;
46 import java.util.Collections;
47 import java.util.Enumeration;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.Iterator;
51 import java.util.LinkedHashSet;
53 import java.util.Properties;
55 import java.util.Vector;
58 * This class centralizes all security properties and common security methods.
59 * One of its primary uses is to manage providers.
61 * @author Mark Benvenuto (ivymccough@worldnet.att.net)
63 public final class Security
65 private static final String ALG_ALIAS = "Alg.Alias.";
67 private static Vector providers = new Vector();
68 private static Properties secprops = new Properties();
72 GetPropertyAction getProp = new GetPropertyAction("gnu.classpath.home.url");
73 String base = (String) AccessController.doPrivileged(getProp);
74 getProp = new GetPropertyAction("gnu.classpath.vm.shortname");
75 String vendor = (String) AccessController.doPrivileged(getProp);
77 // Try VM specific security file
78 boolean loaded = loadProviders (base, vendor);
80 // Append classpath standard provider if possible
81 if (!loadProviders (base, "classpath")
83 && providers.size() == 0)
85 // No providers found and both security files failed to load properly.
87 ("WARNING: could not properly read security provider files:");
89 (" " + base + "/security/" + vendor + ".security");
91 (" " + base + "/security/" + "classpath" + ".security");
93 (" Falling back to standard GNU security provider");
94 providers.addElement (new gnu.java.security.provider.Gnu());
98 // This class can't be instantiated.
104 * Tries to load the vender specific security providers from the given
105 * base URL. Returns true if the resource could be read and completely
106 * parsed successfully, false otherwise.
108 private static boolean loadProviders(String baseUrl, String vendor)
110 if (baseUrl == null || vendor == null)
113 boolean result = true;
114 String secfilestr = baseUrl + "/security/" + vendor + ".security";
117 InputStream fin = new URL(secfilestr).openStream();
122 while ((name = secprops.getProperty("security.provider." + i)) != null)
124 Exception exception = null;
127 providers.addElement(Class.forName(name).newInstance());
129 catch (ClassNotFoundException x)
133 catch (InstantiationException x)
137 catch (IllegalAccessException x)
142 if (exception != null)
144 System.err.println ("WARNING: Error loading security provider "
145 + name + ": " + exception);
151 catch (IOException ignored)
160 * Gets a specified property for an algorithm. The algorithm name should be a
161 * standard name. See Appendix A in the Java Cryptography Architecture API
162 * Specification & Reference for information about standard algorithm
163 * names. One possible use is by specialized algorithm parsers, which may map
164 * classes to algorithms which they understand (much like {@link Key} parsers
167 * @param algName the algorithm name.
168 * @param propName the name of the property to get.
169 * @return the value of the specified property.
170 * @deprecated This method used to return the value of a proprietary property
171 * in the master file of the "SUN" Cryptographic Service Provider in order to
172 * determine how to parse algorithm-specific parameters. Use the new
173 * provider-based and algorithm-independent {@link AlgorithmParameters} and
174 * {@link KeyFactory} engine classes (introduced in the Java 2 platform)
177 public static String getAlgorithmProperty(String algName, String propName)
179 if (algName == null || propName == null)
182 String property = String.valueOf(propName) + "." + String.valueOf(algName);
184 for (Iterator i = providers.iterator(); i.hasNext(); )
186 p = (Provider) i.next();
187 for (Iterator j = p.keySet().iterator(); j.hasNext(); )
189 String key = (String) j.next();
190 if (key.equalsIgnoreCase(property))
191 return p.getProperty(key);
198 * <p>Adds a new provider, at a specified position. The position is the
199 * preference order in which providers are searched for requested algorithms.
200 * Note that it is not guaranteed that this preference will be respected. The
201 * position is 1-based, that is, <code>1</code> is most preferred, followed by
202 * <code>2</code>, and so on.</p>
204 * <p>If the given provider is installed at the requested position, the
205 * provider that used to be at that position, and all providers with a
206 * position greater than position, are shifted up one position (towards the
207 * end of the list of installed providers).</p>
209 * <p>A provider cannot be added if it is already installed.</p>
211 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
212 * </code> method is called with the string <code>"insertProvider."+provider.
213 * getName()</code> to see if it's ok to add a new provider. If the default
214 * implementation of <code>checkSecurityAccess()</code> is used (i.e., that
215 * method is not overriden), then this will result in a call to the security
216 * manager's <code>checkPermission()</code> method with a
217 * <code>SecurityPermission("insertProvider."+provider.getName())</code>
220 * @param provider the provider to be added.
221 * @param position the preference position that the caller would like for
223 * @return the actual preference position in which the provider was added, or
224 * <code>-1</code> if the provider was not added because it is already
226 * @throws SecurityException if a security manager exists and its
227 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
228 * to add a new provider.
229 * @see #getProvider(String)
230 * @see #removeProvider(String)
231 * @see SecurityPermission
233 public static int insertProviderAt(Provider provider, int position)
235 SecurityManager sm = System.getSecurityManager();
237 sm.checkSecurityAccess("insertProvider." + provider.getName());
240 int max = providers.size ();
241 for (int i = 0; i < max; i++)
243 if (((Provider) providers.elementAt(i)).getName().equals(provider.getName()))
252 providers.insertElementAt(provider, position);
258 * <p>Adds a provider to the next position available.</p>
260 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
261 * </code> method is called with the string <code>"insertProvider."+provider.
262 * getName()</code> to see if it's ok to add a new provider. If the default
263 * implementation of <code>checkSecurityAccess()</code> is used (i.e., that
264 * method is not overriden), then this will result in a call to the security
265 * manager's <code>checkPermission()</code> method with a
266 * <code>SecurityPermission("insertProvider."+provider.getName())</code>
269 * @param provider the provider to be added.
270 * @return the preference position in which the provider was added, or
271 * <code>-1</code> if the provider was not added because it is already
273 * @throws SecurityException if a security manager exists and its
274 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
275 * to add a new provider.
276 * @see #getProvider(String)
277 * @see #removeProvider(String)
278 * @see SecurityPermission
280 public static int addProvider(Provider provider)
282 return insertProviderAt (provider, providers.size () + 1);
286 * <p>Removes the provider with the specified name.</p>
288 * <p>When the specified provider is removed, all providers located at a
289 * position greater than where the specified provider was are shifted down
290 * one position (towards the head of the list of installed providers).</p>
292 * <p>This method returns silently if the provider is not installed.</p>
294 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
295 * </code> method is called with the string <code>"removeProvider."+name</code>
296 * to see if it's ok to remove the provider. If the default implementation of
297 * <code>checkSecurityAccess()</code> is used (i.e., that method is not
298 * overriden), then this will result in a call to the security manager's
299 * <code>checkPermission()</code> method with a <code>SecurityPermission(
300 * "removeProvider."+name)</code> permission.</p>
302 * @param name the name of the provider to remove.
303 * @throws SecurityException if a security manager exists and its
304 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
305 * to remove the provider.
306 * @see #getProvider(String)
307 * @see #addProvider(Provider)
309 public static void removeProvider(String name)
311 SecurityManager sm = System.getSecurityManager();
313 sm.checkSecurityAccess("removeProvider." + name);
315 int max = providers.size ();
316 for (int i = 0; i < max; i++)
318 if (((Provider) providers.elementAt(i)).getName().equals(name))
327 * Returns an array containing all the installed providers. The order of the
328 * providers in the array is their preference order.
330 * @return an array of all the installed providers.
332 public static Provider[] getProviders()
334 Provider[] array = new Provider[providers.size ()];
335 providers.copyInto (array);
340 * Returns the provider installed with the specified name, if any. Returns
341 * <code>null</code> if no provider with the specified name is installed.
343 * @param name the name of the provider to get.
344 * @return the provider of the specified name.
345 * @see #removeProvider(String)
346 * @see #addProvider(Provider)
348 public static Provider getProvider(String name)
351 int max = providers.size ();
352 for (int i = 0; i < max; i++)
354 p = (Provider) providers.elementAt(i);
355 if (p.getName().equals(name))
362 * <p>Gets a security property value.</p>
364 * <p>First, if there is a security manager, its <code>checkPermission()</code>
365 * method is called with a <code>SecurityPermission("getProperty."+key)</code>
366 * permission to see if it's ok to retrieve the specified security property
369 * @param key the key of the property being retrieved.
370 * @return the value of the security property corresponding to key.
371 * @throws SecurityException if a security manager exists and its
372 * {@link SecurityManager#checkPermission(Permission)} method denies access
373 * to retrieve the specified security property value.
374 * @see #setProperty(String, String)
375 * @see SecurityPermission
377 public static String getProperty(String key)
379 SecurityManager sm = System.getSecurityManager();
381 sm.checkSecurityAccess("getProperty." + key);
383 return secprops.getProperty(key);
387 * <p>Sets a security property value.</p>
389 * <p>First, if there is a security manager, its <code>checkPermission()</code>
390 * method is called with a <code>SecurityPermission("setProperty."+key)</code>
391 * permission to see if it's ok to set the specified security property value.
394 * @param key the name of the property to be set.
395 * @param datnum the value of the property to be set.
396 * @throws SecurityException if a security manager exists and its
397 * {@link SecurityManager#checkPermission(Permission)} method denies access
398 * to set the specified security property value.
399 * @see #getProperty(String)
400 * @see SecurityPermission
402 public static void setProperty(String key, String datnum)
404 SecurityManager sm = System.getSecurityManager();
406 sm.checkSecurityAccess("setProperty." + key);
408 secprops.put(key, datnum);
412 * Returns a Set of Strings containing the names of all available algorithms
413 * or types for the specified Java cryptographic service (e.g., Signature,
414 * MessageDigest, Cipher, Mac, KeyStore). Returns an empty Set if there is no
415 * provider that supports the specified service. For a complete list of Java
416 * cryptographic services, please see the Java Cryptography Architecture API
417 * Specification & Reference. Note: the returned set is immutable.
419 * @param serviceName the name of the Java cryptographic service (e.g.,
420 * Signature, MessageDigest, Cipher, Mac, KeyStore). Note: this parameter is
422 * @return a Set of Strings containing the names of all available algorithms
423 * or types for the specified Java cryptographic service or an empty set if
424 * no provider supports the specified service.
427 public static Set getAlgorithms(String serviceName)
429 HashSet result = new HashSet();
430 if (serviceName == null || serviceName.length() == 0)
433 serviceName = serviceName.trim();
434 if (serviceName.length() == 0)
437 serviceName = serviceName.toUpperCase()+".";
438 Provider[] providers = getProviders();
440 for (int i = 0; i < providers.length; i++)
441 for (Enumeration e = providers[i].propertyNames(); e.hasMoreElements(); )
443 String service = ((String) e.nextElement()).trim();
444 if (service.toUpperCase().startsWith(serviceName))
446 service = service.substring(serviceName.length()).trim();
447 ndx = service.indexOf(' '); // get rid of attributes
449 service = service.substring(0, ndx);
453 return Collections.unmodifiableSet(result);
457 * <p>Returns an array containing all installed providers that satisfy the
458 * specified selection criterion, or <code>null</code> if no such providers
459 * have been installed. The returned providers are ordered according to their
460 * preference order.</p>
462 * <p>A cryptographic service is always associated with a particular
463 * algorithm or type. For example, a digital signature service is always
464 * associated with a particular algorithm (e.g., <i>DSA</i>), and a
465 * CertificateFactory service is always associated with a particular
466 * certificate type (e.g., <i>X.509</i>).</p>
468 * <p>The selection criterion must be specified in one of the following two
472 * <li><p><crypto_service>.<algorithm_or_type></p>
473 * <p>The cryptographic service name must not contain any dots.</p>
474 * <p>A provider satisfies the specified selection criterion iff the
475 * provider implements the specified algorithm or type for the specified
476 * cryptographic service.</p>
477 * <p>For example, "CertificateFactory.X.509" would be satisfied by any
478 * provider that supplied a CertificateFactory implementation for X.509
479 * certificates.</p></li>
481 * <li><p><crypto_service>.<algorithm_or_type> <attribute_name>:<attribute_value></p>
482 * <p>The cryptographic service name must not contain any dots. There must
483 * be one or more space charaters between the the <algorithm_or_type>
484 * and the <attribute_name>.</p>
485 * <p>A provider satisfies this selection criterion iff the provider
486 * implements the specified algorithm or type for the specified
487 * cryptographic service and its implementation meets the constraint
488 * expressed by the specified attribute name/value pair.</p>
489 * <p>For example, "Signature.SHA1withDSA KeySize:1024" would be satisfied
490 * by any provider that implemented the SHA1withDSA signature algorithm
491 * with a keysize of 1024 (or larger).</p></li>
494 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
495 * & Reference for information about standard cryptographic service names,
496 * standard algorithm names and standard attribute names.</p>
498 * @param filter the criterion for selecting providers. The filter is case-
500 * @return all the installed providers that satisfy the selection criterion,
501 * or null if no such providers have been installed.
502 * @throws InvalidParameterException if the filter is not in the required
504 * @see #getProviders(Map)
506 public static Provider[] getProviders(String filter)
508 if (providers == null || providers.isEmpty())
511 if (filter == null || filter.length() == 0)
512 return getProviders();
514 HashMap map = new HashMap(1);
515 int i = filter.indexOf(':');
516 if (i == -1) // <service>.<algorithm>
518 else // <service>.<algorithm> <attribute>:<value>
519 map.put(filter.substring(0, i), filter.substring(i+1));
521 return getProviders(map);
525 * <p>Returns an array containing all installed providers that satisfy the
526 * specified selection criteria, or <code>null</code> if no such providers
527 * have been installed. The returned providers are ordered according to their
528 * preference order.</p>
530 * <p>The selection criteria are represented by a map. Each map entry
531 * represents a selection criterion. A provider is selected iff it satisfies
532 * all selection criteria. The key for any entry in such a map must be in one
533 * of the following two formats:</p>
536 * <li><p><crypto_service>.<algorithm_or_type></p>
537 * <p>The cryptographic service name must not contain any dots.</p>
538 * <p>The value associated with the key must be an empty string.</p>
539 * <p>A provider satisfies this selection criterion iff the provider
540 * implements the specified algorithm or type for the specified
541 * cryptographic service.</p></li>
543 * <li><p><crypto_service>.<algorithm_or_type> <attribute_name></p>
544 * <p>The cryptographic service name must not contain any dots. There must
545 * be one or more space charaters between the <algorithm_or_type> and
546 * the <attribute_name>.</p>
547 * <p>The value associated with the key must be a non-empty string. A
548 * provider satisfies this selection criterion iff the provider implements
549 * the specified algorithm or type for the specified cryptographic service
550 * and its implementation meets the constraint expressed by the specified
551 * attribute name/value pair.</p></li>
554 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
555 * & Reference for information about standard cryptographic service names,
556 * standard algorithm names and standard attribute names.</p>
558 * @param filter the criteria for selecting providers. The filter is case-
560 * @return all the installed providers that satisfy the selection criteria,
561 * or <code>null</code> if no such providers have been installed.
562 * @throws InvalidParameterException if the filter is not in the required
564 * @see #getProviders(String)
566 public static Provider[] getProviders(Map filter)
568 if (providers == null || providers.isEmpty())
572 return getProviders();
574 Set querries = filter.keySet();
575 if (querries == null || querries.isEmpty())
576 return getProviders();
578 LinkedHashSet result = new LinkedHashSet(providers); // assume all
580 String querry, service, algorithm, attribute, value;
581 LinkedHashSet serviceProviders = new LinkedHashSet(); // preserve insertion order
582 for (Iterator i = querries.iterator(); i.hasNext(); )
584 querry = (String) i.next();
585 if (querry == null) // all providers
588 querry = querry.trim();
589 if (querry.length() == 0) // all providers
592 dot = querry.indexOf('.');
593 if (dot == -1) // syntax error
594 throw new InvalidParameterException(
595 "missing dot in '" + String.valueOf(querry)+"'");
597 value = (String) filter.get(querry);
598 // deconstruct querry into [service, algorithm, attribute]
599 if (value == null || value.trim().length() == 0) // <service>.<algorithm>
603 service = querry.substring(0, dot).trim();
604 algorithm = querry.substring(dot+1).trim();
606 else // <service>.<algorithm> <attribute>
608 ws = querry.indexOf(' ');
610 throw new InvalidParameterException(
611 "value (" + String.valueOf(value) +
612 ") is not empty, but querry (" + String.valueOf(querry) +
613 ") is missing at least one space character");
614 value = value.trim();
615 attribute = querry.substring(ws+1).trim();
616 // was the dot in the attribute?
617 if (attribute.indexOf('.') != -1)
618 throw new InvalidParameterException(
619 "attribute_name (" + String.valueOf(attribute) +
620 ") in querry (" + String.valueOf(querry) + ") contains a dot");
622 querry = querry.substring(0, ws).trim();
623 service = querry.substring(0, dot).trim();
624 algorithm = querry.substring(dot+1).trim();
627 // service and algorithm must not be empty
628 if (service.length() == 0)
629 throw new InvalidParameterException(
630 "<crypto_service> in querry (" + String.valueOf(querry) +
633 if (algorithm.length() == 0)
634 throw new InvalidParameterException(
635 "<algorithm_or_type> in querry (" + String.valueOf(querry) +
638 selectProviders(service, algorithm, attribute, value, result, serviceProviders);
639 result.retainAll(serviceProviders); // eval next retaining found providers
640 if (result.isEmpty()) // no point continuing
644 if (result.isEmpty())
647 return (Provider[]) result.toArray(new Provider[0]);
650 private static void selectProviders(String svc, String algo, String attr,
651 String val, LinkedHashSet providerSet,
652 LinkedHashSet result)
654 result.clear(); // ensure we start with an empty result set
655 for (Iterator i = providerSet.iterator(); i.hasNext(); )
657 Provider p = (Provider) i.next();
658 if (provides(p, svc, algo, attr, val))
663 private static boolean provides(Provider p, String svc, String algo,
664 String attr, String val)
667 String serviceDotAlgorithm = null;
670 boolean found = false;
671 // if <svc>.<algo> <attr> is in the set then so is <svc>.<algo>
672 // but it may be stored under an alias <algo>. resolve
673 outer: for (int r = 0; r < 3; r++) // guard against circularity
675 serviceDotAlgorithm = (svc+"."+String.valueOf(algo)).trim();
676 for (it = p.keySet().iterator(); it.hasNext(); )
678 key = (String) it.next();
679 if (key.equalsIgnoreCase(serviceDotAlgorithm)) // eureka
684 // it may be there but as an alias
685 if (key.equalsIgnoreCase(ALG_ALIAS + serviceDotAlgorithm))
687 algo = p.getProperty(key);
690 // else continue inner
697 // found a candidate for the querry. do we have an attr to match?
698 if (val == null) // <service>.<algorithm> querry
701 // <service>.<algorithm> <attribute>; find the key entry that match
703 int limit = serviceDotAlgorithm.length() + 1;
704 for (it = p.keySet().iterator(); it.hasNext(); )
706 key = (String) it.next();
707 if (key.length() <= limit)
710 if (key.substring(0, limit).equalsIgnoreCase(serviceDotAlgorithm+" "))
712 realAttr = key.substring(limit).trim();
713 if (! realAttr.equalsIgnoreCase(attr))
716 // eveything matches so far. do the value
717 realVal = p.getProperty(key);
721 realVal = realVal.trim();
722 // is it a string value?
723 if (val.equalsIgnoreCase(realVal))
726 // assume value is a number. cehck for greater-than-or-equal
727 return (new Integer(val).intValue() >= new Integer(realVal).intValue());