Merge from mainline
[official-gcc.git] / libjava / classpath / java / security / Security.java
blobd26d049c524be9df13c412ef96b6610bdd5f2ef8
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 import gnu.classpath.VMStackWalker;
47 import java.io.IOException;
48 import java.io.InputStream;
49 import java.net.URL;
50 import java.util.Collections;
51 import java.util.Enumeration;
52 import java.util.HashMap;
53 import java.util.HashSet;
54 import java.util.Iterator;
55 import java.util.LinkedHashSet;
56 import java.util.Map;
57 import java.util.Properties;
58 import java.util.Set;
59 import java.util.Vector;
61 /**
62 * This class centralizes all security properties and common security methods.
63 * One of its primary uses is to manage providers.
65 * @author Mark Benvenuto (ivymccough@worldnet.att.net)
67 public final class Security
69 private static final String ALG_ALIAS = "Alg.Alias.";
71 private static Vector providers = new Vector();
72 private static Properties secprops = new Properties();
74 static
76 String base = SystemProperties.getProperty("gnu.classpath.home.url");
77 String vendor = SystemProperties.getProperty("gnu.classpath.vm.shortname");
79 // Try VM specific security file
80 boolean loaded = loadProviders (base, vendor);
82 // Append classpath standard provider if possible
83 if (!loadProviders (base, "classpath")
84 && !loaded
85 && providers.size() == 0)
87 if (Configuration.DEBUG)
89 /* No providers found and both security files failed to
90 * load properly. Give a warning in case of DEBUG is
91 * enabled. Could be done with java.util.logging later.
93 System.err.println
94 ("WARNING: could not properly read security provider files:");
95 System.err.println
96 (" " + base + "/security/" + vendor
97 + ".security");
98 System.err.println
99 (" " + base + "/security/" + "classpath"
100 + ".security");
101 System.err.println
102 (" Falling back to standard GNU security provider");
104 providers.addElement (new gnu.java.security.provider.Gnu());
107 // This class can't be instantiated.
108 private Security()
113 * Tries to load the vender specific security providers from the given
114 * base URL. Returns true if the resource could be read and completely
115 * parsed successfully, false otherwise.
117 private static boolean loadProviders(String baseUrl, String vendor)
119 if (baseUrl == null || vendor == null)
120 return false;
122 boolean result = true;
123 String secfilestr = baseUrl + "/security/" + vendor + ".security";
126 InputStream fin = new URL(secfilestr).openStream();
127 secprops.load(fin);
129 int i = 1;
130 String name;
131 while ((name = secprops.getProperty("security.provider." + i)) != null)
133 Exception exception = null;
136 providers.addElement(Class.forName(name).newInstance());
138 catch (ClassNotFoundException x)
140 exception = x;
142 catch (InstantiationException x)
144 exception = x;
146 catch (IllegalAccessException x)
148 exception = x;
151 if (exception != null)
153 System.err.println ("WARNING: Error loading security provider "
154 + name + ": " + exception);
155 result = false;
157 i++;
160 catch (IOException ignored)
162 result = false;
165 return result;
169 * Gets a specified property for an algorithm. The algorithm name should be a
170 * standard name. See Appendix A in the Java Cryptography Architecture API
171 * Specification & Reference for information about standard algorithm
172 * names. One possible use is by specialized algorithm parsers, which may map
173 * classes to algorithms which they understand (much like {@link Key} parsers
174 * do).
176 * @param algName the algorithm name.
177 * @param propName the name of the property to get.
178 * @return the value of the specified property.
179 * @deprecated This method used to return the value of a proprietary property
180 * in the master file of the "SUN" Cryptographic Service Provider in order to
181 * determine how to parse algorithm-specific parameters. Use the new
182 * provider-based and algorithm-independent {@link AlgorithmParameters} and
183 * {@link KeyFactory} engine classes (introduced in the Java 2 platform)
184 * instead.
186 public static String getAlgorithmProperty(String algName, String propName)
188 if (algName == null || propName == null)
189 return null;
191 String property = String.valueOf(propName) + "." + String.valueOf(algName);
192 Provider p;
193 for (Iterator i = providers.iterator(); i.hasNext(); )
195 p = (Provider) i.next();
196 for (Iterator j = p.keySet().iterator(); j.hasNext(); )
198 String key = (String) j.next();
199 if (key.equalsIgnoreCase(property))
200 return p.getProperty(key);
203 return null;
207 * <p>Adds a new provider, at a specified position. The position is the
208 * preference order in which providers are searched for requested algorithms.
209 * Note that it is not guaranteed that this preference will be respected. The
210 * position is 1-based, that is, <code>1</code> is most preferred, followed by
211 * <code>2</code>, and so on.</p>
213 * <p>If the given provider is installed at the requested position, the
214 * provider that used to be at that position, and all providers with a
215 * position greater than position, are shifted up one position (towards the
216 * end of the list of installed providers).</p>
218 * <p>A provider cannot be added if it is already installed.</p>
220 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
221 * </code> method is called with the string <code>"insertProvider."+provider.
222 * getName()</code> to see if it's ok to add a new provider. If the default
223 * implementation of <code>checkSecurityAccess()</code> is used (i.e., that
224 * method is not overriden), then this will result in a call to the security
225 * manager's <code>checkPermission()</code> method with a
226 * <code>SecurityPermission("insertProvider."+provider.getName())</code>
227 * permission.</p>
229 * @param provider the provider to be added.
230 * @param position the preference position that the caller would like for
231 * this provider.
232 * @return the actual preference position in which the provider was added, or
233 * <code>-1</code> if the provider was not added because it is already
234 * installed.
235 * @throws SecurityException if a security manager exists and its
236 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
237 * to add a new provider.
238 * @see #getProvider(String)
239 * @see #removeProvider(String)
240 * @see SecurityPermission
242 public static int insertProviderAt(Provider provider, int position)
244 SecurityManager sm = System.getSecurityManager();
245 if (sm != null)
246 sm.checkSecurityAccess("insertProvider." + provider.getName());
248 position--;
249 int max = providers.size ();
250 for (int i = 0; i < max; i++)
252 if (((Provider) providers.elementAt(i)).getName().equals(provider.getName()))
253 return -1;
256 if (position < 0)
257 position = 0;
258 if (position > max)
259 position = max;
261 providers.insertElementAt(provider, position);
263 return position + 1;
267 * <p>Adds a provider to the next position available.</p>
269 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
270 * </code> method is called with the string <code>"insertProvider."+provider.
271 * getName()</code> to see if it's ok to add a new provider. If the default
272 * implementation of <code>checkSecurityAccess()</code> is used (i.e., that
273 * method is not overriden), then this will result in a call to the security
274 * manager's <code>checkPermission()</code> method with a
275 * <code>SecurityPermission("insertProvider."+provider.getName())</code>
276 * permission.</p>
278 * @param provider the provider to be added.
279 * @return the preference position in which the provider was added, or
280 * <code>-1</code> if the provider was not added because it is already
281 * installed.
282 * @throws SecurityException if a security manager exists and its
283 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
284 * to add a new provider.
285 * @see #getProvider(String)
286 * @see #removeProvider(String)
287 * @see SecurityPermission
289 public static int addProvider(Provider provider)
291 return insertProviderAt (provider, providers.size () + 1);
295 * <p>Removes the provider with the specified name.</p>
297 * <p>When the specified provider is removed, all providers located at a
298 * position greater than where the specified provider was are shifted down
299 * one position (towards the head of the list of installed providers).</p>
301 * <p>This method returns silently if the provider is not installed.</p>
303 * <p>First, if there is a security manager, its <code>checkSecurityAccess()
304 * </code> method is called with the string <code>"removeProvider."+name</code>
305 * to see if it's ok to remove the provider. If the default implementation of
306 * <code>checkSecurityAccess()</code> is used (i.e., that method is not
307 * overriden), then this will result in a call to the security manager's
308 * <code>checkPermission()</code> method with a <code>SecurityPermission(
309 * "removeProvider."+name)</code> permission.</p>
311 * @param name the name of the provider to remove.
312 * @throws SecurityException if a security manager exists and its
313 * {@link SecurityManager#checkSecurityAccess(String)} method denies access
314 * to remove the provider.
315 * @see #getProvider(String)
316 * @see #addProvider(Provider)
318 public static void removeProvider(String name)
320 SecurityManager sm = System.getSecurityManager();
321 if (sm != null)
322 sm.checkSecurityAccess("removeProvider." + name);
324 int max = providers.size ();
325 for (int i = 0; i < max; i++)
327 if (((Provider) providers.elementAt(i)).getName().equals(name))
329 providers.remove(i);
330 break;
336 * Returns an array containing all the installed providers. The order of the
337 * providers in the array is their preference order.
339 * @return an array of all the installed providers.
341 public static Provider[] getProviders()
343 Provider[] array = new Provider[providers.size ()];
344 providers.copyInto (array);
345 return array;
349 * Returns the provider installed with the specified name, if any. Returns
350 * <code>null</code> if no provider with the specified name is installed.
352 * @param name the name of the provider to get.
353 * @return the provider of the specified name.
354 * @see #removeProvider(String)
355 * @see #addProvider(Provider)
357 public static Provider getProvider(String name)
359 if (name == null)
360 return null;
361 else
363 name = name.trim();
364 if (name.length() == 0)
365 return null;
367 Provider p;
368 int max = providers.size ();
369 for (int i = 0; i < max; i++)
371 p = (Provider) providers.elementAt(i);
372 if (p.getName().equals(name))
373 return p;
375 return null;
379 * <p>Gets a security property value.</p>
381 * <p>First, if there is a security manager, its <code>checkPermission()</code>
382 * method is called with a <code>SecurityPermission("getProperty."+key)</code>
383 * permission to see if it's ok to retrieve the specified security property
384 * value.</p>
386 * @param key the key of the property being retrieved.
387 * @return the value of the security property corresponding to key.
388 * @throws SecurityException if a security manager exists and its
389 * {@link SecurityManager#checkPermission(Permission)} method denies access
390 * to retrieve the specified security property value.
391 * @see #setProperty(String, String)
392 * @see SecurityPermission
394 public static String getProperty(String key)
396 // XXX To prevent infinite recursion when the SecurityManager calls us,
397 // don't do a security check if the caller is trusted (by virtue of having
398 // been loaded by the bootstrap class loader).
399 SecurityManager sm = System.getSecurityManager();
400 if (sm != null && VMStackWalker.getCallingClassLoader() != null)
401 sm.checkSecurityAccess("getProperty." + key);
403 return secprops.getProperty(key);
407 * <p>Sets a security property value.</p>
409 * <p>First, if there is a security manager, its <code>checkPermission()</code>
410 * method is called with a <code>SecurityPermission("setProperty."+key)</code>
411 * permission to see if it's ok to set the specified security property value.
412 * </p>
414 * @param key the name of the property to be set.
415 * @param datum the value of the property to be set.
416 * @throws SecurityException if a security manager exists and its
417 * {@link SecurityManager#checkPermission(Permission)} method denies access
418 * to set the specified security property value.
419 * @see #getProperty(String)
420 * @see SecurityPermission
422 public static void setProperty(String key, String datum)
424 SecurityManager sm = System.getSecurityManager();
425 if (sm != null)
426 sm.checkSecurityAccess("setProperty." + key);
428 if (datum == null)
429 secprops.remove(key);
430 else
431 secprops.put(key, datum);
435 * Returns a Set of Strings containing the names of all available algorithms
436 * or types for the specified Java cryptographic service (e.g., Signature,
437 * MessageDigest, Cipher, Mac, KeyStore). Returns an empty Set if there is no
438 * provider that supports the specified service. For a complete list of Java
439 * cryptographic services, please see the Java Cryptography Architecture API
440 * Specification &amp; Reference. Note: the returned set is immutable.
442 * @param serviceName the name of the Java cryptographic service (e.g.,
443 * Signature, MessageDigest, Cipher, Mac, KeyStore). Note: this parameter is
444 * case-insensitive.
445 * @return a Set of Strings containing the names of all available algorithms
446 * or types for the specified Java cryptographic service or an empty set if
447 * no provider supports the specified service.
448 * @since 1.4
450 public static Set getAlgorithms(String serviceName)
452 HashSet result = new HashSet();
453 if (serviceName == null || serviceName.length() == 0)
454 return result;
456 serviceName = serviceName.trim();
457 if (serviceName.length() == 0)
458 return result;
460 serviceName = serviceName.toUpperCase()+".";
461 Provider[] providers = getProviders();
462 int ndx;
463 for (int i = 0; i < providers.length; i++)
464 for (Enumeration e = providers[i].propertyNames(); e.hasMoreElements(); )
466 String service = ((String) e.nextElement()).trim();
467 if (service.toUpperCase().startsWith(serviceName))
469 service = service.substring(serviceName.length()).trim();
470 ndx = service.indexOf(' '); // get rid of attributes
471 if (ndx != -1)
472 service = service.substring(0, ndx);
473 result.add(service);
476 return Collections.unmodifiableSet(result);
480 * <p>Returns an array containing all installed providers that satisfy the
481 * specified selection criterion, or <code>null</code> if no such providers
482 * have been installed. The returned providers are ordered according to their
483 * preference order.</p>
485 * <p>A cryptographic service is always associated with a particular
486 * algorithm or type. For example, a digital signature service is always
487 * associated with a particular algorithm (e.g., <i>DSA</i>), and a
488 * CertificateFactory service is always associated with a particular
489 * certificate type (e.g., <i>X.509</i>).</p>
491 * <p>The selection criterion must be specified in one of the following two
492 * formats:</p>
494 * <ul>
495 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt;</p>
496 * <p>The cryptographic service name must not contain any dots.</p>
497 * <p>A provider satisfies the specified selection criterion iff the
498 * provider implements the specified algorithm or type for the specified
499 * cryptographic service.</p>
500 * <p>For example, "CertificateFactory.X.509" would be satisfied by any
501 * provider that supplied a CertificateFactory implementation for X.509
502 * certificates.</p></li>
504 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt; &lt;attribute_name&gt;:&lt;attribute_value&gt;</p>
505 * <p>The cryptographic service name must not contain any dots. There must
506 * be one or more space charaters between the the &lt;algorithm_or_type&gt;
507 * and the &lt;attribute_name&gt;.</p>
508 * <p>A provider satisfies this selection criterion iff the provider
509 * implements the specified algorithm or type for the specified
510 * cryptographic service and its implementation meets the constraint
511 * expressed by the specified attribute name/value pair.</p>
512 * <p>For example, "Signature.SHA1withDSA KeySize:1024" would be satisfied
513 * by any provider that implemented the SHA1withDSA signature algorithm
514 * with a keysize of 1024 (or larger).</p></li>
515 * </ul>
517 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
518 * &amp; Reference for information about standard cryptographic service names,
519 * standard algorithm names and standard attribute names.</p>
521 * @param filter the criterion for selecting providers. The filter is case-
522 * insensitive.
523 * @return all the installed providers that satisfy the selection criterion,
524 * or null if no such providers have been installed.
525 * @throws InvalidParameterException if the filter is not in the required
526 * format.
527 * @see #getProviders(Map)
529 public static Provider[] getProviders(String filter)
531 if (providers == null || providers.isEmpty())
532 return null;
534 if (filter == null || filter.length() == 0)
535 return getProviders();
537 HashMap map = new HashMap(1);
538 int i = filter.indexOf(':');
539 if (i == -1) // <service>.<algorithm>
540 map.put(filter, "");
541 else // <service>.<algorithm> <attribute>:<value>
542 map.put(filter.substring(0, i), filter.substring(i+1));
544 return getProviders(map);
548 * <p>Returns an array containing all installed providers that satisfy the
549 * specified selection criteria, or <code>null</code> if no such providers
550 * have been installed. The returned providers are ordered according to their
551 * preference order.</p>
553 * <p>The selection criteria are represented by a map. Each map entry
554 * represents a selection criterion. A provider is selected iff it satisfies
555 * all selection criteria. The key for any entry in such a map must be in one
556 * of the following two formats:</p>
558 * <ul>
559 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt;</p>
560 * <p>The cryptographic service name must not contain any dots.</p>
561 * <p>The value associated with the key must be an empty string.</p>
562 * <p>A provider satisfies this selection criterion iff the provider
563 * implements the specified algorithm or type for the specified
564 * cryptographic service.</p></li>
566 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt; &lt;attribute_name&gt;</p>
567 * <p>The cryptographic service name must not contain any dots. There must
568 * be one or more space charaters between the &lt;algorithm_or_type&gt; and
569 * the &lt;attribute_name&gt;.</p>
570 * <p>The value associated with the key must be a non-empty string. A
571 * provider satisfies this selection criterion iff the provider implements
572 * the specified algorithm or type for the specified cryptographic service
573 * and its implementation meets the constraint expressed by the specified
574 * attribute name/value pair.</p></li>
575 * </ul>
577 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
578 * &amp; Reference for information about standard cryptographic service names,
579 * standard algorithm names and standard attribute names.</p>
581 * @param filter the criteria for selecting providers. The filter is case-
582 * insensitive.
583 * @return all the installed providers that satisfy the selection criteria,
584 * or <code>null</code> if no such providers have been installed.
585 * @throws InvalidParameterException if the filter is not in the required
586 * format.
587 * @see #getProviders(String)
589 public static Provider[] getProviders(Map filter)
591 if (providers == null || providers.isEmpty())
592 return null;
594 if (filter == null)
595 return getProviders();
597 Set querries = filter.keySet();
598 if (querries == null || querries.isEmpty())
599 return getProviders();
601 LinkedHashSet result = new LinkedHashSet(providers); // assume all
602 int dot, ws;
603 String querry, service, algorithm, attribute, value;
604 LinkedHashSet serviceProviders = new LinkedHashSet(); // preserve insertion order
605 for (Iterator i = querries.iterator(); i.hasNext(); )
607 querry = (String) i.next();
608 if (querry == null) // all providers
609 continue;
611 querry = querry.trim();
612 if (querry.length() == 0) // all providers
613 continue;
615 dot = querry.indexOf('.');
616 if (dot == -1) // syntax error
617 throw new InvalidParameterException(
618 "missing dot in '" + String.valueOf(querry)+"'");
620 value = (String) filter.get(querry);
621 // deconstruct querry into [service, algorithm, attribute]
622 if (value == null || value.trim().length() == 0) // <service>.<algorithm>
624 value = null;
625 attribute = null;
626 service = querry.substring(0, dot).trim();
627 algorithm = querry.substring(dot+1).trim();
629 else // <service>.<algorithm> <attribute>
631 ws = querry.indexOf(' ');
632 if (ws == -1)
633 throw new InvalidParameterException(
634 "value (" + String.valueOf(value) +
635 ") is not empty, but querry (" + String.valueOf(querry) +
636 ") is missing at least one space character");
637 value = value.trim();
638 attribute = querry.substring(ws+1).trim();
639 // was the dot in the attribute?
640 if (attribute.indexOf('.') != -1)
641 throw new InvalidParameterException(
642 "attribute_name (" + String.valueOf(attribute) +
643 ") in querry (" + String.valueOf(querry) + ") contains a dot");
645 querry = querry.substring(0, ws).trim();
646 service = querry.substring(0, dot).trim();
647 algorithm = querry.substring(dot+1).trim();
650 // service and algorithm must not be empty
651 if (service.length() == 0)
652 throw new InvalidParameterException(
653 "<crypto_service> in querry (" + String.valueOf(querry) +
654 ") is empty");
656 if (algorithm.length() == 0)
657 throw new InvalidParameterException(
658 "<algorithm_or_type> in querry (" + String.valueOf(querry) +
659 ") is empty");
661 selectProviders(service, algorithm, attribute, value, result, serviceProviders);
662 result.retainAll(serviceProviders); // eval next retaining found providers
663 if (result.isEmpty()) // no point continuing
664 break;
667 if (result.isEmpty())
668 return null;
670 return (Provider[]) result.toArray(new Provider[result.size()]);
673 private static void selectProviders(String svc, String algo, String attr,
674 String val, LinkedHashSet providerSet,
675 LinkedHashSet result)
677 result.clear(); // ensure we start with an empty result set
678 for (Iterator i = providerSet.iterator(); i.hasNext(); )
680 Provider p = (Provider) i.next();
681 if (provides(p, svc, algo, attr, val))
682 result.add(p);
686 private static boolean provides(Provider p, String svc, String algo,
687 String attr, String val)
689 Iterator it;
690 String serviceDotAlgorithm = null;
691 String key = null;
692 String realVal;
693 boolean found = false;
694 // if <svc>.<algo> <attr> is in the set then so is <svc>.<algo>
695 // but it may be stored under an alias <algo>. resolve
696 outer: for (int r = 0; r < 3; r++) // guard against circularity
698 serviceDotAlgorithm = (svc+"."+String.valueOf(algo)).trim();
699 for (it = p.keySet().iterator(); it.hasNext(); )
701 key = (String) it.next();
702 if (key.equalsIgnoreCase(serviceDotAlgorithm)) // eureka
704 found = true;
705 break outer;
707 // it may be there but as an alias
708 if (key.equalsIgnoreCase(ALG_ALIAS + serviceDotAlgorithm))
710 algo = p.getProperty(key);
711 continue outer;
713 // else continue inner
717 if (!found)
718 return false;
720 // found a candidate for the querry. do we have an attr to match?
721 if (val == null) // <service>.<algorithm> querry
722 return true;
724 // <service>.<algorithm> <attribute>; find the key entry that match
725 String realAttr;
726 int limit = serviceDotAlgorithm.length() + 1;
727 for (it = p.keySet().iterator(); it.hasNext(); )
729 key = (String) it.next();
730 if (key.length() <= limit)
731 continue;
733 if (key.substring(0, limit).equalsIgnoreCase(serviceDotAlgorithm+" "))
735 realAttr = key.substring(limit).trim();
736 if (! realAttr.equalsIgnoreCase(attr))
737 continue;
739 // eveything matches so far. do the value
740 realVal = p.getProperty(key);
741 if (realVal == null)
742 return false;
744 realVal = realVal.trim();
745 // is it a string value?
746 if (val.equalsIgnoreCase(realVal))
747 return true;
749 // assume value is a number. cehck for greater-than-or-equal
750 return (new Integer(val).intValue() >= new Integer(realVal).intValue());
754 return false;