Merge from mainline (gomp-merge-2005-02-26).
[official-gcc.git] / libjava / java / security / Security.java
blob01c0a0587d6b77834ffdd8e6c20e3944d500ef0b
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)
9 any later version.
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
19 02111-1307 USA.
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
24 combination.
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 gnu.classpath.Configuration;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.net.URL;
48 import java.util.Collections;
49 import java.util.Enumeration;
50 import java.util.HashMap;
51 import java.util.HashSet;
52 import java.util.Iterator;
53 import java.util.LinkedHashSet;
54 import java.util.Map;
55 import java.util.Properties;
56 import java.util.Set;
57 import java.util.Vector;
59 /**
60 * This class centralizes all security properties and common security methods.
61 * One of its primary uses is to manage providers.
63 * @author Mark Benvenuto (ivymccough@worldnet.att.net)
65 public final class Security
67 private static final String ALG_ALIAS = "Alg.Alias.";
69 private static Vector providers = new Vector();
70 private static Properties secprops = new Properties();
72 static
74 GetPropertyAction getProp = new GetPropertyAction("gnu.classpath.home.url");
75 String base = (String) AccessController.doPrivileged(getProp);
76 getProp = new GetPropertyAction("gnu.classpath.vm.shortname");
77 String vendor = (String) AccessController.doPrivileged(getProp);
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 Provider p;
360 int max = providers.size ();
361 for (int i = 0; i < max; i++)
363 p = (Provider) providers.elementAt(i);
364 if (p.getName().equals(name))
365 return p;
367 return null;
371 * <p>Gets a security property value.</p>
373 * <p>First, if there is a security manager, its <code>checkPermission()</code>
374 * method is called with a <code>SecurityPermission("getProperty."+key)</code>
375 * permission to see if it's ok to retrieve the specified security property
376 * value.</p>
378 * @param key the key of the property being retrieved.
379 * @return the value of the security property corresponding to key.
380 * @throws SecurityException if a security manager exists and its
381 * {@link SecurityManager#checkPermission(Permission)} method denies access
382 * to retrieve the specified security property value.
383 * @see #setProperty(String, String)
384 * @see SecurityPermission
386 public static String getProperty(String key)
388 SecurityManager sm = System.getSecurityManager();
389 if (sm != null)
390 sm.checkSecurityAccess("getProperty." + key);
392 return secprops.getProperty(key);
396 * <p>Sets a security property value.</p>
398 * <p>First, if there is a security manager, its <code>checkPermission()</code>
399 * method is called with a <code>SecurityPermission("setProperty."+key)</code>
400 * permission to see if it's ok to set the specified security property value.
401 * </p>
403 * @param key the name of the property to be set.
404 * @param datnum the value of the property to be set.
405 * @throws SecurityException if a security manager exists and its
406 * {@link SecurityManager#checkPermission(Permission)} method denies access
407 * to set the specified security property value.
408 * @see #getProperty(String)
409 * @see SecurityPermission
411 public static void setProperty(String key, String datnum)
413 SecurityManager sm = System.getSecurityManager();
414 if (sm != null)
415 sm.checkSecurityAccess("setProperty." + key);
417 secprops.put(key, datnum);
421 * Returns a Set of Strings containing the names of all available algorithms
422 * or types for the specified Java cryptographic service (e.g., Signature,
423 * MessageDigest, Cipher, Mac, KeyStore). Returns an empty Set if there is no
424 * provider that supports the specified service. For a complete list of Java
425 * cryptographic services, please see the Java Cryptography Architecture API
426 * Specification &amp; Reference. Note: the returned set is immutable.
428 * @param serviceName the name of the Java cryptographic service (e.g.,
429 * Signature, MessageDigest, Cipher, Mac, KeyStore). Note: this parameter is
430 * case-insensitive.
431 * @return a Set of Strings containing the names of all available algorithms
432 * or types for the specified Java cryptographic service or an empty set if
433 * no provider supports the specified service.
434 * @since 1.4
436 public static Set getAlgorithms(String serviceName)
438 HashSet result = new HashSet();
439 if (serviceName == null || serviceName.length() == 0)
440 return result;
442 serviceName = serviceName.trim();
443 if (serviceName.length() == 0)
444 return result;
446 serviceName = serviceName.toUpperCase()+".";
447 Provider[] providers = getProviders();
448 int ndx;
449 for (int i = 0; i < providers.length; i++)
450 for (Enumeration e = providers[i].propertyNames(); e.hasMoreElements(); )
452 String service = ((String) e.nextElement()).trim();
453 if (service.toUpperCase().startsWith(serviceName))
455 service = service.substring(serviceName.length()).trim();
456 ndx = service.indexOf(' '); // get rid of attributes
457 if (ndx != -1)
458 service = service.substring(0, ndx);
459 result.add(service);
462 return Collections.unmodifiableSet(result);
466 * <p>Returns an array containing all installed providers that satisfy the
467 * specified selection criterion, or <code>null</code> if no such providers
468 * have been installed. The returned providers are ordered according to their
469 * preference order.</p>
471 * <p>A cryptographic service is always associated with a particular
472 * algorithm or type. For example, a digital signature service is always
473 * associated with a particular algorithm (e.g., <i>DSA</i>), and a
474 * CertificateFactory service is always associated with a particular
475 * certificate type (e.g., <i>X.509</i>).</p>
477 * <p>The selection criterion must be specified in one of the following two
478 * formats:</p>
480 * <ul>
481 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt;</p>
482 * <p>The cryptographic service name must not contain any dots.</p>
483 * <p>A provider satisfies the specified selection criterion iff the
484 * provider implements the specified algorithm or type for the specified
485 * cryptographic service.</p>
486 * <p>For example, "CertificateFactory.X.509" would be satisfied by any
487 * provider that supplied a CertificateFactory implementation for X.509
488 * certificates.</p></li>
490 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt; &lt;attribute_name&gt;:&lt;attribute_value&gt;</p>
491 * <p>The cryptographic service name must not contain any dots. There must
492 * be one or more space charaters between the the &lt;algorithm_or_type&gt;
493 * and the &lt;attribute_name&gt;.</p>
494 * <p>A provider satisfies this selection criterion iff the provider
495 * implements the specified algorithm or type for the specified
496 * cryptographic service and its implementation meets the constraint
497 * expressed by the specified attribute name/value pair.</p>
498 * <p>For example, "Signature.SHA1withDSA KeySize:1024" would be satisfied
499 * by any provider that implemented the SHA1withDSA signature algorithm
500 * with a keysize of 1024 (or larger).</p></li>
501 * </ul>
503 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
504 * &amp; Reference for information about standard cryptographic service names,
505 * standard algorithm names and standard attribute names.</p>
507 * @param filter the criterion for selecting providers. The filter is case-
508 * insensitive.
509 * @return all the installed providers that satisfy the selection criterion,
510 * or null if no such providers have been installed.
511 * @throws InvalidParameterException if the filter is not in the required
512 * format.
513 * @see #getProviders(Map)
515 public static Provider[] getProviders(String filter)
517 if (providers == null || providers.isEmpty())
518 return null;
520 if (filter == null || filter.length() == 0)
521 return getProviders();
523 HashMap map = new HashMap(1);
524 int i = filter.indexOf(':');
525 if (i == -1) // <service>.<algorithm>
526 map.put(filter, "");
527 else // <service>.<algorithm> <attribute>:<value>
528 map.put(filter.substring(0, i), filter.substring(i+1));
530 return getProviders(map);
534 * <p>Returns an array containing all installed providers that satisfy the
535 * specified selection criteria, or <code>null</code> if no such providers
536 * have been installed. The returned providers are ordered according to their
537 * preference order.</p>
539 * <p>The selection criteria are represented by a map. Each map entry
540 * represents a selection criterion. A provider is selected iff it satisfies
541 * all selection criteria. The key for any entry in such a map must be in one
542 * of the following two formats:</p>
544 * <ul>
545 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt;</p>
546 * <p>The cryptographic service name must not contain any dots.</p>
547 * <p>The value associated with the key must be an empty string.</p>
548 * <p>A provider satisfies this selection criterion iff the provider
549 * implements the specified algorithm or type for the specified
550 * cryptographic service.</p></li>
552 * <li><p>&lt;crypto_service&gt;.&lt;algorithm_or_type&gt; &lt;attribute_name&gt;</p>
553 * <p>The cryptographic service name must not contain any dots. There must
554 * be one or more space charaters between the &lt;algorithm_or_type&gt; and
555 * the &lt;attribute_name&gt;.</p>
556 * <p>The value associated with the key must be a non-empty string. A
557 * provider satisfies this selection criterion iff the provider implements
558 * the specified algorithm or type for the specified cryptographic service
559 * and its implementation meets the constraint expressed by the specified
560 * attribute name/value pair.</p></li>
561 * </ul>
563 * <p>See Appendix A in the Java Cryptogaphy Architecture API Specification
564 * &amp; Reference for information about standard cryptographic service names,
565 * standard algorithm names and standard attribute names.</p>
567 * @param filter the criteria for selecting providers. The filter is case-
568 * insensitive.
569 * @return all the installed providers that satisfy the selection criteria,
570 * or <code>null</code> if no such providers have been installed.
571 * @throws InvalidParameterException if the filter is not in the required
572 * format.
573 * @see #getProviders(String)
575 public static Provider[] getProviders(Map filter)
577 if (providers == null || providers.isEmpty())
578 return null;
580 if (filter == null)
581 return getProviders();
583 Set querries = filter.keySet();
584 if (querries == null || querries.isEmpty())
585 return getProviders();
587 LinkedHashSet result = new LinkedHashSet(providers); // assume all
588 int dot, ws;
589 String querry, service, algorithm, attribute, value;
590 LinkedHashSet serviceProviders = new LinkedHashSet(); // preserve insertion order
591 for (Iterator i = querries.iterator(); i.hasNext(); )
593 querry = (String) i.next();
594 if (querry == null) // all providers
595 continue;
597 querry = querry.trim();
598 if (querry.length() == 0) // all providers
599 continue;
601 dot = querry.indexOf('.');
602 if (dot == -1) // syntax error
603 throw new InvalidParameterException(
604 "missing dot in '" + String.valueOf(querry)+"'");
606 value = (String) filter.get(querry);
607 // deconstruct querry into [service, algorithm, attribute]
608 if (value == null || value.trim().length() == 0) // <service>.<algorithm>
610 value = null;
611 attribute = null;
612 service = querry.substring(0, dot).trim();
613 algorithm = querry.substring(dot+1).trim();
615 else // <service>.<algorithm> <attribute>
617 ws = querry.indexOf(' ');
618 if (ws == -1)
619 throw new InvalidParameterException(
620 "value (" + String.valueOf(value) +
621 ") is not empty, but querry (" + String.valueOf(querry) +
622 ") is missing at least one space character");
623 value = value.trim();
624 attribute = querry.substring(ws+1).trim();
625 // was the dot in the attribute?
626 if (attribute.indexOf('.') != -1)
627 throw new InvalidParameterException(
628 "attribute_name (" + String.valueOf(attribute) +
629 ") in querry (" + String.valueOf(querry) + ") contains a dot");
631 querry = querry.substring(0, ws).trim();
632 service = querry.substring(0, dot).trim();
633 algorithm = querry.substring(dot+1).trim();
636 // service and algorithm must not be empty
637 if (service.length() == 0)
638 throw new InvalidParameterException(
639 "<crypto_service> in querry (" + String.valueOf(querry) +
640 ") is empty");
642 if (algorithm.length() == 0)
643 throw new InvalidParameterException(
644 "<algorithm_or_type> in querry (" + String.valueOf(querry) +
645 ") is empty");
647 selectProviders(service, algorithm, attribute, value, result, serviceProviders);
648 result.retainAll(serviceProviders); // eval next retaining found providers
649 if (result.isEmpty()) // no point continuing
650 break;
653 if (result.isEmpty())
654 return null;
656 return (Provider[]) result.toArray(new Provider[0]);
659 private static void selectProviders(String svc, String algo, String attr,
660 String val, LinkedHashSet providerSet,
661 LinkedHashSet result)
663 result.clear(); // ensure we start with an empty result set
664 for (Iterator i = providerSet.iterator(); i.hasNext(); )
666 Provider p = (Provider) i.next();
667 if (provides(p, svc, algo, attr, val))
668 result.add(p);
672 private static boolean provides(Provider p, String svc, String algo,
673 String attr, String val)
675 Iterator it;
676 String serviceDotAlgorithm = null;
677 String key = null;
678 String realVal;
679 boolean found = false;
680 // if <svc>.<algo> <attr> is in the set then so is <svc>.<algo>
681 // but it may be stored under an alias <algo>. resolve
682 outer: for (int r = 0; r < 3; r++) // guard against circularity
684 serviceDotAlgorithm = (svc+"."+String.valueOf(algo)).trim();
685 for (it = p.keySet().iterator(); it.hasNext(); )
687 key = (String) it.next();
688 if (key.equalsIgnoreCase(serviceDotAlgorithm)) // eureka
690 found = true;
691 break outer;
693 // it may be there but as an alias
694 if (key.equalsIgnoreCase(ALG_ALIAS + serviceDotAlgorithm))
696 algo = p.getProperty(key);
697 continue outer;
699 // else continue inner
703 if (!found)
704 return false;
706 // found a candidate for the querry. do we have an attr to match?
707 if (val == null) // <service>.<algorithm> querry
708 return true;
710 // <service>.<algorithm> <attribute>; find the key entry that match
711 String realAttr;
712 int limit = serviceDotAlgorithm.length() + 1;
713 for (it = p.keySet().iterator(); it.hasNext(); )
715 key = (String) it.next();
716 if (key.length() <= limit)
717 continue;
719 if (key.substring(0, limit).equalsIgnoreCase(serviceDotAlgorithm+" "))
721 realAttr = key.substring(limit).trim();
722 if (! realAttr.equalsIgnoreCase(attr))
723 continue;
725 // eveything matches so far. do the value
726 realVal = p.getProperty(key);
727 if (realVal == null)
728 return false;
730 realVal = realVal.trim();
731 // is it a string value?
732 if (val.equalsIgnoreCase(realVal))
733 return true;
735 // assume value is a number. cehck for greater-than-or-equal
736 return (new Integer(val).intValue() >= new Integer(realVal).intValue());
740 return false;