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

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

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