Merge from mainline
[official-gcc.git] / libjava / java / security / Security.java
blob001d35ee0268aa2cf0d38f7eb1079968660295e0
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)
10 any later version.
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
20 02110-1301 USA.
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
25 combination.
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;
50 import java.net.URL;
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;
57 import java.util.Map;
58 import java.util.Properties;
59 import java.util.Set;
60 import java.util.Vector;
62 /**
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();
75 static
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")
85 && !loaded
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.
94 System.err.println
95 ("WARNING: could not properly read security provider files:");
96 System.err.println
97 (" " + base + "/security/" + vendor
98 + ".security");
99 System.err.println
100 (" " + base + "/security/" + "classpath"
101 + ".security");
102 System.err.println
103 (" Falling back to standard GNU security provider");
105 providers.addElement (new gnu.java.security.provider.Gnu());
108 // This class can't be instantiated.
109 private Security()
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)
121 return false;
123 boolean result = true;
124 String secfilestr = baseUrl + "/security/" + vendor + ".security";
127 InputStream fin = new URL(secfilestr).openStream();
128 secprops.load(fin);
130 int i = 1;
131 String name;
132 while ((name = secprops.getProperty("security.provider." + i)) != null)
134 Exception exception = null;
137 providers.addElement(Class.forName(name).newInstance());
139 catch (ClassNotFoundException x)
141 exception = x;
143 catch (InstantiationException x)
145 exception = x;
147 catch (IllegalAccessException x)
149 exception = x;
152 if (exception != null)
154 System.err.println ("WARNING: Error loading security provider "
155 + name + ": " + exception);
156 result = false;
158 i++;
161 catch (IOException ignored)
163 result = false;
166 return result;
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
175 * do).
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)
185 * instead.
187 public static String getAlgorithmProperty(String algName, String propName)
189 if (algName == null || propName == null)
190 return null;
192 String property = String.valueOf(propName) + "." + String.valueOf(algName);
193 Provider p;
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);
204 return null;
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>
228 * permission.</p>
230 * @param provider the provider to be added.
231 * @param position the preference position that the caller would like for
232 * this provider.
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
235 * installed.
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();
246 if (sm != null)
247 sm.checkSecurityAccess("insertProvider." + provider.getName());
249 position--;
250 int max = providers.size ();
251 for (int i = 0; i < max; i++)
253 if (((Provider) providers.elementAt(i)).getName().equals(provider.getName()))
254 return -1;
257 if (position < 0)
258 position = 0;
259 if (position > max)
260 position = max;
262 providers.insertElementAt(provider, position);
264 return position + 1;
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>
277 * permission.</p>
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
282 * installed.
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();
322 if (sm != null)
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))
330 providers.remove(i);
331 break;
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);
346 return 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)
360 if (name == null)
361 return null;
362 else
364 name = name.trim();
365 if (name.length() == 0)
366 return null;
368 Provider p;
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))
374 return p;
376 return null;
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
385 * value.</p>
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)
403 if (sm != 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.
415 * </p>
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();
428 if (sm != null)
429 sm.checkSecurityAccess("setProperty." + key);
431 if (datum == null)
432 secprops.remove(key);
433 else
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 &amp; 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
447 * case-insensitive.
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.
451 * @since 1.4
453 public static Set getAlgorithms(String serviceName)
455 HashSet result = new HashSet();
456 if (serviceName == null || serviceName.length() == 0)
457 return result;
459 serviceName = serviceName.trim();
460 if (serviceName.length() == 0)
461 return result;
463 serviceName = serviceName.toUpperCase()+".";
464 Provider[] providers = getProviders();
465 int ndx;
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
474 if (ndx != -1)
475 service = service.substring(0, ndx);
476 result.add(service);
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
495 * formats:</p>
497 * <ul>
498 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt;</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>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt; &lt;attribute_name&gt;:&lt;attribute_value&gt;</p>
508 * <p>The cryptographic service name must not contain any dots. There must
509 * be one or more space charaters between the the &lt;algorithm_or_type&gt;
510 * and the &lt;attribute_name&gt;.</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>
518 * </ul>
520 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
521 * &amp; 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-
525 * insensitive.
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
529 * format.
530 * @see #getProviders(Map)
532 public static Provider[] getProviders(String filter)
534 if (providers == null || providers.isEmpty())
535 return null;
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>
543 map.put(filter, "");
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>
561 * <ul>
562 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt;</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>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt; &lt;attribute_name&gt;</p>
570 * <p>The cryptographic service name must not contain any dots. There must
571 * be one or more space charaters between the &lt;algorithm_or_type&gt; and
572 * the &lt;attribute_name&gt;.</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>
578 * </ul>
580 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
581 * &amp; 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-
585 * insensitive.
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
589 * format.
590 * @see #getProviders(String)
592 public static Provider[] getProviders(Map filter)
594 if (providers == null || providers.isEmpty())
595 return null;
597 if (filter == null)
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
605 int dot, ws;
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
612 continue;
614 querry = querry.trim();
615 if (querry.length() == 0) // all providers
616 continue;
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>
627 value = null;
628 attribute = null;
629 service = querry.substring(0, dot).trim();
630 algorithm = querry.substring(dot+1).trim();
632 else // <service>.<algorithm> <attribute>
634 ws = querry.indexOf(' ');
635 if (ws == -1)
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) +
657 ") is empty");
659 if (algorithm.length() == 0)
660 throw new InvalidParameterException(
661 "<algorithm_or_type> in querry (" + String.valueOf(querry) +
662 ") is empty");
664 selectProviders(service, algorithm, attribute, value, result, serviceProviders);
665 result.retainAll(serviceProviders); // eval next retaining found providers
666 if (result.isEmpty()) // no point continuing
667 break;
670 if (result.isEmpty())
671 return null;
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))
685 result.add(p);
689 private static boolean provides(Provider p, String svc, String algo,
690 String attr, String val)
692 Iterator it;
693 String serviceDotAlgorithm = null;
694 String key = null;
695 String realVal;
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
707 found = true;
708 break outer;
710 // it may be there but as an alias
711 if (key.equalsIgnoreCase(ALG_ALIAS + serviceDotAlgorithm))
713 algo = p.getProperty(key);
714 continue outer;
716 // else continue inner
720 if (!found)
721 return false;
723 // found a candidate for the querry. do we have an attr to match?
724 if (val == null) // <service>.<algorithm> querry
725 return true;
727 // <service>.<algorithm> <attribute>; find the key entry that match
728 String realAttr;
729 int limit = serviceDotAlgorithm.length() + 1;
730 for (it = p.keySet().iterator(); it.hasNext(); )
732 key = (String) it.next();
733 if (key.length() <= limit)
734 continue;
736 if (key.substring(0, limit).equalsIgnoreCase(serviceDotAlgorithm+" "))
738 realAttr = key.substring(limit).trim();
739 if (! realAttr.equalsIgnoreCase(attr))
740 continue;
742 // eveything matches so far. do the value
743 realVal = p.getProperty(key);
744 if (realVal == null)
745 return false;
747 realVal = realVal.trim();
748 // is it a string value?
749 if (val.equalsIgnoreCase(realVal))
750 return true;
752 // assume value is a number. cehck for greater-than-or-equal
753 return (new Integer(val).intValue() >= new Integer(realVal).intValue());
757 return false;