PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/test/sun/security/pkcs11/PKCS11Test.java

https://bitbucket.org/adoptopenjdk/jdk8-jdk
Java | 539 lines | 409 code | 70 blank | 60 comment | 88 complexity | f8ef51f61c571f96c619a9459ad4c883 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause
  1. /*
  2. * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation.
  8. *
  9. * This code is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * version 2 for more details (a copy is included in the LICENSE file that
  13. * accompanied this code).
  14. *
  15. * You should have received a copy of the GNU General Public License version
  16. * 2 along with this work; if not, write to the Free Software Foundation,
  17. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18. *
  19. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20. * or visit www.oracle.com if you need additional information or have any
  21. * questions.
  22. */
  23. // common infrastructure for SunPKCS11 tests
  24. import java.io.*;
  25. import java.util.*;
  26. import java.lang.reflect.*;
  27. import java.security.*;
  28. import java.security.spec.ECGenParameterSpec;
  29. import java.security.spec.ECParameterSpec;
  30. public abstract class PKCS11Test {
  31. // directory of the test source
  32. static final String BASE = System.getProperty("test.src", ".");
  33. static final char SEP = File.separatorChar;
  34. private final static String REL_CLOSED = "../../../../closed/sun/security/pkcs11".replace('/', SEP);
  35. // directory corresponding to BASE in the /closed hierarchy
  36. static final String CLOSED_BASE;
  37. static {
  38. // hack
  39. String absBase = new File(BASE).getAbsolutePath();
  40. int k = absBase.indexOf(SEP + "test" + SEP + "sun" + SEP);
  41. if (k < 0) k = 0;
  42. String p1 = absBase.substring(0, k + 6);
  43. String p2 = absBase.substring(k + 5);
  44. CLOSED_BASE = p1 + "closed" + p2;
  45. }
  46. static String NSPR_PREFIX = "";
  47. // NSS version info
  48. public static enum ECCState { None, Basic, Extended };
  49. static double nss_version = -1;
  50. static ECCState nss_ecc_status = ECCState.Extended;
  51. // The NSS library we need to search for in getNSSLibDir()
  52. // Default is "libsoftokn3.so", listed as "softokn3"
  53. // The other is "libnss3.so", listed as "nss3".
  54. static String nss_library = "softokn3";
  55. static Provider getSunPKCS11(String config) throws Exception {
  56. Class clazz = Class.forName("sun.security.pkcs11.SunPKCS11");
  57. Constructor cons = clazz.getConstructor(new Class[] {String.class});
  58. Object obj = cons.newInstance(new Object[] {config});
  59. return (Provider)obj;
  60. }
  61. public abstract void main(Provider p) throws Exception;
  62. private void premain(Provider p) throws Exception {
  63. long start = System.currentTimeMillis();
  64. System.out.println("Running test with provider " + p.getName() + "...");
  65. main(p);
  66. long stop = System.currentTimeMillis();
  67. System.out.println("Completed test with provider " + p.getName() + " (" + (stop - start) + " ms).");
  68. }
  69. public static void main(PKCS11Test test) throws Exception {
  70. Provider[] oldProviders = Security.getProviders();
  71. try {
  72. System.out.println("Beginning test run " + test.getClass().getName() + "...");
  73. testDefault(test);
  74. testNSS(test);
  75. testDeimos(test);
  76. } finally {
  77. // NOTE: Do not place a 'return' in any finally block
  78. // as it will suppress exceptions and hide test failures.
  79. Provider[] newProviders = Security.getProviders();
  80. boolean found = true;
  81. // Do not restore providers if nothing changed. This is especailly
  82. // useful for ./Provider/Login.sh, where a SecurityManager exists.
  83. if (oldProviders.length == newProviders.length) {
  84. found = false;
  85. for (int i = 0; i<oldProviders.length; i++) {
  86. if (oldProviders[i] != newProviders[i]) {
  87. found = true;
  88. break;
  89. }
  90. }
  91. }
  92. if (found) {
  93. for (Provider p: newProviders) {
  94. Security.removeProvider(p.getName());
  95. }
  96. for (Provider p: oldProviders) {
  97. Security.addProvider(p);
  98. }
  99. }
  100. }
  101. }
  102. public static void testDeimos(PKCS11Test test) throws Exception {
  103. if (new File("/opt/SUNWconn/lib/libpkcs11.so").isFile() == false ||
  104. "true".equals(System.getProperty("NO_DEIMOS"))) {
  105. return;
  106. }
  107. String base = getBase();
  108. String p11config = base + SEP + "nss" + SEP + "p11-deimos.txt";
  109. Provider p = getSunPKCS11(p11config);
  110. test.premain(p);
  111. }
  112. public static void testDefault(PKCS11Test test) throws Exception {
  113. // run test for default configured PKCS11 providers (if any)
  114. if ("true".equals(System.getProperty("NO_DEFAULT"))) {
  115. return;
  116. }
  117. Provider[] providers = Security.getProviders();
  118. for (int i = 0; i < providers.length; i++) {
  119. Provider p = providers[i];
  120. if (p.getName().startsWith("SunPKCS11-")) {
  121. test.premain(p);
  122. }
  123. }
  124. }
  125. private static String PKCS11_BASE;
  126. static {
  127. try {
  128. PKCS11_BASE = getBase();
  129. } catch (Exception e) {
  130. // ignore
  131. }
  132. }
  133. private final static String PKCS11_REL_PATH = "sun/security/pkcs11";
  134. public static String getBase() throws Exception {
  135. if (PKCS11_BASE != null) {
  136. return PKCS11_BASE;
  137. }
  138. File cwd = new File(System.getProperty("test.src", ".")).getCanonicalFile();
  139. while (true) {
  140. File file = new File(cwd, "TEST.ROOT");
  141. if (file.isFile()) {
  142. break;
  143. }
  144. cwd = cwd.getParentFile();
  145. if (cwd == null) {
  146. throw new Exception("Test root directory not found");
  147. }
  148. }
  149. PKCS11_BASE = new File(cwd, PKCS11_REL_PATH.replace('/', SEP)).getAbsolutePath();
  150. return PKCS11_BASE;
  151. }
  152. public static String getNSSLibDir() throws Exception {
  153. Properties props = System.getProperties();
  154. String osName = props.getProperty("os.name");
  155. if (osName.startsWith("Win")) {
  156. osName = "Windows";
  157. NSPR_PREFIX = "lib";
  158. }
  159. String osid = osName + "-"
  160. + props.getProperty("os.arch") + "-" + props.getProperty("sun.arch.data.model");
  161. String[] nssLibDirs = osMap.get(osid);
  162. if (nssLibDirs == null) {
  163. System.out.println("Unsupported OS, skipping: " + osid);
  164. return null;
  165. }
  166. if (nssLibDirs.length == 0) {
  167. System.out.println("NSS not supported on this platform, skipping test");
  168. return null;
  169. }
  170. String nssLibDir = null;
  171. for (String dir : nssLibDirs) {
  172. if (new File(dir).exists() &&
  173. new File(dir + System.mapLibraryName(nss_library)).exists()) {
  174. nssLibDir = dir;
  175. System.setProperty("pkcs11test.nss.libdir", nssLibDir);
  176. break;
  177. }
  178. }
  179. return nssLibDir;
  180. }
  181. protected static void safeReload(String lib) throws Exception {
  182. try {
  183. System.load(lib);
  184. } catch (UnsatisfiedLinkError e) {
  185. if (e.getMessage().contains("already loaded")) {
  186. return;
  187. }
  188. }
  189. }
  190. static boolean loadNSPR(String libdir) throws Exception {
  191. // load NSS softoken dependencies in advance to avoid resolver issues
  192. safeReload(libdir + System.mapLibraryName(NSPR_PREFIX + "nspr4"));
  193. safeReload(libdir + System.mapLibraryName(NSPR_PREFIX + "plc4"));
  194. safeReload(libdir + System.mapLibraryName(NSPR_PREFIX + "plds4"));
  195. safeReload(libdir + System.mapLibraryName("sqlite3"));
  196. safeReload(libdir + System.mapLibraryName("nssutil3"));
  197. return true;
  198. }
  199. // Check the provider being used is NSS
  200. public static boolean isNSS(Provider p) {
  201. return p.getName().toUpperCase().equals("SUNPKCS11-NSS");
  202. }
  203. static double getNSSVersion() {
  204. if (nss_version == -1)
  205. getNSSInfo();
  206. return nss_version;
  207. }
  208. static ECCState getNSSECC() {
  209. if (nss_version == -1)
  210. getNSSInfo();
  211. return nss_ecc_status;
  212. }
  213. /* Read the library to find out the verison */
  214. static void getNSSInfo() {
  215. String nssHeader = "$Header: NSS";
  216. boolean found = false;
  217. String s = null;
  218. int i = 0;
  219. String libfile = "";
  220. try {
  221. libfile = getNSSLibDir() + System.mapLibraryName(nss_library);
  222. FileInputStream is = new FileInputStream(libfile);
  223. byte[] data = new byte[1000];
  224. int read = 0;
  225. while (is.available() > 0) {
  226. if (read == 0) {
  227. read = is.read(data, 0, 1000);
  228. } else {
  229. // Prepend last 100 bytes in case the header was split
  230. // between the reads.
  231. System.arraycopy(data, 900, data, 0, 100);
  232. read = 100 + is.read(data, 100, 900);
  233. }
  234. s = new String(data, 0, read);
  235. if ((i = s.indexOf(nssHeader)) > 0) {
  236. found = true;
  237. // If the nssHeader is before 920 we can break, otherwise
  238. // we may not have the whole header so do another read. If
  239. // no bytes are in the stream, that is ok, found is true.
  240. if (i < 920) {
  241. break;
  242. }
  243. }
  244. }
  245. is.close();
  246. } catch (Exception e) {
  247. e.printStackTrace();
  248. }
  249. if (!found) {
  250. System.out.println("NSS version not found, set to 0.0: "+libfile);
  251. nss_version = 0.0;
  252. return;
  253. }
  254. // the index after whitespace after nssHeader
  255. int afterheader = s.indexOf("NSS", i) + 4;
  256. String version = s.substring(afterheader, s.indexOf(' ', afterheader));
  257. // If a "dot dot" release, strip the extra dots for double parsing
  258. String[] dot = version.split("\\.");
  259. if (dot.length > 2) {
  260. version = dot[0]+"."+dot[1];
  261. for (int j = 2; dot.length > j; j++) {
  262. version += dot[j];
  263. }
  264. }
  265. // Convert to double for easier version value checking
  266. try {
  267. nss_version = Double.parseDouble(version);
  268. } catch (NumberFormatException e) {
  269. System.out.println("Failed to parse NSS version. Set to 0.0");
  270. e.printStackTrace();
  271. }
  272. System.out.print("NSS version = "+version+". ");
  273. // Check for ECC
  274. if (s.indexOf("Basic") > 0) {
  275. nss_ecc_status = ECCState.Basic;
  276. System.out.println("ECC Basic.");
  277. } else if (s.indexOf("Extended") > 0) {
  278. nss_ecc_status = ECCState.Extended;
  279. System.out.println("ECC Extended.");
  280. }
  281. }
  282. // Used to set the nss_library file to search for libsoftokn3.so
  283. public static void useNSS() {
  284. nss_library = "nss3";
  285. }
  286. public static void testNSS(PKCS11Test test) throws Exception {
  287. String libdir = getNSSLibDir();
  288. if (libdir == null) {
  289. return;
  290. }
  291. String base = getBase();
  292. if (loadNSPR(libdir) == false) {
  293. return;
  294. }
  295. String libfile = libdir + System.mapLibraryName(nss_library);
  296. String customDBdir = System.getProperty("CUSTOM_DB_DIR");
  297. String dbdir = (customDBdir != null) ?
  298. customDBdir :
  299. base + SEP + "nss" + SEP + "db";
  300. // NSS always wants forward slashes for the config path
  301. dbdir = dbdir.replace('\\', '/');
  302. String customConfig = System.getProperty("CUSTOM_P11_CONFIG");
  303. String customConfigName = System.getProperty("CUSTOM_P11_CONFIG_NAME", "p11-nss.txt");
  304. String p11config = (customConfig != null) ?
  305. customConfig :
  306. base + SEP + "nss" + SEP + customConfigName;
  307. System.setProperty("pkcs11test.nss.lib", libfile);
  308. System.setProperty("pkcs11test.nss.db", dbdir);
  309. Provider p = getSunPKCS11(p11config);
  310. test.premain(p);
  311. }
  312. // Generate a vector of supported elliptic curves of a given provider
  313. static Vector<ECParameterSpec> getKnownCurves(Provider p) throws Exception {
  314. int index;
  315. int begin;
  316. int end;
  317. String curve;
  318. KeyPair kp = null;
  319. Vector<ECParameterSpec> results = new Vector<ECParameterSpec>();
  320. // Get Curves to test from SunEC.
  321. String kcProp = Security.getProvider("SunEC").
  322. getProperty("AlgorithmParameters.EC SupportedCurves");
  323. if (kcProp == null) {
  324. throw new RuntimeException(
  325. "\"AlgorithmParameters.EC SupportedCurves property\" not found");
  326. }
  327. System.out.println("Finding supported curves using list from SunEC\n");
  328. index = 0;
  329. for (;;) {
  330. // Each set of curve names is enclosed with brackets.
  331. begin = kcProp.indexOf('[', index);
  332. end = kcProp.indexOf(']', index);
  333. if (begin == -1 || end == -1) {
  334. break;
  335. }
  336. /*
  337. * Each name is separated by a comma.
  338. * Just get the first name in the set.
  339. */
  340. index = end + 1;
  341. begin++;
  342. end = kcProp.indexOf(',', begin);
  343. if (end == -1) {
  344. // Only one name in the set.
  345. end = index -1;
  346. }
  347. curve = kcProp.substring(begin, end);
  348. ECParameterSpec e = getECParameterSpec(p, curve);
  349. System.out.print("\t "+ curve + ": ");
  350. try {
  351. KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
  352. kpg.initialize(e);
  353. kp = kpg.generateKeyPair();
  354. results.add(e);
  355. System.out.println("Supported");
  356. } catch (ProviderException ex) {
  357. System.out.println("Unsupported: PKCS11: " +
  358. ex.getCause().getMessage());
  359. } catch (InvalidAlgorithmParameterException ex) {
  360. System.out.println("Unsupported: Key Length: " +
  361. ex.getMessage());
  362. }
  363. }
  364. if (results.size() == 0) {
  365. throw new RuntimeException("No supported EC curves found");
  366. }
  367. return results;
  368. }
  369. private static ECParameterSpec getECParameterSpec(Provider p, String name)
  370. throws Exception {
  371. AlgorithmParameters parameters =
  372. AlgorithmParameters.getInstance("EC", p);
  373. parameters.init(new ECGenParameterSpec(name));
  374. return parameters.getParameterSpec(ECParameterSpec.class);
  375. }
  376. // Check support for a curve with a provided Vector of EC support
  377. boolean checkSupport(Vector<ECParameterSpec> supportedEC,
  378. ECParameterSpec curve) {
  379. boolean found = false;
  380. for (ECParameterSpec ec: supportedEC) {
  381. if (ec.equals(curve)) {
  382. return true;
  383. }
  384. }
  385. return false;
  386. }
  387. private static final Map<String,String[]> osMap;
  388. // Location of the NSS libraries on each supported platform
  389. static {
  390. osMap = new HashMap<String,String[]>();
  391. osMap.put("SunOS-sparc-32", new String[]{"/usr/lib/mps/"});
  392. osMap.put("SunOS-sparcv9-64", new String[]{"/usr/lib/mps/64/"});
  393. osMap.put("SunOS-x86-32", new String[]{"/usr/lib/mps/"});
  394. osMap.put("SunOS-amd64-64", new String[]{"/usr/lib/mps/64/"});
  395. osMap.put("Linux-i386-32", new String[]{
  396. "/usr/lib/i386-linux-gnu/", "/usr/lib/"});
  397. osMap.put("Linux-amd64-64", new String[]{
  398. "/usr/lib/x86_64-linux-gnu/", "/usr/lib/x86_64-linux-gnu/nss/",
  399. "/usr/lib64/"});
  400. osMap.put("Windows-x86-32", new String[]{
  401. PKCS11_BASE + "/nss/lib/windows-i586/".replace('/', SEP)});
  402. osMap.put("Windows-amd64-64", new String[]{
  403. PKCS11_BASE + "/nss/lib/windows-amd64/".replace('/', SEP)});
  404. }
  405. private final static char[] hexDigits = "0123456789abcdef".toCharArray();
  406. public static String toString(byte[] b) {
  407. if (b == null) {
  408. return "(null)";
  409. }
  410. StringBuffer sb = new StringBuffer(b.length * 3);
  411. for (int i = 0; i < b.length; i++) {
  412. int k = b[i] & 0xff;
  413. if (i != 0) {
  414. sb.append(':');
  415. }
  416. sb.append(hexDigits[k >>> 4]);
  417. sb.append(hexDigits[k & 0xf]);
  418. }
  419. return sb.toString();
  420. }
  421. public static byte[] parse(String s) {
  422. if (s.equals("(null)")) {
  423. return null;
  424. }
  425. try {
  426. int n = s.length();
  427. ByteArrayOutputStream out = new ByteArrayOutputStream(n / 3);
  428. StringReader r = new StringReader(s);
  429. while (true) {
  430. int b1 = nextNibble(r);
  431. if (b1 < 0) {
  432. break;
  433. }
  434. int b2 = nextNibble(r);
  435. if (b2 < 0) {
  436. throw new RuntimeException("Invalid string " + s);
  437. }
  438. int b = (b1 << 4) | b2;
  439. out.write(b);
  440. }
  441. return out.toByteArray();
  442. } catch (IOException e) {
  443. throw new RuntimeException(e);
  444. }
  445. }
  446. private static int nextNibble(StringReader r) throws IOException {
  447. while (true) {
  448. int ch = r.read();
  449. if (ch == -1) {
  450. return -1;
  451. } else if ((ch >= '0') && (ch <= '9')) {
  452. return ch - '0';
  453. } else if ((ch >= 'a') && (ch <= 'f')) {
  454. return ch - 'a' + 10;
  455. } else if ((ch >= 'A') && (ch <= 'F')) {
  456. return ch - 'A' + 10;
  457. }
  458. }
  459. }
  460. <T> T[] concat(T[] a, T[] b) {
  461. if ((b == null) || (b.length == 0)) {
  462. return a;
  463. }
  464. T[] r = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), a.length + b.length);
  465. System.arraycopy(a, 0, r, 0, a.length);
  466. System.arraycopy(b, 0, r, a.length, b.length);
  467. return r;
  468. }
  469. }