diff options
Diffstat (limited to 'pki/base/silent')
50 files changed, 27491 insertions, 0 deletions
diff --git a/pki/base/silent/LICENSE b/pki/base/silent/LICENSE new file mode 100644 index 000000000..e36f2269a --- /dev/null +++ b/pki/base/silent/LICENSE @@ -0,0 +1,311 @@ +This Program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published +by the Free Software Foundation; version 2 of the License. + +This Program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License +along with this Program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + +In addition, as a special exception, Red Hat, Inc. gives You the additional +right to link the code of this Program with code not covered under the GNU +General Public License ("Non-GPL Code") and to distribute linked combinations +including the two, subject to the limitations in this paragraph. Non-GPL +Code permitted under this exception must only link to the code of this +Program through those well defined interfaces identified in the file named +EXCEPTION found in the source code files (the "Approved Interfaces"). + +The files of Non-GPL Code may instantiate templates or use macros or inline +functions from the Approved Interfaces without causing the resulting work to +be covered by the GNU General Public License. Only Red Hat, Inc. may make +changes or additions to the list of Approved Interfaces. You must obey the +GNU General Public License in all respects for all of the Program code and +other code used in conjunction with the Program except the Non-GPL Code +covered by this exception. If you modify this file, you may extend this +exception to your version of the file, but you are not obligated to do so. +If you do not wish to provide this exception without modification, you must +delete this exception statement from your version and license this file +solely under the GPL without exception. + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. diff --git a/pki/base/silent/build.xml b/pki/base/silent/build.xml new file mode 100644 index 000000000..06d8fcc1a --- /dev/null +++ b/pki/base/silent/build.xml @@ -0,0 +1,317 @@ +<!-- ### BEGIN COPYRIGHT BLOCK ### + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + Copyright (C) 2007 Red Hat, Inc. + All rights reserved. + ### END COPYRIGHT BLOCK ### --> +<project name="silent" default="main" basedir="."> + + <import file="config/product.xml"/> + <import file="config/product-ext.xml" optional="true"/> + + <property name="jss.home" value="${jni-jar.home}${dirsec}"/> + <property name="jss.jar" value="${jss.home}/jss4.jar"/> + <property name="osutil.jar" value="${jni-jar.home}/osutil.jar"/> + <property name="symkey.jar" value="${jni-jar.home}/symkey.jar"/> + <property name="ldapjdk.jar" value="${jar.home}/ldapjdk.jar"/> + <property name="certsrv.jar" value="${pki-jar.home}/certsrv.jar"/> + <property name="cms.jar" value="${pki-jar.home}/cms.jar"/> + <property name="cmsutil.jar" value="${pki-jar.home}/cmsutil.jar"/> + <property name="nsutil.jar" value="${pki-jar.home}/nsutil.jar"/> + + <path id="classpath"> + <pathelement location="${servlet.jar}"/> + <pathelement location="${jss.jar}"/> + <pathelement location="${ldapjdk.jar}"/> + <pathelement location="${nsutil.jar}"/> + <pathelement location="${cmsutil.jar}"/> + <pathelement location="${osutil.jar}"/> + <pathelement location="${symkey.jar}"/> + <pathelement location="${cms.jar}"/> + <pathelement location="${certsrv.jar}"/> + </path> + + + <target name="clean" + depends="" + description="--> remove component directories"> + <echo message="${begin.clean.log.message}"/> + <delete dir="${dist.base}"/> + <delete dir="${build.dir}"/> + <echo message="${end.clean.log.message}"/> + </target> + + + <target name="download" + depends="" + description="--> download dependent components"> + <echo message="${begin.download.log.message}"/> + <echo message="${empty.download.log.message}"/> + <echo message="${end.download.log.message}"/> + </target> + + + <target name="compile_java" + depends="" + description="--> compile java source code into classes"> + <echo message="${begin.compile.java.log.message}"/> + <mkdir dir="${build.classes}"/> + <javac debug="on" + srcdir="${src.dir}" + destdir="${build.classes}"> + <classpath refid="classpath"/> + </javac> + <echo message="${end.compile.java.log.message}"/> + </target> + + + <target name="build_jars" + depends="compile_java" + description="--> generate jar files"> + <echo message="${begin.build.jars.log.message}"/> + <mkdir dir="${build.jars}"/> + <jar jarfile="${build.jars}/${product}.jar"> + <fileset dir="${build.classes}"> + <include name="**"/> + </fileset> + </jar> + <echo message="${end.build.jars.log.message}"/> + </target> + + + <target name="build_jni_headers" + depends="compile_java" + description="--> generate jni header files"> + <echo message="${begin.build.jni.headers.log.message}"/> + <echo message="${empty.build.jni.headers.log.message}"/> + <echo message="${end.build.jni.headers.log.message}"/> + </target> + + + <target name="build" + depends="build_jars,build_jni_headers" + description="--> build classes, jars, and jni headers"> + <echo message="${notify.build.log.message}"/> + </target> + + + <target name="compile_junit_tests" + depends="build" + description="--> compile junit test source code"> + <echo message="${begin.compile.junit.tests.log.message}"/> + <echo message="${empty.compile.junit.tests.log.message}"/> + <echo message="${end.compile.junit.tests.log.message}"/> + </target> + + + <target name="run_junit_tests" + depends="compile_junit_tests" + description="--> execute junit tests"> + <echo message="${begin.run.junit.tests.log.message}"/> + <echo message="${empty.run.junit.tests.log.message}"/> + <echo message="${end.run.junit.tests.log.message}"/> + </target> + + + <target name="verify" + depends="run_junit_tests" + description="--> build and execute junit tests"> + <echo message="${notify.verify.log.message}"/> + </target> + + + <target name="clean_javadocs" + depends="" + description="--> remove javadocs directory"> + <echo message="${begin.clean.javadocs.log.message}"/> + <echo message="${empty.clean.javadocs.log.message}"/> + <echo message="${end.clean.javadocs.log.message}"/> + </target> + + + <target name="compose_javadocs" + depends="build" + description="--> generate javadocs"> + <echo message="${begin.compose.javadocs.log.message}"/> + <echo message="${empty.compose.javadocs.log.message}"/> + <echo message="${end.compose.javadocs.log.message}"/> + </target> + + + <target name="document" + depends="clean_javadocs,compose_javadocs" + description="--> remove old javadocs and compose new javadocs"> + <echo message="${notify.document.log.message}"/> + </target> + + + <target name="distribute_binaries" + depends="document" + description="--> create the zip and gzipped tar binary distributions"> + <echo message="${begin.distribute.binaries.log.message}"/> + <mkdir dir="${dist.base.binaries}"/> + + <echo message="${begin.binary.wrappers.log.message}"/> + <echo message="${empty.binary.wrappers.log.message}"/> + <echo message="${end.binary.wrappers.log.message}"/> + + <echo message="${begin.binary.zip.log.message}"/> + <zip destfile="${dist.base.binaries}/${dist.name}.zip"> + <zipfileset dir="./build/jars" + filemode="755" + prefix="usr/share/java"> + <include name="**"/> + </zipfileset> + <zipfileset dir="./scripts" + filemode="755" + prefix="usr/bin"> + <include name="**"/> + </zipfileset> + <zipfileset dir="." + filemode="755" + prefix="usr/share/doc/${dist.name}"> + <include name="LICENSE"/> + </zipfileset> + </zip> + <echo message="${end.binary.zip.log.message}"/> + + <echo message="${begin.binary.tar.log.message}"/> + <tar longfile="gnu" + destfile="${dist.base.binaries}/${dist.name}.tar"> + <tarfileset dir="./build/jars" + mode="755" + prefix="${dist.name}/usr/share/java"> + <include name="**"/> + </tarfileset> + <tarfileset dir="./scripts" + mode="755" + prefix="${dist.name}/usr/bin"> + <include name="**"/> + </tarfileset> + <tarfileset dir="." + mode="755" + prefix="${dist.name}/usr/share/doc/${dist.name}"> + <include name="LICENSE"/> + </tarfileset> + </tar> + <echo message="${end.binary.tar.log.message}"/> + + <echo message="${begin.binary.gtar.log.message}"/> + <gzip destfile="${dist.base.binaries}/${dist.name}.tar.gz" + src="${dist.base.binaries}/${dist.name}.tar"/> + <delete file="${dist.base.binaries}/${dist.name}.tar"/> + <delete dir="${dist.name}"/> + <checksum fileext=".md5"> + <fileset dir="${dist.base.binaries}/"> + <include name="**/*"/> + <exclude name="**/*.asc"/> + <exclude name="**/*.md5"/> + </fileset> + </checksum> + <checksum fileext=".sha1" + algorithm="SHA"> + <fileset dir="${dist.base.binaries}/"> + <include name="**/*"/> + <exclude name="**/*.asc"/> + <exclude name="**/*.md5"/> + </fileset> + </checksum> + <echo message="${end.binary.gtar.log.message}"/> + + <echo message="${end.distribute.binaries.log.message}"/> + </target> + + + <target name="distribute_source" + depends="" + description="--> create the zip and gzipped tar source distributions"> + <echo message="${begin.distribute.source.log.message}"/> + <mkdir dir="${dist.base.source}"/> + + <echo message="${begin.source.zip.log.message}"/> + <zip destfile="${dist.base.source}/${src.dist.name}.zip"> + <zipfileset dir="." + filemode="755" + prefix="${src.dist.name}"> + <include name="${specfile}"/> + <include name="LICENSE"/> + <include name="build.xml"/> + <include name="config/product*.xml"/> + <include name="config/release*.xml"/> + <include name="release"/> + <include name="scripts/**"/> + <include name="src/**"/> + </zipfileset> + </zip> + <echo message="${end.source.zip.log.message}"/> + + <echo message="${begin.source.tar.log.message}"/> + <tar longfile="gnu" + destfile="${dist.base.source}/${src.dist.name}.tar"> + <tarfileset dir="." + mode="755" + prefix="${src.dist.name}"> + <include name="${specfile}"/> + <include name="LICENSE"/> + <include name="build.xml"/> + <include name="config/product*.xml"/> + <include name="config/release*.xml"/> + <include name="release"/> + <include name="scripts/**"/> + <include name="src/**"/> + </tarfileset> + </tar> + <echo message="${end.source.tar.log.message}"/> + + <echo message="${begin.source.gtar.log.message}"/> + <gzip destfile="${dist.base.source}/${src.dist.name}.tar.gz" + src="${dist.base.source}/${src.dist.name}.tar"/> + <delete file="${dist.base.source}/${src.dist.name}.tar"/> + <delete dir="${dist.name}"/> + <checksum fileext=".md5"> + <fileset dir="${dist.base.source}/"> + <include name="**/*"/> + <exclude name="**/*.asc"/> + <exclude name="**/*.md5"/> + </fileset> + </checksum> + <checksum fileext=".sha1" + algorithm="SHA"> + <fileset dir="${dist.base.source}/"> + <include name="**/*"/> + <exclude name="**/*.asc"/> + <exclude name="**/*.md5"/> + </fileset> + </checksum> + <echo message="${end.source.gtar.log.message}"/> + + <echo message="${end.distribute.source.log.message}"/> + </target> + + + <target name="distribute" + depends="distribute_binaries,distribute_source" + description="--> create binary and source component distributions"> + <echo message="${notify.distribute.log.message}"/> + </target> + + + <target name="main" + depends="clean,distribute" + description="--> clean, build, verify, document, distribute [default]"> + <echo message="${notify.main.log.message}"/> + </target> + +</project> + diff --git a/pki/base/silent/config/product.xml b/pki/base/silent/config/product.xml new file mode 100644 index 000000000..33caf48ed --- /dev/null +++ b/pki/base/silent/config/product.xml @@ -0,0 +1,305 @@ +<!-- ### BEGIN COPYRIGHT BLOCK ### + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + Copyright (C) 2007 Red Hat, Inc. + All rights reserved. + ### END COPYRIGHT BLOCK ### --> +<project name="product.xml" default="main" basedir="."> + + <!-- Set up properties based upon the user's default Ant configuration --> + <property file=".ant.properties"/> + <property file="${user.home}/.ant.properties"/> + <property environment="env"/> + + + <!-- Check for required properties passed-in via the build scripts --> + <fail message="The '-Dspecfile=SPECFILE' property MUST always be specified!" + unless="specfile"/> + + + <!-- Set up optional properties passed-in via the build scripts --> + <property name="basedir" value=""/> + <property name="dirsec" value=""/> + <property name="target" value=""/> + + + <!-- Set up properties obtained from the spec file --> + <exec executable="perl" + failonerror="true" + outputproperty="Name"> + <arg value="-ne"/> + <arg value="print $1 if /%define base_product\s+(.*)/"/> + <arg value="${specfile}"/> + </exec> + + <exec executable="perl" + failonerror="true" + outputproperty="spec.product.ui.prefix"> + <arg value="-ne"/> + <arg value="print $1 if /%define base_ui_prefix\s+(\S+)/"/> + <arg value="${specfile}"/> + </exec> + + <exec executable="perl" + failonerror="true" + outputproperty="product.prefix"> + <arg value="-ne"/> + <arg value="print $1 if /%define base_prefix\s+(\S+)/"/> + <arg value="${specfile}"/> + </exec> + + <exec executable="perl" + failonerror="true" + outputproperty="product"> + <arg value="-ne"/> + <arg value="print $1 if /%define base_component\s+(\S+)/"/> + <arg value="${specfile}"/> + </exec> + + <!-- if "spec.product.ui.prefix" is "" or "linux", --> + <!-- set "product.ui.prefix" to ""; otherwise --> + <!-- set "product.ui.prefix" to "spec.product.ui.prefix" --> + <condition property="product.ui.prefix" + value="" + else="${spec.product.ui.prefix}"> + <or> + <equals arg1="${spec.product.ui.prefix}" + arg2=""/> + <equals arg1="${spec.product.ui.prefix}" + arg2="linux"/> + </or> + </condition> + + <!-- "product.name" is of the form "x-y-z" --> + <condition property="product.name" + value="${product.ui.prefix}-${product.prefix}-${product}"> + <not> + <equals arg1="${product.ui.prefix}" + arg2=""/> + </not> + </condition> + + <!-- "product.name" is of the form "x-y" --> + <condition property="product.name" + value="${product.prefix}-${product}"> + <and> + <equals arg1="${product.ui.prefix}" + arg2=""/> + <not> + <equals arg1="${product.prefix}" + arg2=""/> + </not> + </and> + </condition> + + <!-- "product.name" is of the form "x" --> + <condition property="product.name" + value="${product}"> + <and> + <equals arg1="${product.ui.prefix}" + arg2=""/> + <equals arg1="${product.prefix}" + arg2=""/> + </and> + </condition> + + <exec executable="perl" + failonerror="true" + outputproperty="version"> + <arg value="-ne"/> + <arg value="print $1 if /%define base_version\s+(\S+)/"/> + <arg value="${specfile}"/> + </exec> + + + <!-- Set up architecture-dependent properties --> + <exec executable="uname" + failonerror="true" + outputproperty="arch"> + <arg line="-i"/> + </exec> + + <!-- Set up architecture-independent properties --> + <property name="jar.home" value="/usr/share/java"/> + <property name="pki-jar.home" value="${jar.home}/${product.prefix}"/> + <property name="jni-jar.home" value="/usr/lib/java"/> + + <!-- Set up properties that control various build options --> + <property name="debug" value="true"/> + <property name="chmod.fail" value="true"/> + <property name="chmod.maxparallel" value="250"/> + <property name="deprecation" value="false"/> + <property name="optimize" value="true"/> + + + <!-- Set up properties related to the source tree --> + <property name="docs.dir" value="docs"/> + <property name="lib.dir" value="lib"/> + <property name="src.dir" value="src"/> + <property name="test.dir" value="test"/> + <property name="etc.dir" value="${src.dir}/etc"/> + <property name="script.dir" value="${src.dir}/script"/> + + + <!-- Set up properties for the release area --> + <property name="release.root" value="."/> + + + <!-- Set up properties for the build area --> + <property name="build.dir" value="build"/> + <property name="bootstrap.dir" value="bootstrap"/> + <property name="build.jars" value="${build.dir}/jars"/> + <property name="build.classes" value="${build.dir}/classes"/> + <property name="build.lib" value="${build.dir}/lib"/> + <property name="build.javadocs" value="${build.dir}/javadocs"/> + <property name="build.tests" value="${build.dir}/testcases"/> + <property name="build.tests.javadocs" value="${build.dir}/javadocs.test/"/> + <property name="manifest.tmp" value="${build.dir}/optional.manifest"/> + + + <!-- Set up properties for the distribution area --> + <property name="dist.name" value="${product.name}-${version}"/> + <property name="dist.base" value="dist"/> + <property name="dist.base.source" value="${dist.base}/source"/> + <property name="dist.base.binaries" value="${dist.base}/binary"/> + <property name="dist.dir" value="dist"/> + <property name="dist.bin" value="${dist.dir}/bin"/> + <property name="dist.lib" value="${dist.dir}/lib"/> + <property name="dist.docs" value="${dist.dir}/docs"/> + <property name="dist.etc" value="${dist.dir}/etc"/> + <property name="src.dist.name" value="${product.name}-${version}"/> + <property name="src.dist.dir" value="dist-src"/> + <property name="src.dist.src" value="${src.dist.dir}/src"/> + <property name="src.dist.docs" value="${src.dist.dir}/docs"/> + <property name="src.dist.lib" value="${src.dist.dir}/lib"/> + + + <!-- Set up properties for log messages --> + <property name="begin.clean.log.message" + value="Removing '${product.name}' component directories ..."/> + <property name="empty.clean.log.message" + value="Nothing to do!"/> + <property name="end.clean.log.message" + value="Completed removing '${product.name}' component directories."/> + <property name="begin.download.log.message" + value="Downloading '${product.name}' dependent components ..."/> + <property name="empty.download.log.message" + value="Nothing to do!"/> + <property name="end.download.log.message" + value="Completed downloading '${product.name}' dependent components."/> + <property name="begin.compile.java.log.message" + value="Compiling '${product.name}' java code from '${src.dir}' into '${build.classes}' ..."/> + <property name="empty.compile.java.log.message" + value="Nothing to do!"/> + <property name="end.compile.java.log.message" + value="Completed compiling '${product.name}' java code from '${src.dir}' into '${build.classes}'."/> + <property name="begin.build.jars.log.message" + value="Generating '${product.name}' jar files ..."/> + <property name="empty.build.jars.log.message" + value="Nothing to do!"/> + <property name="end.build.jars.log.message" + value="Completed generating '${product.name}' jar files."/> + <property name="begin.build.jni.headers.log.message" + value="Generating '${product.name}' java header files ..."/> + <property name="empty.build.jni.headers.log.message" + value="Nothing to do!"/> + <property name="end.build.jni.headers.log.message" + value="Completed generating '${product.name}' java header files."/> + <property name="notify.build.log.message" + value="Built classes, jars, and jni headers for the '${product.name}' component."/> + <property name="begin.compile.junit.tests.log.message" + value="Compiling '${product.name}' junit tests from '${test.dir}' into '${build.tests}' ..."/> + <property name="empty.compile.junit.tests.log.message" + value="Nothing to do!"/> + <property name="end.compile.junit.tests.log.message" + value="Completed compiling '${product.name}' junit tests from '${test.dir}' into '${build.tests}'."/> + <property name="begin.run.junit.tests.log.message" + value="Executing '${product.name}' tests ..."/> + <property name="empty.run.junit.tests.log.message" + value="Nothing to do!"/> + <property name="end.run.junit.tests.log.message" + value="Completed executing '${product.name}' tests."/> + <property name="notify.verify.log.message" + value="Verified the '${product.name}' component."/> + <property name="begin.clean.javadocs.log.message" + value="Removing '${product.name}' javadocs directory ..."/> + <property name="empty.clean.javadocs.log.message" + value="Nothing to do!"/> + <property name="end.clean.javadocs.log.message" + value="Completed removing '${product.name}' javadocs directory."/> + <property name="begin.compose.javadocs.log.message" + value="Composing '${product.name}' javadocs ..."/> + <property name="empty.compose.javadocs.log.message" + value="Nothing to do!"/> + <property name="end.compose.javadocs.log.message" + value="Completed composing '${product.name}' javadocs."/> + <property name="notify.document.log.message" + value="Documented '${product.name}' javadocs."/> + <property name="begin.distribute.binaries.log.message" + value="Creating '${product.name}' binary distributions ..."/> + <property name="begin.binary.wrappers.log.message" + value=" Creating '${product.name}' binary wrappers ..."/> + <property name="empty.binary.wrappers.log.message" + value=" Nothing to do!"/> + <property name="end.binary.wrappers.log.message" + value=" Completed creating '${product.name}' binary wrappers."/> + <property name="begin.binary.zip.log.message" + value=" Creating '${product.name}' binary zip files ..."/> + <property name="empty.binary.zip.log.message" + value=" Nothing to do!"/> + <property name="end.binary.zip.log.message" + value=" Completed creating '${product.name}' binary zip files."/> + <property name="begin.binary.tar.log.message" + value=" Creating '${product.name}' binary tar files ..."/> + <property name="empty.binary.tar.log.message" + value=" Nothing to do!"/> + <property name="end.binary.tar.log.message" + value=" Completed creating '${product.name}' binary tar files."/> + <property name="begin.binary.gtar.log.message" + value=" Creating '${product.name}' binary gzip files ..."/> + <property name="empty.binary.gtar.log.message" + value=" Nothing to do!"/> + <property name="end.binary.gtar.log.message" + value=" Completed creating '${product.name}' binary gzip files."/> + <property name="end.distribute.binaries.log.message" + value="Completed creating '${product.name}' binary distributions."/> + <property name="begin.distribute.source.log.message" + value="Creating '${product.name}' source distributions ..."/> + <property name="begin.source.zip.log.message" + value=" Creating '${product.name}' source zip files ..."/> + <property name="empty.source.zip.log.message" + value=" Nothing to do!"/> + <property name="end.source.zip.log.message" + value=" Completed creating '${product.name}' source zip files."/> + <property name="begin.source.tar.log.message" + value=" Creating '${product.name}' source tar files ..."/> + <property name="empty.source.tar.log.message" + value=" Nothing to do!"/> + <property name="end.source.tar.log.message" + value=" Completed creating '${product.name}' source tar files."/> + <property name="begin.source.gtar.log.message" + value=" Creating '${product.name}' source gzip files ..."/> + <property name="empty.source.gtar.log.message" + value=" Nothing to do!"/> + <property name="end.source.gtar.log.message" + value=" Completed creating '${product.name}' source gzip files."/> + <property name="end.distribute.source.log.message" + value="Completed creating '${product.name}' source distributions."/> + <property name="notify.distribute.log.message" + value="Distributed '${product.name}' distribution packages."/> + <property name="notify.main.log.message" + value="Built, verified, documented, and distributed a fresh '${product.name}' component."/> + +</project> + diff --git a/pki/base/silent/config/release.xml b/pki/base/silent/config/release.xml new file mode 100644 index 000000000..fc43aaeb7 --- /dev/null +++ b/pki/base/silent/config/release.xml @@ -0,0 +1,86 @@ +<!-- ### BEGIN COPYRIGHT BLOCK ### + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + Copyright (C) 2007 Red Hat, Inc. + All rights reserved. + ### END COPYRIGHT BLOCK ### --> +<project name="release.xml" default="main" basedir="${basedir}"> + + <echo message="Importing shared properties ..."/> + <import file="product.xml"/> + <import file="product-ext.xml" optional="true"/> + <import file="release-ext.xml" optional="true"/> + <echo message="Completed importing shared properties."/> + + + <target name="local" + depends="" + description="--> Generate this target locally"> + <echo message="Generating the '${product.name}' target locally ..."/> + <exec executable="ant" dir="${release.root}"> + <arg value="-Dspecfile=${product.name}.spec"/> + <arg value="-Ddirsec=${dirsec}"/> + <arg value="${target}"/> + </exec> + <echo message="Completed generating the '${product.name}' target locally."/> + </target> + + + <target name="main" + depends="" + description="--> Generate component RPMS and SRPMS"> + <echo message="Generating '${product.name}' RPMS and SRPMS ..."/> + + <exec executable="pwd" + failonerror="true" + outputproperty="top.dir"/> + <echo message="Established the '${top.dir}' top-level directory."/> + + <echo message="Creating the '${product.name}' source distribution ..."/> + <exec executable="ant" + dir="${release.root}"> + <arg value="-Dspecfile=${product.name}.spec"/> + <arg value="-Ddirsec=${dirsec}"/> + <arg value="distribute_source"/> + </exec> + <echo message="Completed creating the '${product.name}' source distribution."/> + + <echo message="Creating '${product.name}' RPM directories ..."/> + <mkdir dir="${release.root}/dist/rpmpkg"/> + <mkdir dir="${release.root}/dist/rpmpkg/SOURCES"/> + <mkdir dir="${release.root}/dist/rpmpkg/RPMS"/> + <mkdir dir="${release.root}/dist/rpmpkg/SRPMS"/> + <mkdir dir="${release.root}/dist/rpmpkg/SPECS"/> + <mkdir dir="${release.root}/dist/rpmpkg/BUILD"/> + <echo message="Completed creating '${product.name}' RPM directories."/> + + <echo message="Building '${product.name}' RPMS and SRPMS ..."/> + <exec executable="rpmbuild" + dir="${release.root}"> + <arg value="--define"/> + <arg value="_topdir ${top.dir}/${release.root}/dist/rpmpkg"/> + <arg value="-ta"/> + <arg value="${top.dir}/${release.root}/dist/source/${product.name}-${version}.tar.gz"/> + </exec> + <echo message="Completed building '${product.name}' RPMS and SRPMS."/> + + <echo message="Removing various '${product.name}' RPM directories and files ..."/> + <delete dir="${release.root}/dist/rpmpkg/BUILD"/> + <echo message="Completed removing various '${product.name}' RPM directories and files."/> + + <echo message="Completed generating '${product.name}' RPMS and SRPMS."/> + </target> + +</project> + diff --git a/pki/base/silent/scripts/pkisilent b/pki/base/silent/scripts/pkisilent new file mode 100755 index 000000000..b05e0d689 --- /dev/null +++ b/pki/base/silent/scripts/pkisilent @@ -0,0 +1,163 @@ +#!/usr/bin/perl +# --- BEGIN COPYRIGHT BLOCK --- +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301 USA +# +# Copyright (C) 2007 Red Hat, Inc. +# All rights reserved. +# --- END COPYRIGHT BLOCK --- + +############################################################################### +## (1) Specify variables used by this script. ## +############################################################################### + +my $PRODUCT="rhpki"; +my $libpath=""; + + +############################################################################### +## (2) Define helper functions. ## +############################################################################### + +sub invalid_operating_system() +{ + print "\n"; + print "ERROR: pkisilent does not execute on this operating system!\n"; + print "ERROR: check to make sure rhpki-native-tools package is installed!\n"; + print "\n"; +} + +sub invalid_architecture() +{ + print "\n"; + print "ERROR: pkisilent does not execute on this architecture\n"; + print "ERROR: check to make sure rhpki-native-tools package is installed!\n"; + print "\n"; +} + + +############################################################################### +## (3) Set the LD_LIBRARY_PATH environment variable ## +## (as well as the ${libpath} java property) to determine the ## +## search order this command uses to find shared libraries. ## +############################################################################### + +my $OS=`pkiname`; +my $ARCHITECTURE=`pkiarch`; +chop($OS); +chop($ARCHITECTURE); + + +if($OS eq "Linux") +{ + if($ARCHITECTURE eq "i386") + { + $libpath="/usr/lib"; + + $ENV{LD_LIBRARY_PATH} = "/usr/lib/java::" + . "/usr/lib/${PRODUCT}:" + . "/usr/lib/dirsec:" + . "/usr/lib/java/dirsec:" + . "/usr/lib/jvm/jre-1.5.0-ibm/lib/i386/:" + . "/usr/lib/jvm/jre-1.5.0-ibm/lib/i386/native_threads:" + . "/usr/lib/:/lib/:" ; + } + + elsif($ARCHITECTURE eq "x86_64") + { + $libpath="/usr/lib64"; + + $ENV{LD_LIBRARY_PATH} = "/usr/lib/java:/usr/lib:/lib" + . "/usr/lib/${PRODUCT}:" + . "/usr/lib/dirsec:" + . "/usr/lib/java/dirsec:" + . "/usr/lib64/java:/usr/lib64:/lib64:" + . "/usr/lib64/${PRODUCT}:" + . "/usr/lib64/dirsec:" + . "/usr/lib64/java/dirsec:"; + } + else + { + invalid_architecture(); + exit(255); + } +} +elsif (${OS} eq "SunOS") +{ + if (${ARCHITECTURE} eq "sparc") + { + $libpath="/usr/lib"; + $ENV{LD_LIBRARY_PATH} = "/usr/lib/java:/usr/lib:/lib" + . "/usr/lib/${PRODUCT}:" + . "/usr/lib/dirsec:" + . "/usr/lib/java/dirsec:"; + } + + elsif (${ARCHITECTURE} eq "sparcv9") + { + $libpath="/usr/lib/sparcv9"; + + $ENV{LD_LIBRARY_PATH} = "/usr/lib/java:/usr/lib:/lib" + . "/usr/lib/${PRODUCT}:" + . "/usr/lib/dirsec:" + . "/usr/lib/sparcv9:/lib/sparcv9:" + . "/usr/lib/sparcv9/java:" + . "/usr/lib/sparcv9/${PRODUCT}:" + . "/usr/lib/sparcv9/dirsec:" + . "/usr/lib/sparcv9/java/dirsec:"; + } + else + { + invalid_architecture(); + exit(255); + } +} +else +{ + invalid_operating_system(); + exit(255); +} + + +############################################################################### +## (4) Set the CP environment variable to determine the search ## +## order this command wrapper uses to find jar files. ## +############################################################################### + +print "libpath=$libpath\n"; + +$ENV{CLASSPATH} = "/usr/share/java/pkisilent.jar:" + . "${libpath}/java/dirsec/jss4.jar:" + . "/usr/share/java/ldapjdk.jar:" + . "/usr/share/java/${PRODUCT}/certsrv.jar:" + . "/usr/share/java/${PRODUCT}/cmscore.jar:" + . "/usr/share/java/${PRODUCT}/nsutil.jar:" + . "/usr/share/java/${PRODUCT}/cmsutil.jar:" + . "/usr/share/java/${PRODUCT}/cstools.jar:" + . "/usr/share/${PRODUCT}/classes:" + . "/usr/share/java/xml-commons-resolver.jar:" + . "/usr/share/java/xerces-j2.jar:" + . "/usr/lib/java/osutil.jar:"; + + +############################################################################### +## (5) Execute the java command specified by this java command wrapper ## +## based upon the preset LD_LIBRARY_PATH and CP environment variables. ## +############################################################################### + +my $output = `java -cp $ENV{CLASSPATH} @ARGV`; + +print "#######################################################################\n"; +print "$output\n"; +print "#######################################################################\n"; diff --git a/pki/base/silent/src/argparser/ArgParseException.java b/pki/base/silent/src/argparser/ArgParseException.java new file mode 100644 index 000000000..9253ca24f --- /dev/null +++ b/pki/base/silent/src/argparser/ArgParseException.java @@ -0,0 +1,48 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +import java.io.IOException; + +/** + * Exception class used by <code>ArgParser</code> when + * command line arguments contain an error. + * + * @author John E. Lloyd, Fall 2004 + * @see ArgParser + */ +public class ArgParseException extends IOException +{ + /** + * Creates a new ArgParseException with the given message. + * + * @param msg Exception message + */ + public ArgParseException (String msg) + { super (msg); + } + + /** + * Creates a new ArgParseException from the given + * argument and message. + * + * @param arg Offending argument + * @param msg Error message + */ + public ArgParseException (String arg, String msg) + { super (arg + ": " + msg); + } +} diff --git a/pki/base/silent/src/argparser/ArgParser.java b/pki/base/silent/src/argparser/ArgParser.java new file mode 100755 index 000000000..cd1b777de --- /dev/null +++ b/pki/base/silent/src/argparser/ArgParser.java @@ -0,0 +1,2284 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use, + * copy, modify and redistribute is granted, provided that this copyright + * notice is retained and the author is given credit whenever appropriate. + * + * This software is distributed "as is", without any warranty, including + * any implied warranty of merchantability or fitness for a particular + * use. The author assumes no responsibility for, and shall not be liable + * for, any special, indirect, or consequential damages, or any damages + * whatsoever, arising out of or in connection with the use of this + * software. + */ + +import java.io.PrintStream; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.File; +import java.io.FileReader; +import java.io.Reader; +import java.util.Vector; + +import java.lang.reflect.Array; + +/** + * ArgParser is used to parse the command line arguments for a java + * application program. It provides a compact way to specify options and match + * them against command line arguments, with support for + * <a href=#rangespec>range checking</a>, + * <a href=#multipleOptionNames>multiple option names</a> (aliases), + * <a href=#singleWordOptions>single word options</a>, + * <a href=#multipleOptionValues>multiple values associated with an option</a>, + * <a href=#multipleOptionInvocation>multiple option invocation</a>, + * <a href=#helpInfo>generating help information</a>, + * <a href=#customArgParsing>custom argument parsing</a>, and + * <a href=#argsFromAFile>reading arguments from a file</a>. The + * last feature is particularly useful and makes it + * easy to create ad-hoc configuration files for an application. + * + * <h3><a name="example">Basic Example</a></h3> + * + * <p>Here is a simple example in which an application has three + * command line options: + * <code>-theta</code> (followed by a floating point value), + * <code>-file</code> (followed by a string value), and + * <code>-debug</code>, which causes a boolean value to be set. + * + * <pre> + * + * static public void main (String[] args) + * { + * // create holder objects for storing results ... + * + * DoubleHolder theta = new DoubleHolder(); + * StringHolder fileName = new StringHolder(); + * BooleanHolder debug = new BooleanHolder(); + * + * // create the parser and specify the allowed options ... + * + * ArgParser parser = new ArgParser("java argparser.SimpleExample"); + * parser.addOption ("-theta %f #theta value (in degrees)", theta); + * parser.addOption ("-file %s #name of the operating file", fileName); + * parser.addOption ("-debug %v #enables display of debugging info", debug); + * + * // match the arguments ... + * + * parser.matchAllArgs (args); + * + * // and print out the values + * + * System.out.println ("theta=" + theta.value); + * System.out.println ("fileName=" + fileName.value); + * System.out.println ("debug=" + debug.value); + * } + * </pre> + * <p>A command line specifying all three options might look like this: + * <pre> + * java argparser.SimpleExample -theta 7.8 -debug -file /ai/lloyd/bar + * </pre> + * + * <p>The application creates an instance of ArgParser and then adds + * descriptions of the allowed options using {@link #addOption addOption}. The + * method {@link #matchAllArgs(String[]) matchAllArgs} is then used to match + * these options against the command line arguments. Values associated with + * each option are returned in the <code>value</code> field of special + * ``holder'' classes (e.g., {@link argparser.DoubleHolder DoubleHolder}, + * {@link argparser.StringHolder StringHolder}, etc.). + * + * <p> The first argument to {@link #addOption addOption} is a string that + * specifies (1) the option's name, (2) a conversion code for its associated + * value (e.g., <code>%f</code> for floating point, <code>%s</code> for a + * string, <code>%v</code> for a boolean flag), and (3) an optional description + * (following the <code>#</code> character) which is used for generating help + * messages. The second argument is the holder object through which the value + * is returned. This may be either a type-specific object (such as {@link + * argparser.DoubleHolder DoubleHolder} or {@link argparser.StringHolder + * StringHolder}), an array of the appropriate type, or + * <a href=#multipleOptionInvocation> an instance of + * <code>java.util.Vector</code></a>. + * + * <p>By default, arguments that don't match the specified options, are <a + * href=#rangespec>out of range</a>, or are otherwise formatted incorrectly, + * will cause <code>matchAllArgs</code> to print a message and exit the + * program. Alternatively, an application can use {@link + * #matchAllArgs(String[],int,int) matchAllArgs(args,idx,exitFlags)} to obtain + * an array of unmatched arguments which can then be + * <a href=#customArgParsing>processed separately</a> + * + * <h3><a name="rangespec">Range Specification</a></h3> + * + * The values associated with options can also be given range specifications. A + * range specification appears in curly braces immediately following the + * conversion code. In the code fragment below, we show how to specify an + * option <code>-name</code> that expects to be provided with one of three + * string values (<code>john</code>, <code>mary</code>, or <code>jane</code>), + * an option <code>-index</code> that expects to be supplied with a integer + * value in the range 1 to 256, an option <code>-size</code> that expects to be + * supplied with integer values of either 1, 2, 4, 8, or 16, and an option + * <code>-foo</code> that expects to be supplied with floating point values in + * the ranges -99 < foo <= -50, or 50 <= foo < 99. + * + * <pre> + * StringHolder name = new StringHolder(); + * IntHolder index = new IntHolder(); + * IntHolder size = new IntHolder(); + * DoubleHolder foo = new DoubleHolder(); + * + * parser.addOption ("-name %s {john,mary,jane}", name); + * parser.addOption ("-index %d {[1,256]}", index); + * parser.addOption ("-size %d {1,2,4,8,16}", size); + * parser.addOption ("-foo %f {(-99,-50],[50,99)}", foo); + * </pre> + * + * If an argument value does not lie within a specified range, an error is + * generated. + * + * <h3><a name="multipleOptionNames">Multiple Option Names</a></h3> + * + * An option may be given several names, or aliases, in the form of + * a comma seperated list: + * + * <pre> + * parser.addOption ("-v,--verbose %v #print lots of info"); + * parser.addOption ("-of,-outfile,-outputFile %s #output file"); + * </pre> + * + * <h3><a name="singleWordOptions">Single Word Options</a></h3> + * + * Normally, options are assumed to be "multi-word", meaning + * that any associated value must follow the option as a + * separate argument string. For + * example, + * <pre> + * parser.addOption ("-file %s #file name"); + * </pre> + * will cause the parser to look for two strings in the argument list + * of the form + * <pre> + * -file someFileName + * </pre> + * However, if there is no white space separting the option's name from + * it's conversion code, then values associated with that + * option will be assumed to be part of the same argument + * string as the option itself. For example, + * <pre> + * parser.addOption ("-file=%s #file name"); + * </pre> + * will cause the parser to look for a single string in the argument + * list of the form + * <pre> + * -file=someFileName + * </pre> + * Such an option is called a "single word" option. + * + * <p> + * In cases where an option has multiple names, then this single + * word behavior is invoked if there is no white space between + * the last indicated name and the conversion code. However, previous + * names in the list will still be given multi-word behavior + * if there is white space between the name and the + * following comma. For example, + * <pre> + * parser.addOption ("-nb=,-number ,-n%d #number of blocks"); + * </pre> + * will cause the parser to look for one, two, and one word constructions + * of the forms + * <pre> + * -nb=N + * -number N + * -nN + * </pre> + * + * <h3><a name="multipleOptionValues">Multiple Option Values</a></h3> + * + * If may be useful for an option to be followed by several values. + * For instance, we might have an option <code>-velocity</code> + * which should be followed by three numbers denoting + * the x, y, and z components of a velocity vector. + * We can require multiple values for an option + * by placing a <i>multiplier</i> specification, + * of the form <code>X</code>N, where N is an integer, + * after the conversion code (or range specification, if present). + * For example, + * + * <pre> + * double[] pos = new double[3]; + * + * addOption ("-position %fX3 #position of the object", pos); + * </pre> + * will cause the parser to look for + * <pre> + * -position xx yy zz + * </pre> + * + * in the argument list, where <code>xx</code>, <code>yy</code>, and + * <code>zz</code> are numbers. The values are stored in the array + * <code>pos</code>. + * + * Options requiring multiple values must use arrays to + * return their values, and cannot be used in single word format. + * + * <h3><a name="multipleOptionInvocation">Multiple Option Invocation</a></h3> + * + * Normally, if an option appears twice in the command list, the + * value associated with the second instance simply overwrites the + * value associated with the first instance. + * + * However, the application can instead arrange for the storage of <i>all</i> + * values associated with multiple option invocation, by supplying a instance + * of <code>java.util.Vector</code> to serve as the value holder. Then every + * time the option appears in the argument list, the parser will create a value + * holder of appropriate type, set it to the current value, and store the + * holder in the vector. For example, the construction + * + * <pre> + * Vector vec = new Vector(10); + * + * parser.addOption ("-foo %f", vec); + * parser.matchAllArgs(args); + * </pre> + * when supplied with an argument list that contains + * <pre> + * -foo 1.2 -foo 1000 -foo -78 + * </pre> + * + * will create three instances of {@link argparser.DoubleHolder DoubleHolder}, + * initialized to <code>1.2</code>, <code>1000</code>, and <code>-78</code>, + * and store them in <code>vec</code>. + * + * <h3><a name="helpInfo">Generating help information</a></h3> + * + * ArgParser automatically generates help information for the options, and this + * information may be printed in response to a <i>help</i> option, or may be + * queried by the application using {@link #getHelpMessage getHelpMessage}. + * The information for each option consists of the option's name(s), it's + * required value(s), and an application-supplied description. Value + * information is generated automaticlly from the conversion code, range, and + * multiplier specifications (although this can be overriden, as + * <a href=#valueInfo>described below</a>). + * The application-supplied description is whatever + * appears in the specification string after the optional <code>#</code> + * character. The string returned by {@link #getHelpMessage getHelpMessage} for + * the <a href=#example>first example above</a> would be + * + * <pre> + * Usage: java argparser.SimpleExample + * Options include: + * + * -help,-? displays help information + * -theta <float> theta value (in degrees) + * -file <string> name of the operating file + * -debug enables display of debugging info + * </pre> + * + * The options <code>-help</code> and <code>-?</code> are including in the + * parser by default as help options, and they automatically cause the help + * message to be printed. To exclude these + * options, one should use the constructor {@link #ArgParser(String,boolean) + * ArgParser(synopsis,false)}. + * Help options can also be specified by the application using {@link + * #addOption addOption} and the conversion code <code>%h</code>. Help options + * can be disabled using {@link #setHelpOptionsEnabled + * setHelpOptionsEnabled(false)}. + * + * <p><a name=valueInfo> + * A description of the required values for an option can be + * specified explicitly + * by placing a second <code>#</code> character in the specification + * string. Everything between the first and second <code>#</code> + * characters then becomes the value description, and everything + * after the second <code>#</code> character becomes the option + * description. + * For example, if the <code>-theta</code> option + * above was specified with + * <pre> + * parser.addOption ("-theta %f #NUMBER#theta value (in degrees)",theta); + * </pre> + * instead of + * <pre> + * parser.addOption ("-theta %f #theta value (in degrees)", theta); + * </pre> + * then the corresponding entry in the help message would look + * like + * <pre> + * -theta NUMBER theta value (in degrees) + * </pre> + * + * <h3><a name="customArgParsing">Custom Argument Parsing</a></h3> + * + * An application may find it necessary to handle arguments that + * don't fit into the framework of this class. There are a couple + * of ways to do this. + * + * <p> + * First, the method {@link #matchAllArgs(String[],int,int) + * matchAllArgs(args,idx,exitFlags)} returns an array of + * all unmatched arguments, which can then be handled + * specially: + * <pre> + * String[] unmatched = + * parser.matchAllArgs (args, 0, parser.EXIT_ON_ERROR); + * for (int i = 0; i < unmatched.length; i++) + * { ... handle unmatched arguments ... + * } + * </pre> + * + * For instance, this would be useful for an applicatoon that accepts an + * arbitrary number of input file names. The options can be parsed using + * <code>matchAllArgs</code>, and the remaining unmatched arguments + * give the file names. + * + * <p> If we need more control over the parsing, we can parse arguments one at + * a time using {@link #matchArg matchArg}: + * + * <pre> + * int idx = 0; + * while (idx < args.length) + * { try + * { idx = parser.matchArg (args, idx); + * if (parser.getUnmatchedArgument() != null) + * { + * ... handle this unmatched argument ourselves ... + * } + * } + * catch (ArgParserException e) + * { // malformed or erroneous argument + * parser.printErrorAndExit (e.getMessage()); + * } + * } + * </pre> + * + * {@link #matchArg matchArg(args,idx)} matches one option at location + * <code>idx</code> in the argument list, and then returns the location value + * that should be used for the next match. If an argument does + * not match any option, + * {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy of the + * unmatched argument. + * + * <h3><a name="argsFromAFile">Reading Arguments From a File</a></h3> + * + * The method {@link #prependArgs prependArgs} can be used to automatically + * read in a set of arguments from a file and prepend them onto an existing + * argument list. Argument words correspond to white-space-delimited strings, + * and the file may contain the comment character <code>#</code> (which + * comments out everything to the end of the current line). A typical usage + * looks like this: + * + * <pre> + * ... create parser and add options ... + * + * args = parser.prependArgs (new File(".configFile"), args); + * + * parser.matchAllArgs (args); + * </pre> + * + * This makes it easy to generate simple configuration files for an + * application. + * + * @author John E. Lloyd, Fall 2004 + */ +public class ArgParser +{ + Vector matchList; +// int tabSpacing = 8; + String synopsisString; + boolean helpOptionsEnabled = true; + Record defaultHelpOption = null; + Record firstHelpOption = null; + PrintStream printStream = System.out; + int helpIndent = 24; + String errMsg = null; + String unmatchedArg = null; + + static String validConversionCodes = "iodxcbfsvh"; + + /** + * Indicates that the program should exit with an appropriate message + * in the event of an erroneous or malformed argument.*/ + public static int EXIT_ON_ERROR = 1; + + /** + * Indicates that the program should exit with an appropriate message + * in the event of an unmatched argument.*/ + public static int EXIT_ON_UNMATCHED = 2; + + /** + * Returns a string containing the valid conversion codes. These + * are the characters which may follow the <code>%</code> character in + * the specification string of {@link #addOption addOption}. + * + * @return Valid conversion codes + * @see #addOption + */ + public static String getValidConversionCodes() + { + return validConversionCodes; + } + + static class NameDesc + { + String name; + // oneWord implies that any value associated with + // option is concatenated onto the argument string itself + boolean oneWord; + NameDesc next = null; + } + + static class RangePnt + { + double dval = 0; + long lval = 0; + String sval = null; + boolean bval = true; + boolean closed = true; + + RangePnt (String s, boolean closed) + { sval = s; + this.closed = closed; + } + + RangePnt (double d, boolean closed) + { dval = d; + this.closed = closed; + } + + RangePnt (long l, boolean closed) + { lval = l; + this.closed = closed; + } + + RangePnt (boolean b, boolean closed) + { bval = b; + this.closed = closed; + } + + RangePnt (StringScanner scanner, int type) + throws IllegalArgumentException + { + String typeName = null; + try + { switch (type) + { + case Record.CHAR: + { typeName = "character"; + lval = scanner.scanChar(); + break; + } + case Record.INT: + case Record.LONG: + { typeName = "integer"; + lval = scanner.scanInt(); + break; + } + case Record.FLOAT: + case Record.DOUBLE: + { typeName = "float"; + dval = scanner.scanDouble(); + break; + } + case Record.STRING: + { typeName = "string"; + sval = scanner.scanString(); + break; + } + case Record.BOOLEAN: + { typeName = "boolean"; + bval = scanner.scanBoolean(); + break; + } + } + } + catch (StringScanException e) + { throw new IllegalArgumentException ( + "Malformed " + typeName + " '" + + scanner.substring(scanner.getIndex(), + e.getFailIndex()+1) + + "' in range spec"); + } +// this.closed = closed; + } + + void setClosed (boolean closed) + { this.closed = closed; + } + + boolean getClosed() + { return closed; + } + + int compareTo (double d) + { if (dval < d) + { return -1; + } + else if (d == dval) + { return 0; + } + else + { return 1; + } + } + + int compareTo (long l) + { if (lval < l) + { return -1; + } + else if (l == lval) + { return 0; + } + else + { return 1; + } + } + + int compareTo (String s) + { return sval.compareTo (s); + } + + int compareTo (boolean b) + { if (b == bval) + { return 0; + } + else + { return 1; + } + } + + public String toString() + { return "{ dval=" + dval + ", lval=" + lval + + ", sval=" + sval + ", bval=" + bval + + ", closed=" + closed + "}"; + } + } + + class RangeAtom + { + RangePnt low = null; + RangePnt high = null; + RangeAtom next = null; + + RangeAtom (RangePnt p0, RangePnt p1, int type) + throws IllegalArgumentException + { + int cmp = 0; + switch (type) + { + case Record.CHAR: + case Record.INT: + case Record.LONG: + { cmp = p0.compareTo (p1.lval); + break; + } + case Record.FLOAT: + case Record.DOUBLE: + { cmp = p0.compareTo (p1.dval); + break; + } + case Record.STRING: + { cmp = p0.compareTo (p1.sval); + break; + } + } + if (cmp > 0) + { // then switch high and low + low = p1; + high = p0; + } + else + { low = p0; + high = p1; + } + } + + RangeAtom (RangePnt p0) + throws IllegalArgumentException + { + low = p0; + } + + boolean match (double d) + { int lc = low.compareTo(d); + if (high != null) + { int hc = high.compareTo(d); + return (lc*hc < 0 || + (low.closed && lc==0) || + (high.closed && hc==0)); + } + else + { return lc == 0; + } + } + + boolean match (long l) + { int lc = low.compareTo(l); + if (high != null) + { int hc = high.compareTo(l); + return (lc*hc < 0 || + (low.closed && lc==0) || + (high.closed && hc==0)); + } + else + { return lc == 0; + } + } + + boolean match (String s) + { int lc = low.compareTo(s); + if (high != null) + { int hc = high.compareTo(s); + return (lc*hc < 0 || + (low.closed && lc==0) || + (high.closed && hc==0)); + } + else + { return lc == 0; + } + } + + boolean match (boolean b) + { return low.compareTo(b) == 0; + } + + public String toString() + { return "low=" + (low==null ? "null" : low.toString()) + + ", high=" + (high==null ? "null" : high.toString()); + } + } + + class Record + { + NameDesc nameList; + static final int NOTYPE = 0; + static final int BOOLEAN = 1; + static final int CHAR = 2; + static final int INT = 3; + static final int LONG = 4; + static final int FLOAT = 5; + static final int DOUBLE = 6; + static final int STRING = 7; + int type; + int numValues; + boolean vectorResult = false; + + String helpMsg = null; + String valueDesc = null; + String rangeDesc = null; + Object resHolder = null; + RangeAtom rangeList = null; + RangeAtom rangeTail = null; + char convertCode; + boolean vval = true; // default value for now + + NameDesc firstNameDesc() + { + return nameList; + } + + RangeAtom firstRangeAtom() + { + return rangeList; + } + + int numRangeAtoms() + { int cnt = 0; + for (RangeAtom ra=rangeList; ra!=null; ra=ra.next) + { cnt++; + } + return cnt; + } + + void addRangeAtom (RangeAtom ra) + { if (rangeList == null) + { rangeList = ra; + } + else + { rangeTail.next = ra; + } + rangeTail = ra; + } + + boolean withinRange (double d) + { + if (rangeList == null) + { return true; + } + for (RangeAtom ra=rangeList; ra!=null; ra=ra.next) + { if (ra.match (d)) + { return true; + } + } + return false; + } + + boolean withinRange (long l) + { + if (rangeList == null) + { return true; + } + for (RangeAtom ra=rangeList; ra!=null; ra=ra.next) + { if (ra.match (l)) + { return true; + } + } + return false; + } + + boolean withinRange (String s) + { + if (rangeList == null) + { return true; + } + for (RangeAtom ra=rangeList; ra!=null; ra=ra.next) + { if (ra.match (s)) + { return true; + } + } + return false; + } + + boolean withinRange (boolean b) + { + if (rangeList == null) + { return true; + } + for (RangeAtom ra=rangeList; ra!=null; ra=ra.next) + { if (ra.match (b)) + { return true; + } + } + return false; + } + + String valTypeName() + { + switch (convertCode) + { + case 'i': + { return ("integer"); + } + case 'o': + { return ("octal integer"); + } + case 'd': + { return ("decimal integer"); + } + case 'x': + { return ("hex integer"); + } + case 'c': + { return ("char"); + } + case 'b': + { return ("boolean"); + } + case 'f': + { return ("float"); + } + case 's': + { return ("string"); + } + } + return ("unknown"); + } + + void scanValue (Object result, String name, String s, int resultIdx) + throws ArgParseException + { + double dval = 0; + String sval = null; + long lval = 0; + boolean bval = false; + + if (s.length()==0) + { throw new ArgParseException + (name, "requires a contiguous value"); + } + StringScanner scanner = new StringScanner(s); + try + { + switch (convertCode) + { + case 'i': + { lval = scanner.scanInt(); + break; + } + case 'o': + { lval = scanner.scanInt (8, false); + break; + } + case 'd': + { lval = scanner.scanInt (10, false); + break; + } + case 'x': + { lval = scanner.scanInt (16, false); + break; + } + case 'c': + { lval = scanner.scanChar(); + break; + } + case 'b': + { bval = scanner.scanBoolean(); + break; + } + case 'f': + { dval = scanner.scanDouble(); + break; + } + case 's': + { sval = scanner.getString(); + break; + } + } + } + catch (StringScanException e) + { throw new ArgParseException ( + name, "malformed " + valTypeName() + " '" + s + "'"); + } + scanner.skipWhiteSpace(); + if (!scanner.atEnd()) + { throw new ArgParseException ( + name, "malformed " + valTypeName() + " '" + s + "'"); + } + boolean outOfRange = false; + switch (type) + { + case CHAR: + case INT: + case LONG: + { outOfRange = !withinRange (lval); + break; + } + case FLOAT: + case DOUBLE: + { outOfRange = !withinRange (dval); + break; + } + case STRING: + { outOfRange = !withinRange (sval); + break; + } + case BOOLEAN: + { outOfRange = !withinRange (bval); + break; + } + } + if (outOfRange) + { String errmsg = "value " + s + " not in range "; + throw new ArgParseException ( + name, "value '" + s + "' not in range " + rangeDesc); + } + if (result.getClass().isArray()) + { + switch (type) + { + case BOOLEAN: + { ((boolean[])result)[resultIdx] = bval; + break; + } + case CHAR: + { ((char[])result)[resultIdx] = (char)lval; + break; + } + case INT: + { ((int[])result)[resultIdx] = (int)lval; + break; + } + case LONG: + { ((long[])result)[resultIdx] = lval; + break; + } + case FLOAT: + { ((float[])result)[resultIdx] = (float)dval; + break; + } + case DOUBLE: + { ((double[])result)[resultIdx] = dval; + break; + } + case STRING: + { ((String[])result)[resultIdx] = sval; + break; + } + } + } + else + { + switch (type) + { + case BOOLEAN: + { ((BooleanHolder)result).value = bval; + break; + } + case CHAR: + { ((CharHolder)result).value = (char)lval; + break; + } + case INT: + { ((IntHolder)result).value = (int)lval; + break; + } + case LONG: + { ((LongHolder)result).value = lval; + break; + } + case FLOAT: + { ((FloatHolder)result).value = (float)dval; + break; + } + case DOUBLE: + { ((DoubleHolder)result).value = dval; + break; + } + case STRING: + { ((StringHolder)result).value = sval; + break; + } + } + } + } + } + + private String firstHelpOptionName() + { + if (firstHelpOption != null) + { return firstHelpOption.nameList.name; + } + else + { return null; + } + } + + /** + * Creates an <code>ArgParser</code> with a synopsis + * string, and the default help options <code>-help</code> and + * <code>-?</code>. + * + * @param synopsisString string that briefly describes program usage, + * for use by {@link #getHelpMessage getHelpMessage}. + * @see ArgParser#getSynopsisString + * @see ArgParser#getHelpMessage + */ + public ArgParser(String synopsisString) + { + this (synopsisString, true); + } + + /** + * Creates an <code>ArgParser</code> with a synopsis + * string. The help options <code>-help</code> and + * <code>-?</code> are added if <code>defaultHelp</code> + * is true. + * + * @param synopsisString string that briefly describes program usage, + * for use by {@link #getHelpMessage getHelpMessage}. + * @param defaultHelp if true, adds the default help options + * @see ArgParser#getSynopsisString + * @see ArgParser#getHelpMessage + */ + public ArgParser(String synopsisString, boolean defaultHelp) + { + matchList = new Vector(128); + this.synopsisString = synopsisString; + if (defaultHelp) + { addOption ("-help,-? %h #displays help information", null); + defaultHelpOption = firstHelpOption = (Record)matchList.get(0); + } + } + + /** + * Returns the synopsis string used by the parser. + * The synopsis string is a short description of how to invoke + * the program, and usually looks something like + * <p> + * <prec> + * "java somepackage.SomeClass [options] files ..." + * </prec> + * + * <p> It is used in help and error messages. + * + * @return synopsis string + * @see ArgParser#setSynopsisString + * @see ArgParser#getHelpMessage + */ + public String getSynopsisString () + { + return synopsisString; + } + + /** + * Sets the synopsis string used by the parser. + * + * @param s new synopsis string + * @see ArgParser#getSynopsisString + * @see ArgParser#getHelpMessage + */ + public void setSynopsisString (String s) + { + synopsisString = s; + } + + /** + * Indicates whether or not help options are enabled. + * + * @return true if help options are enabled + * @see ArgParser#setHelpOptionsEnabled + * @see ArgParser#addOption + */ + public boolean getHelpOptionsEnabled () + { + return helpOptionsEnabled; + } + + /** + * Enables or disables help options. Help options are those + * associated with a conversion code of <code>%h</code>. If + * help options are enabled, and a help option is matched, + * then the string produced by + * {@link #getHelpMessage getHelpMessage} + * is printed to the default print stream and the program + * exits with code 0. Otherwise, arguments which match help + * options are ignored. + * + * @param enable enables help options if <code>true</code>. + * @see ArgParser#getHelpOptionsEnabled + * @see ArgParser#addOption + * @see ArgParser#setDefaultPrintStream */ + public void setHelpOptionsEnabled(boolean enable) + { helpOptionsEnabled = enable; + } + + /** + * Returns the default print stream used for outputting help + * and error information. + * + * @return default print stream + * @see ArgParser#setDefaultPrintStream + */ + public PrintStream getDefaultPrintStream() + { return printStream; + } + + /** + * Sets the default print stream used for outputting help + * and error information. + * + * @param stream new default print stream + * @see ArgParser#getDefaultPrintStream + */ + public void setDefaultPrintStream (PrintStream stream) + { + printStream = stream; + } + + /** + * Gets the indentation used by {@link #getHelpMessage + * getHelpMessage}. + * + * @return number of indentation columns + * @see ArgParser#setHelpIndentation + * @see ArgParser#getHelpMessage + */ + public int getHelpIndentation() + { + return helpIndent; + } + + /** + * Sets the indentation used by {@link #getHelpMessage + * getHelpMessage}. This is the number of columns that an option's help + * information is indented. If the option's name and value information + * can fit within this number of columns, then all information about + * the option is placed on one line. Otherwise, the indented help + * information is placed on a separate line. + * + * @param indent number of indentation columns + * @see ArgParser#getHelpIndentation + * @see ArgParser#getHelpMessage + */ + public void setHelpIndentation (int indent) + { helpIndent = indent; + } + +// public void setTabSpacing (int n) +// { tabSpacing = n; +// } + +// public int getTabSpacing () +// { return tabSpacing; +// } + + private void scanRangeSpec (Record rec, String s) + throws IllegalArgumentException + { + StringScanner scanner = new StringScanner (s); + int i0, i = 1; + char c, c0, c1; + + scanner.setStringDelimiters (")],}"); + c = scanner.getc(); // swallow the first '{' + scanner.skipWhiteSpace(); + while ((c=scanner.peekc()) != '}') + { RangePnt p0, p1; + + if (c == '[' || c == '(') + { + if (rec.convertCode == 'v' || rec.convertCode == 'b') + { throw new IllegalArgumentException + ("Sub ranges not supported for %b or %v"); + } + c0 = scanner.getc(); // record & swallow character + scanner.skipWhiteSpace(); + p0 = new RangePnt (scanner, rec.type); + scanner.skipWhiteSpace(); + if (scanner.getc() != ',') + { throw new IllegalArgumentException + ("Missing ',' in subrange specification"); + } + p1 = new RangePnt (scanner, rec.type); + scanner.skipWhiteSpace(); + if ((c1=scanner.getc()) != ']' && c1 != ')') + { throw new IllegalArgumentException + ("Unterminated subrange"); + } + if (c0 == '(') + { p0.setClosed (false); + } + if (c1 == ')') + { p1.setClosed (false); + } + rec.addRangeAtom (new RangeAtom (p0, p1, rec.type)); + } + else + { scanner.skipWhiteSpace(); + p0 = new RangePnt (scanner, rec.type); + rec.addRangeAtom (new RangeAtom (p0)); + } + scanner.skipWhiteSpace(); + if ((c=scanner.peekc()) == ',') + { scanner.getc(); + scanner.skipWhiteSpace(); + } + else if (c != '}') + { + throw new IllegalArgumentException + ("Range spec: ',' or '}' expected"); + } + } + if (rec.numRangeAtoms()==1) + { rec.rangeDesc = s.substring (1, s.length()-1); + } + else + { rec.rangeDesc = s; + } + } + + private int defaultResultType (char convertCode) + { + switch (convertCode) + { + case 'i': + case 'o': + case 'd': + case 'x': + { return Record.LONG; + } + case 'c': + { return Record.CHAR; + } + case 'v': + case 'b': + { return Record.BOOLEAN; + } + case 'f': + { return Record.DOUBLE; + } + case 's': + { return Record.STRING; + } + } + return Record.NOTYPE; + } + + /** + * Adds a new option description to the parser. The method takes two + * arguments: a specification string, and a result holder in which to + * store the associated value. + * + * <p>The specification string has the general form + * + * <p> <var>optionNames</var> + * <code>%</code><var>conversionCode</var> + * [<code>{</code><var>rangeSpec</var><code>}</code>] + * [<code>X</code><var>multiplier</var>] + * [<code>#</code><var>valueDescription</var>] + * [<code>#</code><var>optionDescription</var>] </code> + * + * <p> + * where + * <ul> <p><li><var>optionNames</var> is a + * comma-separated list of names for the option + * (such as <code>-f, --file</code>). + * + * <p><li><var>conversionCode</var> is a single letter, + * following a <code>%</code> character, specifying + * information about what value the option requires: + * + * <table> + * <tr><td><code>%f</code></td><td>a floating point number</td> + * <tr><td><code>%i</code></td><td>an integer, in either decimal, + * hex (if preceeded by <code>0x</code>), or + * octal (if preceeded by <code>0</code>)</td> + * <tr valign=top> + * <td><code>%d</code></td><td>a decimal integer</td> + * <tr valign=top> + * <td><code>%o</code></td><td>an octal integer</td> + * <tr valign=top> + * <td><code>%h</code></td><td>a hex integer (without the + * preceeding <code>0x</code>)</td> + * <tr valign=top> + * <td><code>%c</code></td><td>a single character, including + * escape sequences (such as <code>\n</code> or <code>\007</code>), + * and optionally enclosed in single quotes + * <tr valign=top> + * <td><code>%b</code></td><td>a boolean value (<code>true</code> + * or <code>false</code>)</td> + * <tr valign=top> + * <td><code>%s</code></td><td>a string. This will + * be the argument string itself (or its remainder, in + * the case of a single word option)</td> + * <tr valign=top> + * <td><code>%v</code></td><td>no explicit value is expected, + * but a boolean value of <code>true</code> (by default) + * will be stored into the associated result holder if this + * option is matched. If one wishes to have a value of + * <code>false</code> stored instead, then the <code>%v</code> + * should be followed by a "range spec" containing + * <code>false</code>, as in <code>%v{false}</code>. + * </table> + * + * <p><li><var>rangeSpec</var> is an optional range specification, + * placed inside curly braces, consisting of a + * comma-separated list of range items each specifying + * permissible values for the option. A range item may be an + * individual value, or it may itself be a subrange, + * consisting of two individual values, separated by a comma, + * and enclosed in square or round brackets. Square and round + * brackets denote closed and open endpoints of a subrange, indicating + * that the associated endpoint value is included or excluded + * from the subrange. + * The values specified in the range spec need to be + * consistent with the type of value expected by the option. + * + * <p><b>Examples:</b> + * + * <p>A range spec of <code>{2,4,8,16}</code> for an integer + * value will allow the integers 2, 4, 8, or 16. + * + * <p>A range spec of <code>{[-1.0,1.0]}</code> for a floating + * point value will allow any floating point number in the + * range -1.0 to 1.0. + * + * <p>A range spec of <code>{(-88,100],1000}</code> for an integer + * value will allow values > -88 and <= 100, as well as 1000. + * + * <p>A range spec of <code>{"foo", "bar", ["aaa","zzz")} </code> for a + * string value will allow strings equal to <code>"foo"</code> or + * <code>"bar"</code>, plus any string lexically greater than or equal + * to <code>"aaa"</code> but less then <code>"zzz"</code>. + * + * <p><li><var>multiplier</var> is an optional integer, + * following a <code>X</code> character, + * indicating the number of values which the option expects. + * If the multiplier is not specified, it is assumed to be + * 1. If the multiplier value is greater than 1, then the + * result holder should be either an array (of appropriate + * type) with a length greater than or equal to the multiplier + * value, or a <code>java.util.Vector</code> + * <a href=#vectorHolder>as discussed below</a>. + * + * <p><li><var>valueDescription</var> is an optional + * description of the option's value requirements, + * and consists of all + * characters between two <code>#</code> characters. + * The final <code>#</code> character initiates the + * <i>option description</i>, which may be empty. + * The value description is used in + * <a href=#helpInfo>generating help messages</a>. + * + * <p><li><var>optionDescription</var> is an optional + * description of the option itself, consisting of all + * characters between a <code>#</code> character + * and the end of the specification string. + * The option description is used in + * <a href=#helpInfo>generating help messages</a>. + * </ul> + * + * <p>The result holder must be an object capable of holding + * a value compatible with the conversion code, + * or it must be a <code>java.util.Vector</code>. + * When the option is matched, its associated value is + * placed in the result holder. If the same option is + * matched repeatedly, the result holder value will be overwritten, + * unless the result holder is a <code>java.util.Vector</code>, + * in which + * case new holder objects for each match will be allocated + * and added to the vector. Thus if + * multiple instances of an option are desired by the + * program, the result holder should be a + * <code>java.util.Vector</code>. + * + * <p>If the result holder is not a <code>Vector</code>, then + * it must correspond as follows to the conversion code: + * + * <table> + * <tr valign=top> + * <td><code>%i</code>, <code>%d</code>, <code>%x</code>, + * <code>%o</code></td> + * <td>{@link argparser.IntHolder IntHolder}, + * {@link argparser.LongHolder LongHolder}, <code>int[]</code>, or + * <code>long[]</code></td> + * </tr> + * + * <tr valign=top> + * <td><code>%f</code></td> + * <td>{@link argparser.FloatHolder FloatHolder}, + * {@link argparser.DoubleHolder DoubleHolder}, + * <code>float[]</code>, or + * <code>double[]</code></td> + * </tr> + * + * <tr valign=top> + * <td><code>%b</code>, <code>%v</code></td> + * <td>{@link argparser.BooleanHolder BooleanHolder} or + * <code>boolean[]</code></td> + * </tr> + * + * <tr valign=top> + * <td><code>%s</code></td> + * <td>{@link argparser.StringHolder StringHolder} or + * <code>String[]</code></td> + * </tr> + * + * <tr valign=top> + * <td><code>%c</code></td> + * <td>{@link argparser.CharHolder CharHolder} or + * <code>char[]</code></td> + * </tr> + * </table> + * + * <p>In addition, if the multiplier is greater than 1, + * then only the array type indicated above may be used, + * and the array must be at least as long as the multiplier. + * + * <p><a name=vectorHolder>If the result holder is a + * <code>Vector</code>, then the system will create an appropriate + * result holder object and add it to the vector. Multiple occurances + * of the option will cause multiple results to be added to the vector. + * + * <p>The object allocated by the system to store the result + * will correspond to the conversion code as follows: + * + * <table> + * <tr valign=top> + * <td><code>%i</code>, <code>%d</code>, <code>%x</code>, + * <code>%o</code></td> + * <td>{@link argparser.LongHolder LongHolder}, or + * <code>long[]</code> if the multiplier value exceeds 1</td> + * </tr> + * + * <tr valign=top> + * <td><code>%f</code></td> + * <td>{@link argparser.DoubleHolder DoubleHolder}, or + * <code>double[]</code> if the multiplier value exceeds 1</td> + * </tr> + * + * <tr valign=top> + * <td><code>%b</code>, <code>%v</code></td> + * <td>{@link argparser.BooleanHolder BooleanHolder}, or + * <code>boolean[]</code> + * if the multiplier value exceeds 1</td> + * </tr> + * + * <tr valign=top> + * <td><code>%s</code></td> + * <td>{@link argparser.StringHolder StringHolder}, or + * <code>String[]</code> + * if the multiplier value exceeds 1</td> + * </tr> + * + * <tr valign=top> + * <td><code>%c</code></td> + * <td>{@link argparser.CharHolder CharHolder}, or <code>char[]</code> + * if the multiplier value exceeds 1</td> + * </tr> + * </table> + * + * @param spec the specification string + * @param resHolder object in which to store the associated + * value + * @throws IllegalArgumentException if there is an error in + * the specification or if the result holder is of an invalid + * type. */ + public void addOption (String spec, Object resHolder) + throws IllegalArgumentException + { + // null terminated string is easier to parse + StringScanner scanner = new StringScanner(spec); + Record rec = null; + NameDesc nameTail = null; + NameDesc ndesc; + int i0, i1; + char c; + + do + { ndesc = new NameDesc(); + boolean nameEndsInWhiteSpace = false; + + scanner.skipWhiteSpace(); + i0 = scanner.getIndex(); + while (!Character.isWhitespace(c=scanner.getc()) && + c != ',' && c != '%' && c != '\000') + ; + i1 = scanner.getIndex(); + if (c!='\000') + { i1--; + } + if (i0==i1) + { // then c is one of ',' '%' or '\000' + throw new IllegalArgumentException + ("Null option name given"); + } + if (Character.isWhitespace(c)) + { nameEndsInWhiteSpace = true; + scanner.skipWhiteSpace(); + c = scanner.getc(); + } + if (c=='\000') + { throw new IllegalArgumentException + ("No conversion character given"); + } + if (c != ',' && c != '%') + { throw new IllegalArgumentException + ("Names not separated by ','"); + } + ndesc.name = scanner.substring (i0, i1); + if (rec == null) + { rec = new Record(); + rec.nameList = ndesc; + } + else + { nameTail.next = ndesc; + } + nameTail = ndesc; + ndesc.oneWord = !nameEndsInWhiteSpace; + } + while (c != '%'); + + if (nameTail == null) + { throw new IllegalArgumentException + ("Null option name given"); + } + if (!nameTail.oneWord) + { for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next) + { ndesc.oneWord = false; + } + } + c = scanner.getc(); + if (c=='\000') + { throw new IllegalArgumentException + ("No conversion character given"); + } + if (validConversionCodes.indexOf(c) == -1) + { throw new IllegalArgumentException + ("Conversion code '" + c + "' not one of '" + + validConversionCodes + "'"); + } + rec.convertCode = c; + + if (resHolder instanceof Vector) + { rec.vectorResult = true; + rec.type = defaultResultType (rec.convertCode); + } + else + { + switch (rec.convertCode) + { + case 'i': + case 'o': + case 'd': + case 'x': + { if (resHolder instanceof LongHolder || + resHolder instanceof long[]) + { rec.type = Record.LONG; + } + else if (resHolder instanceof IntHolder || + resHolder instanceof int[]) + { rec.type = Record.INT; + } + else + { throw new IllegalArgumentException ( + "Invalid result holder for %" + c); + } + break; + } + case 'c': + { if (!(resHolder instanceof CharHolder) && + !(resHolder instanceof char[])) + { throw new IllegalArgumentException ( + "Invalid result holder for %c"); + } + rec.type = Record.CHAR; + break; + } + case 'v': + case 'b': + { if (!(resHolder instanceof BooleanHolder) && + !(resHolder instanceof boolean[])) + { throw new IllegalArgumentException ( + "Invalid result holder for %" + c); + } + rec.type = Record.BOOLEAN; + break; + } + case 'f': + { if (resHolder instanceof DoubleHolder || + resHolder instanceof double[]) + { rec.type = Record.DOUBLE; + } + else if (resHolder instanceof FloatHolder || + resHolder instanceof float[]) + { rec.type = Record.FLOAT; + } + else + { throw new IllegalArgumentException ( + "Invalid result holder for %f"); + } + break; + } + case 's': + { if (!(resHolder instanceof StringHolder) && + !(resHolder instanceof String[])) + { throw new IllegalArgumentException ( + "Invalid result holder for %s"); + } + rec.type = Record.STRING; + break; + } + case 'h': + { // resHolder is ignored for this type + break; + } + } + } + if (rec.convertCode == 'h') + { rec.resHolder = null; + } + else + { rec.resHolder = resHolder; + } + + scanner.skipWhiteSpace(); + // get the range specification, if any + if (scanner.peekc() == '{') + { + if (rec.convertCode == 'h') + { throw new IllegalArgumentException + ("Ranges not supported for %h"); + } +// int bcnt = 0; + i0 = scanner.getIndex(); // beginning of range spec + do + { c = scanner.getc(); + if (c=='\000') + { throw new IllegalArgumentException + ("Unterminated range specification"); + } +// else if (c=='[' || c=='(') +// { bcnt++; +// } +// else if (c==']' || c==')') +// { bcnt--; +// } +// if ((rec.convertCode=='v'||rec.convertCode=='b') && bcnt>1) +// { throw new IllegalArgumentException +// ("Sub ranges not supported for %b or %v"); +// } + } + while (c != '}'); +// if (c != ']') +// { throw new IllegalArgumentException +// ("Range specification must end with ']'"); +// } + i1 = scanner.getIndex(); // end of range spec + scanRangeSpec (rec, scanner.substring (i0, i1)); + if (rec.convertCode == 'v' && rec.rangeList!=null) + { rec.vval = rec.rangeList.low.bval; + } + } + // check for value multiplicity information, if any + if (scanner.peekc() == 'X') + { + if (rec.convertCode == 'h') + { throw new IllegalArgumentException + ("Multipliers not supported for %h"); + } + scanner.getc(); + try + { rec.numValues = (int)scanner.scanInt(); + } + catch (StringScanException e) + { throw new IllegalArgumentException + ("Malformed value multiplier"); + } + if (rec.numValues <= 0) + { throw new IllegalArgumentException + ("Value multiplier number must be > 0"); + } + } + else + { rec.numValues = 1; + } + if (rec.numValues > 1) + { for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next) + { if (ndesc.oneWord) + { throw new IllegalArgumentException ( +"Multiplier value incompatible with one word option " + ndesc.name); + } + } + } + if (resHolder != null && resHolder.getClass().isArray()) + { if (Array.getLength(resHolder) < rec.numValues) + { throw new IllegalArgumentException ( +"Result holder array must have a length >= " + rec.numValues); + } + } + else + { if (rec.numValues > 1 && !(resHolder instanceof Vector)) + { throw new IllegalArgumentException ( +"Multiplier requires result holder to be an array of length >= " ++ rec.numValues); + } + } + + // skip white space following conversion information + scanner.skipWhiteSpace(); + + // get the help message, if any + + if (!scanner.atEnd()) + { if (scanner.getc() != '#') + { throw new IllegalArgumentException + ("Illegal character(s), expecting '#'"); + } + String helpInfo = scanner.substring (scanner.getIndex()); + // look for second '#'. If there is one, then info + // between the first and second '#' is the value descriptor. + int k = helpInfo.indexOf ("#"); + if (k != -1) + { rec.valueDesc = helpInfo.substring (0, k); + rec.helpMsg = helpInfo.substring (k+1); + } + else + { rec.helpMsg = helpInfo; + } + } + else + { rec.helpMsg = ""; + } + // add option information to match list + if (rec.convertCode == 'h' && firstHelpOption == defaultHelpOption) + { matchList.remove (defaultHelpOption); + firstHelpOption = rec; + } + matchList.add (rec); + } + + Record lastMatchRecord () + { return (Record)matchList.lastElement(); + } + + private Record getRecord (String arg, ObjectHolder ndescHolder) + { + NameDesc ndesc; + for (int i=0; i<matchList.size(); i++) + { Record rec = (Record)matchList.get(i); + for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next) + { if (rec.convertCode != 'v' && ndesc.oneWord) + { if (arg.startsWith (ndesc.name)) + { if (ndescHolder != null) + { ndescHolder.value = ndesc; + } + return rec; + } + } + else + { if (arg.equals (ndesc.name)) + { if (ndescHolder != null) + { ndescHolder.value = ndesc; + } + return rec; + } + } + } + } + return null; + } + + Object getResultHolder (String arg) + { + Record rec = getRecord(arg, null); + return (rec != null) ? rec.resHolder : null; + } + + String getOptionName (String arg) + { + ObjectHolder ndescHolder = new ObjectHolder(); + Record rec = getRecord(arg, ndescHolder); + return (rec != null) ? ((NameDesc)ndescHolder.value).name : null; + } + + String getOptionRangeDesc (String arg) + { + Record rec = getRecord(arg, null); + return (rec != null) ? rec.rangeDesc : null; + } + + String getOptionTypeName (String arg) + { + Record rec = getRecord(arg, null); + return (rec != null) ? rec.valTypeName() : null; + } + + private Object createResultHolder (Record rec) + { + if (rec.numValues == 1) + { switch (rec.type) + { case Record.LONG: + { return new LongHolder(); + } + case Record.CHAR: + { return new CharHolder(); + } + case Record.BOOLEAN: + { return new BooleanHolder(); + } + case Record.DOUBLE: + { return new DoubleHolder(); + } + case Record.STRING: + { return new StringHolder(); + } + } + } + else + { switch (rec.type) + { case Record.LONG: + { return new long[rec.numValues]; + } + case Record.CHAR: + { return new char[rec.numValues]; + } + case Record.BOOLEAN: + { return new boolean[rec.numValues]; + } + case Record.DOUBLE: + { return new double[rec.numValues]; + } + case Record.STRING: + { return new String[rec.numValues]; + } + } + } + return null; // can't happen + } + + static void stringToArgs (Vector vec, String s, + boolean allowQuotedStrings) + throws StringScanException + { + StringScanner scanner = new StringScanner(s); + scanner.skipWhiteSpace(); + while (!scanner.atEnd()) + { if (allowQuotedStrings) + { vec.add (scanner.scanString()); + } + else + { vec.add (scanner.scanNonWhiteSpaceString()); + } + scanner.skipWhiteSpace(); + } + } + + /** + * Reads in a set of strings from a reader and prepends them to an + * argument list. Strings are delimited by either whitespace or + * double quotes <code>"</code>. The character <code>#</code> acts as + * a comment character, causing input to the end of the current line to + * be ignored. + * + * @param reader Reader from which to read the strings + * @param args Initial set of argument values. Can be + * specified as <code>null</code>. + * @throws IOException if an error occured while reading. + */ + public static String[] prependArgs (Reader reader, String[] args) + throws IOException + { + if (args == null) + { args = new String[0]; + } + LineNumberReader lineReader = new LineNumberReader (reader); + Vector vec = new Vector(100, 100); + String line; + int i, k; + + while ((line = lineReader.readLine()) != null) + { int commentIdx = line.indexOf ("#"); + if (commentIdx != -1) + { line = line.substring (0, commentIdx); + } + try + { stringToArgs (vec, line, /*allowQuotedStings=*/true); + } + catch (StringScanException e) + { throw new IOException ( + "malformed string, line "+lineReader.getLineNumber()); + } + } + String[] result = new String[vec.size()+args.length]; + for (i=0; i<vec.size(); i++) + { result[i] = (String)vec.get(i); + } + for (k=0; k<args.length; k++) + { result[i++] = args[k]; + } + return result; + } + + /** + * Reads in a set of strings from a file and prepends them to an + * argument list. Strings are delimited by either whitespace or double + * quotes <code>"</code>. The character <code>#</code> acts as a + * comment character, causing input to the end of the current line to + * be ignored. + * + * @param file File to be read + * @param args Initial set of argument values. Can be + * specified as <code>null</code>. + * @throws IOException if an error occured while reading the file. + */ + public static String[] prependArgs (File file, String[] args) + throws IOException + { + if (args == null) + { args = new String[0]; + } + if (!file.canRead()) + { return args; + } + try + { return prependArgs (new FileReader (file), args); + } + catch (IOException e) + { throw new IOException ( +"File " + file.getName() + ": " + e.getMessage()); + } + } + + /** + * Sets the parser's error message. + * + * @param s Error message + */ + protected void setError (String msg) + { + errMsg = msg; + } + + /** + * Prints an error message, along with a pointer to help options, + * if available, and causes the program to exit with code 1. + */ + public void printErrorAndExit (String msg) + { + if (helpOptionsEnabled && firstHelpOptionName() != null) + { msg += "\nUse "+firstHelpOptionName()+" for help information"; + } + if (printStream != null) + { printStream.println (msg); + } + System.exit(1); + } + + /** + * Matches arguments within an argument list. + * + * <p>In the event of an erroneous or unmatched argument, the method + * prints a message and exits the program with code 1. + * + * <p>If help options are enabled and one of the arguments matches a + * help option, then the result of {@link #getHelpMessage + * getHelpMessage} is printed to the default print stream and the + * program exits with code 0. If help options are not enabled, they + * are ignored. + * + * @param args argument list + * @see ArgParser#getDefaultPrintStream + */ + public void matchAllArgs (String[] args) + { + matchAllArgs (args, 0, EXIT_ON_UNMATCHED | EXIT_ON_ERROR); + } + + /** + * Matches arguments within an argument list and returns + * those which were not matched. The matching starts at a location + * in <code>args</code> specified by <code>idx</code>, and + * unmatched arguments are returned in a String array. + * + * <p>In the event of an erroneous argument, the method either prints a + * message and exits the program (if {@link #EXIT_ON_ERROR} is + * set in <code>exitFlags</code>) + * or terminates the matching and creates a error message that + * can be retrieved by {@link #getErrorMessage}. + * + * <p>In the event of an umatched argument, the method will print a + * message and exit if {@link #EXIT_ON_UNMATCHED} is set + * in <code>errorFlags</code>. + * Otherwise, the unmatched argument will be appended to the returned + * array of unmatched values, and the matching will continue at the + * next location. + * + * <p>If help options are enabled and one of the arguments matches a + * help option, then the result of {@link #getHelpMessage + * getHelpMessage} is printed to the the default print stream and the + * program exits with code 0. If help options are not enabled, then + * they will not be matched. + * + * @param args argument list + * @param idx starting location in list + * @param exitFlags conditions causing the program to exit. Should be + * an or-ed combintion of {@link #EXIT_ON_ERROR} or {@link + * #EXIT_ON_UNMATCHED}. + * @return array of arguments that were not matched, or + * <code>null</code> if all arguments were successfully matched + * @see ArgParser#getErrorMessage + * @see ArgParser#getDefaultPrintStream + */ + public String[] matchAllArgs (String[] args, int idx, int exitFlags) + { + Vector unmatched = new Vector(10); + + while (idx < args.length) + { try + { idx = matchArg (args, idx); + if (unmatchedArg != null) + { if ((exitFlags & EXIT_ON_UNMATCHED) != 0) + { printErrorAndExit ( + "Unrecognized argument: " + unmatchedArg); + } + else + { unmatched.add (unmatchedArg); + } + } + } + catch (ArgParseException e) + { if ((exitFlags & EXIT_ON_ERROR) != 0) + { printErrorAndExit (e.getMessage()); + } + break; + } + } + if (unmatched.size() == 0) + { return null; + } + else + { return (String[])unmatched.toArray(new String[0]); + } + } + + /** + * Matches one option starting at a specified location in an argument + * list. The method returns the location in the list where the next + * match should begin. + * + * <p>In the event of an erroneous argument, the method throws + * an {@link argparser.ArgParseException ArgParseException} + * with an appropriate error message. This error + * message can also be retrieved using + * {@link #getErrorMessage getErrorMessage}. + * + * <p>In the event of an umatched argument, the method will return idx + * + 1, and {@link #getUnmatchedArgument getUnmatchedArgument} will + * return a copy of the unmatched argument. If an argument is matched, + * {@link #getUnmatchedArgument getUnmatchedArgument} will return + * <code>null</code>. + * + * <p>If help options are enabled and the argument matches a help + * option, then the result of {@link #getHelpMessage getHelpMessage} is printed to + * the the default print stream and the program exits with code 0. If + * help options are not enabled, then they are ignored. + * + * @param args argument list + * @param idx location in list where match should start + * @return location in list where next match should start + * @throws ArgParseException if there was an error performing + * the match (such as improper or insufficient values). + * @see ArgParser#setDefaultPrintStream + * @see ArgParser#getHelpOptionsEnabled + * @see ArgParser#getErrorMessage + * @see ArgParser#getUnmatchedArgument + */ + public int matchArg (String[] args, int idx) + throws ArgParseException + { + unmatchedArg = null; + setError (null); + try + { ObjectHolder ndescHolder = new ObjectHolder(); + Record rec = getRecord (args[idx], ndescHolder); + if (rec == null || (rec.convertCode=='h' && !helpOptionsEnabled)) + { // didn't match + unmatchedArg = new String(args[idx]); + return idx+1; + } + NameDesc ndesc = (NameDesc)ndescHolder.value; + Object result; + if (rec.resHolder instanceof Vector) + { result = createResultHolder (rec); + } + else + { result = rec.resHolder; + } + if (rec.convertCode == 'h') + { if (helpOptionsEnabled) + { printStream.println (getHelpMessage()); + System.exit (0); + } + else + { return idx+1; + } + } + else if (rec.convertCode != 'v') + { if (ndesc.oneWord) + { rec.scanValue ( + result, ndesc.name, + args[idx].substring (ndesc.name.length()), 0); + } + else + { if (idx+rec.numValues >= args.length) + { throw new ArgParseException ( + ndesc.name, "requires " + rec.numValues + " value" + + (rec.numValues > 1 ? "s" : "")); + } + for (int k=0; k<rec.numValues; k++) + { rec.scanValue (result, ndesc.name, args[++idx], k); + } + } + } + else + { if (rec.resHolder instanceof BooleanHolder) + { ((BooleanHolder)result).value = rec.vval; + } + else + { for (int k=0; k<rec.numValues; k++) + { ((boolean[])result)[k] = rec.vval; + } + } + } + if (rec.resHolder instanceof Vector) + { ((Vector)rec.resHolder).add (result); + } + } + catch (ArgParseException e) + { setError (e.getMessage()); + throw e; + } + return idx+1; + } + + private String spaceString (int n) + { + StringBuffer sbuf = new StringBuffer(n); + for (int i=0; i<n; i++) + { sbuf.append(' '); + } + return sbuf.toString(); + } + +// public String getShortHelpMessage () +// { +// String s; +// Record rec; +// NameDesc ndesc; +// int initialIndent = 8; +// int col = initialIndent; + +// if (maxcols <= 0) +// { maxcols = 80; +// } +// if (matchList.size() > 0) +// { ps.print (spaceString(initialIndent)); +// } +// for (int i=0; i<matchList.size(); i++) +// { rec = (Record)matchList.get(i); +// s = "["; +// for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next) +// { s = s + ndesc.name; +// if (ndesc.oneWord == false) +// { s = s + " "; +// } +// if (ndesc.next != null) +// { s = s + ","; +// } +// } +// if (rec.convertCode != 'v' && rec.convertCode != 'h') +// { if (rec.valueDesc != null) +// { s += rec.valueDesc; +// } +// else +// { s = s + "<" + rec.valTypeName() + ">"; +// if (rec.numValues > 1) +// { s += "X" + rec.numValues; +// } +// } +// } +// s = s + "]"; +// /* +// (col+=s.length()) > (maxcols-1) => we will spill over edge. +// we use (maxcols-1) because if we go right to the edge +// (maxcols), we get wrap new line inserted "for us". +// i != 0 means we print the first entry, no matter +// how long it is. Subsequent entries are printed +// full length anyway. */ + +// if ((col+=s.length()) > (maxcols-1) && i != 0) +// { col = initialIndent+s.length(); +// ps.print ("\n" + spaceString(initialIndent)); +// } +// ps.print (s); +// } +// if (matchList.size() > 0) +// { ps.print ('\n'); +// ps.flush(); +// } +// } + + /** + * Returns a string describing the allowed options + * in detail. + * + * @return help information string. + */ + public String getHelpMessage () + { + Record rec; + NameDesc ndesc; + boolean hasOneWordAlias = false; + String s; + + s = "Usage: " + synopsisString + "\n"; + s += "Options include:\n\n"; + for (int i=0; i<matchList.size(); i++) + { String optionInfo = ""; + rec = (Record)matchList.get(i); + if (rec.convertCode=='h' && !helpOptionsEnabled) + { continue; + } + for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next) + { if (ndesc.oneWord) + { hasOneWordAlias = true; + break; + } + } + for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next) + { optionInfo += ndesc.name; + if (hasOneWordAlias && !ndesc.oneWord) + { optionInfo += " "; + } + if (ndesc.next != null) + { optionInfo += ","; + } + } + if (!hasOneWordAlias) + { optionInfo += " "; + } + if (rec.convertCode != 'v' && rec.convertCode != 'h') + { if (rec.valueDesc != null) + { optionInfo += rec.valueDesc; + } + else + { if (rec.rangeDesc != null) + { optionInfo += "<" + rec.valTypeName() + " " + + rec.rangeDesc + ">"; + } + else + { optionInfo += "<" + rec.valTypeName() + ">"; + } + } + } + if (rec.numValues > 1) + { optionInfo += "X" + rec.numValues; + } + s += optionInfo; + if (rec.helpMsg.length() > 0) + { int pad = helpIndent - optionInfo.length(); + if (pad < 2) + { //s += '\n'; + pad = helpIndent; + } +// s += spaceString(pad) + rec.helpMsg; + s += spaceString(4) + rec.helpMsg; + } + s += '\n'; + } + return s; + } + + /** + * Returns the parser's error message. This is automatically + * set whenever an error is encountered in <code>matchArg</code> + * or <code>matchAllArgs</code>, and is automatically set to + * <code>null</code> at the beginning of these methods. + * + * @return error message + */ + public String getErrorMessage() + { + return errMsg; + } + + /** + * Returns the value of an unmatched argument discovered {@link + * #matchArg matchArg} or {@link #matchAllArgs(String[],int,int) + * matchAllArgs}. If there was no unmatched argument, + * <code>null</code> is returned. + * + * @return unmatched argument + */ + public String getUnmatchedArgument() + { + return unmatchedArg; + } +} + + diff --git a/pki/base/silent/src/argparser/ArgParserTest.java b/pki/base/silent/src/argparser/ArgParserTest.java new file mode 100644 index 000000000..74b4c03e1 --- /dev/null +++ b/pki/base/silent/src/argparser/ArgParserTest.java @@ -0,0 +1,1571 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use, + * copy, modify and redistribute is granted, provided that this copyright + * notice is retained and the author is given credit whenever appropriate. + * + * This software is distributed "as is", without any warranty, including + * any implied warranty of merchantability or fitness for a particular + * use. The author assumes no responsibility for, and shall not be liable + * for, any special, indirect, or consequential damages, or any damages + * whatsoever, arising out of or in connection with the use of this + * software. + */ + +import java.io.*; + +import java.lang.reflect.Array; +import java.util.Vector; + +/** + * Testing class for the class ArgParser. Executing the <code>main</code> + * method of this class will perform a suite of tests to help verify correct + * operation of the parser class. + * + * @author John E. Lloyd, Fall 2004 + * @see ArgParser + */ +public class ArgParserTest +{ + ArgParser parser; + + static final boolean CLOSED = true; + static final boolean OPEN = false; + + static final boolean ONE_WORD = true; + static final boolean MULTI_WORD = false; + + private static void verify (boolean ok, String msg) + { if (!ok) + { Throwable e = new Throwable(); + System.out.println ("Verification failed:" + msg); + e.printStackTrace(); + System.exit(1); + } + } + + private static String[] argsFromString (String s) + { + Vector vec = new Vector(100); + try + { ArgParser.stringToArgs (vec, s, /*allowQuotedStings=*/false); + } + catch (StringScanException e) + { e.printStackTrace(); + System.exit (1); + } + String[] result = new String[vec.size()]; + for (int i=0; i<vec.size(); i++) + { result[i] = (String)vec.get(i); + } + return result; + } + + static class RngCheck + { + ArgParser.RangePnt low = null; + ArgParser.RangePnt high = null; + int type; + + RngCheck (String s) + { low = new ArgParser.RangePnt (s, CLOSED); + type = 's'; + } + + RngCheck (double d) + { low = new ArgParser.RangePnt (d, CLOSED); + type = 'd'; + } + + RngCheck (long l) + { low = new ArgParser.RangePnt (l, CLOSED); + type = 'l'; + } + + RngCheck (boolean b) + { low = new ArgParser.RangePnt (b, CLOSED); + type = 'b'; + } + + RngCheck (String s1, boolean c1, String s2, boolean c2) + { low = new ArgParser.RangePnt (s1, c1); + high = new ArgParser.RangePnt (s2, c2); + type = 's'; + } + + RngCheck (double d1, boolean c1, double d2, boolean c2) + { low = new ArgParser.RangePnt (d1, c1); + high = new ArgParser.RangePnt (d2, c2); + type = 'd'; + } + + RngCheck (long l1, boolean c1, long l2, boolean c2) + { low = new ArgParser.RangePnt (l1, c1); + high = new ArgParser.RangePnt (l2, c2); + type = 'l'; + } + + void check (ArgParser.RangeAtom ra) + { + verify ((ra.low==null) == (low==null), + "(ra.low==null)=" + (ra.low==null) + + "(low==null)=" + (low==null)); + verify ((ra.high==null) == (high==null), + "(ra.high==null)=" + (ra.high==null) + + "(high==null)=" + (high==null)); + + if (ra.low != null) + { switch (type) + { case 'l': + { verify (ra.low.lval==low.lval, + "ra.low=" + ra.low + " low=" + low); + break; + } + case 'd': + { verify (ra.low.dval==low.dval, + "ra.low=" + ra.low + " low=" + low); + break; + } + case 's': + { verify (ra.low.sval.equals (low.sval), + "ra.low=" + ra.low + " low=" + low); + break; + } + case 'b': + { verify (ra.low.bval==low.bval, + "ra.low=" + ra.low + " low=" + low); + break; + } + } + verify (ra.low.closed==low.closed, + "ra.low=" + ra.low + " low=" + low); + } + if (ra.high != null) + { switch (type) + { case 'l': + { verify (ra.high.lval==high.lval, + "ra.high=" + ra.high + " high=" + high); + break; + } + case 'd': + { verify (ra.high.dval==high.dval, + "ra.high=" + ra.high + " high=" + high); + break; + } + case 's': + { verify (ra.high.sval.equals (high.sval), + "ra.high=" + ra.high + " high=" + high); + break; + } + case 'b': + { verify (ra.high.bval==high.bval, + "ra.high=" + ra.high + " high=" + high); + break; + } + } + verify (ra.high.closed==high.closed, + "ra.high=" + ra.high + " high=" + high); + } + } + } + + ArgParserTest () + { parser = new ArgParser("fubar"); + } + + static void checkException (Exception e, String errmsg) + { if (errmsg != null) + { if (!e.getMessage().equals(errmsg)) + { System.out.println ( +"Expecting exception '" + errmsg + "' but got '" + + e.getMessage() + "'"); + e.printStackTrace(); + (new Throwable()).printStackTrace(); + System.exit(1); + } + } + else + { System.out.println ( +"Unexpected exception '" + e.getMessage() + "'"); + e.printStackTrace(); + (new Throwable()).printStackTrace(); + System.exit(1); + } + } + + void checkPrintHelp (String msg) + { + ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000); + PrintStream ps = new PrintStream(buf); + ps.println (parser.getHelpMessage()); + System.out.print (buf.toString()); + } + +// void checkGetSynopsis (String msg) +// { +// ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000); +// PrintStream ps = new PrintStream(buf); +// parser.printSynopsis (ps, 80); +// System.out.print (buf.toString()); +// } + + void checkAdd (String s, Object resHolder, String errmsg) + { + checkAdd (s, resHolder, 0, 0, null, null, null, errmsg); + } + + void add (String s, Object resHolder) + { try + { parser.addOption (s, resHolder); + } + catch (Exception e) + { e.printStackTrace(); + System.exit (1); + } + } + + void checkStringArray (String msg, String[] strs, String[] check) + { + boolean dontMatch = false; + if (strs.length != check.length) + { dontMatch = true; + } + else + { for (int i=0; i<strs.length; i++) + { if (!strs[i].equals (check[i])) + { dontMatch = true; + break; + } + } + } + if (dontMatch) + { System.out.println (msg); + System.out.print ("Expected: "); + for (int i=0; i<check.length; i++) + { System.out.print ("'" + check[i] + "'"); + if (i<check.length-1) + { System.out.print (" "); + } + } + System.out.println (""); + System.out.print ("Got: "); + for (int i=0; i<strs.length; i++) + { System.out.print ("'" + strs[i] + "'"); + if (i<strs.length-1) + { System.out.print (" "); + } + } + System.out.println (""); + System.exit(1); + } + } + + void checkAdd (String s, Object resHolder, int code, int numValues, + Object names, RngCheck[] rngCheck, + String helpMsg, String errmsg) + { + boolean exceptionThrown = false; + String[] namelist = null; + try + { parser.addOption (s, resHolder); + } + catch (Exception e) + { exceptionThrown = true; + checkException (e, errmsg); + } + if (names instanceof String) + { namelist = new String[] { (String)names }; + } + else + { namelist = (String[])names; + } + if (!exceptionThrown) + { verify (errmsg == null, + "Expecting exception " + errmsg); + ArgParser.Record rec = parser.lastMatchRecord(); + verify (rec.convertCode==code, + "code=" + rec.convertCode + ", expecting " + code); + ArgParser.NameDesc nd; + int i=0; + for (nd=rec.firstNameDesc(); nd!=null; nd=nd.next) + { i++; + } + verify (i==namelist.length, + "numNames=" + i + ", expecting " +namelist.length); + i=0; + for (nd=rec.firstNameDesc(); nd!=null; nd=nd.next) + { String ss; + if (!nd.oneWord) + { ss = new String(nd.name) + ' '; + } + else + { ss = nd.name; + } + verify (ss.equals(namelist[i]), + "have name '"+ss+"', expecting '"+namelist[i]+"'"); + i++; + } + ArgParser.RangeAtom ra; + i=0; + for (ra=rec.firstRangeAtom(); ra!=null; ra=ra.next) + { i++; + } + int expectedRangeNum = 0; + if (rngCheck!=null) + { expectedRangeNum = rngCheck.length; + } + verify (i==expectedRangeNum, + "numRangeAtoms="+i+", expecting "+expectedRangeNum); + i=0; + for (ra=rec.firstRangeAtom(); ra!=null; ra=ra.next) + { rngCheck[i++].check(ra); + } + verify (rec.helpMsg.equals(helpMsg), + "helpMsg="+rec.helpMsg+", expecting "+helpMsg); + verify (rec.numValues==numValues, + "numValues="+rec.numValues+", expecting "+numValues); + } + } + + double getDoubleValue (Object obj, int k) + { + if (obj instanceof DoubleHolder) + { return ((DoubleHolder)obj).value; + } + else if (obj instanceof FloatHolder) + { return ((FloatHolder)obj).value; + } + else if (obj instanceof double[]) + { return ((double[])obj)[k]; + } + else if (obj instanceof float[]) + { return ((float[])obj)[k]; + } + else + { verify (false, "object doesn't contain double values"); + return 0; + } + } + + long getLongValue (Object obj, int k) + { + if (obj instanceof LongHolder) + { return ((LongHolder)obj).value; + } + else if (obj instanceof IntHolder) + { return ((IntHolder)obj).value; + } + else if (obj instanceof long[]) + { return ((long[])obj)[k]; + } + else if (obj instanceof int[]) + { return ((int[])obj)[k]; + } + else + { verify (false, "object doesn't contain long values"); + return 0; + } + } + + String getStringValue (Object obj, int k) + { + if (obj instanceof StringHolder) + { return ((StringHolder)obj).value; + } + else if (obj instanceof String[]) + { return ((String[])obj)[k]; + } + else + { verify (false, "object doesn't contain String values"); + return null; + } + } + + boolean getBooleanValue (Object obj, int k) + { + if (obj instanceof BooleanHolder) + { return ((BooleanHolder)obj).value; + } + else if (obj instanceof boolean[]) + { return ((boolean[])obj)[k]; + } + else + { verify (false, "object doesn't contain boolean values"); + return false; + } + } + + char getCharValue (Object obj, int k) + { + if (obj instanceof CharHolder) + { return ((CharHolder)obj).value; + } + else if (obj instanceof char[]) + { return ((char[])obj)[k]; + } + else + { verify (false, "object doesn't contain char values"); + return 0; + } + } + + static class MErr + { + int code; + String valStr; + + MErr (int code, String valStr) + { this.code = code; + this.valStr = valStr; + } + } + + static class MTest + { + String args; + Object result; + int resultIdx; + + MTest (String args, Object result) + { this (args, result, -1); + } + + MTest (String args, Object result, int resultIdx) + { this.args = args; + this.result = result; + this.resultIdx = resultIdx; + } + }; + + void checkMatch (String args[], int idx, String errMsg) + { getMatchResult (args, idx, -1, errMsg, -1); + } + + void checkMatch (String args[], int idx, int cnt, + long check, int resultIdx) + { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx); + long result = getLongValue(rholder,0); + verify (result==check, "result " + result + " vs. " + check); + } + + void checkMatch (String args[], int idx, int cnt, + double check, int resultIdx) + { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx); + double result = getDoubleValue(rholder,0); + verify (result==check, "result " + result + " vs. " + check); + } + + void checkMatch (String args[], int idx, int cnt, + String check, int resultIdx) + { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx); + String result = getStringValue(rholder,0); + verify (result.equals(check), "result " + result + " vs. " + check); + } + + void checkMatch (String args[], int idx, int cnt, + boolean check, int resultIdx) + { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx); + boolean result = getBooleanValue(rholder,0); + verify (result==check, "result " + result + " vs. " + check); + } + + void checkMatch (String args[], int idx, int cnt, + char check, int resultIdx) + { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx); + char result = getCharValue(rholder,0); + verify (result==check, "result " + result + " vs. " + check); + } + + void checkMatch (String args[], int idx, int cnt, + Object checkArray, int resultIdx) + { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx); + if (!checkArray.getClass().isArray()) + { verify (false, "check is not an array"); + } + for (int i=0; i<Array.getLength(checkArray); i++) + { if (checkArray instanceof long[]) + { long result = getLongValue(rholder,i); + long check = ((long[])checkArray)[i]; + verify (result==check, + "result ["+i+"] " + result + " vs. " + check); + } + else if (checkArray instanceof double[]) + { double result = getDoubleValue(rholder,i); + double check = ((double[])checkArray)[i]; + verify (result==check, + "result ["+i+"] " + result + " vs. " + check); + } + else if (checkArray instanceof String[]) + { String result = getStringValue(rholder,i); + String check = ((String[])checkArray)[i]; + verify (result.equals(check), + "result ["+i+"] " + result + " vs. " + check); + } + else if (checkArray instanceof boolean[]) + { boolean result = getBooleanValue(rholder,i); + boolean check = ((boolean[])checkArray)[i]; + verify (result==check, + "result ["+i+"] " + result + " vs. " + check); + } + else if (checkArray instanceof char[]) + { char result = getCharValue(rholder,i); + char check = ((char[])checkArray)[i]; + verify (result==check, + "result ["+i+"] " + result + " vs. " + check); + } + else + { verify (false, "unknown type for checkArray"); + } + } + } + + void checkMatch (MTest test, boolean oneWord) + { String[] argv; + if (oneWord) + { argv = new String[1]; + argv[0] = test.args; + } + else + { argv = argsFromString(test.args); + } + if (test.result instanceof Long) + { checkMatch (argv, 0, argv.length, + ((Long)test.result).longValue(), + test.resultIdx); + } + else if (test.result instanceof Double) + { checkMatch (argv, 0, argv.length, + ((Double)test.result).doubleValue(), + test.resultIdx); + } + else if (test.result instanceof String) + { checkMatch (argv, 0, argv.length, + (String)test.result, + test.resultIdx); + } + else if (test.result instanceof Boolean) + { checkMatch (argv, 0, argv.length, + ((Boolean)test.result).booleanValue(), + test.resultIdx); + } + else if (test.result instanceof Character) + { checkMatch (argv, 0, argv.length, + ((Character)test.result).charValue(), + test.resultIdx); + } + else if (test.result.getClass().isArray()) + { checkMatch (argv, 0, argv.length, test.result, + test.resultIdx); + } + else if (test.result instanceof MErr) + { MErr err = (MErr)test.result; + String argname = parser.getOptionName (argv[0]); + String msg = ""; + + switch (err.code) + { case 'c': + { msg = "requires a contiguous value"; + break; + } + case 'm': + { msg = "malformed " + parser.getOptionTypeName(argv[0]) + + " '" + err.valStr + "'"; + break; + } + case 'r': + { msg = "value '" + err.valStr + "' not in range " + + parser.getOptionRangeDesc(argv[0]); + break; + } + case 'v': + { msg = "requires " + err.valStr + " values"; + break; + } + } + checkMatch (argv, 0, argname + ": " + msg); + } + else + { verify (false, "Unknown result type"); + } + } + + void checkMatches (MTest[] tests, boolean oneWord) + { for (int i=0; i<tests.length; i++) + { checkMatch (tests[i], oneWord); + } + } + + Object getMatchResult (String args[], int idx, int cnt, + String errMsg, int resultIdx) + { + boolean exceptionThrown = false; + int k = 0; + try + { k = parser.matchArg (args, idx); + } + catch (Exception e) + { exceptionThrown = true; + checkException (e, errMsg); + } + if (!exceptionThrown) + { verify (k==idx+cnt, + "Expecting result index " + (idx+cnt) + ", got " + k); + Object result = parser.getResultHolder(args[0]); + if (resultIdx >= 0) + { verify (result instanceof Vector, + "Expecting result to be stored in a vector"); + Vector vec = (Vector)result; + verify (vec.size()==resultIdx+1, + "Expecting result vector size " + (resultIdx+1)); + return vec.get(resultIdx); + } + else + { return result; + } + } + else + { return null; + } + } + + /** + * Runs a set of tests to verify correct operation of the + * ArgParser class. If all the tests run correctly, the + * program prints the message <code>Passed</code> and terminates. + * Otherwise, diagnostic information is printed at the first + * point of failure. + */ + public static void main (String[] args) + { + ArgParserTest test = new ArgParserTest(); + + BooleanHolder bh = new BooleanHolder(); + boolean[] b3 = new boolean[3]; + CharHolder ch = new CharHolder(); + char[] c3 = new char[3]; + IntHolder ih = new IntHolder(); + int[] i3 = new int[3]; + LongHolder lh = new LongHolder(); + long[] l3 = new long[3]; + FloatHolder fh = new FloatHolder(); + float[] f3 = new float[3]; + DoubleHolder dh = new DoubleHolder(); + double[] d3 = new double[3]; + StringHolder sh = new StringHolder(); + String[] s3 = new String[3]; + + test.checkAdd ("-foo %i{[0,10)}X3 #sets the value of foo", +// 0123456789012345 + i3, 'i', 3, new String[] { "-foo " }, + new RngCheck[] { + new RngCheck(0, CLOSED, 10, OPEN) }, + "sets the value of foo", null); + + test.checkAdd ("-arg1,,", null, "Null option name given"); + test.checkAdd ("-arg1,,goo %f ", null, "Null option name given"); + test.checkAdd (" ", null, "Null option name given"); + test.checkAdd ("", null, "Null option name given"); + test.checkAdd (" %v", null, "Null option name given"); + test.checkAdd ("-foo ", null, "No conversion character given"); + test.checkAdd ("-foo %", null, "No conversion character given"); + test.checkAdd ("foo, aaa bbb ",null,"Names not separated by ','"); + test.checkAdd (" foo aaa %d", null, "Names not separated by ','"); + test.checkAdd ("-arg1,-b,", null, "Null option name given"); + test.checkAdd ("-arg1,-b", null, "No conversion character given"); + test.checkAdd ("-arg1 ", null, "No conversion character given"); + test.checkAdd ("-arg1, %v", null, "Null option name given"); + test.checkAdd ("-arg1,%v", null, "Null option name given"); + test.checkAdd ("-foo %V", null, + "Conversion code 'V' not one of 'iodxcbfsvh'"); + test.checkAdd ("-h %hX5",null,"Multipliers not supported for %h"); + test.checkAdd ("-h %h{}",null,"Ranges not supported for %h"); + test.checkAdd ("-help, -h %h #here is how we help you", + null, 'h', 1, new String[] {"-help ", "-h " }, + null, "here is how we help you", null); + + test.checkAdd ( + "-arg1 ,-arg2=%d{0,3,(7,16]}X1 #x3 test", + l3, 'd', 1, new String[] { "-arg1 ", "-arg2=" }, + new RngCheck[] + { new RngCheck(0), + new RngCheck(3), + new RngCheck(7, OPEN, 16, CLOSED), + }, + "x3 test", null); + + test.checkAdd ( + "bbb,ccc%x{[1,2]} #X3 x3 test", + l3, 'x', 1, new String[] { "bbb", "ccc" }, + new RngCheck[] + { new RngCheck(1, CLOSED, 2, CLOSED), + }, + "X3 x3 test", null); + + test.checkAdd ( + " bbb ,ccc, ddd ,e , f=%bX1 #x3 test", + b3, 'b', 1, new String[] { "bbb ", "ccc", "ddd ", "e ", "f=" }, + null, + "x3 test", null); + + test.checkAdd ( + " bbb ,ccc, ddd ,e , f= %bX3 #x3 test", + b3, 'b', 3, new String[] { "bbb ", "ccc ", "ddd ", "e ","f= " }, + null, + "x3 test", null); + + test.checkAdd ( + "-b,--bar %s{[\"john\",\"jerry\"),fred,\"harry\"} #sets bar", + sh, 's', 1, new String[] { "-b ", "--bar " }, + new RngCheck[] { + new RngCheck("jerry",OPEN,"john",CLOSED), + new RngCheck("fred"), + new RngCheck("harry") }, + "sets bar", null); + + test.checkAdd ( + "-c ,coven%f{0.0,9.0,(6,5],[-9.1,10.2]} ", + dh, 'f', 1, new String[] { "-c ", "coven" }, + new RngCheck[] { + new RngCheck(0.0), + new RngCheck(9.0), + new RngCheck(5.0,CLOSED,6.0,OPEN), + new RngCheck(-9.1,CLOSED,10.2,CLOSED) }, + "", null); + + test.checkAdd ( + "-b %b #a boolean value ", + bh, 'b', 1, new String[] { "-b "}, + new RngCheck[] { }, + "a boolean value ", null); + + test.checkAdd ("-a %i", ih, 'i', 1, "-a ", null, "", null); + test.checkAdd ("-a %o", lh, 'o', 1, "-a ", null, "", null); + test.checkAdd ("-a %d", i3, 'd', 1, "-a ", null, "", null); + test.checkAdd ("-a %x", l3, 'x', 1, "-a ", null, "", null); + test.checkAdd ("-a %c", ch, 'c', 1, "-a ", null, "", null); + test.checkAdd ("-a %c", c3, 'c', 1, "-a ", null, "", null); + test.checkAdd ("-a %v", bh, 'v', 1, "-a ", null, "", null); + test.checkAdd ("-a %b", b3, 'b', 1, "-a ", null, "", null); + test.checkAdd ("-a %f", fh, 'f', 1, "-a ", null, "", null); + test.checkAdd ("-a %f", f3, 'f', 1, "-a ", null, "", null); + test.checkAdd ("-a %f", dh, 'f', 1, "-a ", null, "", null); + test.checkAdd ("-a %f", d3, 'f', 1, "-a ", null, "", null); + + test.checkAdd ("-a %i", fh, 'i', 1, "-a ", null, "", + "Invalid result holder for %i"); + test.checkAdd ("-a %c", i3, 'c', 1, "-a ", null, "", + "Invalid result holder for %c"); + test.checkAdd ("-a %v", d3, 'v', 1, "-a ", null, "", + "Invalid result holder for %v"); + test.checkAdd ("-a %f", sh, 'f', 1, "-a ", null, "", + "Invalid result holder for %f"); + test.checkAdd ("-a %s", l3, 's', 1, "-a ", null, "", + "Invalid result holder for %s"); + + test.checkAdd ("-foo %i{} ", ih, 'i', 1, "-foo ", null, "", null); + test.checkAdd ("-foo%i{}", ih, 'i', 1, "-foo", null, "", null); + test.checkAdd ("-foo%i{ }", ih, 'i', 1, "-foo", null, "", null); + test.checkAdd ("-foo%i{ }}", ih, + "Illegal character(s), expecting '#'"); + test.checkAdd ("-foo%i{ ", ih,"Unterminated range specification"); + test.checkAdd ("-foo%i{", ih, "Unterminated range specification"); + test.checkAdd ("-foo%i{0,9", ih, "Unterminated range specification"); + test.checkAdd ("-foo%i{1,2,3)", ih, + "Unterminated range specification"); + + test.checkAdd ("-b %f{0.9}", fh, 'f', 1, "-b ", + new RngCheck[] { new RngCheck(0.9) }, + "", null); + test.checkAdd ("-b %f{ 0.9 ,7, -0.5,-4 ,6 }", fh, 'f', 1, "-b ", + new RngCheck[] { new RngCheck(0.9), + new RngCheck(7.0), + new RngCheck(-0.5), + new RngCheck(-4.0), + new RngCheck(6.0) }, + "", null); + test.checkAdd ("-b %f{ [0.9,7), (-0.5,-4),[9,6] , (10,13.4] }", + fh, 'f', 1, "-b ", + new RngCheck[] { new RngCheck(0.9,CLOSED,7.0,OPEN), + new RngCheck(-4.0,OPEN,-.5,OPEN), + new RngCheck(6.0,CLOSED,9.0,CLOSED), + new RngCheck(10.0,OPEN,13.4,CLOSED), + }, + "", null); + test.checkAdd ("-b %f{(8 9]}", fh, + "Missing ',' in subrange specification"); + test.checkAdd ("-b %f{(8,9,]}", fh, + "Unterminated subrange"); + test.checkAdd ("-b %f{(8,9 ,]}", fh, + "Unterminated subrange"); + test.checkAdd ("-b %f{(8,9 8]}", fh, + "Unterminated subrange"); + test.checkAdd ("-b %f{8 9}", fh, + "Range spec: ',' or '}' expected"); + test.checkAdd ("-b %f{8 *}", fh, + "Range spec: ',' or '}' expected"); + + test.checkAdd ("-b %f{8y}", fh, + "Range spec: ',' or '}' expected"); + test.checkAdd ("-b %f{.}", fh, + "Malformed float '.}' in range spec"); + test.checkAdd ("-b %f{1.0e}", fh, + "Malformed float '1.0e}' in range spec"); + test.checkAdd ("-b %f{[*]}", fh, + "Malformed float '*' in range spec"); + test.checkAdd ("-b %f{1.2e5t}", fh, + "Range spec: ',' or '}' expected"); + + + test.checkAdd ("-b %i{8}", ih, 'i', 1, "-b ", + new RngCheck[] { new RngCheck(8) }, + "", null); + test.checkAdd ("-b %i{8, 9,10 }", ih, 'i', 1, "-b ", + new RngCheck[] { new RngCheck(8), + new RngCheck(9), + new RngCheck(10) }, + "", null); + test.checkAdd ("-b %i{8, [-9,10),[-17,15],(2,-33),(8,9] }", + ih, 'i', 1, "-b ", + new RngCheck[] { new RngCheck(8), + new RngCheck(-9,CLOSED,10,OPEN), + new RngCheck(-17,CLOSED,15,CLOSED), + new RngCheck(-33,OPEN,2,OPEN), + new RngCheck(8,OPEN,9,CLOSED), + }, + "", null); + test.checkAdd ("-b %i{8.7}", ih, + "Range spec: ',' or '}' expected"); + test.checkAdd ("-b %i{6,[*]}", ih, + "Malformed integer '*' in range spec"); + test.checkAdd ("-b %i{g76}", ih, + "Malformed integer 'g' in range spec"); + + test.checkAdd ("-b %s{foobar}", sh, 's', 1, "-b ", + new RngCheck[] { new RngCheck("foobar") }, + "", null); + test.checkAdd ("-b %s{foobar, 0x233,\" \"}", sh, 's', 1, "-b ", + new RngCheck[] { new RngCheck("foobar"), + new RngCheck("0x233"), + new RngCheck(" ") }, + "", null); + test.checkAdd ("-b %s{foobar,(bb,aa], [\"01\",02]}", + sh, 's', 1, "-b ", + new RngCheck[] + { new RngCheck("foobar"), + new RngCheck("aa",CLOSED,"bb",OPEN), + new RngCheck("01",CLOSED,"02",CLOSED), + }, + "", null); + + test.checkAdd ("-b %c{'a'}", ch, 'c', 1, "-b ", + new RngCheck[] { new RngCheck('a') }, + "", null); + test.checkAdd ("-b %c{'\\n', '\\002', 'B'}", ch, 'c', 1, "-b ", + new RngCheck[] { new RngCheck('\n'), + new RngCheck('\002'), + new RngCheck('B') }, + "", null); + test.checkAdd ("-b %c{'q',('g','a'], ['\t','\\003']}", + ch, 'c', 1, "-b ", + new RngCheck[] + { new RngCheck('q'), + new RngCheck('a',CLOSED,'g',OPEN), + new RngCheck('\003',CLOSED,'\t',CLOSED), + }, + "", null); + + test.checkAdd ("-b %b{true}X2", b3, 'b', 2, "-b ", + new RngCheck[] { new RngCheck(true) }, + "", null); + test.checkAdd ("-b %b{ true , false, true }", bh, 'b', 1, "-b ", + new RngCheck[] { new RngCheck(true), + new RngCheck(false), + new RngCheck(true) }, + "", null); + test.checkAdd ("-b %v{true,[true,false)}", bh, + "Sub ranges not supported for %b or %v"); + test.checkAdd ("-b %v{true,[]}", bh, + "Sub ranges not supported for %b or %v"); + test.checkAdd ("-b %b{tru}", bh, + "Malformed boolean 'tru}' in range spec"); + + test.checkAdd ("-b %iX2", i3, 'i', 2, "-b ", null, "", null); + test.checkAdd ("-b %vX3", b3, 'v', 3, "-b ", null, "", null); + test.checkAdd ("-b %v{ }X3", b3, 'v', 3, "-b ", null, "", null); + + test.checkAdd ("-b=%iX2", i3, 'i', 2, "-b", null, "", +"Multiplier value incompatible with one word option -b="); + test.checkAdd ("-b %iX0", i3, 'i', 0, "-b ", null, "", + "Value multiplier number must be > 0"); + test.checkAdd ("-b %iX-6", i3, 'i', 0, "-b ", null, "", + "Value multiplier number must be > 0"); + test.checkAdd ("-b %iXy", i3, 'i', 0, "-b ", null, "", + "Malformed value multiplier"); + test.checkAdd ("-b %iX4", i3, 'i', 4, "-b ", null, "", + "Result holder array must have a length >= 4"); + test.checkAdd ("-b %iX4", ih, 'i', 4, "-b ", null, "", +"Multiplier requires result holder to be an array of length >= 4"); + + test.checkAdd ("-b %i #X4", ih, 'i', 1, "-b ", null, "X4", null); + test.checkAdd ("-b %i #[}X4",ih, 'i', 1, "-b ", null, "[}X4", null); + +// test.checkPrintHelp(""); +// test.checkPrintUsage(""); + + test = new ArgParserTest(); + + test.checkAdd ( + "-intarg %i{1,2,(9,18],[22,27],[33,38),(45,48)} #test int arg", + ih, 'i', 1, "-intarg ", + new RngCheck[] + { new RngCheck (1), + new RngCheck (2), + new RngCheck (9,OPEN,18,CLOSED), + new RngCheck (22,CLOSED,27,CLOSED), + new RngCheck (33,CLOSED,38,OPEN), + new RngCheck (45,OPEN,48,OPEN), + }, + "test int arg", null); + + MTest[] tests; + + tests = new MTest[] + { + new MTest("-intarg 1", new Long(1) ), + new MTest("-intarg 3", new MErr ('r', "3") ), + new MTest("-intarg 9", new MErr ('r', "9") ), + new MTest("-intarg 11", new Long(11) ), + new MTest("-intarg 18", new Long(18)), + new MTest("-intarg 22", new Long(22)), + new MTest("-intarg 25", new Long(25)), + new MTest("-intarg 27", new Long(27)), + new MTest("-intarg 33", new Long(33)), + new MTest("-intarg 35", new Long(35)), + new MTest("-intarg 38", new MErr ('r', "38") ), + new MTest("-intarg 45", new MErr ('r', "45")), + new MTest("-intarg 46", new Long(46)), + new MTest("-intarg 48", new MErr ('r', "48")), + new MTest("-intarg 100", new MErr ('r', "100")), + new MTest("-intarg 0xbeef", new MErr ('r', "0xbeef")), + new MTest("-intarg 0x2f", new Long (0x2f)), + new MTest("-intarg 041", new Long(041) ), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-farg %f{1,2,(9,18],[22,27],[33,38),(45,48)} #test float arg", + dh, 'f', 1, "-farg ", + new RngCheck[] + { + new RngCheck (1.0), + new RngCheck (2.0), + new RngCheck (9.0,OPEN,18.0,CLOSED), + new RngCheck (22.0,CLOSED,27.0,CLOSED), + new RngCheck (33.0,CLOSED,38.0,OPEN), + new RngCheck (45.0,OPEN,48.0,OPEN), + }, + "test float arg", null); + + tests = new MTest[] + { + new MTest("-farg 1", new Double(1)), + new MTest("-farg 3", new MErr('r', "3")), + new MTest("-farg 9", new MErr('r', "9")), + new MTest("-farg 9.0001", new Double(9.0001)), + new MTest("-farg 11", new Double(11)), + new MTest("-farg 18", new Double(18)), + new MTest("-farg 22", new Double(22)), + new MTest("-farg 25", new Double(25)), + new MTest("-farg 27", new Double(27)), + new MTest("-farg 33", new Double(33)), + new MTest("-farg 35", new Double(35)), + new MTest("-farg 37.9999",new Double(37.9999)), + new MTest("-farg 38", new MErr('r', "38")), + new MTest("-farg 45", new MErr('r', "45")), + new MTest("-farg 45.0001", new Double(45.0001)), + new MTest("-farg 46",new Double(46)), + new MTest("-farg 47.9999",new Double(47.9999)), + new MTest("-farg 48", new MErr('r', "48")), + new MTest("-farg 100", new MErr('r', "100")), + new MTest("-farg 0", new MErr('r', "0")), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-sarg %s{1,2,(AA,AZ],[BB,BX],[C3,C8),(d5,d8)} #test string arg", + s3, 's', 1, "-sarg ", + new RngCheck[] + { new RngCheck ("1"), + new RngCheck ("2"), + new RngCheck ("AA",OPEN,"AZ",CLOSED), + new RngCheck ("BB",CLOSED,"BX",CLOSED), + new RngCheck ("C3",CLOSED,"C8",OPEN), + new RngCheck ("d5",OPEN,"d8",OPEN), + }, + "test string arg", null); + + tests = new MTest[] + { + new MTest ("-sarg 1", "1"), + new MTest ("-sarg 3", new MErr('r',"3")), + new MTest ("-sarg AA", new MErr('r',"AA")), + new MTest ("-sarg AM", "AM"), + new MTest ("-sarg AZ", "AZ"), + new MTest ("-sarg BB", "BB"), + new MTest ("-sarg BL", "BL"), + new MTest ("-sarg BX", "BX"), + new MTest ("-sarg C3", "C3"), + new MTest ("-sarg C6", "C6"), + new MTest ("-sarg C8", new MErr('r',"C8")), + new MTest ("-sarg d5", new MErr('r',"d5")), + new MTest ("-sarg d6", "d6"), + new MTest ("-sarg d8", new MErr('r',"d8")), + new MTest ("-sarg zzz", new MErr('r',"zzz")), + new MTest ("-sarg 0", new MErr('r',"0")), + }; + test.checkMatches (tests, MULTI_WORD); + + test = new ArgParserTest(); + + test.checkAdd ( + "-carg %c{1,2,(a,z],['A','Z'],['\\001',\\007),(4,8)}", + c3, 'c', 1, "-carg ", + new RngCheck[] + { new RngCheck ('1'), + new RngCheck ('2'), + new RngCheck ('a',OPEN,'z',CLOSED), + new RngCheck ('A',CLOSED,'Z',CLOSED), + new RngCheck ('\001',CLOSED,'\007',OPEN), + new RngCheck ('4',OPEN,'8',OPEN), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-carg 1", new Character('1')), + new MTest ("-carg 3", new MErr('r',"3")), + new MTest ("-carg a", new MErr('r',"a")), + new MTest ("-carg m", new Character('m')), + new MTest ("-carg z", new Character('z')), + new MTest ("-carg A", new Character('A')), + new MTest ("-carg 'L'", new Character('L')), + new MTest ("-carg 'Z'", new Character('Z')), + new MTest ("-carg \\001", new Character('\001')), + new MTest ("-carg \\005", new Character('\005')), + new MTest ("-carg '\\007'", new MErr('r',"'\\007'")), + new MTest ("-carg '4'", new MErr('r',"'4'")), + new MTest ("-carg 6", new Character('6')), + new MTest ("-carg 8", new MErr('r',"8")), + new MTest ("-carg '\\012'", new MErr('r',"'\\012'")), + new MTest ("-carg 0", new MErr('r',"0")), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-foo=%i{[-50,100]}", ih, 'i', 1, "-foo=", + new RngCheck[] + { new RngCheck (-50,CLOSED,100,CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-foo=-51", new MErr('r',"-51")), + new MTest ("-foo=-0x32", new Long(-0x32)), + new MTest ("-foo=-0x33", new MErr('r',"-0x33")), + new MTest ("-foo=-0777", new MErr('r',"-0777")), + new MTest ("-foo=-07", new Long(-07)), + new MTest ("-foo=0", new Long(0)), + new MTest ("-foo=100", new Long(100)), + new MTest ("-foo=0x5e", new Long(0x5e)), + new MTest ("-foo=066", new Long(066)), + new MTest ("-foo=06677", new MErr('r',"06677")), + new MTest ("-foo=0xbeef", new MErr('r',"0xbeef")), + new MTest ("-foo=foo", new MErr('m',"foo")), + new MTest ("-foo=-51d", new MErr('m',"-51d")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-foo2=%i", ih, 'i', 1, "-foo2=", null, "", null); + tests = new MTest[] + { + new MTest ("-foo2=-51", new Long(-51)), + new MTest ("-foo2=-0x33", new Long(-0x33)), + new MTest ("-foo2=-0777", new Long(-0777)), + new MTest ("-foo2=06677", new Long(06677)), + new MTest ("-foo2=0xbeef", new Long(0xbeef)), + new MTest ("-foo2=foo", new MErr('m',"foo")), + new MTest ("-foo2=-51d", new MErr('m',"-51d")), + new MTest ("-foo2=-51", new Long(-51)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-foo3 %iX3", i3, 'i', 3, "-foo3 ", null, "", null); + tests = new MTest[] + { + new MTest ("-foo3 -51 678 0x45", + new long[] { -51, 678, 0x45 }), + new MTest ("-foo3 55 16f 55", new MErr ('m', "16f")), + new MTest ("-foo3 55 16", new MErr ('v', "3")), + }; + test.checkMatches (tests, MULTI_WORD); + + Vector vec = new Vector(100); + + test.checkAdd ("-foov3 %iX3", vec,'i',3,"-foov3 ",null,"",null); + tests = new MTest[] + { new MTest ("-foov3 -1 2 4", new long[] {-1, 2, 4}, 0), + new MTest ("-foov3 10 3 9", new long[] {10, 3, 9}, 1), + new MTest ("-foov3 123 1 0", new long[] {123, 1, 0}, 2), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + test.checkAdd ("-foov %i", vec,'i',1,"-foov ",null,"",null); + tests = new MTest[] + { new MTest ("-foov 11", new Long(11), 0), + new MTest ("-foov 12", new Long(12), 1), + new MTest ("-foov 13", new Long(13), 2), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-foo4 %i{[-50,100]}X2", i3, 'i', 2, "-foo4 ", + new RngCheck[] + { new RngCheck (-50,CLOSED,100,CLOSED), + }, + "", null); + tests = new MTest[] + { + new MTest ("-foo4 -49 78", + new long[] { -49, 78 }), + new MTest ("-foo4 -48 102", new MErr ('r', "102")), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-oct=%o{[-062,0144]}", ih, 'o', 1, "-oct=", + new RngCheck[] + { new RngCheck (-50,CLOSED,100,CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-oct=-063", new MErr('r',"-063")), + new MTest ("-oct=-0x32", new MErr('m',"-0x32")), + new MTest ("-oct=-0777", new MErr('r',"-0777")), + new MTest ("-oct=-07", new Long(-07)), + new MTest ("-oct=0", new Long(0)), + new MTest ("-oct=100", new Long(64)), + new MTest ("-oct=0xae", new MErr('m',"0xae")), + new MTest ("-oct=66", new Long(066)), + new MTest ("-oct=06677", new MErr('r',"06677")), + new MTest ("-oct=0xbeef", new MErr('m',"0xbeef")), + new MTest ("-oct=foo", new MErr('m',"foo")), + new MTest ("-oct=-51d", new MErr('m',"-51d")), + new MTest ("-oct=78", new MErr('m',"78")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-oct2=%o", ih, 'o', 1, "-oct2=", null, "", null); + tests = new MTest[] + { + new MTest ("-oct2=-063", new Long(-063)), + new MTest ("-oct2=-0777", new Long(-0777)), + new MTest ("-oct2=06677", new Long(06677)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ( + "-dec=%d{[-0x32,0x64]}", ih, 'd', 1, "-dec=", + new RngCheck[] + { new RngCheck (-50,CLOSED,100,CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-dec=-063", new MErr('r',"-063")), + new MTest ("-dec=-0x32", new MErr('m',"-0x32")), + new MTest ("-dec=-0777", new MErr('r',"-0777")), + new MTest ("-dec=-07", new Long(-07)), + new MTest ("-dec=0", new Long(0)), + new MTest ("-dec=100", new Long(100)), + new MTest ("-dec=0xae", new MErr('m',"0xae")), + new MTest ("-dec=66", new Long(66)), + new MTest ("-dec=06677", new MErr('r',"06677")), + new MTest ("-dec=0xbeef", new MErr('m',"0xbeef")), + new MTest ("-dec=foo", new MErr('m',"foo")), + new MTest ("-dec=-51d", new MErr('m',"-51d")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-dec2=%d", ih, 'd', 1, "-dec2=", null, "", null); + tests = new MTest[] + { + new MTest ("-dec2=-063", new Long(-63)), + new MTest ("-dec2=-0777", new Long(-777)), + new MTest ("-dec2=06677", new Long(6677)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ( + "-hex=%x{[-0x32,0x64]}", ih, 'x', 1, "-hex=", + new RngCheck[] + { new RngCheck (-50,CLOSED,100,CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-hex=-06", new Long(-0x6)), + new MTest ("-hex=-0x3g2", new MErr('m',"-0x3g2")), + new MTest ("-hex=-0777", new MErr('r',"-0777")), + new MTest ("-hex=-017", new Long(-0x17)), + new MTest ("-hex=0", new Long(0)), + new MTest ("-hex=64", new Long(0x64)), + new MTest ("-hex=5e", new Long(0x5e)), + new MTest ("-hex=66", new MErr('r',"66")), + new MTest ("-hex=06677", new MErr('r',"06677")), + new MTest ("-hex=0xbeef", new MErr('m',"0xbeef")), + new MTest ("-hex=foo", new MErr('m',"foo")), + new MTest ("-hex=-51d", new MErr('r',"-51d")), + new MTest ("-hex=-51g", new MErr('m',"-51g")), + new MTest ("-hex=", new MErr('c',"")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-hex2=%x", ih, 'x', 1, "-hex2=", null, "", null); + tests = new MTest[] + { + new MTest ("-hex2=-0777", new Long(-0x777)), + new MTest ("-hex2=66", new Long(0x66)), + new MTest ("-hex2=06677", new Long(0x6677)), + new MTest ("-hex2=-51d", new Long(-0x51d)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ( + "-char=%c{['b','m']}", ch, 'c', 1, "-char=", + new RngCheck[] + { new RngCheck ('b',CLOSED,'m',CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-char=a", new MErr('r',"a")), + new MTest ("-char=b", new Character('b')), + new MTest ("-char='b'", new Character('b')), + new MTest ("-char='\142'", new Character('b')), + new MTest ("-char='\141'", new MErr('r',"'\141'")), + new MTest ("-char=\142", new Character('b')), + new MTest ("-char=\141", new MErr('r',"\141")), + new MTest ("-char=m", new Character('m')), + new MTest ("-char=z", new MErr('r', "z")), + new MTest ("-char=bb", new MErr('m', "bb")), + new MTest ("-char='b", new MErr('m', "'b")), + new MTest ("-char='", new MErr('m', "'")), + new MTest ("-char=a'", new MErr('m', "a'")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-char2=%c", ch, 'c', 1, "-char2=",null,"",null); + tests = new MTest[] + { + new MTest ("-char2=a", new Character('a')), + new MTest ("-char2='\141'", new Character('\141')), + new MTest ("-char2=\141", new Character('\141')), + new MTest ("-char2=z", new Character('z')), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-charv3 %cX3", vec,'c',3,"-charv3 ",null,"",null); + tests = new MTest[] + { new MTest ("-charv3 a b c", new char[] {'a', 'b', 'c'}, 0), + new MTest ("-charv3 'g' f '\\n'", new char[]{'g','f','\n'}, 1), + new MTest ("-charv3 1 \001 3", new char[] {'1', '\001', '3'}, 2), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + test.checkAdd ("-charv=%c", vec,'c',1,"-charv=",null,"",null); + tests = new MTest[] + { new MTest ("-charv=d", new Character('d'), 0), + new MTest ("-charv='g'", new Character('g'), 1), + new MTest ("-charv=\111", new Character('\111'), 2), + }; + vec.clear(); + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ( + "-bool=%b{true}", bh, 'b', 1, "-bool=", + new RngCheck[] + { new RngCheck (true), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-bool=true", new Boolean(true)), + new MTest ("-bool=false", new MErr('r', "false")), + new MTest ("-bool=fals", new MErr('m', "fals")), + new MTest ("-bool=falsem", new MErr('m', "falsem")), + new MTest ("-bool=truex", new MErr('m', "truex")), + new MTest ("-bool=foo", new MErr('m', "foo")), + new MTest ("-bool=1", new MErr('m', "1")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ( + "-boo2=%b{true,false}", bh, 'b', 1, "-boo2=", + new RngCheck[] + { new RngCheck (true), + new RngCheck (false), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-boo2=true", new Boolean(true)), + new MTest ("-boo2=false", new Boolean(false)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-boo3=%b", bh, 'b', 1, "-boo3=", null, "", null); + tests = new MTest[] + { + new MTest ("-boo3=true", new Boolean(true)), + new MTest ("-boo3=false", new Boolean(false)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-boo3 %bX3", b3, 'b', 3, "-boo3 ", null, "", null); + tests = new MTest[] + { + new MTest ("-boo3 true false true", + new boolean[] { true, false, true }), + new MTest ("-boo3 true fals true", new MErr ('m', "fals")), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ("-boov3 %bX3", vec,'b',3,"-boov3 ",null,"",null); + tests = new MTest[] + { new MTest ("-boov3 true true false", + new boolean [] { true, true, false }, 0), + new MTest ("-boov3 false false true", + new boolean [] { false, false, true }, 1), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + test.checkAdd ("-boov %b", vec,'b',1,"-boov ",null,"",null); + tests = new MTest[] + { new MTest ("-boov true", new Boolean (true), 0), + new MTest ("-boov false", new Boolean (false), 1), + new MTest ("-boov true", new Boolean (true), 2), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + + + test.checkAdd ("-v3 %vX2", b3, 'v', 2, "-v3 ", null, "", null); + tests = new MTest[] + { new MTest ("-v3", new boolean[] { true, true }), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-vf %v{false,true}X2", b3, 'v', 2, "-vf ", + new RngCheck[] + { new RngCheck(false), + new RngCheck(true), + }, + "", null); + tests = new MTest[] + { new MTest ("-vf", new boolean[] { false, false }), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ( + "-str=%s{(john,zzzz]}", sh, 's', 1, "-str=", + new RngCheck[] + { new RngCheck ("john", OPEN, "zzzz", CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-str=john", new MErr ('r', "john")), + new MTest ("-str=joho ", "joho "), + new MTest ("-str=joho ", "joho "), + new MTest ("-str=zzzz", "zzzz"), + new MTest ("-str= joho", new MErr ('r', " joho")), + new MTest ("-str=jnhn ", new MErr ('r', "jnhn ")), + new MTest ("-str=zzzzz", new MErr ('r', "zzzzz")), + new MTest ("-str=\"joho\"", new MErr ('r', "\"joho\"")), + new MTest ("-str=\"joho", new MErr('r', "\"joho")), + new MTest ("-str=joho j", "joho j"), // new MErr('m', "joho j")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-str2=%s", sh,'s',1,"-str2=",null,"",null); + tests = new MTest[] + { + new MTest ("-str2= jnhn", " jnhn"), + new MTest ("-str2=zzzzz", "zzzzz"), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-str3 %sX3",s3,'s',3,"-str3 ",null,"",null); + tests = new MTest[] + { + new MTest ("-str3 foo bar johnny", + new String[] { "foo", "bar", "johnny" }), + new MTest ("-str3 zzzzz \"bad foo", + new String[] { "zzzzz", "\"bad", "foo" + }), // new MErr('m', "\"bad")), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ("-strv3 %sX3", vec,'s',3,"-strv3 ",null,"",null); + tests = new MTest[] + { new MTest ("-strv3 foo bar \"hihi\"", + new String[] {"foo", "bar", "\"hihi\""}, 0), + new MTest ("-strv3 a 123 gg", + new String[]{"a", "123", "gg"}, 1), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + test.checkAdd ("-strv=%s", vec,'s',1,"-strv=",null,"",null); + tests = new MTest[] + { new MTest ("-strv=d", "d", 0), + new MTest ("-strv='g'", "'g'", 1), + new MTest ("-strv=\\111", "\\111", 2), + }; + vec.clear(); + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ( + "-float=%f{(-0.001,1000.0]}", dh, 'f', 1, "-float=", + new RngCheck[] + { new RngCheck (-0.001, OPEN, 1000.0, CLOSED), + }, + "", null); + + tests = new MTest[] + { + new MTest ("-float=-0.000999", new Double(-0.000999)), + new MTest ("-float=1e-3", new Double(0.001)), + new MTest ("-float=12.33e1", new Double(123.3)), + new MTest ("-float=1e3", new Double(1e3)), + new MTest ("-float=1000.000", new Double(1000.0)), + new MTest ("-float=-0.001", new MErr('r', "-0.001")), + new MTest ("-float=-1e-3", new MErr('r', "-1e-3")), + new MTest ("-float=1000.001", new MErr('r', "1000.001")), + new MTest ("-float=.", new MErr('m', ".")), + new MTest ("-float= 124.5 ", new Double (124.5)), + new MTest ("-float=124.5x", new MErr('m', "124.5x")), + new MTest ("-float= foo ", new MErr('m', " foo ")), + new MTest ("-float=1e1", new Double(10)), + new MTest ("-float=1e ", new MErr('m', "1e ")), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-float2=%f", dh,'f',1,"-float2=",null,"",null); + tests = new MTest[] + { + new MTest ("-float2=-0.001", new Double(-0.001)), + new MTest ("-float2=-1e-3", new Double(-1e-3)), + new MTest ("-float2=1000.001", new Double(1000.001)), + }; + test.checkMatches (tests, ONE_WORD); + + test.checkAdd ("-f3 %fX3", d3,'f',3,"-f3 ",null,"",null); + tests = new MTest[] + { + new MTest ("-f3 -0.001 1.23e5 -9.88e-4", + new double[] { -0.001, 1.23e5, -9.88e-4 }), + new MTest ("-f3 7.88 foo 9.0", new MErr ('m', "foo")), + new MTest ("-f3 7.88 . 9.0", new MErr ('m', ".")), + new MTest ("-f3 7.88 3.0 9.0x", new MErr ('m', "9.0x")), + }; + test.checkMatches (tests, MULTI_WORD); + + test.checkAdd ("-fv3 %fX3", vec,'f',3,"-fv3 ",null,"",null); + tests = new MTest[] + { new MTest ("-fv3 1.0 3.444 6.7", + new double[] {1.0, 3.444, 6.7}, 0), + new MTest ("-fv3 13e-5 145.678 0.0001e45", + new double[]{13e-5, 145.678, 0.0001e45}, 1), + new MTest ("-fv3 11.11 3.1245 -1e-4", + new double[] {11.11, 3.1245, -1e-4}, 2), + new MTest ("-fv3 1.0 2 3", + new double[] { 1.0, 2.0, 3.0 }, 3), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + test.checkAdd ("-fv %f", vec,'f',1,"-fv ",null,"",null); + tests = new MTest[] + { new MTest ("-fv -15.1234", new Double(-15.1234), 0), + new MTest ("-fv -1.234e-7", new Double(-1.234e-7), 1), + new MTest ("-fv 0.001111", new Double(0.001111), 2), + }; + vec.clear(); + test.checkMatches (tests, MULTI_WORD); + + + IntHolder intHolder = new IntHolder(); + StringHolder strHolder = new StringHolder(); + + ArgParser parser = new ArgParser ("test"); + parser.addOption ("-foo %d #an int", intHolder); + parser.addOption ("-bar %s #a string", strHolder); + args = new String[] + { "zzz", "-cat", "-foo", "123", "yyy", "-bar", "xxxx", "xxx" + }; + + String[] unmatchedCheck = new String[] + { "zzz", "-cat", "yyy", "xxx" + }; + + String[] unmatched = parser.matchAllArgs (args, 0, 0); + test.checkStringArray ( + "Unmatched args:", unmatched, unmatchedCheck); + + vec.clear(); + for (int i=0; i<args.length; ) + { try + { i = parser.matchArg (args, i); + if (parser.getUnmatchedArgument() != null) + { vec.add (parser.getUnmatchedArgument()); + } + } + catch (Exception e) + { + } + } + unmatched = (String[])vec.toArray(new String[0]); + test.checkStringArray ( + "My unmatched args:", unmatched, unmatchedCheck); + + System.out.println ("\nPassed\n"); + + } +} diff --git a/pki/base/silent/src/argparser/BooleanHolder.java b/pki/base/silent/src/argparser/BooleanHolder.java new file mode 100644 index 000000000..18a35c058 --- /dev/null +++ b/pki/base/silent/src/argparser/BooleanHolder.java @@ -0,0 +1,49 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' a boolean value, + * enabling methods to return boolean values through + * arguments. + */ +public class BooleanHolder implements java.io.Serializable +{ + /** + * Value of the boolean, set and examined + * by the application as needed. + */ + public boolean value; + + /** + * Constructs a new <code>BooleanHolder</code> with an initial + * value of <code>false</code>. + */ + public BooleanHolder () + { value = false; + } + + /** + * Constructs a new <code>BooleanHolder</code> with a + * specific initial value. + * + * @param b Initial boolean value. + */ + public BooleanHolder (boolean b) + { value = b; + } +} diff --git a/pki/base/silent/src/argparser/CharHolder.java b/pki/base/silent/src/argparser/CharHolder.java new file mode 100644 index 000000000..b096df9ca --- /dev/null +++ b/pki/base/silent/src/argparser/CharHolder.java @@ -0,0 +1,51 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' a character value, + * enabling methods to return character values through + * arguments. + */ +public class CharHolder implements java.io.Serializable +{ + /** + * Value of the character, set and examined + * by the application as needed. + */ + public char value; + + /** + * Constructs a new <code>CharHolder</code> with an initial + * value of 0. + */ + public CharHolder () + { value = 0; + } + + /** + * Constructs a new <code>CharHolder</code> with a + * specific initial value. + * + * @param c Initial character value. + */ + public CharHolder (char c) + { value = c; + } +} + + diff --git a/pki/base/silent/src/argparser/DoubleHolder.java b/pki/base/silent/src/argparser/DoubleHolder.java new file mode 100644 index 000000000..3728ebf2e --- /dev/null +++ b/pki/base/silent/src/argparser/DoubleHolder.java @@ -0,0 +1,50 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' a double value, + * enabling methods to return double values through + * arguments. + */ +public class DoubleHolder implements java.io.Serializable +{ + /** + * Value of the double, set and examined + * by the application as needed. + */ + public double value; + + /** + * Constructs a new <code>DoubleHolder</code> with an initial + * value of 0. + */ + public DoubleHolder () + { value = 0; + } + + /** + * Constructs a new <code>DoubleHolder</code> with a + * specific initial value. + * + * @param d Initial double value. + */ + public DoubleHolder (double d) + { value = d; + } +} + diff --git a/pki/base/silent/src/argparser/FloatHolder.java b/pki/base/silent/src/argparser/FloatHolder.java new file mode 100644 index 000000000..4cded9aa4 --- /dev/null +++ b/pki/base/silent/src/argparser/FloatHolder.java @@ -0,0 +1,51 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' a float value, + * enabling methods to return float values through + * arguments. + */ +public class FloatHolder implements java.io.Serializable +{ + /** + * Value of the float, set and examined + * by the application as needed. + */ + public float value; + + /** + * Constructs a new <code>FloatHolder</code> with an initial + * value of 0. + */ + public FloatHolder () + { value = 0; + } + + /** + * Constructs a new <code>FloatHolder</code> with a + * specific initial value. + * + * @param f Initial float value. + */ + public FloatHolder (float f) + { value = f; + } +} + + diff --git a/pki/base/silent/src/argparser/IntHolder.java b/pki/base/silent/src/argparser/IntHolder.java new file mode 100644 index 000000000..fd8403bd1 --- /dev/null +++ b/pki/base/silent/src/argparser/IntHolder.java @@ -0,0 +1,50 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' an integer value, + * enabling methods to return integer values through + * arguments. + */ +public class IntHolder implements java.io.Serializable +{ + /** + * Value of the integer, set and examined + * by the application as needed. + */ + public int value; + + /** + * Constructs a new <code>IntHolder</code> with an initial + * value of 0. + */ + public IntHolder () + { value = 0; + } + + /** + * Constructs a new <code>IntHolder</code> with a + * specific initial value. + * + * @param i Initial integer value. + */ + public IntHolder (int i) + { value = i; + } +} + diff --git a/pki/base/silent/src/argparser/LongHolder.java b/pki/base/silent/src/argparser/LongHolder.java new file mode 100644 index 000000000..13a84008b --- /dev/null +++ b/pki/base/silent/src/argparser/LongHolder.java @@ -0,0 +1,50 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' a long value, + * enabling methods to return long values through + * arguments. + */ +public class LongHolder implements java.io.Serializable +{ + /** + * Value of the long, set and examined + * by the application as needed. + */ + public long value; + + /** + * Constructs a new <code>LongHolder</code> with an initial + * value of 0. + */ + public LongHolder () + { value = 0; + } + + /** + * Constructs a new <code>LongHolder</code> with a + * specific initial value. + * + * @param l Initial long value. + */ + public LongHolder (long l) + { value = l; + } +} + diff --git a/pki/base/silent/src/argparser/ObjectHolder.java b/pki/base/silent/src/argparser/ObjectHolder.java new file mode 100644 index 000000000..8e3493e1d --- /dev/null +++ b/pki/base/silent/src/argparser/ObjectHolder.java @@ -0,0 +1,49 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' an Object reference, + * enabling methods to return Object references through + * arguments. + */ +public class ObjectHolder implements java.io.Serializable +{ + /** + * Value of the Object reference, set and examined + * by the application as needed. + */ + public Object value; + + /** + * Constructs a new <code>ObjectHolder</code> with an initial + * value of <code>null</code>. + */ + public ObjectHolder () + { value = null; + } + + /** + * Constructs a new <code>ObjectHolder</code> with a + * specific initial value. + * + * @param o Initial Object reference. + */ + public ObjectHolder (Object o) + { value = o; + } +} diff --git a/pki/base/silent/src/argparser/SimpleExample.java b/pki/base/silent/src/argparser/SimpleExample.java new file mode 100644 index 000000000..58e4d4656 --- /dev/null +++ b/pki/base/silent/src/argparser/SimpleExample.java @@ -0,0 +1,55 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Gives a very simple example of the use of + * {@link argparser.ArgParser ArgParser}. + */ +public class SimpleExample +{ + /** + * Run this to invoke command line parsing. + */ + public static void main (String[] args) + { + // create holder objects for storing results ... + + DoubleHolder theta = new DoubleHolder(); + StringHolder fileName = new StringHolder(); + BooleanHolder debug = new BooleanHolder(); + + // create the parser and specify the allowed options ... + + ArgParser parser = new ArgParser("java argparser.SimpleExample"); + parser.addOption ("-theta %f #theta value (in degrees)", theta); + parser.addOption ("-file %s #name of the operating file", fileName); + parser.addOption ("-debug %v #enables display of debugging info", + debug); + + // and then match the arguments + + parser.matchAllArgs (args); + + // now print out the values + + System.out.println ("theta=" + theta.value); + System.out.println ("fileName=" + fileName.value); + System.out.println ("debug=" + debug.value); + } +} + diff --git a/pki/base/silent/src/argparser/StringHolder.java b/pki/base/silent/src/argparser/StringHolder.java new file mode 100644 index 000000000..7737fa4cd --- /dev/null +++ b/pki/base/silent/src/argparser/StringHolder.java @@ -0,0 +1,50 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Wrapper class which ``holds'' a String reference, + * enabling methods to return String references through + * arguments. + */ +public class StringHolder implements java.io.Serializable +{ + /** + * Value of the String reference, set and examined + * by the application as needed. + */ + public String value; + + /** + * Constructs a new <code>StringHolder</code> with an + * initial value of <code>null</code>. + */ + public StringHolder () + { value = null; + } + + /** + * Constructs a new <code>StringHolder</code> with a + * specific initial value. + * + * @param s Initial String reference. + */ + public StringHolder (String s) + { value = s; + } +} + diff --git a/pki/base/silent/src/argparser/StringScanException.java b/pki/base/silent/src/argparser/StringScanException.java new file mode 100644 index 000000000..b7b4c7d2d --- /dev/null +++ b/pki/base/silent/src/argparser/StringScanException.java @@ -0,0 +1,53 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.io.IOException; + +/** + * Exception class used by <code>StringScanner</code> when + * command line arguments do not parse correctly. + * + * @author John E. Lloyd, Winter 2001 + * @see StringScanner + */ +class StringScanException extends IOException +{ + int failIdx; + + /** + * Creates a new StringScanException with the given message. + * + * @param msg Error message + * @see StringScanner + */ + + public StringScanException (String msg) + { super (msg); + } + + public StringScanException (int idx, String msg) + { + super (msg); + failIdx = idx; + } + + public int getFailIndex() + { + return failIdx; + } +} diff --git a/pki/base/silent/src/argparser/StringScanner.java b/pki/base/silent/src/argparser/StringScanner.java new file mode 100644 index 000000000..425ad3ac1 --- /dev/null +++ b/pki/base/silent/src/argparser/StringScanner.java @@ -0,0 +1,650 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/** + * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use, + * copy, modify and redistribute is granted, provided that this copyright + * notice is retained and the author is given credit whenever appropriate. + * + * This software is distributed "as is", without any warranty, including + * any implied warranty of merchantability or fitness for a particular + * use. The author assumes no responsibility for, and shall not be liable + * for, any special, indirect, or consequential damages, or any damages + * whatsoever, arising out of or in connection with the use of this + * software. + */ + +class StringScanner +{ + private char[] buf; + private int idx; + private int len; + private String stringDelimiters = ""; + + public StringScanner (String s) + { + buf = new char[s.length()+1]; + s.getChars (0, s.length(), buf, 0); + len = s.length(); + buf[len] = 0; + idx = 0; + } + + public int getIndex() + { return idx; + } + + public void setIndex(int i) + { if (i < 0) + { idx = 0; + } + else if (i > len) + { idx = len; + } + else + { idx = i; + } + } + + public void setStringDelimiters (String s) + { stringDelimiters = s; + } + + public String getStringDelimiters() + { return stringDelimiters; + } + + public char scanChar () + throws StringScanException + { + int idxSave = idx; + skipWhiteSpace(); + try + { if (buf[idx] == '\'') + { return scanQuotedChar(); + } + else + { return scanUnquotedChar(); + } + } + catch (StringScanException e) + { idx = idxSave; + throw e; + } + } + + public char scanQuotedChar () + throws StringScanException + { + StringScanException exception = null; + char retval = 0; + int idxSave = idx; + + skipWhiteSpace(); + if (idx == len) + { exception = new StringScanException (idx, "end of input"); + } + else if (buf[idx++] == '\'') + { try + { retval = scanUnquotedChar(); + } + catch (StringScanException e) + { exception = e; + } + if (exception==null) + { if (idx==len) + { exception = new StringScanException + (idx, "end of input"); + } + else if (buf[idx++] != '\'') + { exception = new StringScanException + (idx-1, "unclosed quoted character"); + } + } + } + else + { exception = new StringScanException + (idx-1, "uninitialized quoted character"); + } + if (exception!=null) + { idx = idxSave; + throw exception; + } + return retval; + } + + public char scanUnquotedChar () + throws StringScanException + { + StringScanException exception = null; + char c, retval = 0; + int idxSave = idx; + + if (idx == len) + { exception = new StringScanException (idx, "end of input"); + } + else if ((c = buf[idx++]) == '\\') + { if (idx == len) + { exception = new StringScanException (idx, "end of input"); + } + else + { + c = buf[idx++]; + if (c == '"') + { retval = '"'; + } + else if (c == '\'') + { retval = '\''; + } + else if (c == '\\') + { retval = '\\'; + } + else if (c == 'n') + { retval = '\n'; + } + else if (c == 't') + { retval = '\t'; + } + else if (c == 'b') + { retval = '\b'; + } + else if (c == 'r') + { retval = '\r'; + } + else if (c == 'f') + { retval = '\f'; + } + else if ('0' <= c && c < '8') + { int v = c - '0'; + for (int j=0; j<2; j++) + { if (idx==len) + { break; + } + c = buf[idx]; + if ('0' <= c && c < '8' && (v*8 + (c-'0')) <= 255) + { v = v*8 + (c-'0'); + idx++; + } + else + { break; + } + } + retval = (char)v; + } + else + { exception = new StringScanException + (idx-1, "illegal escape character '" + c + "'"); + } + } + } + else + { retval = c; + } + if (exception!=null) + { idx = idxSave; + throw exception; + } + return retval; + } + + public String scanQuotedString () + throws StringScanException + { + StringScanException exception = null; + StringBuffer sbuf = new StringBuffer(len); + char c; + int idxSave = idx; + + skipWhiteSpace(); + if (idx == len) + { exception = new StringScanException (idx, "end of input"); + } + else if ((c=buf[idx++]) == '"') + { while (idx<len && (c=buf[idx]) != '"' && c != '\n') + { if (c == '\\') + { try + { c = scanUnquotedChar(); + } + catch (StringScanException e) + { exception = e; + break; + } + } + else + { idx++; + } + sbuf.append (c); + } + if (exception == null && idx>=len) + { exception = new StringScanException (len, "end of input"); + } + else if (exception == null && c == '\n') + { exception = new StringScanException + (idx, "unclosed quoted string"); + } + else + { idx++; + } + } + else + { exception = new StringScanException (idx-1, +"quoted string must start with \""); + } + if (exception != null) + { idx = idxSave; + throw exception; + } + return sbuf.toString(); + } + + public String scanNonWhiteSpaceString() + throws StringScanException + { + StringBuffer sbuf = new StringBuffer(len); + int idxSave = idx; + char c; + + skipWhiteSpace(); + if (idx == len) + { StringScanException e = new StringScanException ( + idx, "end of input"); + idx = idxSave; + throw e; + } + else + { c = buf[idx++]; + while (idx<len && !Character.isWhitespace(c) + && stringDelimiters.indexOf(c) == -1) + { sbuf.append(c); + c = buf[idx++]; + } + if (Character.isWhitespace(c) || + stringDelimiters.indexOf(c) != -1) + { idx--; + } + else + { sbuf.append(c); + } + } + return sbuf.toString(); + } + + public String scanString () + throws StringScanException + { + int idxSave = idx; + skipWhiteSpace(); + try + { if (buf[idx] == '"') + { return scanQuotedString(); + } + else + { return scanNonWhiteSpaceString(); + } + } + catch (StringScanException e) + { idx = idxSave; + throw e; + } + } + + public String getString () + throws StringScanException + { + StringBuffer sbuf = new StringBuffer(len); + while (idx < len) + { sbuf.append (buf[idx++]); + } + return sbuf.toString(); + } + + public long scanInt () + throws StringScanException + { + int idxSave = idx; + char c; + int sign = 1; + + skipWhiteSpace(); + if ((c=buf[idx]) == '-' || c == '+') + { sign = (c == '-' ? -1 : 1); + idx++; + } + try + { if (idx==len) + { throw new StringScanException (len, "end of input"); + } + else if ((c=buf[idx]) == '0') + { if ((c=buf[idx+1]) == 'x' || c == 'X') + { idx += 2; + return sign*scanInt (16, false); + } + else + { return sign*scanInt (8, false); + } + } + else + { return sign*scanInt (10, false); + } + } + catch (StringScanException e) + { idx = idxSave; + throw e; + } + } + + public long scanInt (int radix) + throws StringScanException + { + return scanInt (radix, /*skipWhite=*/true); + } + + private String baseDesc (int radix) + { + switch (radix) + { case 10: + { return "decimal"; + } + case 8: + { return "octal"; + } + case 16: + { return "hex"; + } + default: + { return "base " + radix; + } + } + } + + public long scanInt (int radix, boolean skipWhite) + throws StringScanException + { + StringScanException exception = null; + int charval, idxSave = idx; + char c; + long val = 0; + boolean negate = false; + + if (skipWhite) + { skipWhiteSpace(); + } + if ((c=buf[idx]) == '-' || c == '+') + { negate = (c == '-'); + idx++; + } + if (idx >= len) + { exception = new StringScanException (len, "end of input"); + } + else if ((charval=Character.digit(buf[idx++],radix)) == -1) + { exception = new StringScanException + (idx-1, "malformed " + baseDesc(radix) + " integer"); + } + else + { val = charval; + while ((charval=Character.digit(buf[idx],radix)) != -1) + { val = val*radix + charval; + idx++; + } + if (Character.isLetter(c=buf[idx]) || + Character.isDigit(c) || c == '_') + { exception = new StringScanException + (idx, "malformed " + baseDesc(radix) + " integer"); + } + } + if (exception != null) + { idx = idxSave; + throw exception; + } + return negate ? -val : val; + } + + public double scanDouble () + throws StringScanException + { + StringScanException exception = null; + int idxSave = idx; + char c; + // parse [-][0-9]*[.][0-9]*[eE][-][0-9]* + boolean hasDigits = false; + boolean signed; + double value = 0; + + skipWhiteSpace(); + if (idx == len) + { exception = new StringScanException ("end of input"); + } + else + { + if ((c=buf[idx]) == '-' || c == '+') + { signed = true; + idx++; + } + if (matchDigits()) + { hasDigits = true; + } + if (buf[idx] == '.') + { idx++; + } + if (!hasDigits && (buf[idx] < '0' || buf[idx] > '9')) + { if (idx==len) + { exception = new StringScanException (idx, "end of input"); + } + else + { exception = new StringScanException ( + idx, "malformed floating number: no digits"); + } + } + else + { matchDigits(); + + if ((c=buf[idx]) == 'e' || c == 'E') + { idx++; + if ((c=buf[idx]) == '-' || c == '+') + { signed = true; + idx++; + } + if (buf[idx] < '0' || buf[idx] > '9') + { if (idx==len) + { exception = new StringScanException( + idx, "end of input"); + } + else + { exception = new StringScanException (idx, +"malformed floating number: no digits in exponent"); + } + } + else + { matchDigits(); + } + } + } + } + if (exception == null) + { +// if (Character.isLetterOrDigit(c=buf[idx]) || c == '_') +// { exception = new StringScanException (idx, +//"malformed floating number"); +// } +// else + { + try + { value = Double.parseDouble(new String(buf, idxSave, + idx-idxSave)); + } + catch (NumberFormatException e) + { exception = new StringScanException ( + idx, "malformed floating number"); + } + } + } + if (exception != null) + { idx = idxSave; + throw exception; + } + return value; + } + + public boolean scanBoolean () + throws StringScanException + { + StringScanException exception = null; + int idxSave = idx; + String testStr = "false"; + boolean testval = false; + char c; + + skipWhiteSpace(); + if (buf[idx] == 't') + { testStr = "true"; + testval = true; + } + else + { testval = false; + } + int i = 0; + for (i=0; i<testStr.length(); i++) + { if (testStr.charAt(i) != buf[idx]) + { if (idx==len) + { exception = new StringScanException (idx, "end of input"); + } + break; + } + idx++; + } + if (exception==null) + { if (i<testStr.length() || + Character.isLetterOrDigit(c=buf[idx]) || c == '_') + { exception = new StringScanException (idx, "illegal boolean"); + } + } + if (exception != null) + { idx = idxSave; + throw exception; + } + return testval; + } + + public boolean matchString (String s) + { + int k = idx; + for (int i=0; i<s.length(); i++) + { if (k >= len || s.charAt(i) != buf[k++]) + { return false; + } + } + idx = k; + return true; + } + + public boolean matchDigits () + { + int k = idx; + char c; + + while ((c=buf[k]) >= '0' && c <= '9') + { k++; + } + if (k > idx) + { idx = k; + return true; + } + else + { return false; + } + } + + public void skipWhiteSpace() + { + while (Character.isWhitespace(buf[idx])) + { idx++; + } + } + + private int skipWhiteSpace(int k) + { + while (Character.isWhitespace(buf[k])) + { k++; + } + return k; + } + + public boolean atEnd() + { + return idx == len; + } + + public boolean atBeginning() + { + return idx == 0; + } + + public void ungetc() + { + if (idx > 0) + { idx--; + } + } + + public char getc() + { + char c = buf[idx]; + if (idx < len) + { idx++; + } + return c; + } + + public char peekc() + { + return buf[idx]; + } + + public String substring (int i0, int i1) + { + if (i0 < 0) + { i0 = 0; + } + else if (i0 >= len) + { i0= len-1; + } + if (i1 < 0) + { i1 = 0; + } + else if (i1 > len) + { i1= len; + } + if (i1 <= i0) + { return ""; + } + return new String (buf, i0, i1-i0); + } + + public String substring (int i0) + { + if (i0 < 0) + { i0 = 0; + } + if (i0 >= len) + { return ""; + } + else + { return new String (buf, i0, len-i0); + } + } +} diff --git a/pki/base/silent/src/ca/ConfigureCA.java b/pki/base/silent/src/ca/ConfigureCA.java new file mode 100644 index 000000000..af4815bb4 --- /dev/null +++ b/pki/base/silent/src/ca/ConfigureCA.java @@ -0,0 +1,1023 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import com.netscape.osutil.*; + + +public class ConfigureCA { + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/ca/admin/console/config/login"; + public static String wizard_uri = "/ca/admin/console/config/wizard"; + public static String domain_uri = "/ca/ee/ca/domain"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + public static String pkcs12_uri = "/ca/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String ldap_host = null; + public static String ldap_port = null; + public static String bind_dn = null; + public static String bind_password = null; + public static String base_dn = null; + public static String db_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String save_p12 = null; + public static String backup_pwd = null; + + public static String ca_cert_name = null; + public static String ca_cert_req = null; + public static String ca_cert_pp = null; + public static String ca_cert_cert = null; + + public static String ocsp_cert_name = null; + public static String ocsp_cert_req = null; + public static String ocsp_cert_pp = null; + public static String ocsp_cert_cert = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String ca_subsystem_cert_name = null; + public static String ca_subsystem_cert_req = null; + public static String ca_subsystem_cert_pp = null; + public static String ca_subsystem_cert_cert = null; + + // names + public static String ca_sign_cert_subject_name = null; + public static String ca_subsystem_cert_subject_name = null; + public static String ca_ocsp_cert_subject_name = null; + public static String ca_server_cert_subject_name = null; + + public static String subsystem_name = null; + + public ConfigureCA() {// do nothing :) + } + + public void sleep_time() { + try { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } catch (Exception e) { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // get cookie + String temp = hr.getCookieValue("JSESSIONID"); + + if (temp != null) { + int index = temp.indexOf(";"); + + hc.j_session_id = temp.substring(0, index); + st = true; + } + + hr = null; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return st; + } + + public boolean DomainPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + cs_hostname + ":" + cs_port; + + String query_string = "sdomainURL=" + URLEncoder.encode(domain_url) + + "&sdomainName=" + URLEncoder.encode(domain_name) + + "&choice=newdomain" + "&p=1" + "&op=next" + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + String temp_sdomain = px.getvalue("sdomainName"); + + System.out.println("sdomainname=" + temp_sdomain); + + return true; + + } + + public boolean CreateCAPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=3" + "&op=next" + "&xml=true" + + "&choice=newsubsystem" + "&subsystemName=" + + URLEncoder.encode(subsystem_name); + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // hr = null; + // query_string = "p=4" + "&op=next" + "&xml=true"; + // hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + // bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + // px.parse(bais); + // px.prettyprintxml(); + + + return true; + + } + + public boolean HierarchyPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=6" + "&op=next" + "&xml=true" + "&choice=root"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + /* + hr = null; + hr = hc.sslConnect(cs_hostname,cs_port, + wizard_uri,"p=7&op=next&xml=true"); + + // parse xml to return result + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + */ + + + return true; + + } + + public boolean LdapConnectionPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=7" + "&op=next" + "&xml=true" + "&host=" + + URLEncoder.encode(ldap_host) + "&port=" + + URLEncoder.encode(ldap_port) + "&binddn=" + + URLEncoder.encode(bind_dn) + "&__bindpwd=" + + URLEncoder.encode(bind_password) + "&basedn=" + + URLEncoder.encode(base_dn) + "&database=" + + URLEncoder.encode(db_name) + "&display=" + + URLEncoder.encode("displayStr") + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=8" + "&op=next" + "&xml=true" + "&choice=" + + URLEncoder.encode("Internal Key Storage Token") + ""; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } // HSM + else { + // login to hsm first + query_string = "p=9" + "&op=next" + "&xml=true" + "&uTokName=" + + URLEncoder.encode(token_name) + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + ""; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=8" + "&op=next" + "&xml=true" + "&choice=" + + URLEncoder.encode(token_name) + ""; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + return true; + } + + public boolean KeyPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList al = null; + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + "&signing_keytype=" + + key_type + "&keytype=" + key_type + "&choice=custom" + + "&op=next" + "&custom_size=" + key_size + + "&ocsp_signing_keytype=" + key_type + "&subsystem_keytype=" + + key_type + "&ocsp_signing_custom_size=" + key_size + + "&signing_custom_size=" + key_size + + "&ocsp_signing_choice=custom" + "&signing_choice=custom" + + "&subsystem_choice=custom" + "&sslserver_keytype=" + key_type + + "&sslserver_choice=custom" + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + al = px.constructvaluelist("CertReqPair", "DN"); + // get ca cert subject name + if (al != null) { + for (int i = 0; i < al.size(); i++) { + String temp = (String) al.get(i); + + if (temp.indexOf("Certificate Authority") > 0) { + ca_cert_name = temp; + } else if (temp.indexOf("OCSP Signing Certificate") > 0) { + ocsp_cert_name = temp; + } else if (temp.indexOf("Subsystem Certificate") > 0) { + ca_subsystem_cert_name = temp; + } else { + server_cert_name = temp; + } + } + } + + System.out.println("default: ca_cert_name=" + ca_cert_name); + System.out.println("default: ocsp_cert_name=" + ocsp_cert_name); + System.out.println( + "default: ca_subsystem_cert_name=" + ca_subsystem_cert_name); + System.out.println("default: server_cert_name=" + server_cert_name); + return true; + } + + public boolean CertSubjectPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + + // use subject names provided as input + + String query_string = "p=11" + "&op=next" + "&xml=true" + "&subsystem=" + + URLEncoder.encode(ca_subsystem_cert_subject_name) + + "&ocsp_signing=" + + URLEncoder.encode(ca_ocsp_cert_subject_name) + "&signing=" + + URLEncoder.encode(ca_sign_cert_subject_name) + "&sslserver=" + + URLEncoder.encode(ca_server_cert_subject_name) + "&urls=0" + + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + req_list = px.constructvaluelist("CertReqPair", "Request"); + cert_list = px.constructvaluelist("CertReqPair", "Certificate"); + dn_list = px.constructvaluelist("CertReqPair", "Nickname"); + + System.out.println("req_list_size=" + req_list.size()); + System.out.println("cert_list_size=" + cert_list.size()); + System.out.println("dn_list_size=" + dn_list.size()); + + if (req_list != null && cert_list != null && dn_list != null) { + for (int i = 0; i < dn_list.size(); i++) { + String temp = (String) dn_list.get(i); + + if (temp.indexOf("caSigningCert") >= 0) { + ca_cert_req = (String) req_list.get(i); + ca_cert_cert = (String) cert_list.get(i); + } else if (temp.indexOf("ocspSigningCert") >= 0) { + ocsp_cert_req = (String) req_list.get(i); + ocsp_cert_cert = (String) cert_list.get(i); + } else if (temp.indexOf("subsystemCert") >= 0) { + ca_subsystem_cert_req = (String) req_list.get(i); + ca_subsystem_cert_cert = (String) cert_list.get(i); + } else { + server_cert_req = (String) req_list.get(i); + server_cert_cert = (String) cert_list.get(i); + } + } + } + + System.out.println("ca_cert_name=" + ca_sign_cert_subject_name); + System.out.println("ocsp_cert_name=" + ca_ocsp_cert_subject_name); + System.out.println( + "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name); + System.out.println("server_cert_name=" + ca_server_cert_subject_name); + + System.out.println("ca_cert_req=" + ca_cert_req); + System.out.println("ocsp_cert_req=" + ocsp_cert_req); + System.out.println("ca_subsystem_cert_req=" + ca_subsystem_cert_req); + System.out.println("server_cert_req=" + server_cert_req); + + System.out.println("ca_cert_cert=" + ca_cert_cert); + System.out.println("ocsp_cert_cert=" + ocsp_cert_cert); + System.out.println("ca_subsystem_cert_cert=" + ca_subsystem_cert_cert); + System.out.println("server_cert_cert=" + server_cert_cert); + + return true; + } + + public boolean CertificatePanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + String query_string = "p=12" + "&op=next" + "&xml=true" + "&subsystem=" + + URLEncoder.encode(ca_subsystem_cert_cert) + "&subsystem_cc=" + + "&ocsp_signing=" + URLEncoder.encode(ocsp_cert_cert) + + "&ocsp_signing_cc=" + "&signing=" + + URLEncoder.encode(ca_cert_cert) + "&signing_cc=" + + "&sslserver=" + URLEncoder.encode(server_cert_cert) + + "&sslserver_cc=" + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean BackupPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + if (save_p12.equalsIgnoreCase("true")) { + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&choice=backupkey" + "&__pwd=" + backup_pwd + + "&__pwdagain=" + backup_pwd + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + query_string = ""; + + hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string); + + // dump hr.getResponseData() to file + + try { + FileOutputStream fos = new FileOutputStream("/tmp/tmp-ca.p12"); + + fos.write(hr.getResponseData()); + fos.close(); + + // verify p12 file + // Decode the P12 file + FileInputStream fis = new FileInputStream("/tmp/tmp-ca.p12"); + PFX.Template pfxt = new PFX.Template(); + PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis, 2048)); + + System.out.println("Decoded PFX"); + + // now peruse it for interesting info + System.out.println("Version: " + pfx.getVersion()); + AuthenticatedSafes authSafes = pfx.getAuthSafes(); + SEQUENCE asSeq = authSafes.getSequence(); + + System.out.println( + "AuthSafes has " + asSeq.size() + " SafeContents"); + + fis.close(); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + return true; + } + + public boolean AdminCertReqPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd, + agent_cert_subject, agent_key_size, agent_key_type); + + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if (crmf_request == null) { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=15" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + "&uid=" + admin_user + + "&name=" + admin_user + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + "&profileId=" + + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email) + + "&cert_request=" + URLEncoder.encode(admin_cert_request) + + "&subject=" + agent_cert_subject + "&clone=new" + + "&import=true" + "&securitydomain=" + domain_name + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String cert_to_import = null; + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, ee_uri, query_string); + + System.out.println("Reached here..."); + + try { + // get response data + // cert_to_import = OSUtil.BtoA(hr.getResponseData()); + // Convert a byte array to base64 string + cert_to_import = new sun.misc.BASE64Encoder().encode( + hr.getResponseData()); + + // Convert base64 string to a byte array + // buf = new sun.misc.BASE64Decoder().decodeBuffer(s); + + System.out.println("Cert to Import =" + cert_to_import); + } catch (Exception e) { + System.out.println("ERROR: failed to retrieve cert"); + } + + System.out.println("Cert to Import =" + cert_to_import); + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd, + null, null, null); + + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n"; + String end = "\r\n-----END CERTIFICATE-----"; + + st = cCrypt.importCert(start + cert_to_import + end, agent_name); + if (!st) { + System.out.println( + "ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert"); + return true; + } + + public boolean UpdateDomainPanel() { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=16" + "&op=next" + "&xml=true" + "&caHost=" + + URLEncoder.encode("/") + "&caPort=" + URLEncoder.encode("/") + + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + String caHost = px.getvalue("host"); + String caPort = px.getvalue("port"); + String systemType = px.getvalue("systemType"); + + System.out.println("caHost=" + caHost); + System.out.println("caPort=" + caPort); + System.out.println("systemType=" + systemType); + + /* + query_string = "p=18" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(caHost) + + "&caPort=" + URLEncoder.encode(caPort) + + "&systemType=" + URLEncoder.encode(systemType) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + */ + + return true; + } + + public boolean ConfigureCAInstance() { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd, + null, null, null); + + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + // enable ecc if need be + + if (key_type.equalsIgnoreCase("ecc")) { + boolean st = true; + + hc = new HTTPClient(st); + } else { + hc = new HTTPClient(); + } + + // 1. Login panel + boolean log_st = LoginPanel(); + + if (!log_st) { + System.out.println("ERROR: ConfigureCA: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + + if (!dom_st) { + System.out.println("ERROR: ConfigureCA: DomainPanel() failure"); + return false; + } + + /* + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureCA: DisplayChainPanel() failure"); + return false; + } + */ + + sleep_time(); + // 4. display cert chain panel + boolean disp_cert = CreateCAPanel(); + + if (!disp_cert) { + System.out.println("ERROR: ConfigureCA: CreateCAPanel() failure"); + return false; + } + + // 6. Admin user panel + // boolean disp_ad = AdminUserPanel(); + // if(!disp_ad) + // { + // System.out.println("ERROR: ConfigureCA: AdminUserPanel() failure"); + // return false; + // } + + sleep_time(); + // 5. hierarchy panel + boolean disp_h = HierarchyPanel(); + + if (!disp_h) { + System.out.println("ERROR: ConfigureCA: HierarchyPanel() failure"); + return false; + } + + // Agent Auth panel + // boolean disp_ag = AgentAuthPanel(); + // if(!disp_ag) + // { + // System.out.println("ERROR: ConfigureCA: AgentAuthPanel() failure"); + // return false; + // } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + + if (!disp_ldap) { + System.out.println( + "ERROR: ConfigureCA: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + + if (!disp_token) { + System.out.println("ERROR: ConfigureCA: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + + if (!disp_key) { + System.out.println("ERROR: ConfigureCA: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + + if (!disp_csubj) { + System.out.println("ERROR: ConfigureCA: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + + if (!disp_cp) { + System.out.println("ERROR: ConfigureCA: CertificatePanel() failure"); + return false; + } + + // 12. Certificate PP Panel + // boolean disp_pp = CertPPPanel(); + // if(!disp_pp) + // { + // System.out.println("ERROR: ConfigureCA: CertificatePPPanel() failure"); + // return false; + // } + + sleep_time(); + boolean disp_back = BackupPanel(); + + if (!disp_back) { + System.out.println("ERROR: ConfigureCA: BackupPanel() failure"); + return false; + } + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + + if (!disp_adm) { + System.out.println("ERROR: ConfigureCA: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + + if (!disp_im) { + System.out.println( + "ERROR: ConfigureCA: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + + if (!disp_ud) { + System.out.println("ERROR: ConfigureCA: UpdateDomainPanel() failure"); + return false; + } + + return true; + } + + public static void main(String args[]) { + ConfigureCA ca = new ConfigureCA(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // ldap + + StringHolder x_ldap_host = new StringHolder(); + StringHolder x_ldap_port = new StringHolder(); + StringHolder x_bind_dn = new StringHolder(); + StringHolder x_bind_password = new StringHolder(); + StringHolder x_base_dn = new StringHolder(); + StringHolder x_db_name = new StringHolder(); + + // key size + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + StringHolder x_save_p12 = new StringHolder(); + StringHolder x_backup_pwd = new StringHolder(); + + // separate key size for agent cert + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + // ca cert subject name params + StringHolder x_ca_sign_cert_subject_name = new StringHolder(); + StringHolder x_ca_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_ca_ocsp_cert_subject_name = new StringHolder(); + StringHolder x_ca_server_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("ConfigureCA"); + + parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname); + parser.addOption("-cs_port %s #CS SSL port", x_cs_port); + parser.addOption("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption("-preop_pin %s #pre op pin", x_preop_pin); + parser.addOption("-domain_name %s #domain name", x_domain_name); + parser.addOption("-admin_user %s #Admin User Name", x_admin_user); + parser.addOption("-admin_email %s #Admin email", x_admin_email); + parser.addOption("-admin_password %s #Admin password", x_admin_password); + parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name); + parser.addOption("-agent_key_size %s #Agent Cert Key size", + x_agent_key_size); + parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]", + x_agent_key_type); + parser.addOption("-agent_cert_subject %s #Agent Certificate Subject", + x_agent_cert_subject); + + parser.addOption("-ldap_host %s #ldap host", x_ldap_host); + parser.addOption("-ldap_port %s #ldap port", x_ldap_port); + parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn); + parser.addOption("-bind_password %s #ldap bind password", + x_bind_password); + parser.addOption("-base_dn %s #base dn", x_base_dn); + parser.addOption("-db_name %s #db name", x_db_name); + + parser.addOption("-key_size %s #Key Size", x_key_size); + parser.addOption("-key_type %s #Key type [RSA,ECC]", x_key_type); + parser.addOption("-token_name %s #HSM/Software Token name", x_token_name); + parser.addOption("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + + parser.addOption("-save_p12 %s #Enable/Disable p12 Export[true,false]", + x_save_p12); + parser.addOption("-backup_pwd %s #Backup Password for p12", x_backup_pwd); + + parser.addOption("-ca_sign_cert_subject_name %s #CA cert subject name", + x_ca_sign_cert_subject_name); + parser.addOption( + "-ca_subsystem_cert_subject_name %s #CA subsystem cert subject name", + x_ca_subsystem_cert_subject_name); + parser.addOption( + "-ca_ocsp_cert_subject_name %s #CA ocsp cert subject name", + x_ca_ocsp_cert_subject_name); + parser.addOption( + "-ca_server_cert_subject_name %s #CA server cert subject name", + x_ca_server_cert_subject_name); + + parser.addOption("-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + // and then match the arguments + String[] unmatched = null; + + unmatched = parser.matchAllArgs(args, 0, parser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + ldap_host = x_ldap_host.value; + ldap_port = x_ldap_port.value; + bind_dn = x_bind_dn.value; + bind_password = x_bind_password.value; + base_dn = x_base_dn.value; + db_name = x_db_name.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + save_p12 = x_save_p12.value; + backup_pwd = x_backup_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + ca_sign_cert_subject_name = x_ca_sign_cert_subject_name.value; + ca_subsystem_cert_subject_name = x_ca_subsystem_cert_subject_name.value; + ca_ocsp_cert_subject_name = x_ca_ocsp_cert_subject_name.value; + ca_server_cert_subject_name = x_ca_server_cert_subject_name.value; + + subsystem_name = x_subsystem_name.value; + + boolean st = ca.ConfigureCAInstance(); + + if (!st) { + System.out.println("ERROR: unable to create CA"); + System.exit(-1); + } + + System.out.println("Certficate System - CA Instance Configured."); + System.exit(0); + + } + +} + + +; diff --git a/pki/base/silent/src/ca/DirEnroll.java b/pki/base/silent/src/ca/DirEnroll.java new file mode 100644 index 000000000..1bbd662eb --- /dev/null +++ b/pki/base/silent/src/ca/DirEnroll.java @@ -0,0 +1,463 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + +import org.mozilla.jss.ssl.*; +// import sun.misc.*; +import java.lang.Exception; + + +/** + * CMS Test framework - Legacyenrollment forms for Directory based enrollmnet and Portal based enrollment . + * Certificate issuance through Legacy Directory based enrollment and Portal based enrollment form. + *<P> + */ + + +public class DirEnroll extends TestClient { + + private int i; + private String Authenticator = "UserDir"; + private int port; + private long elapsedTime; + + private String importcert = "false"; + private boolean impStatus = false; + + // Constructors + + /** + * Constructor . Takes the parameter for Properties file name + * <p> + * @param propfilename name of the parameter file + */ + + public DirEnroll(String pfile) { + propfileName = pfile; + } + + /** + * Constructor. Takes hostname , EESSLportnumber as parameter + * <p> + * @param hostname + * @param portnumber + */ + + public DirEnroll(String h, String p) { + host = h; + ports = p; + } + + /** + * Constructor. Takes hostname,EESSLportnumber,uid,password,certdbdirectorypath,certdbpassword,certificatenickname,keysize,teytype + * <p> + * @param hostname + * @param portnumber + * @param subjectdn + * @param admuserid + * @param adminpassword + */ + + + public DirEnroll(String hs, String p, String uid, String pw, String certdir, String certtokenpwd, String nickname, String ksz, String kt) { + + host = hs; + ports = p; + UID = uid; + PWD = pw; + cdir = certdir; + tokenpwd = certtokenpwd; + certnickname = nickname; + keysize = "1024"; + keytype = "RSA"; + } + + // Set and Get functions + + /** + * Use this method to set User Info + */ + public void setUIDInfo(String uid, String pw) { + UID = uid; + PWD = pw; + } + + /** + * Returns a string "UserDir" / "Portal" + */ + + public String getAuthenticator() { + return Authenticator; + } + + /** + * Valid values for s - UserDir for Directory based Authntication + * Portal for Portal based Authentication + */ + public void setAuthenticator(String s) { + Authenticator = s; + } + + public boolean enroll_load() { + buildquery(); + return(Send()); + } + + private boolean pkcs10() { + System.out.println(" In pkcs10 Keysize , key type " + keysize + keytype); + cCrypt.setCertDir(cdir); + cCrypt.setCertnickname("cn=test"); + cCrypt.setKeySize(keysize); + cCrypt.setKeyType(keytype); + cCrypt.setTokenPWD(tokenpwd); + + cCrypt.setDebug(debug); + cCrypt.setGenerateRequest(true); + if (!cCrypt.generateRequest()) { + System.out.println("Request could not be generated "); + return false; + } + pkcs10request = cCrypt.getPkcs10Request(); + + try { + buildquery(); + System.out.println(query); + setStatusString("Congratulations, your certificate has been issued."); + return(Send()); + } catch (Exception e) { + System.err.println("some exception:" + e); + } + + return false; + + } + + /** + * Enroll for certificate . Before calling this mentod SetAuthenticator and setUIDInfo + */ + public boolean enroll() { + return(pkcs10()); + } + + private boolean readProperties() { + + // Read the properties file and assign values to variables . + try { + getProperties(propfileName); + } catch (Exception e) { + System.out.println( + "exception reading Properties File " + e.getMessage()); + return false; + } + + System.out.println("Reading"); + host = props.getProperty("enroll.host"); + ports = props.getProperty("enroll.port"); + UID = props.getProperty("enroll.UID"); + PWD = props.getProperty("enroll.pwd"); + cdir = props.getProperty("enroll.certdir"); + tokenpwd = props.getProperty("enroll.certtokenpwd"); + certnickname = props.getProperty("enroll.nickname"); + keysize = props.getProperty("enroll.keysize"); + keytype = props.getProperty("enroll.keytype"); + Authenticator = props.getProperty("enroll.authenticator"); + GN = props.getProperty("enroll.GN"); + SN = props.getProperty("enroll.SN"); + CN = props.getProperty("enroll.CN"); + OU = props.getProperty("enroll.OU"); + O = props.getProperty("enroll.O"); + MAIL = props.getProperty("enroll.mail"); + L = props.getProperty("enroll.l"); + + importcert = props.getProperty("enroll.importCert"); + if (importcert == null) { + importcert = "false"; + } + String de = props.getProperty("enroll.debug"); + + if (de == null) { + debug = false; + } else if (de.equals("true")) { + debug = true; + } else { + debug = false; + } + + System.out.println("Reading done"); + // Enroll using a pkscks10 request + return true; + } + + // Private functions + + private boolean importCert(String certpack) { + + if (importcert.equals("false")) { + return true; + } + + try { + if (certpack == null) { + return false; + } + + if (debug) { + System.out.println( + "importing cert" + certpack + "certnick" + certnickname); + } + + cCrypt.importCert(certpack, certnickname); + + return true; + + } catch (Exception e) { + System.out.println("exception importing cert " + e.getMessage()); + return false; + } + + } + + private void setElapsedTime(long dif) { + elapsedTime = dif; + } + + private long calculateElapsedTime(GregorianCalendar b, GregorianCalendar e) { + + Date d1 = b.getTime(); + Date d2 = e.getTime(); + long l1 = d1.getTime(); + long l2 = d2.getTime(); + long difference = l2 - l1; + + return difference; + + } + + private boolean Send() { + boolean st = false; + + try { + if (debug) { + System.out.println("Step 3 : Socket initialize"); + } + + Integer x = new Integer(ports); + + port = x.intValue(); + ErrorDetail = null; + GregorianCalendar begin = new GregorianCalendar(); + + // SSLSocket socket = new SSLSocket(host,port); + SSLSocket socket = new SSLSocket(host, port, null, 0, this, null); + + socket.setUseClientMode(true); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + ps.println("POST /enrollment HTTP/1.0"); + ps.println("Connection: Keep-Alive"); + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " + query.length()); + ps.println(""); + ps.println(query); + ps.println("\r"); + ps.flush(); + os.flush(); + BufferedReader stdin = new BufferedReader( + new InputStreamReader(socket.getInputStream())); + + if (debug) { + System.out.println("Step 4: Received the page"); + } + st = false; + String line; + + while ((line = stdin.readLine()) != null) { + if (debug) { + System.out.println(line); + } + if (line.indexOf(STATUS) != -1) { + st = true; + } + if (getError(line)) { + st = true; + } + + if (line.indexOf("record.base64Cert=") > -1) { + String baseCert = line; + + System.out.println("BaseCert : " + baseCert); + if (importcert.equals("true")) { + String strbase = "record.base64Cert="; + + int n = strbase.length() + 1; + + baseCert = baseCert.substring(n); + String tmp = baseCert.substring(0, baseCert.length() - 2); + + if (importCert(tmp)) { + impStatus = true; + } + } else { + impStatus = true; + } + } + + } + stdin.close(); + socket.close(); + os.close(); + rawos.close(); + ps.close(); + os = null; + rawos = null; + stdin = null; + ps = null; + line = null; + + GregorianCalendar end = new GregorianCalendar(); + long diff = calculateElapsedTime(begin, end); + + setElapsedTime(diff); + + } catch (Exception e) { + System.err.println("some exception: in Send routine" + e); + return false; + } + + return st; + + } + + private void buildquery() { + + StringBuffer queryStrBuf = new StringBuffer(); + + queryStrBuf.append("certType=client"); + queryStrBuf.append("&importCert=off"); + queryStrBuf.append("&non_repudiation=true"); + queryStrBuf.append("&submit=Submit"); + queryStrBuf.append("&key_encipherment=true"); + queryStrBuf.append("&digital_signature=true"); + queryStrBuf.append("&ssl_client=true"); + + System.out.println("Authenticator : " + Authenticator); + + if (Authenticator.equals("UserDir")) { + queryStrBuf.append("&authenticator=UserDirEnrollment"); + queryStrBuf.append("&requestFormat=keygen"); + queryStrBuf.append("&uid="); + queryStrBuf.append(URLEncoder.encode(UID)); + queryStrBuf.append("&pwd="); + queryStrBuf.append(URLEncoder.encode(PWD)); + queryStrBuf.append("&email=true"); + queryStrBuf.append("&cryptprovider=1"); + + } + + if (Authenticator.equals("Portal")) { + queryStrBuf.append("&authenticator=PortalEnrollment"); + queryStrBuf.append("&requestFormat=keygen"); + queryStrBuf.append("&uid="); + queryStrBuf.append(URLEncoder.encode(UID)); + queryStrBuf.append("&userPassword="); + queryStrBuf.append(URLEncoder.encode(PWD)); + GN = "test"; + SN = "test"; + CN = "test"; + MAIL = "test@netscape.com"; + OU = "aol"; + O = "aol"; + L = "MV"; + queryStrBuf.append("&givenname="); + queryStrBuf.append(URLEncoder.encode(GN)); + + queryStrBuf.append("&sn="); + queryStrBuf.append(URLEncoder.encode(SN)); + queryStrBuf.append("&cn="); + queryStrBuf.append(URLEncoder.encode(CN)); + + queryStrBuf.append("&mail="); + queryStrBuf.append(URLEncoder.encode(MAIL)); + queryStrBuf.append("&ou="); + queryStrBuf.append(URLEncoder.encode(OU)); + queryStrBuf.append("&o="); + queryStrBuf.append(URLEncoder.encode(O)); + queryStrBuf.append("&l="); + queryStrBuf.append(URLEncoder.encode(L)); + + queryStrBuf.append("&email=true"); + + } + + if (Authenticator.equals("NIS")) { + queryStrBuf.append("&authenticator=NISAuth"); + queryStrBuf.append("&requestFormat=keygen"); + queryStrBuf.append("&uid="); + queryStrBuf.append(URLEncoder.encode(UID)); + queryStrBuf.append("&pwd="); + queryStrBuf.append(URLEncoder.encode(PWD)); + queryStrBuf.append("&email=true"); + + } + + queryStrBuf.append("&pkcs10Request="); + queryStrBuf.append(URLEncoder.encode(pkcs10request)); + query = queryStrBuf.toString(); + + System.out.println(query); + + } + + public static void main(String args[]) { + // Exit Status - (0) for error/Fail + // - requestId Pass + boolean st; + + System.out.println(args.length); + if (args.length < 1) { + System.out.println("Usage : propertiesfile"); + System.exit(0); + } + + DirEnroll t = new DirEnroll(args[0]); + + t.readProperties(); + st = t.enroll(); + if (st) { + System.out.println( + t.getAuthenticator() + " based enrollment successfull. "); + System.exit(1); + } else { + + System.out.println( + t.getAuthenticator() + + " based enrollment was not successful." + + "Error: " + t.getErrorDetail()); + System.exit(0); + } + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/ca/Request.java b/pki/base/silent/src/ca/Request.java new file mode 100644 index 000000000..46711f5a1 --- /dev/null +++ b/pki/base/silent/src/ca/Request.java @@ -0,0 +1,1125 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + +import sun.misc.*; +import java.lang.Exception; +import java.security.*; +import java.net.URLEncoder; + + +/** + * CMS Test framework . + * Submits List,Approve,Reject,cancel requests to agent port + */ + + +public class Request extends TestClient { + + private String validityperiod; + private String approveseqnum, type, reqType, reqState, agenttype; + private int i; + + // Program variables + private String ACTION_PROCESS_CERT_REQUEST = null; + private String ACTION_LISTREQUEST = "/queryReq"; + private int reqtype = 1; + private int seqNumFrom = 1; + private int maxCount = 50; + private int validperiod = 180; + private String cadualcert_name = null; + + private String approveseqnumFrom, approveseqnumTo; + // Request variables + private Vector seqNum = new Vector(); + private String AUTH_ID = null; + + // Cert Detail variables + + private String csrRequestorName, csrRequestorPhone, csrRequestorEmail, subject, subjectdn, reqStatus, certType; + private String requestType, requestID, sslclient, clientcert, servercert, emailcert, objectsigningcert, sslcacert, objectsigningcacert, emailcacert, sigAlgo, totalRecord, validitylength, trustedManager; + + private int totalNumApproved = 0; + + // Constructors + + /** + * Constructor . Takes the parameter for Properties file name + * @param propfileName name of the parameter file. + */ + + + public Request(String pfile) { + propfileName = pfile; + } + + /** + * Constructor . Takes the parameter host , port and "angent type - ca/ra" + * @param hostname. + * @param port + * @param agenttype Whether ca or ra agent + */ + + public Request(String h, String p, String at) { + host = h; + ports = p; + agenttype = at; + } + + /** + * Constructor . Takes the following parmaters + * @param hostName . + * @param port + * @param adminuid + * @param adminpwd + * @param agentcertnickname + * @param certdb + * @param tokenpwd + * @param approveSequncenumber + * @param ApproveSequenceNumberFrom + * @param ApproveSequnceNumberTo + * @param type + * @param reqtype enrollment/revoked + * @param requestState complete/pending + * @param agentType ra/ca + * @param trustedManager true/false + */ + + + public Request(String h, String p, String aid, String apwd, String cname, String cd, String ctpwd, String snum, String sfrom, String sto, String ty, String rty, String rstate, String aty, String tm) { + host = h; + ports = p; + adminid = aid; + adminpwd = apwd; + certnickname = cname; + cdir = cd; + tokenpwd = ctpwd; + approveseqnum = snum; + approveseqnumFrom = sfrom; + if (approveseqnumFrom == null) { + approveseqnumFrom = "1"; + } + + approveseqnumTo = sto; + if (approveseqnumTo == null) { + approveseqnumTo = "100"; + } + + type = ty; + reqType = rty; + reqState = rstate; + agenttype = aty; + if (agenttype == null) { + agenttype = "ca"; + } + + trustedManager = tm; + if (trustedManager.equals("true")) { + trustedManager = "true"; + } else { + trustedManager = "false"; + } + debug = false; + + } + + /** + * Set Agent Cert nick name + */ + public void setAgentCertName(String s) { + certnickname = s; + } + + /** + * List all pending enrollment request. Takes parameters fromRequestNumber,toRequestNumber + * @param fromrequest number + * @param endrequestnumber. + */ + + public Vector ListPendingRequests(String fromRequestNumber, String toRequestNumber) { + reqState = "showWaiting"; + reqType = "enrollment"; + approveseqnumFrom = fromRequestNumber; + approveseqnumTo = toRequestNumber; + listRequest(approveseqnumFrom, approveseqnumTo); + return seqNum; + } + + /** + * List all pending request. Takes parameters fromRequestNumber,toRequestNumber + * @param fromrequest number + * @param endrequestnumber. + */ + + + public Vector ListAllRequests(String fromRequestNumber, String toRequestNumber) { + reqState = "showAll"; + reqType = "enrollment"; + approveseqnumFrom = fromRequestNumber; + approveseqnumTo = toRequestNumber; + listRequest(approveseqnumFrom, approveseqnumTo); + return seqNum; + } + + /** + * Approve pending enrollment request. Takes parameters RequestNumber + * @param request number + */ + + + public int ApproveRequests(String requestNumber) { + reqState = "showWaiting"; + reqType = "enrollment"; + approveseqnum = requestNumber; + approveseqnumFrom = requestNumber; + approveseqnumTo = requestNumber; + if (approveRequest()) { + System.out.println("Approve Request :" + totalNumApproved); + return totalNumApproved; + } else { + return -1; + } + + } + + /** + * Approve profile based pending enrollment request. Takes parameters RequestNumber + * @param request number + */ + + public int ApproveProfileRequests(String RequestNumber) { + + approveseqnum = RequestNumber; + approveseqnumFrom = RequestNumber; + approveseqnumTo = RequestNumber; + + reqtype = 4; + buildquery(); + if (!Send()) { + System.out.println("Error: Approving request " + approveseqnum); + return 0; + } + return 1; + + } + + public boolean Approve_cadualcert_Profile_Request(String RequestNumber, String name) { + + approveseqnum = RequestNumber; + approveseqnumFrom = RequestNumber; + approveseqnumTo = RequestNumber; + + cadualcert_name = name; + + // reqtype = 7 means cadualcert profile request + // this is just a convention that we follow within this file to distinguish + // bet'n the different requests + + reqtype = 7; + + buildquery(); + + if (!Send()) { + System.out.println("Error: Approving request " + approveseqnum); + return false; + } + + return true; + + } + + /** + * Reject profile based pending enrollment request. Takes parameters RequestNumber + * @param request number + */ + + + public int RejectProfileRequests(String RequestNumber) { + + approveseqnum = RequestNumber; + approveseqnumFrom = RequestNumber; + approveseqnumTo = RequestNumber; + + reqtype = 5; + buildquery(); + if (!Send()) { + System.out.println("Error: Rejecting request " + approveseqnum); + return 0; + } + return 1; + + } + + /** + * Cancel profile based pending enrollment request. Takes parameters RequestNumber + * @param request number + */ + + public int CancelProfileRequests(String RequestNumber) { + + approveseqnum = RequestNumber; + approveseqnumFrom = RequestNumber; + approveseqnumTo = RequestNumber; + + reqtype = 6; + buildquery(); + if (!Send()) { + System.out.println("Error: canceling request " + approveseqnum); + return 0; + } + return 1; + + } + + // private methods + private boolean RetrieveProfileCancel(StringBuffer s) { + String res = s.toString(); + int ret = 0; + + ret = res.indexOf("requestStatus="); + String status = res.substring(ret + "requestStatus=".length() + 1, + res.indexOf(";", ret) - 1); + + if (!status.equals("canceled")) { + ErrorDetail = res.substring(ret + "errorReason=".length() + 1, + res.indexOf(";", ret) - 1); + return false; + } + + return true; + } + + private boolean RetrieveProfileReject(StringBuffer s) { + String res = s.toString(); + int ret = 0; + + ret = res.indexOf("requestStatus="); + String status = res.substring(ret + "requestStatus=".length() + 1, + res.indexOf(";", ret) - 1); + + if (!status.equals("rejected")) { + ErrorDetail = res.substring(ret + "errorReason=".length() + 1, + res.indexOf(";", ret) - 1); + return false; + } + + return true; + } + + private boolean RetrieveProfileApproval(StringBuffer s) { + String res = s.toString(); + int ret = 0; + + ret = res.indexOf("requestStatus="); + String status = res.substring(ret + "requestStatus=".length() + 1, + res.indexOf(";", ret) - 1); + + if (!status.equals("complete")) { + ErrorDetail = res.substring(ret + "errorReason=".length() + 1, + res.indexOf(";", ret) - 1); + return false; + } + + return true; + + } + + private boolean RetrieveReq(StringBuffer s) { + String AUTHID = "header.authorityid = "; + String seqnum = "record.seqNum"; + + int size = s.capacity(); + String res = s.toString(); + int ret = 0; + + if ((ret = res.indexOf(AUTHID)) > -1) { + AUTH_ID = res.substring(ret + AUTHID.length() + 1, + res.indexOf(";", ret) - 1); + while (ret > 0) { + if ((ret = res.indexOf(seqnum, ret)) > -1) { + int bi = ret + seqnum.length() + 2; + int be = res.indexOf(";", ret) - 1; + + seqNum.addElement(res.substring(bi, be)); + ret++; + } + + } + + } + + ret = res.indexOf("header.totalRecordCount ="); + totalRecord = res.substring(ret + "header.totalRecordCount = ".length(), + res.indexOf(";", ret)); + + return true; + + } + + private boolean RetrieveCertDetails(StringBuffer s) { + + // System.out.println("Debug : Retrieving cert details "); + String res = s.toString(); + + if (debug) { + System.out.println(res); + } + int ret = 0; + + boolean st = false; + + for (int t = 0; t < 25; t++) { + String cmp = "header.SERVER_ATTRS[" + t + "].name="; + + ret = res.indexOf(cmp); + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "requestId")) { + ret = res.indexOf("header.SERVER_ATTRS[" + t + "].value="); + requestID = res.substring( + ret + "header.SERVER_ATTRS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "requestStatus")) { + ret = res.indexOf("header.SERVER_ATTRS[" + t + "].value="); + reqStatus = res.substring( + ret + "header.SERVER_ATTRS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "requestType")) { + ret = res.indexOf("header.SERVER_ATTRS[" + t + "].value="); + requestType = res.substring( + ret + "header.SERVER_ATTRS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + + } // end of for loop + + // System.out.println("Debug : Retrieving cert details Serverattributes "); + + if (requestID.equals(approveseqnum)) { + st = true; + } + + if (!st) { + System.out.println("Error in retrieving the record " + approveseqnum); + return false; + } + + // System.out.println("Debug : Retrieving cert details HTTP parmas "); + + for (int t = 0; t < 25; t++) { + String cmp = "header.HTTP_PARAMS[" + t + "].name="; + + ret = res.indexOf(cmp); + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "csrRequestorEmail")) { + ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value="); + csrRequestorEmail = res.substring( + ret + "header.HTTP_PARAMS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "csrRequestorPhone")) { + ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value="); + csrRequestorPhone = res.substring( + ret + "header.HTTP_PARAMS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "csrRequestorName")) { + ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value="); + csrRequestorName = res.substring( + ret + "header.HTTP_PARAMS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "subject")) { + ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value="); + subjectdn = res.substring( + ret + "header.HTTP_PARAMS[t].value=".length() + 1, + res.indexOf(";", ret) - 1); + } + + } // end of for loop + + // System.out.println("Debug : Retrieving cert details"); + + ret = res.indexOf("header.subject ="); + if (ret > 0) { + subject = res.substring(ret + "header.subject = ".length() + 1, + res.indexOf(";", ret) - 1); + } + // System.out.println("Debug : Retrieving cert details "); + + sslclient = clientcert = servercert = emailcert = objectsigningcert = sslcacert = objectsigningcacert = emailcacert = "false"; + ret = res.indexOf("header.sslclient ="); + if (ret > 0) { + sslclient = res.substring(ret + "header.sslclient = ".length() + 1, + res.indexOf(";", ret) - 1); + } + // System.out.println("Debug : Retrieving cert details "); + + + ret = res.indexOf("header.ext_ssl_client ="); + if (ret > 0) { + clientcert = res.substring( + ret + "header.ext_ssl_client = ".length() + 1, + res.indexOf(";", ret) - 1); + } + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.ext_email ="); + if (ret > 0) { + emailcert = res.substring(ret + "header.ext_email = ".length() + 1, + res.indexOf(";", ret) - 1); + } + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.ext_ssl_server ="); + if (ret > 0) { + servercert = res.substring( + ret + "header.ext_ssl_server = ".length() + 1, + res.indexOf(";", ret) - 1); + } + + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.ext_object_signing ="); + if (ret > 0) { + objectsigningcert = res.substring( + ret + "header.ext_object_signing = ".length() + 1, + res.indexOf(";", ret) - 1); + } + + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.ext_ssl_ca ="); + if (ret > 0) { + sslcacert = res.substring(ret + "header.ext_ssl_ca = ".length() + 1, + res.indexOf(";", ret) - 1); + } + + // System.out.println("Debug : Retrieving cert details "); + + if (ret > 0) { + ret = res.indexOf("header.ext_object_signing_ca="); + } + objectsigningcacert = res.substring( + ret + "header.ext_object_signing_ca = ".length() + 1, + res.indexOf(";", ret) - 1); + + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.ext_email_ca ="); + if (ret > 0) { + emailcacert = res.substring( + ret + "header.ext_email_ca = ".length() + 1, + res.indexOf(";", ret) - 1); + } + + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.certType ="); + if (ret > 0) { + certType = res.substring(ret + "header.certType = ".length() + 1, + res.indexOf(";", ret) - 1); + } + // System.out.println("Debug : Retrieving cert details "); + + ret = res.indexOf("header.signatureAlgorithmName ="); + if (ret > 0) { + sigAlgo = res.substring( + ret + "header.signatureAlgorithmName = ".length() + 1, + res.indexOf(";", ret) - 1); + } + + ret = res.indexOf("header.validityLength ="); + if (ret > 0) { + validitylength = res.substring( + ret + "header.validityLength = ".length() + 1, + res.indexOf(";", ret) - 1); + } + + return true; + + } + + private boolean approveRequestStatus(StringBuffer s) { + + String res = s.toString(); + + if (debug) { + System.out.println(res); + } + + // Find th Server_ATTRS paramteter value of reqStatus + + int i = 1; + int ret; + + for (int t = 0; t < 25; t++) { + String cmp = "header.SERVER_ATTRS[" + t + "].name="; + + ret = res.indexOf(cmp); + if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals( + "requestStatus")) { + i = t; + break; + } + + } + + String req = "header.SERVER_ATTRS[" + i + "].value="; + + ret = res.indexOf(req); + reqStatus = res.substring(ret + req.length() + 1, + res.indexOf(";", ret) - 1); + + if (reqStatus != null) { + reqStatus.toLowerCase(); + if (reqStatus.equals("complete")) { + return true; + } else { + return false; + } + } + + return false; + + } + + private boolean Send() { + debug = true; + boolean st = false; + + try { + // Covert the string port to int port + + Integer x = new Integer(ports); + + port = x.intValue(); + + Con2Agent con = new Con2Agent(host, port, certnickname, tokenpwd, + cdir); + + con.setQueryString(query); + con.setActionURL(ACTION_STRING); + con.Send(); + StringBuffer s = new StringBuffer(); + + s = con.getPage(); + String line; + + if (debug) { + System.out.println(s.toString()); + } + switch (reqtype) { + case 1: + st = RetrieveReq(s); + break; + + case 2: + st = RetrieveCertDetails(s); + break; + + case 3: + st = approveRequestStatus(s); + break; + + case 4: + st = RetrieveProfileApproval(s); + break; + + case 5: + st = RetrieveProfileReject(s); + break; + + case 6: + st = RetrieveProfileCancel(s); + break; + + case 7: + st = RetrieveProfileApproval(s); + break; + + default: + System.out.println("reqtype not recognized"); + } + } catch (Exception e) { + System.err.println("exception: in Send routine" + e); + return false; + } + + return st; + } + + private void buildquery() { + + if (reqtype == 1) { // req type = list + ACTION_STRING = "/" + agenttype + ACTION_LISTREQUEST; + query = "seqNumFrom=" + seqNumFrom; + query += "&maxCount=" + maxCount; + query += "&reqType=" + reqType; + query += "&reqState=" + reqState; + + } + + if (reqtype == 2) { // get cert details + ACTION_PROCESS_CERT_REQUEST = "/" + AUTH_ID + "/processCertReq"; + ACTION_STRING = ACTION_PROCESS_CERT_REQUEST; + query = "seqNum=" + approveseqnum; + + } + + if (reqtype == 3) { // aaprove cert + + if (validityperiod != null) { + Integer x = new Integer(validityperiod); + + validperiod = x.intValue(); + } else { + validperiod = 180; + } + + ACTION_PROCESS_CERT_REQUEST = "/" + AUTH_ID + "/processCertReq"; + ACTION_STRING = ACTION_PROCESS_CERT_REQUEST; + query = "seqNum=" + approveseqnum; + query += "&toDo=accept"; + if (subjectdn != null) { + query += "&subject=" + URLEncoder.encode(subjectdn); + } else if (subject != null) { + query += "&subject=" + URLEncoder.encode(subject); + } + + if (csrRequestorName != null) { + query += "&csrRequestorName=" + csrRequestorName; + } + if (csrRequestorPhone != null) { + query += "&csrRequestorPhone=" + csrRequestorPhone; + } + + if (csrRequestorEmail != null) { + query += "&csrRequestorEmail=" + csrRequestorEmail; + } + if (sigAlgo != null) { + query += "&signatureAlgorithm=" + sigAlgo; + } + query += "&grantUID=u" + approveseqnum; + + GregorianCalendar begin = new GregorianCalendar(); + GregorianCalendar end = new GregorianCalendar(); + + end.add(GregorianCalendar.DATE, validperiod); + Date begindate = begin.getTime(); + Date enddate = end.getTime(); + + query += "¬ValidBefore=" + begindate.getTime() / 1000; + query += "¬ValidAfter=" + enddate.getTime() / 1000; + + if (clientcert.equals("true")) { + query += "&certTypeSSLClient=" + clientcert; + } + + if (servercert.equals("true")) { + query += "&certTypeSSLServer=" + servercert; + } + + if (emailcert.equals("true")) { + query += "&certTypeEmail=" + emailcert; + } + + if (objectsigningcert.equals("true")) { + query += "&certTypeObjSigning=" + objectsigningcert; + } + + query += "&grantTrustedManagerPrivilege=" + trustedManager; + + } + + if ((reqtype == 4) || (reqtype == 5) || (reqtype == 6)) { // profile based cert request + + if (validityperiod != null) { + Integer x = new Integer(validityperiod); + + validperiod = x.intValue(); + } else { + validperiod = 180; + } + + ACTION_PROCESS_CERT_REQUEST = "/" + agenttype + "/profileProcess"; + ACTION_STRING = ACTION_PROCESS_CERT_REQUEST; + query = "requestId=" + approveseqnum; + query += "&name=" + + URLEncoder.encode( + "UID=test,E=test,CN=test,OU=netscape,O=aol"); + query += "&keyUsageCritical=true"; + query += "&keyUsageDigitalSignature=true"; + query += "&keyUsageNonRepudiation=true"; + query += "&keyUsageKeyEncipherment=true"; + query += "&keyUsageDataEncipherment=false"; + query += "&keyUsageKeyAgreement=false"; + query += "&keyUsageKeyCertSign=false"; + query += "&keyUsageCrlSign=false"; + query += "&keyUsageEncipherOnly=false"; + query += "&keyUsageDecipherOnly=false"; + + query += "&nsCertCritical=false"; + query += "&nsCertSSLClient=true"; + + query += "&nsCertSSLServer=false"; + query += "&nsCertEmail=true"; + query += "&nsCertObjectSigning=false"; + query += "&nsCertSSLCA=false"; + query += "&nsCertEmailCA=false"; + query += "&nsCertObjectSigningCA=false"; + + query += "&subAltNameExtCritical=false"; + query += "&subjAltNames=RFC822Name:" + + URLEncoder.encode(" thomasknscp@aol.com"); + query += "&signingAlg=MD5withRSA"; + + query += "&submit=submit"; + + GregorianCalendar begin = new GregorianCalendar(); + GregorianCalendar end = new GregorianCalendar(); + + end.add(GregorianCalendar.DATE, validperiod); + // Date begindate = begin.getTime(); + // Date enddate = end.getTime(); + String nb = begin.get(Calendar.YEAR) + "-" + + begin.get(Calendar.MONTH) + "-" + begin.get(Calendar.DATE) + + " " + begin.get(Calendar.HOUR) + ":" + + begin.get(Calendar.MINUTE) + ":" + + begin.get(Calendar.SECOND); + + String nat = end.get(Calendar.YEAR) + "-" + end.get(Calendar.MONTH) + + "-" + end.get(Calendar.DATE) + " " + + end.get(Calendar.HOUR) + ":" + end.get(Calendar.MINUTE) + + ":" + end.get(Calendar.SECOND); + + query += "¬Before=" + nb; + query += "¬After=" + nat; + + query += "&authInfoAccessCritical=false"; + query += "&authInfoAccessGeneralNames="; + query += "&exKeyUsageOIDs=" + "1.3.6.1.5.5.7.3.2,1.3.6.1.5.5.7.3.4"; + + } + + if (reqtype == 4) { + query += "&op=approve"; + } + + if (reqtype == 5) { + query += "&op=reject"; + } + + if (reqtype == 6) { + query += "&op=cancel"; + } + + if (reqtype == 7) { + // cadualcert profile approval + ACTION_STRING = "/" + "ca" + "/profileProcess"; + + GregorianCalendar begin = new GregorianCalendar(); + GregorianCalendar end = new GregorianCalendar(); + + end.add(GregorianCalendar.DATE, validperiod); + + String nb = begin.get(Calendar.YEAR) + "-" + + begin.get(Calendar.MONTH) + "-" + begin.get(Calendar.DATE) + + " " + begin.get(Calendar.HOUR) + ":" + + begin.get(Calendar.MINUTE) + ":" + + begin.get(Calendar.SECOND); + + String nat = end.get(Calendar.YEAR) + "-" + end.get(Calendar.MONTH) + + "-" + end.get(Calendar.DATE) + " " + + end.get(Calendar.HOUR) + ":" + end.get(Calendar.MINUTE) + + ":" + end.get(Calendar.SECOND); + + query = "requestId=" + approveseqnum + "&name=" + + URLEncoder.encode(cadualcert_name) + "¬Before=" + nb + + "¬After=" + nat + "&authInfoAccessCritical=false" + + "&authInfoAccessGeneralNames=" + "&keyUsageCritical=true" + + "&keyUsageDigitalSignature=false" + + "&keyUsageNonRepudiation=false" + + "&keyUsageKeyEncipherment=true" + + "&keyUsageDataEncipherment=false" + + "&keyUsageKeyAgreement=false" + + "&keyUsageKeyCertSign=false" + "&keyUsageCrlSign=false" + + "&keyUsageEncipherOnly=false" + + "&keyUsageDecipherOnly=false" + /* -- For Older CMS 6.x servers use these + "&nsCertCritical=false" + + "&nsCertSSLClient=true" + + "&nsCertSSLServer=false" + + "&nsCertEmail=true" + + "&nsCertObjectSigning=false" + + "&nsCertSSLCA=false" + + "&nsCertEmailCA=false" + + "&nsCertObjectSigningCA=false" + + "&subjAltNameExtCritical=false" + + "&subjAltNames=RFC822Name: null" + + "&signingAlg=MD5withRSA" + + */ // For newer CS 7.x servers use these + "&exKeyUsageCritical=false" + + "&exKeyUsageOIDs=1.3.6.1.5.5.7.3.2,1.3.6.1.5.5.7.3.4" + + "&subjAltNameExtCritical=false" + + "&subjAltNames=RFC822Name: null" + + "&signingAlg=SHA1withRSA" + "&requestNotes=" + + "&op=approve" + "&submit=submit"; + + } + + } + + private void readProperties() { + + // Read the properties file and assign values to variables . + try { + getProperties(propfileName); + } catch (Exception e) { + System.out.println( + "exception reading Properties File " + e.getMessage()); + } + + // Read the properties file + host = props.getProperty("enroll.host"); + ports = props.getProperty("enroll.port"); + adminid = props.getProperty("enroll.adminid"); + adminpwd = props.getProperty("enroll.adminpwd"); + certnickname = props.getProperty("enroll.nickname"); + cdir = props.getProperty("enroll.certdir"); + tokenpwd = props.getProperty("enroll.certtokenpwd"); + approveseqnum = props.getProperty("enroll.seqnum"); + if (approveseqnum == null) { + System.out.println("Seq num is null"); + } + + approveseqnumFrom = props.getProperty("enroll.seqnumFrom"); + if (approveseqnumFrom == null) { + approveseqnumFrom = "1"; + } + + approveseqnumTo = props.getProperty("enroll.seqnumTo"); + if (approveseqnumTo == null) { + approveseqnumTo = "100"; + } + validityperiod = props.getProperty("enroll.validperiod"); + type = props.getProperty("enroll.type"); + reqType = props.getProperty("enroll.reqtype"); + reqState = props.getProperty("enroll.reqstate"); + agenttype = props.getProperty("enroll.agenttype"); + if (agenttype == null) { + agenttype = "ca"; + } + + trustedManager = props.getProperty("enroll.trust"); + if (trustedManager.equals("true")) { + trustedManager = "true"; + } else { + trustedManager = "false"; + } + + String de = props.getProperty("enroll.debug"); + + if (de == null) { + debug = false; + } else if (de.equals("true")) { + debug = true; + } else { + debug = false; + } + + } + + private boolean listRequest(String from, String To) { + + Integer x = new Integer(from); + + seqNumFrom = x.intValue(); + + Integer y = new Integer(To); + int t = y.intValue(); + + if ((y.intValue() - seqNumFrom) > 50) { + maxCount = 50; + } else { + maxCount = y.intValue() - x.intValue(); + } + if (maxCount == 0) { + maxCount = 1; + } + + reqtype = 1; + buildquery(); + return(Send()); + } + + private boolean approveRequest() { + + boolean st = true; + + listRequest(approveseqnumFrom, approveseqnumTo); + + if (seqNum.isEmpty()) { + System.out.println("No Requests for approval"); + return false; + } + + if (approveseqnum.length() > 0) { + if (seqNum.contains(approveseqnum)) { + seqNum.removeAllElements(); + seqNum.addElement(approveseqnum); + } else { + System.out.println( + " Seq num " + approveseqnum + " already approved "); + return false; + } + } else { + System.out.println( + " Seq num not specified . Approving all pending request From : " + + approveseqnumFrom + " To : " + approveseqnumTo); + } + + boolean flag = true; + + Integer y = new Integer(approveseqnumTo); + int torequest = y.intValue(); + + while (flag) { + + i = 0; + while (i < seqNum.size()) { + + approveseqnum = (seqNum.elementAt(i)).toString(); + // Get request details + reqtype = 2; + buildquery(); + if (!Send()) { + System.out.println("Error : Getting Request details "); + i++; + continue; + } + + if (debug) { + System.out.println( + csrRequestorName + " " + csrRequestorPhone + " " + + csrRequestorEmail + " " + requestID + " " + + subject); + } + // Now for pending status - approve the request + reqtype = 3; + buildquery(); + if (!Send()) { + System.out.println( + "Error: Approving request " + approveseqnum); + i++; + continue; + } + System.out.println("Request " + approveseqnum + " is approved "); + totalNumApproved++; + i++; + } + Integer x = new Integer(approveseqnum); + + if (x.intValue() >= torequest) { + flag = false; + } else { + listRequest(approveseqnum, approveseqnumTo); + } + + } + return st; + } + + /** + * Use this method when you need to use properties file. + */ + + + public int processRequest() { + if (propfileName != null) { + readProperties(); + } + + if (approveseqnum.length() > 0) { + approveseqnumFrom = approveseqnum; + approveseqnumTo = approveseqnum; + } + + type = type.toLowerCase(); + if (type.equals("approve")) { + if (approveRequest()) { + System.out.println("Approve Request :" + totalNumApproved); + return totalNumApproved; + } else { + return -1; + } + + } + + if (type.equals("list")) { + + if (listRequest(approveseqnumFrom, approveseqnumTo)) { + System.out.println("List Request : " + seqNum.size()); + if (seqNum.size() > 0) { + return seqNum.size(); + } else { + return 0; + } + } else { + return -1; + } + + } + + return -1; + } + + public static void main(String args[]) { + // Exit Status - (0) for error + // - any number > 0 Pass + int st = 0; + + if (args.length < 1) { + System.out.println("Usage : propertiesfile"); + System.exit(0); + } + + Request t = new Request(args[0]); + + st = t.processRequest(); + if (st == -1) { + System.exit(0); + } else { + System.exit(st); + } + + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/ca/UserEnroll.java b/pki/base/silent/src/ca/UserEnroll.java new file mode 100644 index 000000000..4dc277aa0 --- /dev/null +++ b/pki/base/silent/src/ca/UserEnroll.java @@ -0,0 +1,537 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + +import org.mozilla.jss.ssl.*; +import sun.misc.*; +import java.lang.Exception; + + +/** + * CMS Test framework . + * Submits Legacy Manual User Enrollment request from EESSL port. Parses the response from server and return RequestID. + *<P> + */ + + +public class UserEnroll extends TestClient { + + private int i; + private String requestorName, requestorEmail, requestorPhone, requestorComments, requestId, certType, ssl_client; + private int port; + private long elapsedTime; + + // Constructor + public UserEnroll() {} + + /** + * Constructor . Takes the parameter hostname and EESSLport + * <p> + */ + + + + public UserEnroll(String h, String p) { + host = h; + ports = p; + } + + /** + * Constructor . Takes the parameter for Properties file name + * <p> + * @param propfilename name of the parameter file + */ + + + public UserEnroll(String pfile) { + propfileName = pfile; + } + + /** + * Constructor . Takes the parameter for hostname, EESSLportnumber, subjectdn, E, CN,UID,OU,O, CertdbDirecrory(fullpath) , certdbPassword, keysize, keytype, requestorName,requestorEmail and Certtype. + * valid values for Certtype - "ca","ra","ocsp" + * <p> + * @param propfilename name of the parameter file + */ + + + public UserEnroll(String h, String p, String dn, String e, String cn, String uid, String ou, String o, String cd, String tpwd, String sslcl, String ksize, String keyty, String reqname, String reqemail, String ctype) { + + host = h; + ports = p; + DN = dn; + E = e; + CN = cn; + UID = uid; + OU = ou; + O = o; + C = "US"; + cdir = cd; + tokenpwd = tpwd; + ssl_client = sslcl; + keysize = ksize; + keytype = keyty; + requestorName = reqname; + requestorPhone = "650"; + requestorEmail = "lg"; + requestorComments = "load Test"; + certnickname = "cn=test"; + keytype = "RSA"; + keysize = "1024"; + certType = ctype; + if (certType.equals("caSigningCert")) { + certType = "ca"; + } + if (certType.equals("raSigningCert")) { + certType = "ra"; + } + if (certType.equals("ocspSigningCert")) { + certType = "ocsp"; + } + } + + /** + * Set Certificate Request information. Takes parameters - subjectdn,E,CN,UID,OU,O + */ + + public void setUserInfo(String dn, String e, String cn, String uid, String ou, String o) { + DN = dn; + E = e; + CN = cn; + UID = uid; + OU = ou; + O = o; + requestorName = "test"; + requestorPhone = "650"; + requestorEmail = "lg"; + requestorComments = "Test"; + certnickname = "cn=test"; + + } + + public void setUserInfo(String dn, String e, String cn, String uid, String ou, String o, String nickname) { + DN = dn; + E = e; + CN = cn; + UID = uid; + OU = ou; + O = o; + requestorName = "test"; + requestorPhone = "650"; + requestorEmail = "lg"; + requestorComments = "Test"; + certnickname = nickname; + + } + + /** + * Set Certificat Type for which you want to submit a request . Valid values - "ca"/"ra"/"ocsp" + */ + public void setCertType(String ct) { + certType = ct; + } + + private long getElapsedTime() { + return elapsedTime; + } + + public boolean enroll_load() { + buildquery(); + setStatusString(""); + return(Send()); + } + + private boolean pkcs10() { + + System.out.println(" In pkcs10 Keysize , key type " + keysize + keytype); + // ComCrypto cCrypt = new ComCrypto(cdir,tokenpwd,certnickname,keysize,keytype); + cCrypt.setCertDir(cdir); + cCrypt.setCertnickname(adminCertName); + cCrypt.setKeySize(keysize); + cCrypt.setKeyType(keytype); + cCrypt.setTokenPWD(tokenpwd); + cCrypt.setDebug(true); + if (pkcs10request != null) { + cCrypt.setGenerateRequest(false); + cCrypt.loginDB(); + } else { + cCrypt.setGenerateRequest(true); + if (!cCrypt.generateRequest()) { + System.out.println("Request could not be generated "); + return false; + } + pkcs10request = cCrypt.getPkcs10Request(); + } + + try { + System.out.println("Debug: building query "); + buildquery(); + if (debug) { + System.out.println(query); + } + setStatusString(""); + return(Send()); + } catch (Exception e) { + System.err.println("some exception:" + e); + } + + return(false); + + } + + // Private methods + + private void setElapsedTime(long dif) { + elapsedTime = dif; + } + + private long calculateElapsedTime(GregorianCalendar b, GregorianCalendar e) { + + Date d1 = b.getTime(); + Date d2 = e.getTime(); + long l1 = d1.getTime(); + long l2 = d2.getTime(); + long difference = l2 - l1; + + return difference; + + } + + private boolean Send() { + boolean st = false; + + try { + + if (debug) { + System.out.println("Step 3 : Socket initialize"); + } + + Integer x = new Integer(ports); + + port = x.intValue(); + + GregorianCalendar begin = new GregorianCalendar(); + + // SSLSocket socket = new SSLSocket(host,port); + SSLSocket socket = new SSLSocket(host, port, null, 0, this, null); + + socket.setUseClientMode(true); + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + ps.println("POST /enrollment HTTP/1.0"); + ps.println("Connection: Keep-Alive"); + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " + query.length()); + ps.println(""); + ps.println(query); + ps.println("\r"); + ps.flush(); + os.flush(); + BufferedReader stdin = new BufferedReader( + new InputStreamReader(socket.getInputStream())); + + if (debug) { + System.out.println("Step 4: Received the page"); + } + st = false; + String line; + + while ((line = stdin.readLine()) != null) { + if (debug) { + System.out.println(line); + } + if (line.indexOf(STATUS) != -1) { + st = true; + } + if (line.indexOf("fixed.requestId = ") != -1) { + requestId = line.substring("fixed.requestId = ".length() + 1, + line.indexOf(";") - 1); + } + + if (getError(line)) { + st = false; + } + + } + stdin.close(); + socket.close(); + os.close(); + rawos.close(); + ps.close(); + os = null; + rawos = null; + stdin = null; + ps = null; + line = null; + GregorianCalendar end = new GregorianCalendar(); + long diff = calculateElapsedTime(begin, end); + + setElapsedTime(diff); + + } catch (Exception e) { + System.err.println("some exception: in Send routine" + e); + return false; + } + + return st; + + } + + private void buildquery() { + + StringBuffer queryStrBuf = new StringBuffer(); + + if (certType.equals("client")) { + queryStrBuf.append("certType="); + queryStrBuf.append(certType); + queryStrBuf.append("&Send=submit"); + + queryStrBuf.append("&key_encipherment=true"); + + queryStrBuf.append("&digital_signature=true"); + + queryStrBuf.append("&requestFormat=keygen"); + + queryStrBuf.append("&cryptprovider=1"); + if (ssl_client.equals("true")) { + queryStrBuf.append("&ssl_client=true"); + } else { + queryStrBuf.append("&ssl_server=true"); + } + + queryStrBuf.append("&non_repudiation=true"); + + if (requestorName.length() > 0) { + queryStrBuf.append("&csrRequestorName="); + } + queryStrBuf.append(URLEncoder.encode(requestorName)); + if (requestorEmail.length() > 0) { + queryStrBuf.append("&csrRequestorEmail="); + queryStrBuf.append(URLEncoder.encode(requestorEmail)); + queryStrBuf.append("&email=true"); + + } else { + queryStrBuf.append("&email=false"); + } + + if (requestorPhone.length() > 0) { + queryStrBuf.append("&csrRequestorPhone="); + queryStrBuf.append(URLEncoder.encode(requestorPhone)); + } + if (requestorComments.length() > 0) { + queryStrBuf.append("&csrRequestorComments="); + queryStrBuf.append(URLEncoder.encode(requestorComments)); + } + System.out.println("buidlquery client E "); + if (E.length() > 0) { + queryStrBuf.append("&E="); + queryStrBuf.append(E); + } + if (CN.length() > 0) { + queryStrBuf.append("&CN="); + queryStrBuf.append(CN); + } + + if (UID.length() > 0) { + queryStrBuf.append("&UID="); + queryStrBuf.append(UID); + } + if (OU.length() > 0) { + queryStrBuf.append("&OU="); + queryStrBuf.append(OU); + } + // if(O.length() > 0) { queryStrBuf.append("&O=");queryStrBuf.append(O);} + // if(C.length() >0) { queryStrBuf.append("&C=");queryStrBuf.append(C);} + System.out.println("buidlquery client dn "); + queryStrBuf.append("&subject="); + queryStrBuf.append(URLEncoder.encode(DN)); + } + + if (certType.equals("ra")) { + queryStrBuf.append("certType=" + certType); + queryStrBuf.append("&digital_signature=true"); + queryStrBuf.append("&non_repudiation=true"); + queryStrBuf.append("&ssl_client=true"); + } + + if (certType.equals("server")) { + queryStrBuf.append("certType=" + certType); + queryStrBuf.append("&digital_signature=true"); + queryStrBuf.append("&non_repudiation=true"); + queryStrBuf.append("&ssl_server=true"); + queryStrBuf.append("&key_encipherment=true"); + queryStrBuf.append("&data_encipherment=true"); + + } + + if (certType.equals("ocsp")) { + queryStrBuf.append("certType=ocspResponder"); + queryStrBuf.append("&digital_signature=true"); + queryStrBuf.append("&non_repudiation=true"); + queryStrBuf.append("&ssl_client=true"); + } + + if (certType.equals("ca")) { + queryStrBuf.append("certType=" + certType); + queryStrBuf.append("&digital_signature=true"); + queryStrBuf.append("&non_repudiation=true"); + queryStrBuf.append("&ssl_client=true"); + queryStrBuf.append("&object_signing_ca=true"); + queryStrBuf.append("&crl_sign=true"); + queryStrBuf.append("&ssl_ca=true"); + queryStrBuf.append("&key_certsign=true"); + queryStrBuf.append("&email_ca=true"); + + } + + queryStrBuf.append("&pkcs10Request="); + queryStrBuf.append(URLEncoder.encode(pkcs10request)); + System.out.println("before converting bug to string "); + query = queryStrBuf.toString(); + + System.out.println(query); + queryStrBuf = null; + } + + public int getRequestId() { + Integer m = new Integer(requestId); + + return m.intValue(); + + } + + /** + * Submit enrollment request + */ + + public boolean clientCertEnroll() { + certType = "client"; + ssl_client = "true"; + debug = true; + return(pkcs10()); + } + + public boolean Enroll() { + debug = true; + return(pkcs10()); + } + + /** + * Read the properties file + **/ + + public boolean readProperties() { + + // Read the properties file and assign values to variables . + try { + getProperties(propfileName); + } catch (Exception e) { + System.out.println( + "exception reading Properties File " + e.getMessage()); + return false; + } + + host = props.getProperty("enroll.host"); + ports = props.getProperty("enroll.port"); + DN = props.getProperty("enroll.DN"); + requestorName = props.getProperty("enroll.name"); + requestorEmail = props.getProperty("enroll.email"); + requestorPhone = props.getProperty("enroll.phone"); + requestorComments = props.getProperty("enroll.comments"); + E = props.getProperty("enroll.E"); + CN = props.getProperty("enroll.CN"); + UID = props.getProperty("enroll.UID"); + OU = props.getProperty("enroll.OU"); + O = props.getProperty("enroll.O"); + C = props.getProperty("enroll.C"); + cdir = props.getProperty("enroll.certdir"); + tokenpwd = props.getProperty("enroll.certtokenpwd"); + certnickname = props.getProperty("enroll.nickname"); + keysize = props.getProperty("enroll.keysize"); + keytype = props.getProperty("enroll.keytype"); + certType = props.getProperty("enroll.certtype"); + if (certType == null) { + certType = "client"; + } + if (certType.equals("raSigningCert")) { + certType = "ra"; + } + if (certType.equals("ocspSigningCert")) { + certType = "ocsp"; + } + pkcs10request = props.getProperty("enroll.pkcs10"); + ssl_client = props.getProperty("enroll.sslclient"); + if (ssl_client == null) { + ssl_client = "true"; + } + + String de = props.getProperty("enroll.debug"); + + if (de == null) { + debug = false; + } else if (de.equals("true")) { + debug = true; + } else { + debug = false; + } + + // Enroll using a pkscks10 request + return(pkcs10()); + } + + public static void main(String args[]) { + // Exit Status - (0) for error/Fail + // - requestId Pass + boolean st; + + UserEnroll e = new UserEnroll("jupiter2", "1027", + "E=test,cn=test,uid=test", "test", "test", "test", "t1", "t", + "/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptanceJava/data/certdb", + "secret12", "true", "1024", "RSA", "rn", "re", "client"); + + e.clientCertEnroll(); + + /* if ( args.length < 1) + { + System.out.println("Usage : propertiesfile"); + System.exit(0); + } + + + UserEnroll t = new UserEnroll(args[0]); + st=t.enroll(); + if (st){ + System.out.println("User Enrolled successfully . RequestId is "+t.getrequestId()); + System.exit(t.getRequestId()); + } + else{ + + System.out.println("Error: " + t.getErrorDetail()); + System.exit(0); + } + */ + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/ca/checkRequest.java b/pki/base/silent/src/ca/checkRequest.java new file mode 100644 index 000000000..238e87c91 --- /dev/null +++ b/pki/base/silent/src/ca/checkRequest.java @@ -0,0 +1,632 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + +import org.mozilla.jss.ssl.*; +import sun.misc.*; +import java.lang.Exception; + + +/** + * CMS Test framework . + * Submits a checkRequestStatus request to the server. parses the response from server and can import cert to the specified client database. + *<P> + */ + + +public class checkRequest extends TestClient { + + private int i; + private String certfile, importcert = "false", certnickname, serialNumber, ldapformat; + + private String requestId; + private String reqStatus = "false"; + private String pkcsCert, baseCert, ACTION_STRING, issuer, subject, AUTH = "ca"; + private int port; + private boolean impStatus = false; + private int type = 1; + + private long elapsedTime; + + private String host; + private String ports; + private String tokenpwd; + private String cdir; + + // public methods + + /** + * Constructor . Takes the parameter for Properties file name + * <p> + * @param propfilename name of the parameter file + */ + + + public checkRequest(String pfile) { + propfileName = pfile; + } + + /** + * Constructor . Takes the parameter for hostname and EESSLportnumber + * <p> + */ + + public checkRequest(String h, String p) { + host = h; + ports = p; + } + ; + + /** + * Constructor . Takes the parameter for hostname , EESSLportnumber , Requestnumber and ImportCert ( true/false) + * <p> + */ + + public checkRequest(String h, String p, String snum, String impc) { + host = h; + ports = p; + requestId = snum; + importcert = impc; + } + + /** + * Constructor . Takes the parameter for hostname , EESSLportnumber , certdbdir, certdbpassword, Requestnumber ,certnickname and ImportCert ( true/false) + * <p> + */ + + + public checkRequest(String hs, String pt, String certdir, String certtokenpwd, String seqnum, String nickname, String impc) { + host = hs; + ports = pt; + cdir = certdir; + tokenpwd = certtokenpwd; + requestId = seqnum; + if (impc == null) { + importcert = "false"; + } else { + importcert = impc; + } + certnickname = nickname; + + } + + public void setDebug(boolean t) { + debug = t; + } + + public void setreqId(String seqnum) { + requestId = seqnum; + } + + public void setCertNickname(String cname) { + certnickname = cname; + } + + /** + * takes values - true/false + **/ + public void setImportCert(String impc) { + importcert = impc; + } + + public String getpkcs7ChainCert() { + return pkcsCert; + } + + /** + * returns Certificate + **/ + + public String getCert() { + return cCrypt.normalize(baseCert); + } + + /** + * returns Request status - "complete","pending" + **/ + + public String getRequestStatus() { + return reqStatus; + } + + private long getElapsedTime() { + return elapsedTime; + } + + /** + * returns the hex serial number of the certificate + **/ + + + public String getSerialNumberHex() { + return serialNumber; + } + + /** + * returns the serial number as interger + **/ + + public int getSerialNumber() { + if (serialNumber != null) { + Integer y = new Integer(Integer.parseInt(serialNumber, 16)); + + return y.intValue(); + } + return 0; + } + + /** + * Submits a checkRequestStatus request to the server + **/ + + public boolean checkRequestStatus() { + + // Login to dB and genertae request + cCrypt.setCertDir(cdir); + cCrypt.setCertnickname(certnickname); + cCrypt.setKeySize(keysize); + cCrypt.setKeyType(keytype); + cCrypt.setTokenPWD(tokenpwd); + cCrypt.setDebug(debug); + + if (!cCrypt.loginDB()) { + System.out.println("Error : Login certdb failed "); + System.err.println("FAIL : Login certdb failed "); + return false; + } + + try { + + type = 1; + buildquery(); + if (debug) { + System.out.println(query); + } + setStatusString("Congratulations, your certificate has been issued."); + if (Send()) { + if (debug) { + System.out.println("Request Status :" + reqStatus); + } + if (reqStatus.equals("complete")) { + type = 2; + buildquery(); + if (debug) { + System.out.println(query); + } + if (Send()) { + return true; + } + } else { + return true; + } + + } + if (debug) { + System.out.println("Request Status :" + reqStatus); + } + + System.err.println("FAIL: reached end of checkRequestStatus()"); + + return false; + } catch (Exception e) { + System.err.println("some exception:" + e); + } + + return false; + } + + private boolean checkRequest_load() { + + type = 1; + buildquery(); + if (debug) { + System.out.println(query); + } + setStatusString("Congratulations, your certificate has been issued"); + return(Send()); + + } + + // Private functions + + private void setElapsedTime(long dif) { + elapsedTime = dif; + } + + private long calculateElapsedTime(GregorianCalendar b, GregorianCalendar e) { + + Date d1 = b.getTime(); + Date d2 = e.getTime(); + long l1 = d1.getTime(); + long l2 = d2.getTime(); + long difference = l2 - l1; + + return difference; + + } + + private boolean writeCert2File() { + if (serialNumber != null) { + + try { + FileOutputStream fos = new FileOutputStream(certfile); + + if (ldapformat.equals("true")) { + Integer m = new Integer("1"); + String tmp = "description: 2;" + + Integer.parseInt(serialNumber, 16) + ";" + issuer + + ";" + subject + "\n"; + + fos.write(tmp.getBytes()); + tmp = cCrypt.normalizeForLDAP(getCert()); + if (debug) { + System.out.println(tmp); + } + fos.write(("usercertificate:: ").getBytes()); + fos.write(tmp.getBytes()); + fos.close(); + } else { + String tmp = cCrypt.normalize(getCert()); + + if (debug) { + System.out.println(tmp); + } + fos.write(tmp.getBytes()); + fos.close(); + + } + + } catch (Exception e) { + System.out.println( + "exception in writeCert2File: " + e.getMessage()); + return false; + } + + } + + return true; + } + + private boolean importCert(String certpack) { + + if (importcert.equals("false")) { + return true; + } + + try { + if (certpack == null) { + return false; + } + + String s = cCrypt.normalize(certpack); + + if (AUTH.equals("ca")) { + String tmp = "-----BEGIN CERTIFICATE-----\n" + s + "\n" + + "-----END CERTIFICATE-----"; + + if (debug) { + System.out.println( + "importing cert" + tmp + "certnick" + certnickname); + } + s = tmp; + } + + if (cCrypt.importCert(s, certnickname)) { + System.out.println("successfully imported cert"); + return true; + } + + return false; + + } catch (Exception e) { + System.out.println( + "exception importing cert crequest" + e.getMessage()); + return false; + } + + } + + private boolean RetrieveRequestDetail(String line) { + String stat = "header.status = "; + boolean st = true; + + if (debug) { + System.out.println(line); + } + + if (line.indexOf(stat) != -1) { + String tm = line.substring(stat.length() + 1, + line.indexOf(";", 10) - 1); + + reqStatus = tm; + } + if (line.indexOf("header.pkcs7ChainBase64 = ") != -1) { + // if status is complete retrieve cert + pkcsCert = line.substring("header.pkcs7ChainBase64 = ".length() + 1, + line.indexOf(";", 10) - 1); + } + if (line.indexOf("record.serialNumber=") != -1) { + serialNumber = line.substring("record.serialNumber=".length() + 1, + line.indexOf(";", 1) - 1); + } + if (line.indexOf("header.authority =") == 0) { + AUTH = line.substring("header.authority =".length() + 2, + line.indexOf(";", 1) - 1); + } + + if (getError(line)) { + st = false; + } + + return st; + + } + + private boolean RetrieveCertDetails(String line) { + if (debug) { + System.out.println(line); + } + + boolean st = true; + + String retriveStr[] = { + "record.base64Cert=", "record.certPrettyPrint=", + "header.certChainBase64 = ", "header.certPrettyPrint = "}; + String baseCertStr, certPrettyprintStr; + + if (AUTH.equals("ra")) { + baseCertStr = retriveStr[0]; + certPrettyprintStr = retriveStr[1]; + } else { + baseCertStr = retriveStr[2]; + certPrettyprintStr = retriveStr[3]; + } + + if (line.indexOf(baseCertStr) != -1) { + + // if status is complete retrieve cert + baseCert = line.substring(baseCertStr.length() + 1, + line.indexOf(";", 10) - 1); + if (importcert.equals("true")) { + if (importCert(baseCert)) { + st = true; + } + } else { + st = true; + } + } + + if (line.indexOf(certPrettyprintStr) != -1) { + + System.out.println("Found certPrettyPrint"); + int ret = line.indexOf("Issuer: "); + + issuer = line.substring(("Issuer: ").length() + ret, + line.indexOf("Validi", ret) - 14); + ret = line.indexOf("Subject:"); + subject = line.substring(("Subject: ").length() + ret, + line.indexOf("Subject Public", ret) - 14); + + System.out.println(" HEADER : " + issuer); + + } + + // System.out.println("Debug :get Error detail " + line); + if (getError(line)) { + st = false; + } + + return st; + + } + + private synchronized boolean Send() { + boolean st = false; + + try { + if (debug) { + System.out.println("Step 3 : Socket initialize"); + } + + Integer x = new Integer(ports); + + port = x.intValue(); + + GregorianCalendar begin = new GregorianCalendar(); + + impStatus = false; + + // SSLSocket socket = new SSLSocket(host,port); + SSLSocket socket = new SSLSocket(host, port, null, 0, this, null); + + socket.setUseClientMode(true); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + ps.println("POST " + ACTION_STRING + " HTTP/1.0"); + ps.println("Connection: Keep-Alive"); + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " + query.length()); + ps.println(""); + ps.println(query); + ps.println("\r"); + ps.flush(); + os.flush(); + BufferedReader stdin = new BufferedReader( + new InputStreamReader(socket.getInputStream())); + + if (debug) { + System.out.println("Step 4: Received the page"); + } + st = false; + String line; + + while ((line = stdin.readLine()) != null) { + switch (type) { + case 1: + RetrieveRequestDetail(line); + st = true; + break; + + case 2: + st = RetrieveCertDetails(line); + break; + + default: + System.out.println("invalid format"); + + } + + } + stdin.close(); + socket.close(); + os.close(); + rawos.close(); + ps.close(); + os = null; + rawos = null; + stdin = null; + ps = null; + line = null; + + GregorianCalendar end = new GregorianCalendar(); + long diff = calculateElapsedTime(begin, end); + + setElapsedTime(diff); + + } catch (Exception e) { + System.err.println("some exception: in Send routine" + e); + return false; + } + if ((certfile != null) && (type == 2)) { + st = writeCert2File(); + } + + if (debug) { + System.out.println(serialNumber); + } + + return st; + + } + + private void buildquery() { + + StringBuffer queryStrBuf = new StringBuffer(); + + if (type == 1) { + ACTION_STRING = "/checkRequest"; + queryStrBuf.append("requestId="); + queryStrBuf.append(requestId); + queryStrBuf.append("&importCert=true"); + } + + if (type == 2) { + ACTION_STRING = "/" + AUTH + "/displayBySerial"; + if (AUTH.equals("ra")) { + ACTION_STRING = "/displayCertFromRequest"; + queryStrBuf.append("requestId="); + queryStrBuf.append(requestId); + + } else { + ACTION_STRING = "/displayBySerial"; + queryStrBuf.append("op=displayBySerial"); + queryStrBuf.append("&serialNumber=0x"); + queryStrBuf.append(serialNumber); + } + } + + query = queryStrBuf.toString(); + + queryStrBuf = null; + + } + + private boolean readProperties() { + + // Read the properties file and assign values to variables . + try { + getProperties(propfileName); + } catch (Exception e) { + System.out.println( + "exception reading Properties File " + e.getMessage()); + return false; + } + + host = props.getProperty("enroll.host"); + ports = props.getProperty("enroll.port"); + cdir = props.getProperty("enroll.certdir"); + tokenpwd = props.getProperty("enroll.certtokenpwd"); + requestId = props.getProperty("enroll.seqnum"); + certfile = props.getProperty("enroll.certfile"); + importcert = props.getProperty("enroll.importCert"); + if (importcert == null) { + importcert = "false"; + } + ldapformat = props.getProperty("enroll.ldapformat"); + if (ldapformat == null) { + ldapformat = "true"; + } + System.out.println(ldapformat); + certnickname = props.getProperty("enroll.nickname"); + String de = props.getProperty("enroll.debug"); + + if (de == null) { + debug = false; + } else if (de.equals("true")) { + debug = true; + } else { + debug = false; + } + + // Enroll using a pkscks10 request + return(checkRequestStatus()); + } + + public static void main(String args[]) { + // Exit Status - (0) for error/Fail + // - requestId Pass + boolean st; + + if (args.length < 1) { + System.out.println("Usage : propertiesfile"); + System.exit(0); + } + + checkRequest t = new checkRequest(args[0]); + + st = t.readProperties(); + if (st) { + System.exit(t.getSerialNumber()); + } else { + + System.out.println("Request Status :" + t.getRequestStatus()); + System.out.println("Error: " + t.getErrorDetail()); + + System.exit(0); + } + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/common/AutoInstaller.java b/pki/base/silent/src/common/AutoInstaller.java new file mode 100644 index 000000000..fa2eabc53 --- /dev/null +++ b/pki/base/silent/src/common/AutoInstaller.java @@ -0,0 +1,2437 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; + + +/** + * CMS Test Framework. + * Use this class to Configure a CA, RA,DRM,OCSP and SubCA subsystem. + * This simulartes the installation wizard functions and helps to configure a CMS subsystem. + */ + + +public class AutoInstaller { + + private static Properties props = null; + + // Admin Server and InternalDB varialbes + private String adminDomain, adminID, adminPWD, adminPort, machineName, host, serverID, instanceID, serverRoot, sieURL, dbConnPort, dbConnHost, dbInstanceName, dbPassword, dbLDAPauthDN, dbmode, ldapServerDB; + + // CMS Subsystem info + + private String certAdminName, certAdminUid, certAdminPWD, kra, subsystems, ca, ra, ocsp, remoteKRA, wirelessSupport, eeHttpPort, eeHttpsPort, agentHttpsPort, radminHttpsPort, tokenName, tokenPWD, certType, keyType, keyLength, SingleSignOnPWD, subjectName, aki, isCA, ski, sslCABit, objectSigningCABit, mailCABit, hashType, caOComponent, certValidityDays, signingCert, tks; + + // CA info + private String caHostname, caPortnum, caTimeout, caEEPort, enpropfile, cdir, tokenpwd, CAadminId, CAadminPwd, CAcertnickname, caAgentPortnum, cloneInstanceId; + + // Program variables + private int i; + private String configURL, deamonURL, certInstID; + private String inputLine; + private boolean st = false; + + private String postQuery = null; + private String propFileName; + private StringBuffer spage = new StringBuffer(); + // 4.5 server String CERTtokenName="Internal Key Storage Token"; + private String CERTtokenName = "internal"; + + private String certRequestStr = null, ssl_clientcert = "true"; + + private String raSigningCert = null; + private String kraTransportCert = null; + + private boolean subca = false; + + // / Constructors + + public AutoInstaller() {} + + /** + * Constructor . Takes parameter Server Root . + */ + public AutoInstaller(String sr) { + serverRoot = sr; + } + + // Set InternalDBVInfo + /** + * Set Internal Database Information . Takes parameters internaldatabase hostname, internaldatabase port, internaldatabase name, internaldatabase binddn, internaldatabase password + */ + + public void setInternalDBInfo(String dbh, String dbp, String dbname, String dbdn, String dbpswd) { + dbConnPort = dbp; + dbConnHost = dbh; + dbInstanceName = dbname; + dbPassword = dbpswd; + dbLDAPauthDN = dbdn; + dbmode = "local"; + ldapServerDB = "userRoot"; + } + + // Create Password file + private boolean CreatePasswordFile() { + String s = "internal: " + SingleSignOnPWD; + + try { + OutputStream f0 = new FileOutputStream( + serverRoot + "/" + instanceID + "/config/password.conf"); + + f0.write(s.getBytes()); + f0.close(); + return true; + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + return false; + } + + } + + private boolean BackupConfigFile() { + try { + FileInputStream f1 = new FileInputStream( + serverRoot + "/" + instanceID + "/config/CS.cfg"); + int size = f1.available(); + byte b[] = new byte[size]; + + if (f1.read(b) != b.length) { + return false; + } + OutputStream f2 = new FileOutputStream( + serverRoot + "/" + instanceID + "/config/CS.cfg.org"); + + f2.write(b); + + f1.close(); + f2.close(); + return true; + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + return false; + } + + } + + // Get RaSigning Cert + + public String getRASigningCert() { + return raSigningCert; + } + + // Get KRATransportCert + public String getKRATransportCert() { + return kraTransportCert; + } + + // Set Admin Server Info + + /** + * Set Admin Server Information . Takes parameters : hostname, adminserver portnumber , adminId , adminPassword + */ + public void setAdminInfo(String h, String p, String adDN, String id, String adpwd) { + adminDomain = adDN; + adminID = id; + adminPWD = adpwd; + adminPort = p; + host = h; + + } + + // Set CA Server Info + /** + * Set CA server Information . Takes parametrers :CAhostname, CAEEPORT, CAAGENTPORT , CAAdminUID, CAAdminPassword + */ + + public void setCAInfo(String cah, String caeep, String caagp, String caaduid, String caadpwd) { + caHostname = cah; + caPortnum = caagp; + caTimeout = "30"; + caEEPort = caeep; + CAadminId = caaduid; + CAadminPwd = caadpwd; + caAgentPortnum = caagp; + + } + + // Set ClientDB Info; + /** + * Sets Client Database information . Takes paramters : certdbdir, certdbpasswd, certnickanme + */ + + public void setClientDBInfo(String cd, String pwd, String nickname) { + + cdir = cd; + tokenpwd = pwd; + CAcertnickname = nickname; + } + + // Is this Internal or any hardware token and its password; + /** + * Set token info . Takes paramter "Internal" and tokenpasswd + */ + public void setTokenInfo(String t, String tp) { + + tokenName = t; + tokenPWD = tp; + + } + + // Set Subsystem Information for Configuring + + /** + * Takes parameters - sID- ServerID e.x cert1, sRoot- ServerRootK kT- keyType "RSA/DSA" , kL - keylength (1024.2048) , cVD- certificate validity dates e.g 365 for 1 year, sdn - subsystems dn, sAdp - subsystem's Admin port, sAgp - subsystems's Agentport,seSP- subsystem's ee SSL port , sep- Subsystems ee port. + */ + + public void setSubSystemInfo(String sID, String sRoot, String kT, String kL, String hT, String cVD, String sdn, String sAdP, String sAgP, String seSP, String seP) { + serverID = sID; + instanceID = "cert-" + sID; + + keyType = kT; + keyLength = kL; + hashType = hT; + certValidityDays = cVD; + + eeHttpPort = seP; + eeHttpsPort = seSP; + agentHttpsPort = sAgP; + radminHttpsPort = sAdP; + subjectName = sdn; + caOComponent = "test"; + } + + // // Configure CMS Subsystems + + /** + * Confiures a CA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd + */ + public boolean ConfigureCA(String adn, String aduid, String adp, String ssonpwd) { + certAdminName = adn; + certAdminUid = aduid; + certAdminPWD = adp; + SingleSignOnPWD = ssonpwd; + + signingCert = "caSigningCert"; + certType = signingCert; + subsystems = "ca"; + ca = "true"; + kra = "false"; + ra = "false"; + ocsp = "false"; + remoteKRA = "false"; + wirelessSupport = "false"; + aki = "true"; + isCA = "true"; + ski = "true"; + sslCABit = "true"; + objectSigningCABit = "true"; + mailCABit = "true"; + + if (ConfCA()) { + CreatePasswordFile(); + BackupConfigFile(); + return true; + } + + return false; + + } + + public boolean ConfigureTKS(String adn, String aduid, String adp, String ssonpwd) { + + certAdminName = adn; + certAdminUid = aduid; + certAdminPWD = adp; + SingleSignOnPWD = ssonpwd; + signingCert = "raSigningCert"; + certType = signingCert; + subsystems = "tks"; + ra = "false"; + tks = "true"; + kra = "false"; + ca = "false"; + ocsp = "false"; + remoteKRA = "false"; + wirelessSupport = "false"; + aki = "true"; + isCA = "false"; + ski = "true"; + sslCABit = "true"; + objectSigningCABit = "true"; + mailCABit = "true"; + + if (ConfTKS()) { + CreatePasswordFile(); + BackupConfigFile(); + return true; + } + + return false; + + } + + private boolean ConfTKS() { + // Start Configuring + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Create a SSL signing cert + Date tmpdate = new Date(); + + certType = "serverCert"; + subjectName = "CN=" + host + "." + adminDomain + ",OU=ssltest" + + tmpdate.getTime() + ",O=SSL,C=US"; + keyLength = "512"; + keyType = "RSA"; + String mtokenPWD = tokenPWD; + + tokenPWD = ""; + ssl_clientcert = "false"; + signingCert = "server"; + + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!certRequest(false)) { + System.out.println( + "Configuring Cert Instance: error creating Request"); + return false; + } + + // After creating ssl cert + tokenPWD = mtokenPWD; + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + } + + /** + * Confiures a RA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd + */ + + + public boolean ConfigureRA(String adn, String aduid, String adp, String ssonpwd) { + certAdminName = adn; + certAdminUid = aduid; + certAdminPWD = adp; + SingleSignOnPWD = ssonpwd; + + signingCert = "raSigningCert"; + certType = signingCert; + subsystems = "ra"; + ra = "true"; + kra = "false"; + ca = "false"; + ocsp = "false"; + remoteKRA = "false"; + wirelessSupport = "false"; + aki = "true"; + isCA = "true"; + ski = "true"; + sslCABit = "true"; + objectSigningCABit = "true"; + mailCABit = "true"; + + if (ConfRA()) { + CreatePasswordFile(); + BackupConfigFile(); + return true; + } + + return false; + + } + + /** + * Confiures a OCSP Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd + */ + + + public boolean ConfigureOCSP(String adn, String aduid, String adp, String ssonpwd) { + certAdminName = adn; + certAdminUid = aduid; + certAdminPWD = adp; + SingleSignOnPWD = ssonpwd; + + signingCert = "ocspSigningCert"; + certType = signingCert; + subsystems = "ocsp"; + ocsp = "true"; + kra = "false"; + ra = "false"; + ca = "false"; + remoteKRA = "false"; + wirelessSupport = "false"; + aki = "true"; + isCA = "true"; + ski = "true"; + sslCABit = "true"; + objectSigningCABit = "true"; + mailCABit = "true"; + + if (ConfOCSP()) { + CreatePasswordFile(); + BackupConfigFile(); + return true; + } + + return false; + } + + /** + * Confiures a KRA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd + */ + + + public boolean ConfigureKRA(String adn, String aduid, String adp, String ssonpwd) { + certAdminName = adn; + certAdminUid = aduid; + certAdminPWD = adp; + SingleSignOnPWD = ssonpwd; + + signingCert = "kraTransportCert"; + certType = signingCert; + subsystems = "kra"; + kra = "true"; + ca = "false"; + ra = "false"; + ocsp = "false"; + remoteKRA = "false"; + wirelessSupport = "false"; + aki = "true"; + isCA = "true"; + ski = "true"; + sslCABit = "true"; + objectSigningCABit = "true"; + mailCABit = "true"; + if (ConfKRA()) { + CreatePasswordFile(); + BackupConfigFile(); + return true; + } + + return false; + } + + /** + * Confiures a SubCA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd + */ + + + public boolean ConfigureSubCA(String adn, String aduid, String adp, String ssonpwd) { + certAdminName = adn; + certAdminUid = aduid; + certAdminPWD = adp; + SingleSignOnPWD = ssonpwd; + subca = true; + signingCert = "caSigningCert"; + certType = signingCert; + subsystems = "ca"; + ca = "true"; + kra = "false"; + ra = "false"; + ocsp = "false"; + remoteKRA = "false"; + wirelessSupport = "false"; + aki = "true"; + isCA = "true"; + ski = "true"; + sslCABit = "true"; + objectSigningCABit = "true"; + mailCABit = "true"; + + if (ConfSubCA()) { + CreatePasswordFile(); + BackupConfigFile(); + return true; + } + + return false; + } + + // //////////////////////////////////////////////////////// + + private void getProperties(String filePath) throws Exception { + try { + FileInputStream fis = new FileInputStream(filePath); + + props = new Properties(); + props.load(fis); + System.out.println("Reading Properties file successful"); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + private void setPropFile(String fileName) { + propFileName = fileName; + } + + private void setConfigURL() { + configURL = "/" + instanceID + "/Tasks/Operation/config-cert"; + } + + private void setDeamonURL() { + deamonURL = "/" + instanceID + "/Tasks/Operation/start-daemon"; + + } + + private void setPostQueryString(String querystring) { + postQuery = querystring; + } + + private boolean Connect(String myStringUrl) { + // / This functions connects to the URL and POST HTTP Request . + // It compares with NMC_STATUS and return the status. + System.out.println(myStringUrl); + st = false; + + PostQuery sm = new PostQuery(myStringUrl, adminID, adminPWD, postQuery); + boolean st = sm.Send(); + + spage = sm.getPage(); + return st; + } + + private boolean startDeamon() { + // Set StringURL to connect , set the query string and Connect .Get the result + System.out.println("Log Info - configuring Cert Instance : Start Deamon"); + setDeamonURL(); + String myStringUrl = "http://" + host + "." + adminDomain + ":" + + adminPort + deamonURL; + + System.out.println("Log Info -" + myStringUrl); + String query = "instanceID=" + URLEncoder.encode(instanceID); + + query += "&AdminUsername=" + URLEncoder.encode(adminID); + query += "&AdminUserPassword=" + URLEncoder.encode(adminPWD); + + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean configInternalDB() { + + System.out.println( + "Log Info - configuring Cert Instance : configureInternalDB"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&instanceID=" + URLEncoder.encode(instanceID); + query += "&adminUID=" + URLEncoder.encode(adminID); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("createInternalDB"); + query += "&AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&host=" + URLEncoder.encode(host); + query += "&internaldb.ldapconn.host=" + URLEncoder.encode(dbConnHost); + query += "&internaldb.ldapconn.port=" + URLEncoder.encode(dbConnPort); + query += "&internaldb.ldapauth.bindDN=" + + URLEncoder.encode(dbLDAPauthDN); + query += "&db.instanceName=" + URLEncoder.encode(dbInstanceName); + query += "&db.password=" + URLEncoder.encode(dbPassword); + query += "&adminDomain=" + URLEncoder.encode(adminDomain); + query += "&db.mode=" + URLEncoder.encode(dbmode); + query += "&ldapServerDB=" + URLEncoder.encode(ldapServerDB); + query += "&cmsSeed=0"; + // logging + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean createAdminValues() { + System.out.println("configuring Cert Instance : configureAdmin"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&cert.admin.name=" + URLEncoder.encode(certAdminName); + query += "&cert.admin.uid=" + URLEncoder.encode(certAdminUid); + query += "&cert.admin.passwd=" + URLEncoder.encode(certAdminPWD); + query += "&db.password=" + URLEncoder.encode(dbPassword); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("setupAdmin"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean selectSubSystem() { + System.out.println("configuring Cert Instance : SubSystems"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&db.password=" + URLEncoder.encode(dbPassword); + query += "&internaldb.ldapauth.bindDN=" + + URLEncoder.encode(dbLDAPauthDN); + query += "&kra=" + URLEncoder.encode(kra); + query += "&subsystems=" + URLEncoder.encode(subsystems); + query += "&ca=" + URLEncoder.encode(ca); + query += "&ra=" + URLEncoder.encode(ra); + query += "&ocsp=" + URLEncoder.encode(ocsp); + query += "&remoteKRA=" + URLEncoder.encode(remoteKRA); + query += "&wirelessSupport=" + URLEncoder.encode(wirelessSupport); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("selectSubsystems"); + query += "&cmsSeed=0"; + + if (subsystems.equals("ca")) { + query += "&internaldb.ldapconn.host=" + + URLEncoder.encode(dbConnHost); + query += "&internaldb.ldapconn.port=" + + URLEncoder.encode(dbConnPort); + + } + if (subsystems.equals("ra")) { + query += "&caHostname=" + caHostname; + query += "&caPortnum=" + caPortnum; + query += "&caTimeout=" + caTimeout; + } + if (subsystems.equals("tks")) { + query += "&tks=true"; + } + + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean taskCloneMaster() { + System.out.println("configuring Cert Instance : taskCloneMaster"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&"; + query += "&claPortnumEE=" + URLEncoder.encode(caEEPort); + query += "&claPortnum=" + URLEncoder.encode(caAgentPortnum); + query += "&claHostname=" + URLEncoder.encode(caHostname); + query += "&ra=false"; + query += "&ca=true"; + query += "&kra=false"; + query += "&subsystems=ca"; + query += "&cloning=true"; + query += "&cloningInstance=" + URLEncoder.encode(cloneInstanceId); + query += "&claTimeout=" + URLEncoder.encode("60"); + query += "&internaldb.ldapauth.bindDN=" + + URLEncoder.encode(dbLDAPauthDN); + query += "&AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&db.password=" + URLEncoder.encode(dbPassword); + query += "&instanceID=" + URLEncoder.encode(instanceID); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("taskCloneMaster"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean taskCloning() { + System.out.println("configuring Cert Instance : taskCloning"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&"; + query += "&cloneTokenPasswd=" + URLEncoder.encode(dbPassword); + query += "&cloneTokenName=" + URLEncoder.encode("internal"); + query += "&cloningInstance=" + URLEncoder.encode(cloneInstanceId); + query += "&cloneSameMachine=true"; + query += "&AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&certType=" + URLEncoder.encode(certType); + query += "&instanceID=" + URLEncoder.encode(instanceID); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("taskCloning"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean setSerial(String start, String end) { + System.out.println("configuring Cert Instance : setCASerial"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&db.password=" + URLEncoder.encode(dbPassword); + query += "&caSerialNumber=" + URLEncoder.encode(start); + query += "&caEndSerialNumber=" + URLEncoder.encode(end); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("setCASerial"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean setOCSP() { + System.out.println("configuring Cert Instance : setOCSP"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&CAOCSPService=" + URLEncoder.encode("true"); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("addOCSPService"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean networkConfig() { + System.out.println("configuring Cert Instance : Network Config"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + if (subsystems.equals("kra")) { + query += "&agentGateway.https.port=" + + URLEncoder.encode(agentHttpsPort); + query += "&radm.https.port=" + URLEncoder.encode(radminHttpsPort); + query += "&eePortsEnable=" + URLEncoder.encode("false"); + } else { + query += "&eeGateway.http.port=" + URLEncoder.encode(eeHttpPort); + query += "&eeGateway.https.port=" + URLEncoder.encode(eeHttpsPort); + query += "&agentGateway.https.port=" + + URLEncoder.encode(agentHttpsPort); + query += "&radm.https.port=" + URLEncoder.encode(radminHttpsPort); + query += "&eePortsEnable=" + URLEncoder.encode("true"); + query += "&eeGateway.http.enable=" + URLEncoder.encode("true"); + } + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("configureNetwork"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean serverMigration() { + System.out.println("configuring Cert Instance : Server migration"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&migrationEnable=" + URLEncoder.encode("false"); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("migration"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean initializePWD() { + System.out.println("configuring Cert Instance : Initialize token"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&tokenName=" + URLEncoder.encode(tokenName); + query += "&tokenPasswd=" + URLEncoder.encode(tokenPWD); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("initToken"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean initializeToken() { + System.out.println("configuring Cert Instance : Initialize token"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&tokenName=" + URLEncoder.encode(tokenName); + query += "&tokenPasswd=" + URLEncoder.encode(tokenPWD); + query += "&certType=" + URLEncoder.encode(certType); + query += "&keyType=" + URLEncoder.encode(keyType); + query += "&keyLength=" + URLEncoder.encode(keyLength); + query += "&sopPasswd=" + URLEncoder.encode(SingleSignOnPWD); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("initToken"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean keyLength() { + System.out.println("configuring Cert Instance : Check Key length"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&tokenName=" + URLEncoder.encode(tokenName); + query += "&tokenPasswd=" + URLEncoder.encode(tokenPWD); + query += "&certType=" + URLEncoder.encode(certType); + query += "&keyType=" + URLEncoder.encode(keyType); + query += "&keyLength=" + URLEncoder.encode(keyLength); + query += "&sopPasswd=" + URLEncoder.encode(SingleSignOnPWD); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("checkKeyLength"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean checkDN() { + System.out.println("configuring Cert Instance : Check DN"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&certType=" + URLEncoder.encode(certType); + query += "&subjectName=" + URLEncoder.encode(subjectName); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("checkDN"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private String normalize(String s) { + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'n')) { + i++; + continue; + } else if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'r')) { + i++; + continue; + } else if (s.charAt(i) == '"') { + continue; + } + val += s.charAt(i); + } + return val; + } + + private String pkcs7Convertcert(String s) { + + String val = ""; + + int len = s.length(); + + for (int i = 0; i < len; i = i + 64) { + + if (i + 64 < len) { + val = val + s.substring(i, i + 64) + "\n"; + } else { + val = val + s.substring(i, len); + } + + } + return val; + } + + private boolean certRequest(boolean trustM) { + // This function prepares a Certificate Request. + // Submits it to the CA + // Approves the request. + // And then installs it + + System.out.println("configuring Cert Instance : cert Request"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&certType=" + URLEncoder.encode(certType); + query += "&subjectName=" + URLEncoder.encode(subjectName); + query += "&keyType=" + URLEncoder.encode(keyType); + query += "&keyLength=" + URLEncoder.encode(keyLength); + query += "&tokenName=" + URLEncoder.encode(CERTtokenName); + + if (subca) { + query += "&sslCABit=true"; + query += "&objectSigningCABit=true"; + query += "&wirelessSupport=false"; + query += "&mailCABit=true"; + query += "&isCA=true"; + query += "&ski=true"; + query += "&aki=true"; + query += "&keyUsage=true"; + query += "&caSigningCertReqFormat=PKCS10"; + } + + if (subsystems.equals("ra")) { + query += "&aki=" + URLEncoder.encode(aki); + query += "&keyUsage=" + URLEncoder.encode("true"); + query += "&signing_cert=" + signingCert; + } + + if (certType.equals("serverCert")) { + query += "&sslServerBit=" + URLEncoder.encode("true"); + query += "&sslClientBit=" + URLEncoder.encode("true"); + query += "&serverCertReqFormat=PKCS10"; + } else { + if (subsystems.equals("ra")) { + query += "&sslClientBit=" + URLEncoder.encode("true"); + query += "&raSigningCertReqFormat=PKCS10"; + } + + if (subsystems.equals("ocsp")) { + query += "&ocspSigningCertReqFormat=PKCS10"; + } + + if (subsystems.equals("kra")) { + // added keyUsage + query += "&keyUsage=" + URLEncoder.encode("true"); + // added URLEncoder + query += "&aki=" + URLEncoder.encode(aki); + query += "&kraTransportCertReqFormat=PKCS10"; + } + } + + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("certRequest"); + query += "&caHostname=" + caHostname; + query += "&caEEPort=" + caEEPort; + query += "&cmsSeed=0"; + + setPostQueryString(query); + if (!Connect(myStringUrl)) { + System.out.println("Error :certRequest"); + return false; + } + + String res = spage.toString(); + + certRequestStr = res.substring( + res.indexOf("certReq: ") + "certReq: ".length(), + res.indexOf("-----END NEW CERTIFICATE REQUEST-----")); + certRequestStr += "-----END NEW CERTIFICATE REQUEST-----"; + + int ReqId = 0; + + UserEnroll e = new UserEnroll(caHostname, caEEPort, subjectName, "test", + "test", null, "test", "test", cdir, tokenpwd, ssl_clientcert, + keyLength, keyType, null, null, signingCert); + + e.setpkcs10Request(certRequestStr); + if (e.Enroll()) { + ReqId = e.getRequestId(); + } else { + System.out.println("Request was not successful"); + return false; + } + + String trm; + + if (trustM) { + trm = "true"; + } else { + trm = "false"; + } + + Request r = new Request(caHostname, caAgentPortnum, CAadminId, + CAadminPwd, CAcertnickname, cdir, tokenpwd, getString(ReqId), + null, null, "approve", "enrollment", "showWaiting", null, trm); + + if (r.ApproveRequests(getString(ReqId)) <= -1) { + System.out.println( + "Error : Agent request approval was not successful"); + return false; + } + + System.out.println("configuring Cert Instance : req Success"); + + // Checking to see if request is approved. + + setConfigURL(); + myStringUrl = "http://" + host + ":" + adminPort + configURL; + System.out.println(myStringUrl); + + query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&certType=" + URLEncoder.encode(certType); + + if (certType.equals("serverCert")) { + query += "&serverCertReqID=" + ReqId; + } else { + query += "&raSigningCertReqID=" + ReqId; + } + + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&caEEPort=" + caEEPort; + query += "&caHostname=" + host; + query += "&caEEType=https"; + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("reqSuccess"); + query += "&cmsSeed=0"; + + setPostQueryString(query); + if (Connect(myStringUrl)) { + + checkRequest cr = new checkRequest(caHostname, caEEPort, cdir, + tokenpwd, getString(ReqId), null, null); + + if (cr.checkRequestStatus()) { + String cert = cr.getpkcs7ChainCert(); + String certtmp = pkcs7Convertcert(cert); + + certtmp = normalize(certtmp); + cert = "-----BEGIN CERTIFICATE-----" + "\n" + certtmp + "\n" + + "-----END CERTIFICATE-----\n"; + + // install cert + System.out.println( + "configuring Cert Instance : install cert :" + cert); + setConfigURL(); + myStringUrl = "http://" + host + ":" + adminPort + configURL; + System.out.println(myStringUrl); + query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&certType=" + URLEncoder.encode(certType); + query += "&db.password=" + URLEncoder.encode(dbPassword); + + if (certType.equals("raSigningCert")) { + query += "&nickname=" + + URLEncoder.encode(certType + " " + instanceID); + raSigningCert = "-----BEGIN CERTIFICATE-----" + "\n" + + cr.getCert() + "\n" + + "-----END CERTIFICATE-----\n"; + + } + + if (certType.equals("kraTransportCert")) { + ComCrypto cCrypto = new ComCrypto(); + + kraTransportCert = cCrypto.normalize(cr.getCert()); + } + + if (certType.equals("serverCert")) { + query += "&nickname=" + + URLEncoder.encode("Server-Cert" + " " + instanceID); + } + + if (certType.equals("ocspSigningCert")) { + query += "&nickname=" + + URLEncoder.encode(certType + " " + instanceID); + } + + query += "&pkcs10=" + URLEncoder.encode(cert); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("installCert"); + query += "&cmsSeed=0"; + + setPostQueryString(query); + return(Connect(myStringUrl)); + } + + } else { + System.out.println("Error: Request is not approved"); + return false; + } + return true; + } + + private String getString(int m) { + Integer x = new Integer(m); + String s = x.toString(); + + return s; + } + + private boolean createCert() { + System.out.println("configuring Cert Instance : Create Cert"); + + // clauclate the validity dates for the cert. + GregorianCalendar begin = new GregorianCalendar(); + GregorianCalendar end = new GregorianCalendar(); + Integer days = new Integer(certValidityDays); + + end.add(GregorianCalendar.DATE, days.intValue()); + + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&db.password=" + URLEncoder.encode(dbPassword); + query += "&subjectName=" + URLEncoder.encode(subjectName); + query += "&certType=" + URLEncoder.encode(certType); + + query += "&beginYear=" + + URLEncoder.encode(getString(begin.get(GregorianCalendar.YEAR))); + query += "&beginMonth=" + + URLEncoder.encode( + getString(begin.get(GregorianCalendar.MONTH))); + query += "&beginDate=" + + URLEncoder.encode(getString(begin.get(GregorianCalendar.DATE))); + query += "&beginHour=" + + URLEncoder.encode(getString(begin.get(GregorianCalendar.HOUR))); + query += "&beginMin=" + + URLEncoder.encode( + getString(begin.get(GregorianCalendar.MINUTE))); + query += "&beginSec=" + + URLEncoder.encode( + getString(begin.get(GregorianCalendar.SECOND))); + + query += "&afterYear=" + + URLEncoder.encode(getString(end.get(GregorianCalendar.YEAR))); + query += "&afterMonth=" + + URLEncoder.encode(getString(end.get(GregorianCalendar.MONTH))); + query += "&afterDate=" + + URLEncoder.encode(getString(end.get(GregorianCalendar.DATE))); + query += "&afterHour=" + + URLEncoder.encode(getString(end.get(GregorianCalendar.HOUR))); + query += "&afterMin=" + + URLEncoder.encode(getString(end.get(GregorianCalendar.MINUTE))); + query += "&afterSec=" + + URLEncoder.encode(getString(end.get(GregorianCalendar.SECOND))); + + query += "&keyType=" + URLEncoder.encode(keyType); + query += "&keyLength=" + URLEncoder.encode(keyLength); + + query += "&certLen=" + URLEncoder.encode("-1"); + query += "&tokenName=" + URLEncoder.encode(CERTtokenName); + query += "&aki=" + URLEncoder.encode(aki); + query += "&keyUsage=" + URLEncoder.encode("true"); + + if (certType.equals("serverCert")) { + query += "&sslServerBit=" + URLEncoder.encode("true"); + query += "&sslClientBit=" + URLEncoder.encode("true"); + + } else { + query += "&caOComponent=" + URLEncoder.encode(caOComponent); + query += "&caCComponent=" + URLEncoder.encode("us"); + + query += "&isCA=" + URLEncoder.encode(isCA); + query += "&ski=" + URLEncoder.encode(ski); + query += "&tokenPasswd=" + URLEncoder.encode(tokenPWD); + query += "&sslCABit=" + URLEncoder.encode(sslCABit); + query += "&mailCABit=" + URLEncoder.encode(mailCABit); + query += "&objectSigningCABit=" + + URLEncoder.encode(objectSigningCABit); + + } + query += "&hashType=" + URLEncoder.encode(hashType); + + query += "&sopPasswd=" + URLEncoder.encode(SingleSignOnPWD); + query += "&wirelessSupport=" + URLEncoder.encode("false"); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("createCert"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean singleSignON() { + System.out.println("configuring Cert Instance : Single Signon"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String PWTags = "Internal:Internal LDAP Database:singlesignon"; + + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + // query += "&singleSignonPwd=" + URLEncoder.encode(SingleSignOnPWD); + query += "&singleSignonPWTags=" + URLEncoder.encode(PWTags); + query += "&Internal=" + URLEncoder.encode(tokenPWD); + query += "&Internal LDAP Database=" + URLEncoder.encode(dbPassword); + query += "&pwcTokenname=" + URLEncoder.encode("internal"); + + query += "&singlesignon=" + URLEncoder.encode(tokenPWD); + + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("singleSignon"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + + } + + private boolean doMisc() { + System.out.println("configuring Cert Instance : do Miscell"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String PWTags = "Internal:Internal LDAP Database:singlesignon"; + + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&singleSignonPwd=" + URLEncoder.encode(SingleSignOnPWD); + query += "&singleSignonPWTags=" + URLEncoder.encode(PWTags); + query += "&Internal=" + URLEncoder.encode(tokenPWD); + query += "&Internal LDAP Database=" + URLEncoder.encode(dbPassword); + query += "&singlesignon=" + URLEncoder.encode(tokenPWD); + query += "&deletePasswdConf=false"; + + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("doMiscStuffs"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean exitDeamon() { + + System.out.println("configuring Cert Instance : Exit Deamon"); + setDeamonURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("exit"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean ConfOCSP() { + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Step 6: Initialize Token This has been moved to step 1a + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 7 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 8 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 9 : certRequest and Install + if (!certRequest(false)) { + System.out.println("Configuring Cert Instance: error getting cert"); + return false; + } + + // Create a SSL signing cert + Date tmpdate = new Date(); + + certType = "serverCert"; + subjectName = "CN=" + host + "." + adminDomain + ",OU=ssltest" + + tmpdate.getTime() + ",O=SSL,C=US"; + keyLength = "512"; + keyType = "RSA"; + String mtokenPWD = tokenPWD; + + tokenPWD = ""; + ssl_clientcert = "false"; + signingCert = "server"; + + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!certRequest(false)) { + System.out.println( + "Configuring Cert Instance: error creating Request"); + return false; + } + + // After creating ssl cert + tokenPWD = mtokenPWD; + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + + } + + private boolean setupStorageKey() { + System.out.println("configuring Cert Instance : Storage Key"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("storageKey"); + query += "&tokenName=" + URLEncoder.encode("Internal"); + query += "&tokenPasswd=" + URLEncoder.encode(""); + query += "&keyLength=" + URLEncoder.encode("512"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean setupKRAAgents() { + System.out.println("configuring Cert Instance : KRA Agents"); + setConfigURL(); + String myStringUrl = "http://" + host + ":" + adminPort + configURL; + + System.out.println(myStringUrl); + String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD); + + query += "&"; + query += "instanceID=" + URLEncoder.encode(instanceID); + query += "&serverRoot=" + URLEncoder.encode(serverRoot); + query += "&opType=" + URLEncoder.encode("OP_MODIFY"); + query += "&taskID=" + URLEncoder.encode("agents"); + query += "&n=" + URLEncoder.encode("3"); + query += "&m=" + URLEncoder.encode("2"); + query += "&uid2=" + URLEncoder.encode("agent3"); + query += "&uid0=" + URLEncoder.encode("agent1"); + query += "&uid1=" + URLEncoder.encode("agent2"); + query += "&pwd1=" + URLEncoder.encode("netscape"); + query += "&pwd2=" + URLEncoder.encode("netscape"); + query += "&pwd0=" + URLEncoder.encode("netscape"); + query += "&cmsSeed=0"; + setPostQueryString(query); + return Connect(myStringUrl); + } + + private boolean ConfRA() { + // Start Configuring + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Step 6: Initialize Token This has been moved to step 1a + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 7 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 8 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 9 : certRequest and Install i.e approve the request as a trusted manager + if (!certRequest(true)) { + System.out.println("Configuring Cert Instance: error getting cert"); + return false; + } + + // Create a SSL signing cert + Date tmpdate = new Date(); + + certType = "serverCert"; + subjectName = "CN=" + host + "." + adminDomain + ",OU=ssltest" + + tmpdate.getTime() + ",O=SSL,C=US"; + keyLength = "512"; + keyType = "RSA"; + String mtokenPWD = tokenPWD; + + tokenPWD = ""; + ssl_clientcert = "false"; + signingCert = "server"; + + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!certRequest(false)) { + System.out.println( + "Configuring Cert Instance: error creating Request"); + return false; + } + + // After creating ssl cert + tokenPWD = mtokenPWD; + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + } + + private boolean ConfKRA() { + // Start Configuring + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Step 6: Initialize Token This has been moved to step 1a + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 7 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 8 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 9 : certRequest and Install i.e approve the request as a trusted manager + if (!certRequest(true)) { + System.out.println("Configuring Cert Instance: error getting cert"); + return false; + } + + if (!setupStorageKey()) { + System.out.println( + "Configuring Cert Instance: error configuring storage key"); + return false; + } + + // no need to do this from 7.1 due to new acl based key recovery + /* + if (!setupKRAAgents()) + { System.out.println("Configuring Cert Instance: error configuring storage key"); return false;} + */ + + // Create a SSL signing cert + Date tmpdate = new Date(); + + certType = "serverCert"; + subjectName = "CN=" + host + "." + adminDomain + ",OU=ssltest" + + tmpdate.getTime() + ",O=SSL,C=US"; + keyLength = "512"; + keyType = "RSA"; + String mtokenPWD = tokenPWD; + + tokenPWD = ""; + ssl_clientcert = "false"; + signingCert = "server"; + + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!certRequest(false)) { + System.out.println( + "Configuring Cert Instance: error creating Request"); + return false; + } + + // After creating ssl cert + tokenPWD = mtokenPWD; + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + } + + // /// Sub CA configuration + + private boolean ConfSubCA() { + // Start Configuring + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Step 6: Initialize Token This has been moved to step 1a + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 7 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 8 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 9 : certRequest and Install i.e approve the request as a trusted manager + if (!certRequest(false)) { + System.out.println("Configuring Cert Instance: error getting cert"); + return false; + } + + // Create a SSL signing cert + Date tmpdate = new Date(); + + certType = "serverCert"; + subjectName = "CN=" + host + "." + adminDomain + ",OU=ssltest" + + tmpdate.getTime() + ",O=SSL,C=US"; + keyLength = "512"; + keyType = "RSA"; + String mtokenPWD = tokenPWD; + + tokenPWD = ""; + ssl_clientcert = "false"; + signingCert = "server"; + + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!certRequest(false)) { + System.out.println( + "Configuring Cert Instance: error creating Request"); + return false; + } + + // After creating ssl cert + tokenPWD = mtokenPWD; + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + } + + // / CA + + // org + private boolean ConfCA() { + // Start Configuring + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // SetSerial Number + if (!setSerial("1", "1000000")) { + System.out.println( + "Configuring Cert Instance: error setting serial number"); + return false; + } + + if (!setOCSP()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Step 6. setting up Server Migration + + // if (!serverMigration()) + // { System.out.println("Configuring Cert Instance: error configuring server migration"); return false;} + + // Step 7: Initialize Token + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!createCert()) { + System.out.println("Configuring Cert Instance: error creating cert"); + return false; + } + + // Create a SSL signing cert + Date tmpdate = new Date(); + + certType = "serverCert"; + subjectName = "CN=" + host + "." + adminDomain + ",OU=ssltest" + + tmpdate.getTime() + ",O=SSL,C=US"; + keyType = "RSA"; + keyLength = "512"; + String mtokenPWD = tokenPWD; + + tokenPWD = ""; + + if (!initializeToken()) { + System.out.println( + "Configuring Cert Instance: error initializing token"); + return false; + } + + // Step 8 : keyLenth + if (!keyLength()) { + System.out.println( + "Configuring Cert Instance: error configuring KeyLength"); + return false; + } + + // Step 9 : CheckDN + if (!checkDN()) { + System.out.println( + "Configuring Cert Instance: error checking deamon"); + return false; + } + + // Step 10 : + if (!createCert()) { + System.out.println("Configuring Cert Instance: error creating cert"); + return false; + } + + // After creating ssl cert + tokenPWD = mtokenPWD; + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + } + + // Configure Clone + + private boolean ConfClone() { + // Start Configuring + + // Step 1. Start Deamon + + if (!startDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to start deamon"); + return false; + } + + // Sometimes it takes time to start deamon so wait for few seconds + try { + System.out.println("going to sleep for 10 seconds"); + Thread.sleep(10000); + } catch (InterruptedException ie) { + System.out.println("sleep exection"); + } + + // Step 1a: Initialize Token ( Changed in 6.0)jjj + if (!initializePWD()) { + System.out.println( + "Configuring Cert Instance: error initializing pwd token"); + return false; + } + + // Step 2. Configure Internal DB + if (!configInternalDB()) { + System.out.println( + "Configuring Cert Instance: error configuring internal db"); + return false; + } + + // Step 3. Create Admin Values + if (!createAdminValues()) { + System.out.println( + "Configuring Cert Instance: error configuring admin values "); + return false; + } + + // Step 4. SubSystems + + if (!selectSubSystem()) { + System.out.println( + "Configuring Cert Instance: error selecting subsystems"); + return false; + } + + // Step 5. SetCASerial + if (!setSerial("1000000", "2000000")) { + System.out.println("Configuring Cert Instance: error setSerial"); + return false; + } + + if (!setOCSP()) { + System.out.println("Configuring Cert Instance: error setOCSP"); + return false; + } + + // Step 5. Network Configuration + if (!networkConfig()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + if (!taskCloning()) { + System.out.println("Configuring Cert Instance: error Task Cloning "); + return false; + } + + if (!taskCloneMaster()) { + System.out.println( + "Configuring Cert Instance: error configuring network ports "); + return false; + } + + // Create a SSL signing cert + certType = "serverCert"; + + if (!taskCloning()) { + System.out.println("Configuring Cert Instance: error Task Cloning "); + return false; + } + + // Step 11 + if (!singleSignON()) { + System.out.println( + "Configuring Cert Instance: error setting up singlesignon"); + return false; + } + + // Step 11 + if (!doMisc()) { + System.out.println( + "Configuring Cert Instance: error setting up miscell"); + return false; + } + + // Step 12 + if (!exitDeamon()) { + System.out.println( + "Configuring Cert Instance: Unable to exit deamon"); + return false; + } + + return true; + + } + + public boolean readProperties() { + // Read the properties file and assign values to variables . + try { + getProperties(propFileName); + } catch (Exception e) { + System.out.println( + "exception reading Properties File " + e.getMessage()); + } + + // read all properties + + adminDomain = props.getProperty("inst.admin.domain"); + adminID = props.getProperty("inst.admin.uid"); + adminPWD = props.getProperty("inst.admin.pwd"); + adminPort = props.getProperty("inst.admin.port"); + machineName = props.getProperty("inst.machineName"); + host = props.getProperty("inst.host"); + serverID = props.getProperty("inst.serverIdentifier"); + instanceID = "cert-" + serverID; + serverRoot = props.getProperty("inst.serverRoot"); + // Just for debugging" + sieURL = props.getProperty("inst.sie.url"); + dbConnPort = props.getProperty("inst.dbConnPort"); + dbConnHost = props.getProperty("inst.dbConnHost"); + dbInstanceName = props.getProperty("inst.dbInstanceName"); + dbPassword = props.getProperty("inst.dbPassword"); + dbLDAPauthDN = props.getProperty("inst.ldap.auth.dn"); + dbmode = props.getProperty("inst.dbmode"); + ldapServerDB = props.getProperty("inst.ldapServerDB"); + certAdminName = props.getProperty("inst.cert.admin.name"); + certAdminUid = props.getProperty("inst.cert.admin.uid"); + certAdminPWD = props.getProperty("inst.cert.admin.pwd"); + kra = props.getProperty("inst.subsystem.kra"); + subsystems = props.getProperty("inst.subsystem"); + ca = props.getProperty("inst.subsystem.ca"); + ra = props.getProperty("inst.subsystem.ra"); + ocsp = props.getProperty("inst.subsystem.ocsp"); + remoteKRA = props.getProperty("inst.subsystem.remoteKRA"); + wirelessSupport = props.getProperty("inst.subsystem.wireless"); + eeHttpPort = props.getProperty("inst.ee.http.port"); + eeHttpsPort = props.getProperty("inst.ee.https.port"); + agentHttpsPort = props.getProperty("inst.agent.https.port"); + radminHttpsPort = props.getProperty("inst.admin.https.port"); + tokenName = props.getProperty("inst.tokenName"); + tokenPWD = props.getProperty("inst.token.pwd"); + signingCert = props.getProperty("inst.cert.Type"); + certType = signingCert; + keyType = props.getProperty("inst.key.type"); + keyLength = props.getProperty("inst.key.length"); + SingleSignOnPWD = props.getProperty("inst.singlesignon.pwd"); + subjectName = props.getProperty("inst.ca.dn"); + isCA = props.getProperty("inst.isca"); + aki = props.getProperty("inst.aki"); + ski = props.getProperty("inst.ski"); + sslCABit = props.getProperty("inst.sslCABit"); + objectSigningCABit = props.getProperty("inst.objectSigningCABit"); + mailCABit = props.getProperty("inst.mailCABit"); + hashType = props.getProperty("inst.hash.Type"); + caOComponent = props.getProperty("inst.ca.component"); + certValidityDays = props.getProperty("inst.cert.validity"); + caHostname = props.getProperty("inst.cahostname"); + caPortnum = props.getProperty("inst.caportnum"); + caAgentPortnum = props.getProperty("inst.caASport"); + caTimeout = props.getProperty("inst.catimeout"); + caEEPort = props.getProperty("inst.caEEport"); + cloneInstanceId = props.getProperty("inst.cloneid"); + CAadminId = props.getProperty("inst.caAdminId"); + CAadminPwd = props.getProperty("inst.caAdminPwd"); + CAcertnickname = props.getProperty("inst.caCertnickname"); + enpropfile = props.getProperty("inst.propfile"); + cdir = props.getProperty("inst.certdir"); + tokenpwd = props.getProperty("inst.certtokenpwd"); + + if (subsystems.equals("ca")) { + return ConfCA(); + } + if (subsystems.equals("ra")) { + return ConfRA(); + } + if (subsystems.equals("ocsp")) { + return ConfOCSP(); + } + if (subsystems.equals("kra")) { + return ConfKRA(); + } + if (subsystems.equals("subca")) { + subca = true; + subsystems = "ca"; + return ConfSubCA(); + } + + return true; + } // end of r + + public static void main(String args[]) { + // Exit Status - (-1) for error + // - 1 Configured and server Alive + // - 0 Configured bur could not sart server + + + AutoInstaller t = new AutoInstaller(); + + System.out.println(args.length); + t.setPropFile(args[0]); + + if (args.length < 1) { + System.out.println("Usage : PropertiesFilePath"); + System.exit(-1); + } + + System.out.println("configuring Cert Instance : Start"); + + boolean st = t.readProperties(); + + if (st) { + System.out.println("Configuring Cert Instance : Successful"); + System.exit(1); + } else { + + System.out.println("Configuring Cert Instance : Error "); + System.exit(0); + } + } + +} // end of class + diff --git a/pki/base/silent/src/common/BaseState.java b/pki/base/silent/src/common/BaseState.java new file mode 100644 index 000000000..e4347c749 --- /dev/null +++ b/pki/base/silent/src/common/BaseState.java @@ -0,0 +1,122 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + + +/** + * CMS Test framework . + * This class reads and sets the values for a CMS subsytems Config file (CS.cfg) + * Using this class you can set the server to a base state. + */ + + + +public class BaseState { + + private String CMSConfigFile; + private CMSConfig cmscfg = null; + private String ldapbase, ldaphost, ldapport, ldapdn, ldapdnpw; + private boolean ldapsecConn = false; + // Constructor + + + + public BaseState() {} + + /** + * Constructor . Takes the parameter CMSConfigfilename ( with fullpath) + * @param CMSConfigfile. + */ + + public BaseState(String cmscfilename) { + CMSConfigFile = cmscfilename; + + } + + /** + * Set the publishing directory information . Takes the paramters ldaphost,ldapport,ldapDN, ldapDN password, BaseDN , Secure coonection (true/false) + */ + public void setLDAPInfo(String h, String p, String dn, String pw, String base, boolean sc) { + ldaphost = h; + ldapport = p; + ldapdn = dn; + ldapdnpw = pw; + ldapbase = base; + ldapsecConn = sc; + + } + + /** + * Enable SSL Client authentication for Directory enrollment and publishing + */ + + public void EnableSSLClientAuth() { + ldapsecConn = true; + cmscfg = new CMSConfig(CMSConfigFile); + // Enable DirBaseEnrollment + cmscfg.EnableDirEnrollment(ldapsecConn, ldapbase, ldaphost, ldapport); + // Enable Publishing + cmscfg.EnablePublishing(ldapsecConn, ldapdn, ldapdnpw, ldaphost, + ldapport); + cmscfg.saveCMSConfig(); + + } + + /** + * Set to CA 's base state . Enables Directory based enrollment , publishing and Portal enrollment + */ + + public void CABaseState() { + cmscfg = new CMSConfig(CMSConfigFile); + cmscfg.EnableAdminEnrollment(); + // Enable DirBaseEnrollment + cmscfg.EnableDirEnrollment(ldapsecConn, ldapbase, ldaphost, ldapport); + // Enable Publishing + cmscfg.DisablePublishing(ldapsecConn, ldapdn, ldapdnpw, ldaphost, + ldapport, ldapbase); + // Enable Portalbased enrollment + cmscfg.EnablePortalAuth(ldapsecConn, ldapdn, ldapdnpw, ldaphost, + ldapport, ldapbase); + cmscfg.saveCMSConfig(); + + } + + /** + * Set to RA 's base state . Enables Directory based enrollment and Portal enrollment + */ + + + public void RABaseState() { + cmscfg = new CMSConfig(CMSConfigFile); + cmscfg.EnableAdminEnrollment(); + // Enable DirBaseEnrollment + cmscfg.EnableDirEnrollment(ldapsecConn, ldapbase, ldaphost, ldapport); + // Enable Portalbased enrollment + cmscfg.EnablePortalAuth(ldapsecConn, ldapdn, ldapdnpw, ldaphost, + ldapport, ldapbase); + cmscfg.saveCMSConfig(); + + } + + public static void main(String args[]) {}// end of function main + +} diff --git a/pki/base/silent/src/common/CMSConfig.java b/pki/base/silent/src/common/CMSConfig.java new file mode 100644 index 000000000..7f219dfdf --- /dev/null +++ b/pki/base/silent/src/common/CMSConfig.java @@ -0,0 +1,626 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; + + +/** + * CMS Test framework . + * This class reads,modifies and saves CS.cfg file + */ + + +public class CMSConfig extends ServerInfo { + + /** + * Constructor . Reads the CS.cfg file .Takes the parameter for Configfile ( Provide fullpath) + */ + + + public CMSConfig(String confFile) { + CMSConfigFile = confFile; + System.out.println(CMSConfigFile); + readCMSConfig(); + } + + private void getProperties(String filePath) throws Exception { + try { + FileInputStream fis = new FileInputStream(filePath); + + props = new CMSProperties(); + props.load(fis); + System.out.println("Reading Properties file successful"); + fis.close(); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + private void readCMSConfig() { + + try { + FileInputStream fiscfg = new FileInputStream(CMSConfigFile); + + CMSprops = new CMSProperties(); + CMSprops.load(fiscfg); + System.out.println("Reading CMS Config file successful"); + fiscfg.close(); + System.out.println("Number in size " + CMSprops.size()); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + /** + * Saves the config file + **/ + + public void saveCMSConfig() { + try { + // Properties s = new Properties(CMSprops); + FileOutputStream fos = new FileOutputStream(CMSConfigFile); + + System.out.println("Number in size " + CMSprops.size()); + // CMSprops.list(System.out); + CMSprops.store(fos, null); + System.out.println("Writing to CMS Config file successful"); + fos.close(); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + // AdminEnrollment + + public void EnableAdminEnrollment() { + CMSprops.setProperty("cmsgateway.enableAdminEnroll", "true"); + + } + + // Authentication + + + // Enable DirectoryBased Authentication + /** + * Takes parameters : secureConnection( true/false), basedn, ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port) + */ + + public void EnableDirEnrollment(boolean secureConn, String ldapbase, String lhost, String lport) { + CMSprops.setProperty("auths.instance.UserDirEnrollment.dnpattern", + "UID=$attr.uid,E=$attr.mail.1,CN=$attr.cn,OU=$dn.ou.2,O=$dn.o,C=US"); + CMSprops.setProperty("auths.instance.UserDirEnrollment.ldap.basedn", + ldapbase); + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldap.ldapconn.host", lhost); + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldap.ldapconn.version", "3"); + CMSprops.setProperty("auths.instance.UserDirEnrollment.ldap.maxConns", + "8"); + CMSprops.setProperty("auths.instance.UserDirEnrollment.ldap.minConns", + "2"); + // CMSprops.setProperty("auths.instance.UserDirEnrollment.ldapByteAttributes=",""); + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldapStringAttributes", "mail"); + CMSprops.setProperty("auths.instance.UserDirEnrollment.pluginName", + "UidPwdDirAuth"); + if (secureConn) { + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn", + "true"); + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldap.ldapconn.port", lport); + + } else { + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn", + "false"); + CMSprops.setProperty( + "auths.instance.UserDirEnrollment.ldap.ldapconn.port", lport); + + } + } + + public void DisableDirEnrollment() { + CMSprops.remove("auths.instance.UserDirEnrollment.dnpattern"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldap.basedn"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.host"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.port"); + CMSprops.remove( + "auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.version"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldap.maxConns"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldap.minConns"); + CMSprops.remove("auths.instance.UserDirEnrollment.ldapByteAttributes="); + CMSprops.remove("auths.instance.UserDirEnrollment.ldapStringAttributes"); + CMSprops.remove("auths.instance.UserDirEnrollment.pluginName"); + + } + + public void EnableCMCAuth() { + + CMSprops.setProperty("auths.instance.testcmc.pluginName", + "CMCAuthentication"); + } + + /** + * Takes parameters : secureConnection( true/false), ldapbinddn, ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port), basedn (e.g ou=people,o=mcom.com) + */ + + void EnablePortalAuth(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport, String lbsuffix) { + String certnickname = null; + + CMSprops.setProperty("auths.instance.PortalEnrollment.pluginName", + "PortalEnroll"); + CMSprops.setProperty("auths.instance.PortalEnrollment.dnpattern", + "uid=$attr.uid,cn=$attr.cn,O=$dn.co,C=$dn.c"); + CMSprops.setProperty("auths.instance.PortalEnrollment.ldap.basedn", + lbsuffix); + CMSprops.setProperty("auths.instance.PortalEnrollment.ldap.maxConns", + "3"); + CMSprops.setProperty("auths.instance.PortalEnrollment.ldap.minConns", + "2"); + CMSprops.setProperty("auths.instance.PortalEnrollment.ldap.objectclass", + "inetOrgPerson"); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapauth.bindDN", + ldaprootDN); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapauth.bindPassword", + ldaprootDNPW); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapauth.bindPWPrompt", + "Rule PortalEnrollment"); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapconn.host", lhost); + if (secureConn) { + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapconn.secureConn", + "true"); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapauth.clientCertNickname", + certnickname); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapauth.authtype", + "SslClientAuth"); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapconn.port", lport); + + } else { + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapconn.secureConn", + "false"); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapconn.port", lport); + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapauth.authtype", + "BasicAuth"); + } + + CMSprops.setProperty( + "auths.instance.PortalEnrollment.ldap.ldapconn.version", "3"); + + } + + // Publishing + /** + * Takes parameters : secureConnection( true/false), ldapbinddn, ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port) + */ + + public void EnablePublishing(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport) { + + CMSprops.setProperty("ca.publish.enable", "true"); + CMSprops.setProperty("ca.publish.ldappublish.enable", "true"); + if (secureConn) { + CMSprops.setProperty( + "ca.publish.ldappublish.ldap.ldapconn.secureConn", "true"); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port", + lport); + + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype", + "SslClientAuth"); + } else { + CMSprops.setProperty( + "ca.publish.ldappublish.ldap.ldapconn.secureConn", "false"); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port", + lport); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype", + "BasicAuth"); + } + + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindDN", + ldaprootDN); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPassword", + ldaprootDNPW); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt", + "CA LDAP Publishing"); + + // set the hostname with fully qulified name if you are using SSL + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.host", lhost); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.version", "3"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapCaSimpleMap.class", + "com.netscape.cms.publish.mappers.LdapCaSimpleMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapDNCompsMap.class", + "com.netscape.cms.publish.mappers.Lda pCertCompsMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapDNExactMap.class", + "com.netscape.cms.publish.mappers.LdapCertExactMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapEnhancedMap.class", + "com.netscape.cms.publish.mappers.LdapEnhancedMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapSimpleMap.class", + "com.netscape.cms.publish.mappers.LdapSimpleMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapSubjAttrMap.class", + "com.netscape.cms.publish.mappers.LdapCertSubjMap"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCaCertMap.createCAEntry", "true"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCaCertMap.dnPattern", + "UID=CManager,OU=people,O=mcom.com"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCaCertMap.pluginName", + "LdapCaSimpleMap"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCrlMap.createCAEntry", "true"); + CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.dnPattern", + "UID=CManager,OU=people,O=mcom.com"); + CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.pluginName", + "LdapCaSimpleMap"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapUserCertMap.dnPattern", + "UID=$subj.UID,OU=people,O=mcom.com"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapUserCertMap.pluginName", + "LdapSimpleMap"); + CMSprops.setProperty( + "ca.publish.publisher.impl.FileBasedPublisher.class", + "com.netscape.cms.publish.publishers.FileBasedPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.impl.LdapCaCertPublisher.class", + "com.netscape.cms.publish.publishers.LdapCaCertPublisher"); + CMSprops.setProperty("ca.publish.publisher.impl.LdapCrlPublisher.class", + "com.netscape.cms.publish.publishers.LdapCrlPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.impl.LdapUserCertPublisher.class", + "com.netscape.cms.publish.publishers.LdapUserCertPublisher"); + CMSprops.setProperty("ca.publish.publisher.impl.OCSPPublisher.class", + "com.netscape.cms.publish.publishers.OCSPPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCaCertPublisher.caCertAttr", + "caCertificate;binary"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCaCertPublisher.caObjectClass", + "certificationAuthority"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCaCertPublisher.pluginName", + "LdapCaCertPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCrlPublisher.crlAttr", + "certificateRevocationList;binary"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCrlPublisher.pluginName", + "LdapCrlPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapUserCertPublisher.certAttr", + "userCertificate;binary"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapUserCertPublisher.pluginName", + "LdapUserCertPublisher"); + } + + public void DisablePublishing(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport, String base) { + + CMSprops.setProperty("ca.publish.enable", "false"); + CMSprops.setProperty("ca.publish.ldappublish.enable", "false"); + if (secureConn) { + CMSprops.setProperty( + "ca.publish.ldappublish.ldap.ldapconn.secureConn", "false"); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port", + lport); + + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype", + "SslClientAuth"); + } else { + CMSprops.setProperty( + "ca.publish.ldappublish.ldap.ldapconn.secureConn", "false"); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port", + lport); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype", + "BasicAuth"); + } + + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindDN", + ldaprootDN); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPassword", + ldaprootDNPW); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt", + "CA LDAP Publishing"); + + // set the hostname with fully qulified name if you are using SSL + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.host", lhost); + CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.version", "3"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapCaSimpleMap.class", + "com.netscape.cms.publish.mappers.LdapCaSimpleMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapDNCompsMap.class", + "com.netscape.cms.publish.mappers.Lda pCertCompsMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapDNExactMap.class", + "com.netscape.cms.publish.mappers.LdapCertExactMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapEnhancedMap.class", + "com.netscape.cms.publish.mappers.LdapEnhancedMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapSimpleMap.class", + "com.netscape.cms.publish.mappers.LdapSimpleMap"); + CMSprops.setProperty("ca.publish.mapper.impl.LdapSubjAttrMap.class", + "com.netscape.cms.publish.mappers.LdapCertSubjMap"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCaCertMap.createCAEntry", + "false"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCaCertMap.dnPattern", + "UID=CManager,OU=people," + base); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCaCertMap.pluginName", + "LdapCaSimpleMap"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapCrlMap.createCAEntry", "false"); + CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.dnPattern", + "UID=CManager,OU=people," + base); + CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.pluginName", + "LdapCaSimpleMap"); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapUserCertMap.dnPattern", + "UID=$subj.UID,OU=people," + base); + CMSprops.setProperty( + "ca.publish.mapper.instance.LdapUserCertMap.pluginName", + "LdapSimpleMap"); + CMSprops.setProperty( + "ca.publish.publisher.impl.FileBasedPublisher.class", + "com.netscape.cms.publish.publishers.FileBasedPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.impl.LdapCaCertPublisher.class", + "com.netscape.cms.publish.publishers.LdapCaCertPublisher"); + CMSprops.setProperty("ca.publish.publisher.impl.LdapCrlPublisher.class", + "com.netscape.cms.publish.publishers.LdapCrlPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.impl.LdapUserCertPublisher.class", + "com.netscape.cms.publish.publishers.LdapUserCertPublisher"); + CMSprops.setProperty("ca.publish.publisher.impl.OCSPPublisher.class", + "com.netscape.cms.publish.publishers.OCSPPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCaCertPublisher.caCertAttr", + "caCertificate;binary"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCaCertPublisher.caObjectClass", + "certificationAuthority"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCaCertPublisher.pluginName", + "LdapCaCertPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCrlPublisher.crlAttr", + "certificateRevocationList;binary"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapCrlPublisher.pluginName", + "LdapCrlPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapUserCertPublisher.certAttr", + "userCertificate;binary"); + CMSprops.setProperty( + "ca.publish.publisher.instance.LdapUserCertPublisher.pluginName", + "LdapUserCertPublisher"); + } + + public void CreateOCSPPublisher(String OCSPHost, String OCSPPort, String OCSPEEPort) { + // Set host nmae with fully qualified hostname + String location = "http://" + OCSPHost + ":" + OCSPEEPort + "/ocsp"; + + CMSprops.setProperty("ca.crl.MasterCRL.alwaysUpdate", "true"); + CMSprops.setProperty( + "ca.publish.publisher.instance.CAOCSPPublisher.host", OCSPHost); + CMSprops.setProperty( + "ca.publish.publisher.instance.CAOCSPPublisher.path", + "/ocsp/addCRL"); + CMSprops.setProperty( + "ca.publish.publisher.instance.CAOCSPPublisher.pluginName", + "OCSPPublisher"); + CMSprops.setProperty( + "ca.publish.publisher.instance.CAOCSPPublisher.port", OCSPPort); + CMSprops.setProperty( + "ca.publish.rule.instance.OCSPPublishingRule.enable", "true"); + CMSprops.setProperty( + "ca.publish.rule.instance.OCSPPublishingRule.mapper", ""); + CMSprops.setProperty( + "ca.publish.rule.instance.OCSPPublishingRule.pluginName", "Rule"); + CMSprops.setProperty( + "ca.publish.rule.instance.OCSPPublishingRule.predicate", ""); + CMSprops.setProperty( + "ca.publish.rule.instance.OCSPPublishingRule.publisher", + "CAOCSPPublisher"); + CMSprops.setProperty("ca.publish.rule.instance.OCSPPublishingRule.type", + "crl"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.ad0_location", + location); + CMSprops.setProperty( + "ca.Policy.rule.AuthInfoAccessExt.ad0_location_type", "URL"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.ad0_method", + "ocsp"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.critical", + "false"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.enable", "true"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.implName", + "AuthInfoAccessExt"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.numADs", "1"); + CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.predicate", + "HTTP_PARAMS.certType == client"); + + } + + public void EnableOCSPLDAPStore(String certInstanceID) { + String certNickName = "ocspSigningCert cert-" + certInstanceID; + + CMSprops.setProperty("ocsp.storeId", "ldapStore"); + CMSprops.setProperty("ocsp.store.defStore.byName", "true"); + CMSprops.setProperty("ocsp.store.defStore.class", + "com.netscape.cms.ocsp.DefStore"); + CMSprops.setProperty("ocsp.store.defStore.includeNextUpdate", "true"); + CMSprops.setProperty("ocsp.store.defStore.notFoundAsGood", "true"); + CMSprops.setProperty("ocsp.store.ldapStore.baseDN0", ldapBaseSuffix); + CMSprops.setProperty("ocsp.store.ldapStore.byName", "true"); + CMSprops.setProperty("ocsp.store.ldapStore.caCertAttr", + "cACertificate;binary"); + CMSprops.setProperty("ocsp.store.ldapStore.class", + "com.netscape.cms.ocsp.LDAPStore"); + CMSprops.setProperty("ocsp.store.ldapStore.crlAttr", + "certificateRevocationList;binary"); + CMSprops.setProperty("ocsp.store.ldapStore.host0", ldapHost); + CMSprops.setProperty("ocsp.store.ldapStore.includeNextUpdate", "true"); + CMSprops.setProperty("ocsp.store.ldapStore.notFoundAsGood", "true"); + CMSprops.setProperty("ocsp.store.ldapStore.numConns", "1"); + CMSprops.setProperty("ocsp.store.ldapStore.port0", ldapPort); + CMSprops.setProperty("ocsp.store.ldapStore.refreshInSec0", "864"); + CMSprops.setProperty("ocsp.signing.certnickname", certNickName); + CMSprops.setProperty("ocsp.signing.defaultSigningAlgorithm", + "MD5withRSA"); + CMSprops.setProperty("ocsp.signing.tokenname", "internal"); + + } + + public void SetupKRAConnectorInCA(String certInstanceID, String KRAHost, String KRAPort) { + String certNickName = "Server-Cert " + certInstanceID; + + CMSprops.setProperty("ca.connector.KRA.enable", "true"); + CMSprops.setProperty("ca.connector.KRA.host", KRAHost); + CMSprops.setProperty("ca.connector.KRA.local", "false"); + CMSprops.setProperty("ca.connector.KRA.nickName", certNickName); + CMSprops.setProperty("ca.connector.KRA.port", KRAPort); + CMSprops.setProperty("ca.connector.KRA.timeout", "30"); + CMSprops.setProperty("ca.connector.KRA.uri", "/kra/connector"); + + } + + public void DisableCardCryptoValidationinTKS() { + CMSprops.setProperty("cardcryptogram.validate.enable", "false"); + } + + private void ARLOn() { + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.critical", + "true"); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.enable", + "true"); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.indirectCRL", + "false"); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.onlyContainsCACerts", + "true"); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.onlyContainsUserCerts", + "false"); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.onlySomeReasons", + null); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.pointName", + null); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.pointType", + "DirectoryName"); + CMSprops.setProperty( + "ca.crl.MasterCRL.extension.IssuingDistributionPoint.type", + "CRLExtension"); + CMSprops.setProperty("ca.crl.MasterCRL.allowExtensions", "true"); + CMSprops.setProperty("ca.crl.MasterCRL.alwaysUpdate", "true"); + CMSprops.setProperty("ca.crl.MasterCRL.autoUpdateInterval", "5"); + CMSprops.setProperty("ca.crl.MasterCRL.caCertsOnly", "true"); + CMSprops.setProperty("ca.crl.MasterCRL.cacheUpdateInterval", "5"); + CMSprops.setProperty("ca.crl.MasterCRL.class", + "com.netscape.cmscore.ca.CRLIssuingPoint"); + + CMSprops.setProperty("ca.crl.MasterCRL.description", + "CA's complete Certificate Revocation List"); + CMSprops.setProperty("ca.crl.MasterCRL.enableCRLCache", "true"); + CMSprops.setProperty("ca.crl.MasterCRL.includeExpiredCerts", "true"); + CMSprops.setProperty("ca.crl.MasterCRL.nextUpdateSkew", "5"); + CMSprops.setProperty("ca.crl.MasterCRL.signingAlgorithm", "SHA1withRSA"); + + } + + // Policies + public void DefaultValidityRule(String SubsystemType, String lagtime, String leadtime, String maxValidity) { + if (SubsystemType.equals("ca")) { + CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.enable", + "true"); + CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.implName", + "ValidityConstraints"); + CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.lagTime", + lagtime); + CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.leadTime", + leadtime); + CMSprops.setProperty( + "ca.Policy.rule.DefaultValidityRule.maxValidity", + maxValidity); + CMSprops.setProperty( + "ca.Policy.rule.DefaultValidityRule.minValidity", "1"); + CMSprops.setProperty( + "ca.Policy.rule.DefaultValidityRule.notBeforeSkew", "5"); + CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.predicate", + null); + } else { + + CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.enable", + "true"); + CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.implName", + "ValidityConstraints"); + CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.lagTime", + lagtime); + CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.leadTime", + leadtime); + CMSprops.setProperty( + "ra.Policy.rule.DefaultValidityRule.maxValidity", + maxValidity); + CMSprops.setProperty( + "ra.Policy.rule.DefaultValidityRule.minValidity", "1"); + CMSprops.setProperty( + "ra.Policy.rule.DefaultValidityRule.notBeforeSkew", "5"); + CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.predicate", + null); + } + + } + + // Main Function + public static void main(String args[]) { + System.out.println(args.length); + + if (args.length < 1) { + System.out.println("Usage : ConfigFilePath"); + System.exit(-1); + } + + CMSConfig s = new CMSConfig(args[0]); + boolean secureC = false; + + // s.EnableDirEnrollment(secureC); + s.saveCMSConfig(); + + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/common/CMSInstance.java b/pki/base/silent/src/common/CMSInstance.java new file mode 100644 index 000000000..d8fccb284 --- /dev/null +++ b/pki/base/silent/src/common/CMSInstance.java @@ -0,0 +1,304 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; + + +public class CMSInstance { + + private int i; + private boolean st; + private String host, port, AdminDN, AdminDNPW, serverRoot, instanceID, sieurl, adminDomain, machineName; + + /** + * CMS Test framework . + * This class Creates and Removes a CMS server instance + */ + + + /** + * Constructor. Takes parameters hostname, adminserverport, adminDN, adminDNpassword, Dominanname, ServerRoot( full path) , instanceID, mnameand sieURL. mname is the fully qualified name of the server ( jupiter2.nscp.aoltw.net) sieURL is ("ldap://jupiter2.nscp.aoltw.net:(ConfigLADPPort)/o=NetscapeRoot" + */ + + private String cs_server_root, cs_tps_root, tps_hostname, tps_fqdn, tps_instanceid, tps_ee_port, tps_agent_port, tps_auth_ldap_host, tps_auth_ldap_port, tps_auth_ldap_suffix, ca_hostname, ca_ee_port, tks_hostname, tks_agent_port, token_db_hostname, token_db_port, token_db_suffix, token_db_passwd; + + public CMSInstance(String h, String p, String AdDN, String pwd, String domain, String sroot, String insID, String mname, String sieURL) { + + host = h; + port = p; + AdminDN = AdDN; + AdminDNPW = pwd; + adminDomain = domain; + serverRoot = sroot; + machineName = mname; + instanceID = insID; + sieurl = sieURL; + } + + public CMSInstance(String croot, + String troot, + String th, + String tfqdn, + String tid, + String tep, + String tagp, + String tldaphost, + String tldapport, + String tldapsuffix, + String ch, + String ceep, + String tkh, + String tkagp, + String toh, + String toagp, + String tosuffix, + String topasswd) { + + cs_server_root = croot; + cs_tps_root = troot; + tps_hostname = th; + tps_fqdn = tfqdn; + tps_instanceid = tid; + tps_ee_port = tep; + tps_agent_port = tagp; + tps_auth_ldap_host = tldaphost; + tps_auth_ldap_port = tldapport; + tps_auth_ldap_suffix = tldapsuffix; + ca_hostname = ch; + ca_ee_port = ceep; + tks_hostname = tkh; + tks_agent_port = tkagp; + token_db_hostname = toh; + token_db_port = toagp; + token_db_suffix = tosuffix; + token_db_passwd = topasswd; + + } + + public boolean CreateTPSInstance() throws IOException { + // steps + // 1. create .cfg file + // 2. run create.pl with that .cfg file + + FileOutputStream out = new FileOutputStream( + cs_server_root + "/tps_auto_config.cfg"); + BufferedWriter awriter; + + awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1")); + awriter.write("CS_SERVER_ROOT=" + cs_server_root); + awriter.newLine(); + awriter.write("CS_TPS_ROOT=" + cs_tps_root); + awriter.newLine(); + awriter.write("TPS_HOSTNAME=" + tps_hostname); + awriter.newLine(); + awriter.write("TPS_FQDN=" + tps_fqdn); + awriter.newLine(); + awriter.write("TPS_INSTANCEID=" + tps_instanceid); + awriter.newLine(); + awriter.write("TPS_EE_PORT=" + tps_ee_port); + awriter.newLine(); + awriter.write("TPS_AGENT_PORT=" + tps_agent_port); + awriter.newLine(); + awriter.write("TPS_AUTH_LDAP_HOST=" + tps_auth_ldap_host); + awriter.newLine(); + awriter.write("TPS_AUTH_LDAP_PORT=" + tps_auth_ldap_port); + awriter.newLine(); + awriter.write("TPS_AUTH_LDAP_SUFFIX=" + tps_auth_ldap_suffix); + awriter.newLine(); + awriter.write("CA_HOSTNAME=" + ca_hostname); + awriter.newLine(); + awriter.write("CA_EE_PORT=" + ca_ee_port); + awriter.newLine(); + awriter.write("TKS_HOSTNAME=" + tks_hostname); + awriter.newLine(); + awriter.write("TKS_AGENT_PORT=" + tks_agent_port); + awriter.newLine(); + awriter.write("TOKEN_DB_HOSTNAME=" + token_db_hostname); + awriter.newLine(); + awriter.write("TOKEN_DB_PORT=" + token_db_port); + awriter.newLine(); + awriter.write("TOKEN_DB_SUFFIX=" + token_db_suffix); + awriter.newLine(); + awriter.write("TOKEN_DB_PASSWD=" + token_db_passwd); + awriter.newLine(); + + awriter.flush(); + out.close(); + + try { + Process p = null; + Runtime r = Runtime.getRuntime(); + // String[] se = {"perl", cs_server_root+"/bin/cert/tps/setup/create.pl" , "-i", cs_server_root+"/tps_auto_config.cfg" }; + String[] se = { + "perl", + "/home/ckannan/cms/src/ns/netkeyra/setup/create.pl", "-i", + cs_server_root + "/tps_auto_config.cfg" }; + + System.out.println(se); + p = r.exec(se); + p.waitFor(); + String line; + + if (p.exitValue() == 0) { + BufferedReader br = new BufferedReader( + new InputStreamReader(p.getInputStream())); + + while ((line = br.readLine()) != null) { + System.out.println(line); + } + } else { + BufferedReader br = new BufferedReader( + new InputStreamReader(p.getErrorStream())); + + while ((line = br.readLine()) != null) { + System.out.println(line); + } + } + } catch (Throwable e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + return false; + } + + return true; + } + + public boolean CreateInstance() { + + String startURL = "/cert/Tasks/Operation/Create"; + String myStringUrl = "http://" + host + "." + adminDomain + ":" + port + + startURL; + + System.out.println(myStringUrl); + + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&instanceID=" + URLEncoder.encode(instanceID); + query += "&adminDomain=" + URLEncoder.encode(adminDomain); + query += "&sieURL=" + URLEncoder.encode(sieurl); + query += "&adminUID=" + URLEncoder.encode(AdminDN); + query += "&adminPWD=" + URLEncoder.encode(AdminDNPW); + query += "&machineName=" + URLEncoder.encode(machineName); + + PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query); + + return (sm.Send()); + + } + + public boolean RemoveInstance() { + + String startURL = "/cert-" + instanceID + "/Tasks/Operation/Remove"; + String myStringUrl = "http://" + host + ":" + port + startURL; + + System.out.println(myStringUrl); + + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&instanceID=" + URLEncoder.encode(instanceID); + + PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query); + + st = sm.Send(); + + if (st) { + System.out.println("Removed the cert instance"); + } else { + System.out.println("Could not remove the cert instance"); + } + + startURL = "/slapd-" + instanceID + "-db" + "/Tasks/Operation/Remove"; + myStringUrl = "http://" + host + ":" + port + startURL; + + System.out.println(myStringUrl); + + query = "serverRoot=" + URLEncoder.encode(serverRoot); + query += "&InstanceName=" + URLEncoder.encode(instanceID + "-db"); + + PostQuery rmdb = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query); + + rmdb.setNMCStatus("NMC_Status: 0"); + return (rmdb.Send()); + + } + + public static void main(String args[]) { + // Exit Status - (-1) for error + + // Exit Status - (-1) for error + // - 0 FAIL + // - 1 PASS + + boolean st; + + System.out.println(args.length); + if (args.length < 10) { + System.out.println( + "Usage : <task:Create/REmove> host port AdminDN AdminDNPW adminDomain serverRoot instanceID machineName sieURL"); + System.exit(-1); + } + + int task = 0; + + args[0] = args[0].toLowerCase(); + if (args[0].equals("create")) { + task = 0; + } + if (args[0].equals("remove")) { + task = 1; + } + + CMSInstance t = new CMSInstance(args[1], args[2], args[3], args[4], + args[5], args[6], args[7], args[8], args[9]); + + switch (task) { + + case 0: + st = t.CreateInstance(); + if (st) { + System.out.println("server Instance created "); + System.exit(1); + } else { + + System.out.println("Error: Server Instance could not be created"); + System.exit(0); + } + break; + + case 1: + st = t.RemoveInstance(); + if (st) { + System.out.println("Server instance removed"); + System.exit(1); + } else { + + System.out.println("Server instance could not be removed"); + System.exit(0); + } + break; + + default: + System.out.println("Incorrect usage"); + System.exit(-1); + + } // end of switch + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/common/CMSLDAP.java b/pki/base/silent/src/common/CMSLDAP.java new file mode 100644 index 000000000..8f7eed656 --- /dev/null +++ b/pki/base/silent/src/common/CMSLDAP.java @@ -0,0 +1,612 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import netscape.ldap.*; +import java.io.*; +import java.security.cert.X509Certificate; +import java.security.cert.*; + + +/** + * CMS Test framework . + * Using this class you can add a user and user certificate to LDAP server. + * You can also check if a certificate / CRL is published in LDAP server + * USe this class to turn of SSL and turn on SSL in a LDAP server. + */ + + +public class CMSLDAP { + + private String HOST, DN, BASEDN, PASSWORD; + private int PORT; + + private LDAPConnection conn = new LDAPConnection(); + + public CMSLDAP() {} + + /** + * Constructor. Takes parametes ldaphost, ldapport + */ + public CMSLDAP(String h, String p) { + HOST = h; + PORT = Integer.parseInt(p); + } + + /** + * Cosntructor. Takes parameters ldaphost,ldapport,ldapbinddn, ldapbindnpassword. + */ + public CMSLDAP(String h, String p, String dn, String pwd) { + HOST = h; + PORT = Integer.parseInt(p); + DN = dn; + PASSWORD = pwd; + } + + /** + * Connect to ldap server + */ + + public boolean connect() { + try { + conn.connect(HOST, PORT, DN, PASSWORD); + return true; + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + } + + /** + * Disconnect form ldap server + */ + + public void disconnect() { + + if ((conn != null) && conn.isConnected()) { + try { + conn.disconnect(); + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + } + + } + + } + + private boolean RemoveInstance(String basedn) { + try { + conn.delete(basedn); + return true; + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + /** + * Search for certificaterevocationList attribute. Takes basedn and filter as parameters + */ + + public boolean searchCRL(String basedn, String filter) throws LDAPException { + int searchScope = LDAPv2.SCOPE_SUB; + String getAttrs[] = { "certificateRevocationList;binary"}; + LDAPSearchResults results = conn.search(basedn, searchScope, filter, + getAttrs, false); + + if (results == null) { + System.out.println("Could not search"); + return false; + } + while (results.hasMoreElements()) { + LDAPEntry entry = (LDAPEntry) results.nextElement(); + + System.out.println(entry.getDN()); + LDAPAttribute anAttr = entry.getAttribute( + "certificateRevocationList;binary"); + + if (anAttr == null) { + System.out.println("Attribute not found "); + return false; + } else { + System.out.println(anAttr.getName()); + System.out.println(anAttr.getByteValueArray()); + return true; + } + } + return true; + } + + /** + * Search for attriburte usercertificate. Takes parameters basedn and filter + */ + + + + public boolean searchUserCert(String basedn, String filter) throws LDAPException { + int searchScope = LDAPv2.SCOPE_SUB; + String getAttrs[] = { "usercertificate;binary"}; + LDAPSearchResults results = conn.search(basedn, searchScope, filter, + getAttrs, false); + + if (results == null) { + System.out.println("Could not search"); + return false; + } + while (results.hasMoreElements()) { + LDAPEntry entry = (LDAPEntry) results.nextElement(); + + System.out.println(entry.getDN()); + LDAPAttribute anAttr = entry.getAttribute("usercertificate;binary"); + + if (anAttr == null) { + System.out.println("Attribute not found "); + return false; + } else { + System.out.println(anAttr.getName()); + System.out.println(anAttr.getByteValueArray()); + return true; + } + } + return true; + } + + /** + * Adds a user to direcrtory server . Takes parameters basedn, cn,sn,uid and passwd + */ + + public boolean userAdd(String basedn, String cn, String sn, String uid, String pwd) { + try { + LDAPAttributeSet attrSet = new LDAPAttributeSet(); + + attrSet.add( + new LDAPAttribute("objectclass", + new String[] { + "top", "person", "organizationalPerson", + "inetorgperson"})); + attrSet.add(new LDAPAttribute("cn", cn)); + attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com")); + attrSet.add(new LDAPAttribute("userpassword", pwd)); + attrSet.add(new LDAPAttribute("sn", sn)); + attrSet.add(new LDAPAttribute("givenName", cn + sn)); + String name = "uid=" + uid + "," + basedn; + + System.out.println("Basedn " + name); + LDAPEntry entry = new LDAPEntry(name, attrSet); + + conn.add(entry); + System.out.println("ADDED: " + name); + return true; + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + private X509Certificate getXCertificate(byte[] cpack) { + + try { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + ByteArrayInputStream s = new ByteArrayInputStream(cpack); + + System.out.println("Building certificate :" + cpack); + java.security.cert.X509Certificate the_cert = ( + java.security.cert.X509Certificate) cf.generateCertificate(s); + + return the_cert; + } catch (Exception e) { + System.out.println("ERROR: getXCertificate " + e.toString()); + return null; + } + + } + + private String buildDNString(String s) { + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == ',') && (s.charAt(i + 1) == ' ')) { + val += ','; + i++; + continue; + } else { + val += s.charAt(i); + } + } + return val; + } + + /** + * Returns the SerialNumber;issuerDN;SubjectDN string . Takes certficate as parameter + */ + + public String getCertificateString(X509Certificate cert) { + if (cert == null) { + return null; + } + String idn = ((cert.getIssuerDN()).toString()).trim(); + + idn = buildDNString(idn); + String sdn = ((cert.getSubjectDN()).toString()).trim(); + + sdn = buildDNString(sdn); + + System.out.println("GetCertificateString : " + idn + ";" + sdn); + + // note that it did not represent a certificate fully + // return cert.getVersion() + ";" + cert.getSerialNumber().toString() + + // ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN(); + return "2;" + cert.getSerialNumber().toString() + ";" + idn + ";" + sdn; + + } + + /** + * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate as parameters. + */ + public boolean CMSuserAdd(String cn, String sn, String uid, String pwd, byte[] certpack) { + try { + X509Certificate cert = getXCertificate(certpack); + + LDAPAttributeSet attrSet = new LDAPAttributeSet(); + + attrSet.add( + new LDAPAttribute("objectclass", + new String[] { + "top", "person", "organizationalPerson", + "inetorgperson", "cmsuser"})); + attrSet.add(new LDAPAttribute("cn", cn)); + attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com")); + attrSet.add(new LDAPAttribute("userpassword", pwd)); + attrSet.add(new LDAPAttribute("sn", sn)); + attrSet.add(new LDAPAttribute("givenName", cn + sn)); + attrSet.add(new LDAPAttribute("usertype", "sub")); + attrSet.add(new LDAPAttribute("userstate", "1")); + + attrSet.add( + new LDAPAttribute("description", getCertificateString(cert))); + LDAPAttribute attrCertBin = new LDAPAttribute("usercertificate"); + + attrCertBin.addValue(cert.getEncoded()); + attrSet.add(attrCertBin); + + String name = "uid=" + uid + "," + + "ou=People,o=netscapecertificateServer"; + LDAPEntry entry = new LDAPEntry(name, attrSet); + + conn.add(entry); + System.out.println("ADDED: " + name); + return true; + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + /** + * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate as parameters. + */ + + public boolean CMSuserAdd(String cn, String sn, String uid, String pwd, X509Certificate cert) { + + try { + LDAPAttributeSet attrSet = new LDAPAttributeSet(); + + attrSet.add( + new LDAPAttribute("objectclass", + new String[] { + "top", "person", "organizationalPerson", + "inetorgperson", "cmsuser"})); + attrSet.add(new LDAPAttribute("cn", cn)); + attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com")); + attrSet.add(new LDAPAttribute("userpassword", pwd)); + attrSet.add(new LDAPAttribute("sn", sn)); + attrSet.add(new LDAPAttribute("givenName", cn + sn)); + attrSet.add(new LDAPAttribute("usertype", "sub")); + attrSet.add(new LDAPAttribute("userstate", "1")); + + attrSet.add( + new LDAPAttribute("description", getCertificateString(cert))); + + LDAPAttribute attrCertBin = new LDAPAttribute("usercertificate"); + + attrCertBin.addValue(cert.getEncoded()); + attrSet.add(attrCertBin); + + String name = "uid=" + uid + "," + + "ou=People,o=netscapecertificateServer"; + LDAPEntry entry = new LDAPEntry(name, attrSet); + + conn.add(entry); + System.out.println("ADDED: " + name); + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + return true; + } + + /** + * adds a cms user to Trusted Manager Group. Takes uid as parameter. + */ + + public boolean addCMSUserToTMGroup(String uid) { + try { + LDAPAttributeSet attrSet = new LDAPAttributeSet(); + LDAPAttribute um = new LDAPAttribute("uniquemember", + "uid=" + uid + ",ou=People,o=NetscapeCertificateServer"); + + attrSet.add(um); + LDAPModification gr = new LDAPModification(LDAPModification.ADD, um); + + String dn = "cn=Trusted Managers,ou=groups,o=netscapeCertificateServer"; + + conn.modify(dn, gr); + return true; + + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + /** + * adds a cms user to Agent Group. Takes subsytem (ca/ra/ocsp/kra) and uid as parameters . + */ + + public boolean addCMSUserToAgentGroup(String subsystem, String uid) { + try { + String dn = null; + + if (subsystem.equals("ocsp")) { + dn = "cn=Online Certificate Status Manager Agents,ou=groups,o=netscapeCertificateServer"; + } + if (subsystem.equals("kra")) { + dn = "cn=Data Recovery Manager Agents,ou=groups,o=netscapeCertificateServer"; + } + if (subsystem.equals("ra")) { + dn = "cn=Registration Manager Agents,ou=groups,o=netscapeCertificateServer"; + } + if (subsystem.equals("ca")) { + dn = "cn=Certificate Manager Agents,ou=groups,o=netscapeCertificateServer"; + } + if (subsystem.equals("tks")) { + dn = "cn=Token Key Service Manager Agents,ou=groups,o=netscapeCertificateServer"; + } + + LDAPAttributeSet attrSet = new LDAPAttributeSet(); + LDAPAttribute um = new LDAPAttribute("uniquemember", + "uid=" + uid + ",ou=People,o=NetscapeCertificateServer"); + + System.out.println( + "uid=" + uid + ",ou=People,o=NetscapeCertificateServer"); + + attrSet.add(um); + LDAPModification gr = new LDAPModification(LDAPModification.ADD, um); + + conn.modify(dn, gr); + + return true; + + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + /** + * Will trun of SSL in LDAP server + **/ + + public boolean TurnOffSSL() { + try { + + LDAPModificationSet mods = new LDAPModificationSet(); + LDAPAttribute ssl3 = new LDAPAttribute("nsssl3", "off"); + LDAPAttribute ssl3ciphers = new LDAPAttribute("nsssl3ciphers", ""); + LDAPAttribute kfile = new LDAPAttribute("nskeyfile", "alias/"); + LDAPAttribute cfile = new LDAPAttribute("nscertfile", "alias/"); + LDAPAttribute cauth = new LDAPAttribute("nssslclientauth", "allowed"); + + // conn.delete("cn=RSA,cn=encryption,cn=config"); + + + mods.add(LDAPModification.REPLACE, ssl3); + mods.add(LDAPModification.DELETE, ssl3ciphers); + mods.add(LDAPModification.DELETE, kfile); + mods.add(LDAPModification.DELETE, cfile); + mods.add(LDAPModification.DELETE, cauth); + System.out.println("going to mod"); + // conn.modify("cn=encryption,cn=config",mods); + System.out.println("mod en=encryption"); + int i = 4; + + while (i >= 0) { + mods.removeElementAt(i); + i--; + } + + LDAPAttribute sec = new LDAPAttribute("nsslapd-security", "off"); + + mods.add(LDAPModification.REPLACE, sec); + conn.modify("cn=config", mods); + System.out.println("mod cn=config"); + + return true; + + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + /** + * Will Turn ON SSL in LDAP server . Takes certPrefix, certificatenickanme and sslport as parameters. + **/ + + public boolean TurnOnSSL(String certPrefix, String certName, String sslport) { + String dn; + String CIPHERS = "-rsa_null_md5,+rsa_fips_3des_sha,+rsa_fips_des_sha,+rsa_3des_sha,+rsa_rc4_128_md5,+rsa_des_sha,+rsa_rc2_40_md5,+rsa_rc4_40_md5"; + + try { + boolean found = false; + int searchScope = LDAPv2.SCOPE_SUB; + String getAttrs[] = { "nssslactivation"}; + + LDAPModificationSet mods = new LDAPModificationSet(); + LDAPAttribute sec = new LDAPAttribute("nsslapd-security", "on"); + LDAPAttribute sp = new LDAPAttribute("nsslapd-securePort", sslport); + + mods.add(LDAPModification.REPLACE, sec); + mods.add(LDAPModification.REPLACE, sp); + conn.modify("cn=config", mods); + mods.removeElementAt(1); + mods.removeElementAt(0); + + LDAPAttribute ssl3 = new LDAPAttribute("nsssl3", "on"); + LDAPAttribute ssl3ciphers = new LDAPAttribute("nsssl3ciphers", + CIPHERS); + LDAPAttribute kfile = new LDAPAttribute("nskeyfile", + "alias/" + certPrefix + "-key3.db"); + LDAPAttribute cfile = new LDAPAttribute("nscertfile", + "alias/" + certPrefix + "-cert7.db"); + LDAPAttribute cauth = new LDAPAttribute("nssslclientauth", "allowed"); + + mods.add(LDAPModification.REPLACE, ssl3); + mods.add(LDAPModification.REPLACE, ssl3ciphers); + mods.add(LDAPModification.REPLACE, kfile); + mods.add(LDAPModification.REPLACE, cfile); + mods.add(LDAPModification.REPLACE, cauth); + + conn.modify("cn=encryption,cn=config", mods); + int i = 4; + + while (i >= 0) { + mods.removeElementAt(i); + i--; + } + + // conn.delete("cn=RSA,cn=encryption,cn=config"); + try { + LDAPSearchResults results = conn.search( + "cn=RSA,cn=encryption,cn=config", searchScope, null, + getAttrs, false); + LDAPAttribute cn = new LDAPAttribute("cn", "RSA"); + LDAPAttribute ssltoken = new LDAPAttribute("nsssltoken", + "internal (software)"); + LDAPAttribute activation = new LDAPAttribute("nssslactivation", + "on"); + LDAPAttribute cname = new LDAPAttribute("nssslpersonalityssl", + certName); + + mods.add(LDAPModification.REPLACE, cn); + mods.add(LDAPModification.REPLACE, ssltoken); + mods.add(LDAPModification.REPLACE, activation); + mods.add(LDAPModification.REPLACE, cname); + + conn.modify("cn=RSA,cn=encryption,cn=config", mods); + + } catch (Exception e1) { + LDAPAttributeSet attrSet = new LDAPAttributeSet(); + + attrSet.add( + new LDAPAttribute("objectclass", + new String[] { "top", "nsEncryptionModule"})); + attrSet.add(new LDAPAttribute("cn", "RSA")); + attrSet.add( + new LDAPAttribute("nsssltoken", "internal (software)")); + attrSet.add(new LDAPAttribute("nssslactivation", "on")); + attrSet.add(new LDAPAttribute("nssslpersonalityssl", certName)); + LDAPEntry entry = new LDAPEntry("cn=RSA,cn=encryption,cn=config", + attrSet); + + conn.add(entry); + } + + return true; + + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + return false; + } + + } + + public static void main(String args[]) { + String HOST = args[0]; + // int PORT = Integer.parseInt(args[1]); + String PORT = args[1]; + String DN = args[2]; + String PASSWORD = args[3]; + String BASEDN = args[4]; + + String s = "MIICFzCCAYCgAwIBAgIBBjANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVz\ndDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTEyMTUx\nMzZaFw0wNDA0MTAwOTQ2NTVaMFwxCzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNTU0wxHTAbBgNVBAsT\nFHNzbHRlc3QxMDUwMDk3ODkzNzQ1MSAwHgYDVQQDExdqdXBpdGVyMi5uc2NwLmFvbHR3Lm5ldDBc\nMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDCsCTIIQ+bJMfPHi6kwa7HF+/xSTVHcpZ5zsodXsNWjPlD\noRu/5KAO8NotfwGnYmALWdYnqXCF0q0gkaJQalQTAgMBAAGjRjBEMA4GA1UdDwEB/wQEAwIFoDAR\nBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUzxZkSySZT/Y3SxGMEiNyHnLUOPAwDQYJKoZI\nhvcNAQEEBQADgYEALtpqMOtZt6j5KlghDFgdg/dvf36nWiZwC1ap6+ka22shLkA/RjmOix97btzT\nQ+8LcmdkAW5iap4YbtrCu0wdN6IbIEXoQI1QGZBoKO2o02utssXANmTnRCyH/GX2KefQlp1NSRj9\nZNZ+GRT2Qk/8G5Ds9vVjm1I5+/AkzI9jS14="; + + s = "-----BEGIN CERTIFICATE-----" + "\n" + s + "\n" + + "-----END CERTIFICATE-----\n"; + + try { + + System.out.println(HOST + PORT + DN + PASSWORD + BASEDN); + CMSLDAP caIdb = new CMSLDAP(HOST, PORT, DN, PASSWORD); + + /* FileInputStream fis = new FileInputStream("t1"); + DataInputStream dis = new DataInputStream(fis); + + byte[] bytes = new byte[dis.available()]; + dis.readFully(bytes); + + // bytes=s.getBytes(); + */ + + if (!caIdb.connect()) { + System.out.println("Could not connect to CA internal DB port"); + } + + if (!caIdb.searchCRL("o=mcom.com", "uid=CManager")) { + System.out.println("CRL is not published"); + } + + // if(!caIdb.searchUserCert("o=mcom.com","uid=test")) + // System.out.println("USer cert is not published"); + + // if (!caIdb.CMSuserAdd("ra-trust" ,"ra-trust","ra-trust","netscape",bytes)) + // {System.out.println("Trusted MAnager user Could not be add ");} + + // if(!caIdb.addCMSUserToTMGroup("ra-trust")) + // {System.out.println("CMS user Could not be added to Trusted manager group "); } + + // if(!caIdb.addCMSUserToAgentGroup("ra","ra-agent")) + // {System.out.println("CMS user Could not be added to Trusted manager group "); } + /* if(!caIdb.userAdd(BASEDN,"raeetest1","raeetest1","raeetest1","netscape")) + {System.out.println("CMS user Could not be added to Trusted manager group "); } + */ + + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + } + + } +} + diff --git a/pki/base/silent/src/common/CMSProperties.java b/pki/base/silent/src/common/CMSProperties.java new file mode 100644 index 000000000..2c9008b75 --- /dev/null +++ b/pki/base/silent/src/common/CMSProperties.java @@ -0,0 +1,698 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +/* + * @(#)Properties.java 1.60 00/02/02 + * + * Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved. + * + * This software is the proprietary information of Sun Microsystems, Inc. + * Use is subject to license terms. + * + */ + +import java.util.*; +import java.io.IOException; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.BufferedReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.BufferedWriter; +import java.util.Hashtable; + + +/** + * The <code>Properties</code> class represents a persistent set of + * properties. The <code>Properties</code> can be saved to a stream + * or loaded from a stream. Each key and its corresponding value in + * the property list is a string. + * <p> + * A property list can contain another property list as its + * "defaults"; this second property list is searched if + * the property key is not found in the original property list. + * <p> + * Because <code>Properties</code> inherits from <code>Hashtable</code>, the + * <code>put</code> and <code>putAll</code> methods can be applied to a + * <code>Properties</code> object. Their use is strongly discouraged as they + * allow the caller to insert entries whose keys or values are not + * <code>Strings</code>. The <code>setProperty</code> method should be used + * instead. If the <code>store</code> or <code>save</code> method is called + * on a "compromised" <code>Properties</code> object that contains a + * non-<code>String</code> key or value, the call will fail. + * <p> + * <a name="encoding"></a> + * When saving properties to a stream or loading them from a stream, the + * ISO 8859-1 character encoding is used. For characters that cannot be directly + * represented in this encoding, + * <a href="http://java.sun.com/docs/books/jls/html/3.doc.html#100850">Unicode escapes</a> + * are used; however, only a single 'u' character is allowed in an escape sequence. + * The native2ascii tool can be used to convert property files to and from + * other character encodings. + * + * @see <a href="../../../tooldocs/solaris/native2ascii.html">native2ascii tool for Solaris</a> + * @see <a href="../../../tooldocs/win32/native2ascii.html">native2ascii tool for Windows</a> + * + * @author Arthur van Hoff + * @author Michael McCloskey + * @version 1.60, 02/02/00 + * @since JDK1.0 + */ + +class CMSProperties extends Hashtable { + + /** + * use serialVersionUID from JDK 1.1.X for interoperability + */ + private static final long serialVersionUID = 4112578634029874840L; + + /** + * A property list that contains default values for any keys not + * found in this property list. + * + * @serial + */ + protected CMSProperties defaults; + + /** + * Creates an empty property list with no default values. + */ + public CMSProperties() { + this(null); + } + + /** + * Creates an empty property list with the specified defaults. + * + * @param defaults the defaults. + */ + public CMSProperties(CMSProperties defaults) { + this.defaults = defaults; + } + + /** + * Calls the hashtable method <code>put</code>. Provided for + * parallelism with the <tt>getProperty</tt> method. Enforces use of + * strings for property keys and values. + * + * @param key the key to be placed into this property list. + * @param value the value corresponding to <tt>key</tt>. + * @see #getProperty + * @since 1.2 + */ + public synchronized Object setProperty(String key, String value) { + return put(key, value); + } + + private static final String keyValueSeparators = "=: \t\r\n\f"; + + private static final String strictKeyValueSeparators = "=:"; + + private static final String specialSaveChars = " \t\r\n\f"; + + private static final String whiteSpaceChars = " \t\r\n\f"; + + /** + * Reads a property list (key and element pairs) from the input stream. + * The stream is assumed to be using the ISO 8859-1 character encoding. + * <p> + * Every property occupies one line of the input stream. Each line + * is terminated by a line terminator (<code>\n</code> or <code>\r</code> + * or <code>\r\n</code>). Lines from the input stream are processed until + * end of file is reached on the input stream. + * <p> + * A line that contains only whitespace or whose first non-whitespace + * character is an ASCII <code>#</code> or <code>!</code> is ignored + * (thus, <code>#</code> or <code>!</code> indicate comment lines). + * <p> + * Every line other than a blank line or a comment line describes one + * property to be added to the table (except that if a line ends with \, + * then the following line, if it exists, is treated as a continuation + * line, as described + * below). The key consists of all the characters in the line starting + * with the first non-whitespace character and up to, but not including, + * the first ASCII <code>=</code>, <code>:</code>, or whitespace + * character. All of the key termination characters may be included in + * the key by preceding them with a \. + * Any whitespace after the key is skipped; if the first non-whitespace + * character after the key is <code>=</code> or <code>:</code>, then it + * is ignored and any whitespace characters after it are also skipped. + * All remaining characters on the line become part of the associated + * element string. Within the element string, the ASCII + * escape sequences <code>\t</code>, <code>\n</code>, + * <code>\r</code>, <code>\\</code>, <code>\"</code>, <code>\'</code>, + * <code>\  </code>  (a backslash and a space), and + * <code>\u</code><i>xxxx</i> are recognized and converted to single + * characters. Moreover, if the last character on the line is + * <code>\</code>, then the next line is treated as a continuation of the + * current line; the <code>\</code> and line terminator are simply + * discarded, and any leading whitespace characters on the continuation + * line are also discarded and are not part of the element string. + * <p> + * As an example, each of the following four lines specifies the key + * <code>"Truth"</code> and the associated element value + * <code>"Beauty"</code>: + * <p> + * <pre> + * Truth = Beauty + * Truth:Beauty + * Truth :Beauty + * </pre> + * As another example, the following three lines specify a single + * property: + * <p> + * <pre> + * fruits apple, banana, pear, \ + * cantaloupe, watermelon, \ + * kiwi, mango + * </pre> + * The key is <code>"fruits"</code> and the associated element is: + * <p> + * <pre>"apple, banana, pear, cantaloupe, watermelon,kiwi, mango"</pre> + * Note that a space appears before each <code>\</code> so that a space + * will appear after each comma in the final result; the <code>\</code>, + * line terminator, and leading whitespace on the continuation line are + * merely discarded and are <i>not</i> replaced by one or more other + * characters. + * <p> + * As a third example, the line: + * <p> + * <pre>cheeses + * </pre> + * specifies that the key is <code>"cheeses"</code> and the associated + * element is the empty string.<p> + * + * @param inStream the input stream. + * @exception IOException if an error occurred when reading from the + * input stream. + */ + public synchronized void load(InputStream inStream) throws IOException { + + BufferedReader in = new BufferedReader( + new InputStreamReader(inStream, "8859_1")); + + while (true) { + // Get next line + String line = in.readLine(); + + if (line == null) { + return; + } + + if (line.length() > 0) { + // Continue lines that end in slashes if they are not comments + char firstChar = line.charAt(0); + + if ((firstChar != '#') && (firstChar != '!')) { + while (continueLine(line)) { + String nextLine = in.readLine(); + + if (nextLine == null) { + nextLine = new String(""); + } + String loppedLine = line.substring(0, line.length() - 1); + // Advance beyond whitespace on new line + int startIndex = 0; + + for (startIndex = 0; startIndex < nextLine.length(); startIndex++) { + if (whiteSpaceChars.indexOf( + nextLine.charAt(startIndex)) + == -1) { + break; + } + } + nextLine = nextLine.substring(startIndex, + nextLine.length()); + line = new String(loppedLine + nextLine); + } + + // Find start of key + int len = line.length(); + int keyStart; + + for (keyStart = 0; keyStart < len; keyStart++) { + if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1) { + break; + } + } + + // Blank lines are ignored + if (keyStart == len) { + continue; + } + + // Find separation between key and value + int separatorIndex; + + for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) { + char currentChar = line.charAt(separatorIndex); + + if (currentChar == '\\') { + separatorIndex++; + } else if (keyValueSeparators.indexOf(currentChar) != -1) { + break; + } + } + + // Skip over whitespace after key if any + int valueIndex; + + for (valueIndex = separatorIndex; valueIndex < len; valueIndex++) { + if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) + == -1) { + break; + } + } + + // Skip over one non whitespace key value separators if any + if (valueIndex < len) { + if (strictKeyValueSeparators.indexOf( + line.charAt(valueIndex)) + != -1) { + valueIndex++; + } + } + + // Skip over white space after other separators if any + while (valueIndex < len) { + if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) + == -1) { + break; + } + valueIndex++; + } + String key = line.substring(keyStart, separatorIndex); + String value = (separatorIndex < len) + ? line.substring(valueIndex, len) + : ""; + + // Convert then store key and value + key = loadConvert(key); + value = loadConvert(value); + put(key, value); + } + } + } + } + + /* + * Returns true if the given line is a line that must + * be appended to the next line + */ + private boolean continueLine(String line) { + int slashCount = 0; + int index = line.length() - 1; + + while ((index >= 0) && (line.charAt(index--) == '\\')) { + slashCount++; + } + return (slashCount % 2 == 1); + } + + /* + * Converts encoded \uxxxx to unicode chars + * and changes special saved chars to their original forms + */ + private String loadConvert(String theString) { + char aChar; + int len = theString.length(); + StringBuffer outBuffer = new StringBuffer(len); + + for (int x = 0; x < len;) { + aChar = theString.charAt(x++); + if (aChar == '\\') { + aChar = theString.charAt(x++); + if (aChar == 'u') { + // Read the xxxx + int value = 0; + + for (int i = 0; i < 4; i++) { + aChar = theString.charAt(x++); + switch (aChar) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + value = (value << 4) + aChar - '0'; + break; + + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + value = (value << 4) + 10 + aChar - 'a'; + break; + + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + value = (value << 4) + 10 + aChar - 'A'; + break; + + default: + throw new IllegalArgumentException( + "Malformed \\uxxxx encoding."); + } + } + outBuffer.append((char) value); + } else { + if (aChar == 't') { + aChar = '\t'; + } else if (aChar == 'r') { + aChar = '\r'; + } else if (aChar == 'n') { + aChar = '\n'; + } else if (aChar == 'f') { + aChar = '\f'; + } + outBuffer.append(aChar); + } + } else { + outBuffer.append(aChar); + } + } + return outBuffer.toString(); + } + + /* + * Converts unicodes to encoded \uxxxx + * and writes out any of the characters in specialSaveChars + * with a preceding slash + */ + private String saveConvert(String theString, boolean escapeSpace) { + int len = theString.length(); + StringBuffer outBuffer = new StringBuffer(len * 2); + + for (int x = 0; x < len; x++) { + char aChar = theString.charAt(x); + + switch (aChar) { + case ' ': + if (x == 0 || escapeSpace) { + outBuffer.append('\\'); + } + + outBuffer.append(' '); + break; + + case '\\': + outBuffer.append('\\'); + outBuffer.append('\\'); + break; + + case '\t': + outBuffer.append('\\'); + outBuffer.append('t'); + break; + + case '\n': + outBuffer.append('\\'); + outBuffer.append('n'); + break; + + case '\r': + outBuffer.append('\\'); + outBuffer.append('r'); + break; + + case '\f': + outBuffer.append('\\'); + outBuffer.append('f'); + break; + + default: + if ((aChar < 0x0020) || (aChar > 0x007e)) { + outBuffer.append('\\'); + outBuffer.append('u'); + outBuffer.append(toHex((aChar >> 12) & 0xF)); + outBuffer.append(toHex((aChar >> 8) & 0xF)); + outBuffer.append(toHex((aChar >> 4) & 0xF)); + outBuffer.append(toHex(aChar & 0xF)); + } else { + if (specialSaveChars.indexOf(aChar) != -1) { + outBuffer.append('\\'); + } + outBuffer.append(aChar); + } + } + } + return outBuffer.toString(); + } + + /** + * Calls the <code>store(OutputStream out, String header)</code> method + * and suppresses IOExceptions that were thrown. + * + * @deprecated This method does not throw an IOException if an I/O error + * occurs while saving the property list. As of the Java 2 platform v1.2, the preferred + * way to save a properties list is via the <code>store(OutputStream out, + * String header)</code> method. + * + * @param out an output stream. + * @param header a description of the property list. + * @exception ClassCastException if this <code>Properties</code> object + * contains any keys or values that are not <code>Strings</code>. + */ + public synchronized void save(OutputStream out, String header) { + try { + store(out, header); + } catch (IOException e) {} + } + + /** + * Writes this property list (key and element pairs) in this + * <code>Properties</code> table to the output stream in a format suitable + * for loading into a <code>Properties</code> table using the + * <code>load</code> method. + * The stream is written using the ISO 8859-1 character encoding. + * <p> + * Properties from the defaults table of this <code>Properties</code> + * table (if any) are <i>not</i> written out by this method. + * <p> + * If the header argument is not null, then an ASCII <code>#</code> + * character, the header string, and a line separator are first written + * to the output stream. Thus, the <code>header</code> can serve as an + * identifying comment. + * <p> + * Next, a comment line is always written, consisting of an ASCII + * <code>#</code> character, the current date and time (as if produced + * by the <code>toString</code> method of <code>Date</code> for the + * current time), and a line separator as generated by the Writer. + * <p> + * Then every entry in this <code>Properties</code> table is written out, + * one per line. For each entry the key string is written, then an ASCII + * <code>=</code>, then the associated element string. Each character of + * the element string is examined to see whether it should be rendered as + * an escape sequence. The ASCII characters <code>\</code>, tab, newline, + * and carriage return are written as <code>\\</code>, <code>\t</code>, + * <code>\n</code>, and <code>\r</code>, respectively. Characters less + * than <code>\u0020</code> and characters greater than + * <code>\u007E</code> are written as <code>\u</code><i>xxxx</i> for + * the appropriate hexadecimal value <i>xxxx</i>. Leading space characters, + * but not embedded or trailing space characters, are written with a + * preceding <code>\</code>. The key and value characters <code>#</code>, + * <code>!</code>, <code>=</code>, and <code>:</code> are written with a + * preceding slash to ensure that they are properly loaded. + * <p> + * After the entries have been written, the output stream is flushed. The + * output stream remains open after this method returns. + * + * @param out an output stream. + * @param header a description of the property list. + * @exception IOException if writing this property list to the specified + * output stream throws an <tt>IOException</tt>. + * @exception ClassCastException if this <code>Properties</code> object + * contains any keys or values that are not <code>Strings</code>. + */ + public synchronized void store(OutputStream out, String header) + throws IOException { + BufferedWriter awriter; + + awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1")); + if (header != null) { + writeln(awriter, "#" + header); + } + writeln(awriter, "#" + new Date().toString()); + for (Enumeration e = keys(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + String val = (String) get(key); + + key = saveConvert(key, true); + + /* No need to escape embedded and trailing spaces for value, hence + * pass false to flag. + */ + val = saveConvert(val, false); + writeln(awriter, key + "=" + val); + } + awriter.flush(); + } + + private static void writeln(BufferedWriter bw, String s) throws IOException { + bw.write(s); + bw.newLine(); + } + + /** + * Searches for the property with the specified key in this property list. + * If the key is not found in this property list, the default property list, + * and its defaults, recursively, are then checked. The method returns + * <code>null</code> if the property is not found. + * + * @param key the property key. + * @return the value in this property list with the specified key value. + * @see #setProperty + * @see #defaults + */ + public String getProperty(String key) { + Object oval = super.get(key); + String sval = (oval instanceof String) ? (String) oval : null; + + return ((sval == null) && (defaults != null)) + ? defaults.getProperty(key) + : sval; + } + + /** + * Searches for the property with the specified key in this property list. + * If the key is not found in this property list, the default property list, + * and its defaults, recursively, are then checked. The method returns the + * default value argument if the property is not found. + * + * @param key the hashtable key. + * @param defaultValue a default value. + * + * @return the value in this property list with the specified key value. + * @see #setProperty + * @see #defaults + */ + public String getProperty(String key, String defaultValue) { + String val = getProperty(key); + + return (val == null) ? defaultValue : val; + } + + /** + * Returns an enumeration of all the keys in this property list, including + * the keys in the default property list. + * + * @return an enumeration of all the keys in this property list, including + * the keys in the default property list. + * @see java.util.Enumeration + * @see java.util.Properties#defaults + */ + public Enumeration propertyNames() { + Hashtable h = new Hashtable(); + + enumerate(h); + return h.keys(); + } + + /** + * Prints this property list out to the specified output stream. + * This method is useful for debugging. + * + * @param out an output stream. + */ + public void list(PrintStream out) { + out.println("-- listing properties --"); + Hashtable h = new Hashtable(); + + enumerate(h); + for (Enumeration e = h.keys(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + String val = (String) h.get(key); + + if (val.length() > 40) { + val = val.substring(0, 37) + "..."; + } + out.println(key + "=" + val); + } + } + + /** + * Prints this property list out to the specified output stream. + * This method is useful for debugging. + * + * @param out an output stream. + * @since JDK1.1 + */ + + /* + * Rather than use an anonymous inner class to share common code, this + * method is duplicated in order to ensure that a non-1.1 compiler can + * compile this file. + */ + public void list(PrintWriter out) { + out.println("-- listing properties --"); + Hashtable h = new Hashtable(); + + enumerate(h); + for (Enumeration e = h.keys(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + String val = (String) h.get(key); + + if (val.length() > 40) { + val = val.substring(0, 37) + "..."; + } + out.println(key + "=" + val); + } + } + + /** + * Enumerates all key/value pairs in the specified hastable. + * @param h the hashtable + */ + private synchronized void enumerate(Hashtable h) { + if (defaults != null) { + defaults.enumerate(h); + } + for (Enumeration e = keys(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + + h.put(key, get(key)); + } + } + + /** + * Convert a nibble to a hex character + * @param nibble the nibble to convert. + */ + private static char toHex(int nibble) { + return hexDigit[(nibble & 0xF)]; + } + + /** A table of hex digits */ + private static final char[] hexDigit = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', + 'E', 'F' + }; +} diff --git a/pki/base/silent/src/common/CMSTask.java b/pki/base/silent/src/common/CMSTask.java new file mode 100644 index 000000000..31ba4547f --- /dev/null +++ b/pki/base/silent/src/common/CMSTask.java @@ -0,0 +1,185 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; + + +/** + * CS Test framework . + * This class starts and stops CS server from command line + */ + +public class CMSTask { + + private static String operation; + private static String debug; + private static String serverRoot; + private Process p = null; + + /** + * Constructor . Takes CMS server root as parameter + * for example (/export/qa/cert-jupiter2) + **/ + + public CMSTask() {// do nothing + } + + public CMSTask(String sroot) { + serverRoot = sroot; + } + + public boolean CMSStart() { + + try { + System.out.println("Starting Certificate System:"); + Runtime r = Runtime.getRuntime(); + + p = r.exec(serverRoot + "/start-cert"); + + InputStreamReader isr = new InputStreamReader(p.getInputStream()); + BufferedReader br = new BufferedReader(isr); + String s = null; + + try { + while ((s = br.readLine()) != null) { + if (s.indexOf("started") > 0) { + return true; + } + // do something + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + return false; + + } catch (Throwable e) { + e.printStackTrace(); + } + + return false; + } + + public boolean CMSStop() { + try { + Runtime r = Runtime.getRuntime(); + + System.out.println("Stopping Certificate System:"); + p = r.exec(serverRoot + "/stop-cert"); + BufferedReader br = new BufferedReader( + new InputStreamReader(p.getInputStream())); + String line; + + while ((line = br.readLine()) != null) { + System.out.println(" " + line); + if (line.indexOf("server shut down") > -1) { + return true; + } else { + return false; + } + } + } catch (Throwable e) { + e.printStackTrace(); + } + return false; + } + + public boolean CMSRestart() { + try { + System.out.println("Restarting Certificate System:"); + Runtime r = Runtime.getRuntime(); + + p = r.exec(serverRoot + "/restart-cert"); + BufferedReader br = new BufferedReader( + new InputStreamReader(p.getInputStream())); + String line; + + while ((line = br.readLine()) != null) { + System.out.println(" " + line); + if (line.indexOf("started") > -1) { + return true; + } else { + return false; + } + } + + } catch (Throwable e) { + e.printStackTrace(); + } + return false; + } + + public boolean task() { + if (operation.equalsIgnoreCase("stop")) { + CMSStop(); + return true; + } + + if (operation.equalsIgnoreCase("start")) { + CMSStart(); + return true; + } + + if (operation.equalsIgnoreCase("restart")) { + CMSRestart(); + return true; + } + + return false; + } + + public static void main(String args[]) { + CMSTask prof = new CMSTask(); + // parse args + StringHolder x_instance_root = new StringHolder(); + StringHolder x_operation = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("CMSTask"); + + parser.addOption("-instance_root %s #CA Server Root", x_instance_root); + parser.addOption("-operation %s #CA operation [stop,start,restart]", + x_operation); + + // and then match the arguments + String[] unmatched = null; + + unmatched = parser.matchAllArgs(args, 0, parser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + serverRoot = x_instance_root.value; + operation = x_operation.value; + + boolean st = prof.task(); + + if (!st) { + System.out.println("ERROR"); + } + + System.out.println("SUCCESS"); + + } // end of function main + +} // end of class + diff --git a/pki/base/silent/src/common/Certificate_Record.java b/pki/base/silent/src/common/Certificate_Record.java new file mode 100644 index 000000000..0331e02e5 --- /dev/null +++ b/pki/base/silent/src/common/Certificate_Record.java @@ -0,0 +1,50 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.io.*; +import java.net.*; + + +public class Certificate_Record { + + public String revokedOn = null; + public String revokedBy = null; + public String revocation_info = null; + public String signatureAlgorithm = null; + public String serialNumber = null; + public String subjectPublicKeyLength = null; + public String type = null; + public String subject = null; + public String issuedOn = null; + public String validNotBefore = null; + public String validNotAfter = null; + public String issuedBy = null; + public String subjectPublicKeyAlgorithm = null; + public String certChainBase64 = null; + public String certFingerprint = null; + public String pkcs7ChainBase64 = null; + public String certPrettyPrint = null; + + public Certificate_Record() {// Do nothing + } + +} + + +; diff --git a/pki/base/silent/src/common/ComCrypto.java b/pki/base/silent/src/common/ComCrypto.java new file mode 100644 index 000000000..897c13c45 --- /dev/null +++ b/pki/base/silent/src/common/ComCrypto.java @@ -0,0 +1,875 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; +import java.util.Date; +import java.util.StringTokenizer; +import java.net.URL; +import java.net.URLConnection; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.BufferedReader; +import java.net.URLEncoder; +import java.security.KeyPair; +import java.lang.Exception; + +import org.mozilla.jss.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; +import org.mozilla.jss.util.Password; +import org.mozilla.jss.crypto.CryptoToken; +import org.mozilla.jss.crypto.KeyPairGenerator; +import org.mozilla.jss.crypto.KeyPairAlgorithm; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.pkix.crmf.*; + +import netscape.security.provider.RSAPublicKey; +import netscape.security.pkcs.PKCS10; +import netscape.security.x509.X500Name; +import netscape.security.util.BigInt; +import netscape.security.x509.X500Signer; + +import sun.misc.BASE64Encoder; +import sun.misc.BASE64Decoder; +import java.security.Signature; + + +/** + * CMS Test framework . + * Use this class to initalize,add a certificate ,generate a certificate request from certificate database. + */ + + +public class ComCrypto { + + private String cdir, certnickname, keysize, keytype, tokenpwd; + private String certpackage, pkcs10request; + private boolean debug = true; + private boolean DBlogin = false; + private boolean generaterequest = false; + + private String transportcert = null; + private boolean dualkey = false; + public String CRMF_REQUEST = null; + int START = 1; + int END = START + 1; + Password password = null; + + public static CryptoManager manager; + public static CryptoToken token; + private CryptoStore store; + private Password pass1 = null, pass2 = null; + + public String C = null; + public String OU = null; + public String O = null; + public String CN = null; + public String UID = null; + public String L = null; + public String E = null; + + private String bstr = "-----BEGIN NEW CERTIFICATE REQUEST-----"; + private String blob, Blob1 = null; + private String Blob2 = null; + private String estr = "-----END NEW CERTIFICATE REQUEST-----"; + + private String certprefix = null; + + public ComCrypto() {} + ; + + /** + * Constructor . Takes the parameter certificatedbdirectory , passwordfor cert database, certificatenickname,keysize, keytype(RSA/DSA) + * @param certdbdirectory. + * @param certdbpassword + * @param certnickname + * @param keysize (1024/2048/4096) + * @param keytype (RSA/DSA) + */ + + + public ComCrypto(String cd, String tpwd, String cn, String ks, String kt) { + cdir = cd; + tokenpwd = tpwd; + certnickname = cn; + keysize = ks; + keytype = kt; + } + + // Set and Get functions + + public void setCertDir(String cd) { + cdir = cd; + } + + public void setCertnickname(String cd) { + certnickname = cd; + } + + public void setKeySize(String cd) { + keysize = cd; + } + + public void setKeyType(String cd) { + keytype = cd; + } + + public void setTokenPWD(String cd) { + tokenpwd = cd; + } + + public void setCertPackage(String cd) { + certpackage = cd; + } + + public void setGenerateRequest(boolean c) { + generaterequest = c; + } + + public void setDebug(boolean t) { + debug = t; + } + + public void setCertPrefix(String prefix) { + certprefix = prefix; + } + + /* + * setTransportCert() should only be called when the calling profile + * needs to do key archivals with the DRM and make sure the function + * generateCRMFtransport() is called for the CRMF request generation + * part. + */ + public void setTransportCert(String tcert) { + transportcert = tcert; + } + + public void setDualKey(boolean dkey) { + dualkey = dkey; + } + + public String getPkcs10Request() { + return pkcs10request; + } + + /** + * Parses the Certificate and returns SubjectDN . Takes certificate as parameter + */ + + public String getCertificateString(X509Certificate cert) { + if (cert == null) { + return null; + } + + // note that it did not represent a certificate fully + return cert.getVersion() + ";" + cert.getSerialNumber().toString() + ";" + + cert.getIssuerDN() + ";" + cert.getSubjectDN(); + } + + /** + * Finds and returns Certificate . Takes certificatenickname as parameter. + */ + + + public X509Certificate findCert(String certname) { + try { + + X509Certificate cert2 = manager.findCertByNickname(certname); + + return cert2; + + } catch (Exception e) { + System.out.println("exception importing cert " + e.getMessage()); + return null; + } + + } + + /** + * Imports a certificate to Certificate Database. Takes certificate and nickname as parameters. + */ + + + public boolean importCert(X509Certificate xcert, String nickname) { + try { + + System.out.println( + "importCert x509 : importing with nickname: " + nickname); + + InternalCertificate cert2 = manager.importCertToPerm(xcert, nickname); + + cert2.setSSLTrust(2); + return true; + + } catch (Exception e) { + System.out.println("exception importing cert " + e.getMessage()); + return false; + } + + } + + /** + * Imports a certificate to Certificate Database. Takes certificate and nickname as parameters. + */ + + + public boolean importCert(String cpack, String cn) { + + System.out.println("importCert string: importing with nickname: " + cn); + try { + + String tmp = normalize(cpack); + + if (DBlogin) { + System.out.println("Already logged into to DB"); + } + + if (manager == null) { + System.out.println("Manager object is null"); + } + + X509Certificate cert = manager.importCertPackage(tmp.getBytes(), cn); + + return true; + + } catch (Exception e) { + System.out.println( + "ERROR:exception importing cert " + e.getMessage()); + e.printStackTrace(); + return false; + } + + } + + /* imports CA certificate + */ + + public boolean importCACert(String cpack) { + + try { + String tmp = normalize(cpack); + + if (DBlogin) { + System.out.println("Already logged into to DB"); + } + + if (manager == null) { + System.out.println("Manager object is null"); + } + + X509Certificate cert = manager.importCACertPackage(tmp.getBytes()); + + return true; + + } catch (Exception e) { + System.out.println( + "ERROR:exception importing cert " + e.getMessage()); + return false; + } + + } + + /** + * Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server. + */ + + + public String normalize(String s) { + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'n')) { + val += '\n'; + i++; + continue; + } else if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'r')) { + i++; + continue; + } else if (s.charAt(i) == '"') { + continue; + } + val += s.charAt(i); + } + return val; + } + + /** + * Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server. + */ + + + String normalizeForLDAP(String s) { + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'n')) { + val += '\n' + " "; + i++; + continue; + } else if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'r')) { + i++; + continue; + } else if (s.charAt(i) == '"') { + continue; + } + val += s.charAt(i); + } + return val; + } + + /** + * Convert to pkcs7 format + */ + + + public String pkcs7Convertcert(String s) { + + String val = ""; + + int len = s.length(); + + for (int i = 0; i < len; i = i + 64) { + + if (i + 64 < len) { + val = val + s.substring(i, i + 64) + "\n"; + } else { + val = val + s.substring(i, len); + } + + } + return val; + } + + /** + * Delete all keys frim key3.db + **/ + + public void deleteKeys() { + try { + int i = 0; + + store = token.getCryptoStore(); + PrivateKey[] keys = store.getPrivateKeys(); + + if (debug) { + System.out.println("Now we shall delete all the keys!"); + } + + keys = store.getPrivateKeys(); + for (i = 0; i < keys.length; i++) { + PrivateKey key = (PrivateKey) keys[i]; + + store.deletePrivateKey(key); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Creates a new certificate database + **/ + + + public boolean CreateCertDB() { + return loginDB(); + + } + + /** + * Login to cert database + **/ + + public boolean loginDB() { + Password pass1 = null; + + try { + if (debug) { + System.out.println("CRYPTO INIT WITH CERTDB:" + cdir); + } + + // this piece of code is to create db's with certain prefix + if (certprefix != null) { + CryptoManager.InitializationValues vals; + + vals = new CryptoManager.InitializationValues(cdir, certprefix, + certprefix, "secmod.db"); + CryptoManager.initialize(vals); + } else { + CryptoManager.initialize(cdir); + } + + manager = CryptoManager.getInstance(); + token = (PK11Token) manager.getInternalKeyStorageToken(); + pass1 = new Password(tokenpwd.toCharArray()); + if (token.isLoggedIn() && debug) { + System.out.println("Already Logged in "); + } + + if (debug) { + System.out.println("tokenpwd:" + tokenpwd); + } + + token.login(pass1); + pass1.clear(); + + } catch (AlreadyInitializedException e) { + if (debug) { + System.out.println("Crypto manager already initialized"); + } + } catch (Exception e) { + try { + if (!token.isLoggedIn()) { + token.initPassword(pass1, pass1); + } + return true; + } catch (Exception er) { + System.err.println("some exception:" + e); + return false; + } + } + DBlogin = true; + return true; + } + + /** + * Generate Certificate Request + **/ + + public synchronized boolean generateRequest() { + + System.out.println("generating pkcs10 Request"); + loginDB(); + + try { + debug = true; + System.out.println("Generating request : keysize :" + keysize); + System.out.println("Generating request : subject :" + certnickname); + System.out.println("Generating request : keytype :" + keytype); + + Integer n = new Integer(keysize); + + if (generaterequest) { + blob = token.generateCertRequest(certnickname, n.intValue(), + keytype, (byte[]) null, (byte[]) null, (byte[]) null); + + System.out.println("Cert Request Generated."); + + bstr = "-----BEGIN NEW CERTIFICATE REQUEST-----"; + Blob1 = blob.substring(bstr.length() + 1); + Blob2 = Blob1.substring(0, Blob1.indexOf(estr)); + + System.out.println(Blob2); + pkcs10request = Blob2; + } + + return true; + + } catch (Exception e) { + System.out.println("Exception: Unable to generate request: " + e); + } + + return false; + } + + public boolean getNames() throws Exception { + + X500Name name = new X500Name(certnickname); + + try { + C = name.getCountry(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + try { + O = name.getOrganization(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + try { + OU = name.getOrganizationalUnit(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + try { + CN = name.getCommonName(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + try { + UID = name.getCommonName(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + try { + L = name.getLocality(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + try { + E = name.getEmail(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + + } + + return true; + } + + public String generateCRMFrequest() { + URL url = null; + URLConnection conn = null; + InputStream is = null; + BufferedReader reader = null; + boolean success = false; + int num = 1; + long total_time = 0; + KeyPair pair = null; + + System.out.println("Debug : initialize crypto Manager"); + try { + + // Step 1. initialize crypto Manager + try { + CryptoManager.initialize(cdir); + } catch (Exception e) { + // it is ok if it is already initialized + System.out.println("INITIALIZATION ERROR: " + e.toString()); + System.out.println("cdir = " + cdir); + } + + // Step 2 log into database + try { + + System.out.println("Debug : before getInstance"); + + manager = CryptoManager.getInstance(); + String token_pwd = tokenpwd; + + System.out.println("Debug : before get token"); + + token = manager.getInternalKeyStorageToken(); + password = new Password(token_pwd.toCharArray()); + + System.out.println("Debug : before login password"); + + token.login(password); + + System.out.println("Debug : after login password"); + } catch (Exception e) { + System.out.println("INITIALIZATION ERROR: " + e.toString()); + + if (!token.isLoggedIn()) { + token.initPassword(password, password); + } + } + + // Generating CRMF request + + KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA); + + Integer x = new Integer(keysize); + int key_len = x.intValue(); + + kg.initialize(key_len); + + // 1st key pair + pair = kg.genKeyPair(); + + // create CRMF + CertTemplate certTemplate = new CertTemplate(); + + certTemplate.setVersion(new INTEGER(2)); + + // Call getname to split certnickname aka cert subject name + try { + getNames(); + } catch (Exception e) { + System.out.println("Exception: "); + e.getMessage(); + } + + Name n = new Name(); + + if (CN != null) { + n.addCommonName(CN); + } + if (C != null) { + n.addCountryName(C); + } + if (L != null) { + n.addLocalityName(L); + } + if (OU != null) { + n.addOrganizationalUnitName(OU); + } + if (O != null) { + n.addOrganizationName(O); + } + + certTemplate.setSubject(n); + certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic())); + + SEQUENCE seq = new SEQUENCE(); + CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate, + seq); + byte popdata[] = { 0x0, 0x3, 0x0}; + + ProofOfPossession pop = ProofOfPossession.createKeyEncipherment( + POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3))); + + CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null); + + SEQUENCE s1 = new SEQUENCE(); + + // 1st : Encryption key + + s1.addElement(crmfMsg); + + // 2nd : Signing Key + + if (dualkey) { + System.out.println("dualkey = true"); + SEQUENCE seq1 = new SEQUENCE(); + CertRequest certReqSigning = new CertRequest(new INTEGER(1), + certTemplate, seq1); + CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null); + + s1.addElement(signingMsg); + } + + byte encoded[] = ASN1Util.encode(s1); + + BASE64Encoder encoder = new BASE64Encoder(); + String Req1 = encoder.encodeBuffer(encoded); + + // Set CRMF_REQUEST variable + CRMF_REQUEST = Req1; + + System.out.println("CRMF_REQUEST = " + CRMF_REQUEST); + + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + e.printStackTrace(); + return null; + } + + return CRMF_REQUEST; + } + + /* + * This function is used to Generated CRMF requests wrapped with the + * transport cert so that we can do key archival with the drm. + * This function expects transportcert variable to be set in this class. + * Use setTransportCert() to do the same. + */ + + public String generateCRMFtransport() { + + boolean success = false; + int num = 1; + long total_time = 0; + KeyPair pair = null; + + try { + // Step 1. initialize crypto Manager + try { + CryptoManager.initialize(cdir); + } catch (Exception e) { + // it is ok if it is already initialized + System.out.println("INITIALIZATION ERROR: " + e.toString()); + System.out.println("cdir = " + cdir); + } + + // Step 2 log into database + try { + + System.out.println("Debug : before getInstance"); + + manager = CryptoManager.getInstance(); + String token_pwd = tokenpwd; + + System.out.println("Debug : before get token"); + + token = manager.getInternalKeyStorageToken(); + password = new Password(token_pwd.toCharArray()); + + System.out.println("Debug : before login password"); + + token.login(password); + + System.out.println("Debug : after login password"); + } catch (Exception e) { + System.out.println("INITIALIZATION ERROR: " + e.toString()); + + if (!token.isLoggedIn()) { + token.initPassword(password, password); + } + } + + // Key Pair Generation + KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA); + Integer x = new Integer(keysize); + int key_len = x.intValue(); + + kg.initialize(key_len); + + pair = kg.genKeyPair(); + + // wrap private key + BASE64Decoder decoder = new BASE64Decoder(); + byte transport[] = decoder.decodeBuffer(transportcert); + + X509Certificate tcert = manager.importCACertPackage(transport); + + byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1}; + + KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3); + SymmetricKey sk = kg1.generate(); + + // wrap private key using session + KeyWrapper wrapper1 = token.getKeyWrapper( + KeyWrapAlgorithm.DES3_CBC_PAD); + + wrapper1.initWrap(sk, new IVParameterSpec(iv)); + + byte key_data[] = wrapper1.wrap(( + org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()); + + // wrap session using transport + KeyWrapper rsaWrap = token.getKeyWrapper(KeyWrapAlgorithm.RSA); + + rsaWrap.initWrap(tcert.getPublicKey(), null); + + byte session_data[] = rsaWrap.wrap(sk); + + // create CRMF + CertTemplate certTemplate = new CertTemplate(); + + certTemplate.setVersion(new INTEGER(2)); + + // Call getname to split certnickname aka cert subject name + getNames(); + + Name n = new Name(); + + if (CN != null) { + n.addCommonName(CN); + } + if (C != null) { + n.addCountryName(C); + } + if (L != null) { + n.addLocalityName(L); + } + if (OU != null) { + n.addOrganizationalUnitName(OU); + } + if (O != null) { + n.addOrganizationName(O); + } + + certTemplate.setSubject(n); + + certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic())); + + // set extension + AlgorithmIdentifier algS = new AlgorithmIdentifier( + new OBJECT_IDENTIFIER("1.2.840.113549.3.7"), + new OCTET_STRING(iv)); + + EncryptedValue encValue = new EncryptedValue(null, algS, + new BIT_STRING(session_data, 0), null, null, + new BIT_STRING(key_data, 0)); + + EncryptedKey key = new EncryptedKey(encValue); + PKIArchiveOptions opt = new PKIArchiveOptions(key); + + SEQUENCE seq = new SEQUENCE(); + + seq.addElement( + new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"), opt)); + + CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate, + seq); + + // Adding proof of possesion data + byte popdata[] = { 0x0, 0x3, 0x0}; + ProofOfPossession pop = ProofOfPossession.createKeyEncipherment( + POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3))); + + CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null); + + SEQUENCE s1 = new SEQUENCE(); + + // 1st : Encryption key + s1.addElement(crmfMsg); + + // 2nd : Signing Key + + if (dualkey) { + System.out.println("dualkey = true"); + SEQUENCE seq1 = new SEQUENCE(); + CertRequest certReqSigning = new CertRequest(new INTEGER(1), + certTemplate, seq1); + CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null); + + s1.addElement(signingMsg); + } + + byte encoded[] = ASN1Util.encode(s1); + + BASE64Encoder encoder = new BASE64Encoder(); + + CRMF_REQUEST = encoder.encodeBuffer(encoded); + + System.out.println("Generated crmf request: ...... "); + System.out.println(""); + + System.out.println(CRMF_REQUEST); + System.out.println(""); + System.out.println("End crmf Request:"); + } catch (Exception e) { + System.out.println("Exception: " + e.getMessage()); + } + + return CRMF_REQUEST; + } + +} // end of class + diff --git a/pki/base/silent/src/common/Con2Agent.java b/pki/base/silent/src/common/Con2Agent.java new file mode 100644 index 000000000..bbf7a12b2 --- /dev/null +++ b/pki/base/silent/src/common/Con2Agent.java @@ -0,0 +1,329 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + +import org.mozilla.jss.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import sun.misc.*; +import java.lang.Exception; +import java.security.*; +import java.net.URLEncoder; + + +/** + * CMS Test framework . + * Submits a requests to agent port with sslclient authentication. + */ + +public class Con2Agent implements SSLClientCertificateSelectionCallback, + SSLCertificateApprovalCallback { + + private int i, port; + private String host, certdir, certnickname, tokenpwd, certname, query; + private String ACTIONURL; + + private BufferedReader stdin = null; + private StringBuffer stdout = new StringBuffer(); + + public Con2Agent() {} + + /** + *Constructor. Takes hostname , portnumber , certificate nickname, token password ,client certdb directory + * @param hostname + * @param portnumber + * @param agent cert nickname + * @param token password + * @param certdb directory + */ + + + public Con2Agent(String hs, int p, String cname, String tpwd, String cdir) { + host = hs; + port = p; + certnickname = cname; + tokenpwd = tpwd; + certdir = cdir; + } + + public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) { + return true; + } + + public String select(Vector nicknames) { + Enumeration e = nicknames.elements(); + + System.out.println("nicknames size = " + nicknames.size()); + int i = 0; + + while (e.hasMoreElements()) { + String s = (String) e.nextElement(); + + i++; + } + + if (i > 0) { + return (String) nicknames.elementAt(0); + } else { + return null; + } + + } + + // Get and Set methods + + /* + * Get the page returned by the server + */ + + public StringBuffer getPage() { + return stdout; + } + + /* + * Set the query string to be submitted to the server + */ + + public void setQueryString(String qu) { + query = qu; + } + + /* + *Set token password + */ + + public void setTokenPassword(String pwd) { + tokenpwd = pwd; + } + + /* + * Set Client cert database + */ + + public void setCertDBDir(String cdir) { + certdir = cdir; + } + + /* + * Set host name + */ + + public void setHost(String hs) { + host = hs; + } + + /* + * set Agent port number + */ + + public void setPort(int p) { + port = p; + } + + /* + * Set Agent cert nickname + */ + + public void setCertNickName(String cname) { + certnickname = cname; + } + + /* + * Set action URL + */ + + public void setActionURL(String url) { + ACTIONURL = url; + } + + // Submit requests + + public boolean Send() { + boolean st = false; + + try { + + if (!loginCertDB()) { + return false; + } + + SSLSocket socket = new SSLSocket(host, port, null, 0, this, null); + + System.out.println("Con2Agent.java: host = " + host); + System.out.println("Con2Agent.java: port = " + port); + System.out.println("Con2Agent.java: certnickname = " + certnickname); + + socket.setClientCertNickname(certnickname); + System.out.println("Connected to the socket"); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + System.out.println(ACTIONURL); + System.out.println("Query :" + query); + ps.println("POST " + ACTIONURL + " HTTP/1.0"); + ps.println("Connection: Keep-Alive"); + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " + query.length()); + ps.println(""); + ps.println(query); + ps.println("\r"); + ps.flush(); + os.flush(); + BufferedReader stdin1 = new BufferedReader( + new InputStreamReader(socket.getInputStream())); + String line; + + while ((line = stdin1.readLine()) != null) { + stdout.append(line + "\n"); + System.out.println(line); + } + + // Send Connection: close to let the server close the connection. + // Else the socket on the server side continues to remain in TIME_WAIT state + + ps.println("Connection: close"); + ps.flush(); + os.flush(); + os.close(); + rawos.close(); + ps.close(); + stdin1.close(); + socket.close(); + + if (socket.isClosed()) { + System.out.println("Con2Agent.java : Socket is Closed"); + } else { + System.out.println("Con2Agent.java : Socket not Closed"); + } + + } catch (Exception e) { + System.out.println("some exception: in Send routine" + e); + return false; + } + + return true; + + } + + private boolean loginCertDB() { + CryptoManager manager; + Password pass1 = null, pass2 = null; + + try { + System.out.println("Step 1: Initializing CryptoManager"); + CryptoManager.initialize(certdir); + + System.out.println("Step 2: Login to Cert Database"); + manager = CryptoManager.getInstance(); + CryptoToken token = (PK11Token) manager.getInternalKeyStorageToken(); + + if (token.isLoggedIn()) { + System.out.println("Con2Agent: Logged in incorrect"); + } + + System.out.println("tokenpwd:" + tokenpwd); + char[] passchar1 = new char[tokenpwd.length()]; + + tokenpwd.getChars(0, tokenpwd.length(), passchar1, 0); + + pass1 = new Password((char[]) passchar1.clone()); + token.login(pass1); + + X509Certificate cert2 = manager.findCertByNickname(certnickname); + + certname = cert2.getNickname(); + return true; + + } catch (AlreadyInitializedException e) { + System.out.println("Crypto manager already initialized"); + return true; + } catch (NumberFormatException e) { + System.err.println("Invalid key size: " + e); + return false; + } catch (java.security.InvalidParameterException e) { + System.err.println("Invalid key size: " + e); + return false; + + } catch (Exception e) { + System.err.println("some exception:" + e); + e.printStackTrace(); + return false; + } + + } + + public boolean Send_withGET() { + + boolean st = false; + + try { + + if (!loginCertDB()) { + return false; + } + + SSLSocket socket = new SSLSocket(host, port, null, 0, this, null); + + socket.setClientCertNickname(certnickname); + System.out.println("Connected to the socket"); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + System.out.println("Query in con2agent :" + query); + System.out.println("ACTIONURL in con2agent : " + ACTIONURL); + + ps.println("GET " + ACTIONURL + query + " HTTP/1.0"); + ps.println(""); + ps.println("\r"); + ps.flush(); + os.flush(); + BufferedReader stdin2 = new BufferedReader( + new InputStreamReader(socket.getInputStream())); + String line; + + while ((line = stdin2.readLine()) != null) { + stdout.append(line + "\n"); + } + stdin2.close(); + + socket.close(); + + } catch (Exception e) { + System.err.println("some exception: in Send routine" + e); + return false; + } + + return true; + + } + +} // end of class diff --git a/pki/base/silent/src/common/ParseXML.java b/pki/base/silent/src/common/ParseXML.java new file mode 100644 index 000000000..e80c512d0 --- /dev/null +++ b/pki/base/silent/src/common/ParseXML.java @@ -0,0 +1,165 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import org.w3c.dom.*; +import org.apache.xml.serialize.*; + +import javax.xml.parsers.*; +import java.util.*; +import java.io.*; +import java.net.*; + + +public class ParseXML { + Document dom = null; + + public ParseXML() {// nothing + } + + public void parse(java.io.InputStream is) { + try { + // get the factory + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + + // Using factory get an instance of document builder + DocumentBuilder db = dbf.newDocumentBuilder(); + + // parse using builder to get DOM representation of the XML file + dom = db.parse(is); + } catch (Exception se) { + System.out.println("ERROR: unable to parse xml"); + se.printStackTrace(); + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + StringBuilder sb = new StringBuilder(); + String line = null; + + while ((line = br.readLine()) != null) { + sb.append(line + "\n"); + } + + br.close(); + System.out.println("ERROR XML = " + sb.toString()); + } catch (Exception se1) { + System.out.println("ERROR: unable to print xml"); + se1.printStackTrace(); + } + } + } + + public String getvalue(String tag) { + String temp = null; + + try { + + // get the root elememt + Element docEle = dom.getDocumentElement(); + + // get a nodelist of <employee> elements + NodeList nl = docEle.getElementsByTagName(tag); + + if (nl != null && nl.getLength() > 0) { + Element el = (Element) nl.item(0); + + if (el != null) { + temp = el.getFirstChild().getNodeValue(); + } + } + } catch (Exception e) { + System.out.println("ERROR: Tag=" + tag + "has no values"); + return null; + } + + return temp; + } + + public void prettyprintxml() { + try { + // Serialize the document + OutputFormat format = new OutputFormat(dom); + + format.setLineWidth(65); + format.setIndenting(true); + format.setIndent(2); + XMLSerializer serializer = new XMLSerializer(System.out, format); + + serializer.serialize(dom); + } catch (Exception e) {} + } + + private String getTextValue(Element ele, String tagName) { + String textVal = null; + NodeList nl = ele.getElementsByTagName(tagName); + + if (nl != null && nl.getLength() > 0) { + Element el = (Element) nl.item(0); + + textVal = el.getFirstChild().getNodeValue(); + } + + return textVal; + } + + // returns an arraylist of values for the corresponding tag + + public ArrayList constructvaluelist(String first, String second) { + String temp = null; + ArrayList al = new ArrayList(); + + try { + // get the root elememt + Element docEle = dom.getDocumentElement(); + + // get a nodelist of <employee> elements + NodeList nl = docEle.getElementsByTagName(first); + + if (nl != null && nl.getLength() > 0) { + for (int i = 0; i < nl.getLength(); i++) { + Element el = (Element) nl.item(i); + String value = getTextValue(el, second); + + System.out.println("tag=" + second + " value=" + value); + if (value != null) { + al.add(value); + } + } + } + } catch (Exception e) { + System.out.println("ERROR: Tag=" + first + " has no values"); + } + + return al; + } + + public static void main(String args[]) { + try { + + ParseXML px = new ParseXML(); + FileInputStream fiscfg = new FileInputStream("/tmp/test.xml"); + + px.parse(fiscfg); + px.prettyprintxml(); + + } catch (Exception e) {} + } + +} + + +; // end class diff --git a/pki/base/silent/src/common/PostQuery.java b/pki/base/silent/src/common/PostQuery.java new file mode 100644 index 000000000..378eeeef6 --- /dev/null +++ b/pki/base/silent/src/common/PostQuery.java @@ -0,0 +1,134 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; + + +/** + * CMS Test framework . + * This class submits request to admin server after authenticating with UID and Password. You can get back the response by calling the method. getPage(). + */ + + + +public class PostQuery { + + private boolean st; + private String NmcStatus = "NMC_STATUS: 0"; + private String postQuery = null; + private String adminID, adminPWD, URLString; + + private StringBuffer stdout = new StringBuffer(); + + /** + * Constructor . Takes the parameters urlstring("http://hostname:<portnumber> , Id for authenticating to the server, password for authentication to the server and query which needs to be submitted to the server + */ + + public PostQuery(String urlstr, String authid, String authpwd, String querystring) { + + URLString = urlstr; + adminID = authid; + adminPWD = authpwd; + postQuery = querystring; + + } + + public void setNMCStatus(String m) { + NmcStatus = m; + } + + public void setPostQueryString(String querystring) { + postQuery = querystring; + } + + public void setAuth(String ID, String Pwd) { + adminID = ID; + adminPWD = Pwd; + } + + public StringBuffer getPage() { + return stdout; + } + + public boolean Send() { + // / This functions connects to the URL and POST HTTP Request . + // It compares with NMC_STATUS and return the status. + System.out.println(URLString); + st = false; + + try { + + BufferedReader mbufferedReader = null; + URL myUrl = new URL(URLString); + String userPassword = adminID + ":" + adminPWD; + + System.out.println("adminid=" + adminID); + System.out.println("adminpwd=" + adminPWD); + String encoding = new sun.misc.BASE64Encoder().encode( + userPassword.getBytes()); + HttpURLConnection URLCon = (HttpURLConnection) myUrl.openConnection(); + + URLCon.setRequestProperty("Authorization", "Basic " + encoding); + URLCon.setDoOutput(true); + URLCon.setDoInput(true); + URLCon.setUseCaches(false); + URLCon.setRequestProperty("Content-type", + "application/x-www-form-urlencoded"); + // URLCon.setRequestMethod("POST"); + System.out.println("After post"); + + DataOutputStream os = new DataOutputStream(URLCon.getOutputStream()); + + System.out.println("Query: " + postQuery); + + int querylength = postQuery.length(); + + os.writeBytes(postQuery); + os.flush(); + os.close(); + + InputStream Content = (InputStream) URLCon.getInputStream(); + + System.out.println("Configuring Cert Instance : Return Response"); + BufferedReader in = new BufferedReader( + new InputStreamReader(Content)); + String line; + + while ((line = in.readLine()) != null) { + System.out.println(line); + stdout.append(line + "\n"); + st = line.startsWith(NmcStatus); + if (st) { + break; + } + } + URLCon.disconnect(); + } // try + catch (MalformedURLException e) { + System.out.println(URLString + " is not a valid URL."); + + } catch (IOException e) { + System.out.println("exception : " + e.getMessage()); + } + System.out.println(st); + return st; + } + +} diff --git a/pki/base/silent/src/common/ServerInfo.java b/pki/base/silent/src/common/ServerInfo.java new file mode 100644 index 000000000..09d3e4759 --- /dev/null +++ b/pki/base/silent/src/common/ServerInfo.java @@ -0,0 +1,375 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; + + +/** + * CMS Test framework . + * This class fetches all the necssary ServerInformation to run the test . For example AdminServer information linke port , hsotname, Config LDAP server port, CMS servers Agentport,AdminPort, EESSL port, EE port etc.. + */ + + +public class ServerInfo { + + public String serverRoot, instanceRoot, instanceID; + public String ldapPort, ldapHost, ldapSSLPort, ldapBaseSuffix, adminPort, admDN, admDNPW, singleSignOnPWD, domain; + public String caSigningCertNickName, raSigningCertNickName, ocspSigningCertNickName, kraTransportCertNickName; + public String ServerCertNickName, CertAuthority; + public String CMSAgentPort, CMSEESSLPort, CMSEEPort, CMSAdminPort, IDBPort; + + public static CMSProperties props = null; + public static CMSProperties CMSprops = null; + + // Private variables + private int i; + public String CMSConfigFile, AdminConfigFile; + + public ServerInfo() {} + + /** + * Constructor. Takes Server root as parameter for example ( /export/qa). Reads and collects information about adminserver and Config LDAP server. + */ + public ServerInfo(String sroot) { + serverRoot = sroot; + AdminConfigFile = serverRoot + "/admin-serv/config/adm.conf"; + readAdminConfig(); + SystemInfo(); + } + + /** + * Constructor. Takes Serverroot ( /export/qa) and instanceRoot (/export/qa/cert-jupiter2) as parameters . Reads and collects information about Admin Server , Config LDAP server and CMS server . + */ + + + public ServerInfo(String sroot, String instRoot) { + serverRoot = sroot; + instanceRoot = instRoot; + CMSConfigFile = instanceRoot + "/config/CS.cfg"; + AdminConfigFile = serverRoot + "/admin-serv/config/adm.conf"; + instanceID = instanceRoot.substring(instanceRoot.indexOf("cert-") + 5); + readAdminConfig(); + SystemInfo(); + parseServerXML(); + readCMSConfig(); + } + + public String GetAdminPort() { + return adminPort; + } + + public String GetConfigLDAPPort() { + return ldapPort; + } + + public String GetHostName() { + if (domain.indexOf(".") > 0) { + return domain.substring(0, domain.indexOf(".")); + } else { + return domain; + } + } + + public String GetInstanceID() { + return instanceID; + } + + public String GetCMSConfigFileName() { + return CMSConfigFile; + } + + public String GetDomainName() { + return ldapHost.substring(ldapHost.indexOf(".") + 1); + } + + public String GetAgentPort() { + return CMSAgentPort; + } + + public String GetEESSLPort() { + return CMSEESSLPort; + } + + public String GetEEPort() { + return CMSEEPort; + } + + public String GetCMSAdminPort() { + return CMSAdminPort; + } + + public String GetInternalDBPort() { + return IDBPort; + } + + public String GetCertAuthority() { + return CertAuthority; + } + + public String GetCASigningCert() { + return caSigningCertNickName; + } + + public String GetRASigningCert() { + return raSigningCertNickName; + } + + public String GetServerCertNickName() { + return ServerCertNickName; + } + + public void setInstanceRoot(String instRoot) { + instanceRoot = instRoot; + CMSConfigFile = instanceRoot + "/config/CS.cfg"; + AdminConfigFile = serverRoot + "/admin-serv/config/adm.conf"; + instanceID = instanceRoot.substring(instanceRoot.indexOf("cert-") + 5); + SystemInfo(); + parseServerXML(); + readCMSConfig(); + } + + // Private functions + private void SystemInfo() { + try { + domain = InetAddress.getLocalHost().getHostName(); + System.out.println("Debu:SystemInfo " + domain); + } catch (Exception e) { + System.out.println("Exception InetAddress : " + e.getMessage()); + } + + } + + private void parseServerXML() { + int AGENT = 1; + int ADMIN = 2; + int EE_SSL = 3; + int EE_NON_SSL = 4; + int IP = 5; + int PORT = 6; + BufferedReader in = null; + + try { + String xmlFilePath = instanceRoot + "/config/server.xml"; + + in = new BufferedReader(new FileReader(xmlFilePath)); + String s = in.readLine(); + + while (s != null) { + // <SSLPARAMS servercertnickname="Server-Cert cert-firefly" + int index = s.indexOf("servercertnickname"); + + if (index >= 0) { + String str = s.substring(index + 20); + StringTokenizer tokenizer = new StringTokenizer(str, "\""); + + if (tokenizer.hasMoreElements()) { + String mServerCertNickname = tokenizer.nextToken(); + } + } + + // <LS id="agent" ip="0.0.0.0" port="8101" security="on" + // acceptorthreads="1" blocking="no"> + if (s.startsWith("<LS id=")) { + StringTokenizer st = new StringTokenizer(s, "\""); + int index1 = 5, index2 = 3; + + while (st.hasMoreTokens()) { + String token = st.nextToken(); + + if (token.equalsIgnoreCase("agent")) { + index1 = AGENT; + } else if (token.equalsIgnoreCase("admin")) { + index1 = ADMIN; + } else if (token.equalsIgnoreCase("eeSSL")) { + index1 = EE_SSL; + } else if (token.equalsIgnoreCase("ee_nonSSL")) { + index1 = EE_NON_SSL; + } else if (token.equals(" ip=")) { + index2 = IP; + } else if (token.equals(" port=")) { + index2 = PORT; + } + + if (index1 != 5 && index2 == IP && !token.equals(" ip=")) { + String ip = token; + } else if (index2 == PORT && !token.equals(" port=")) { + + switch (index1) { + case 1: + CMSAgentPort = token; + break; + + case 2: + CMSAdminPort = token; + break; + + case 3: + CMSEESSLPort = token; + break; + + case 4: + CMSEEPort = token; + break; + + default: + break; + + } + + break; + } + } // while token + } // if LS + s = in.readLine(); + } // while file no end + in.close(); + } catch (Exception e) { + if (in != null) { + try { + in.close(); + } catch (Exception ex) {} + } + } + } + + private void getProperties(String filePath) throws Exception { + try { + FileInputStream fis = new FileInputStream(filePath); + + props = new CMSProperties(); + props.load(fis); + System.out.println("Reading Properties file successful"); + fis.close(); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + private String stripSpace(String s) { + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == ' ')) { + i++; + continue; + } else { + val += s.charAt(i); + } + } + return val; + } + + private void readAdminConfig() { + String ldapHostStr = "ldapHost:"; + String ldapPortStr = "ldapPort:"; + String adminPortStr = "port:"; + + try { + FileInputStream fis = new FileInputStream(AdminConfigFile); + int size = fis.available(); + byte b[] = new byte[size]; + + if (fis.read(b) != b.length) { + System.out.println("Could not read "); + + } else { + String tmpstr = new String(b, 0, b.length); + int ret; + + if ((ret = tmpstr.indexOf(ldapHostStr)) > -1) { + ldapHost = tmpstr.substring(ret + ldapHostStr.length() + 1, + tmpstr.indexOf("ldapPort", ret) - 1); + ldapHost = stripSpace(ldapHost); + // System.out.println(ldapPort); + } + + if ((ret = tmpstr.indexOf(ldapPortStr)) > -1) { + ldapPort = tmpstr.substring(ret + ldapPortStr.length() + 1, + tmpstr.indexOf("sie", ret) - 1); + ldapPort = stripSpace(ldapPort); + // System.out.println(ldapPort); + } + if ((ret = tmpstr.indexOf(adminPortStr)) > -1) { + adminPort = tmpstr.substring(ret + adminPortStr.length() + 1, + tmpstr.indexOf("ldapStart", ret) - 1); + adminPort = stripSpace(adminPort); + // System.out.println(adminPort); + } + + } + + fis.close(); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + private void readCMSConfig() { + + try { + FileInputStream fis = new FileInputStream(CMSConfigFile); + + CMSprops = new CMSProperties(); + CMSprops.load(fis); + System.out.println("Reading CMS Config file successful"); + CertAuthority = CMSprops.getProperty("subsystem.0.id"); + if (CertAuthority.equals("ca")) { + caSigningCertNickName = CMSprops.getProperty( + "ca.signing.cacertnickname"); + ServerCertNickName = "Server-Cert cert-" + instanceID; + } + if (CertAuthority.equals("ra")) { + raSigningCertNickName = CMSprops.getProperty( + "ra.signing.cacertnickname"); + ServerCertNickName = "Server-Cert cert-" + instanceID; + } + IDBPort = CMSprops.getProperty("internaldb.ldapconn.port"); + + fis.close(); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + public static void main(String args[]) { + ServerInfo s = new ServerInfo("Test", "Test"); + + System.out.println(" Admin Port : " + s.GetAdminPort()); + System.out.println(" LDAP Port : " + s.GetConfigLDAPPort()); + System.out.println("Hostname " + s.GetHostName()); + System.out.println("InstanceID" + s.GetInstanceID()); + System.out.println(" doamin name : " + s.GetDomainName()); + System.out.println("AgentPort " + s.GetAgentPort()); + System.out.println("EESSLPort " + s.GetEESSLPort()); + System.out.println("EEPort " + s.GetEEPort()); + System.out.println("CMSAdminPort :" + s.GetCMSAdminPort()); + System.out.println("CAAuthority : " + s.GetCertAuthority()); + System.out.println("CASigningCert:" + s.GetCASigningCert()); + System.out.println("RASigningCert:" + s.GetRASigningCert()); + System.out.println("ServerCert" + s.GetServerCertNickName()); + + }// end of function main + +} // end of class + diff --git a/pki/base/silent/src/common/TestClient.java b/pki/base/silent/src/common/TestClient.java new file mode 100644 index 000000000..e953f09f7 --- /dev/null +++ b/pki/base/silent/src/common/TestClient.java @@ -0,0 +1,978 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; +import java.util.*; +import java.math.*; + +import org.mozilla.jss.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +// import sun.misc.*; +import java.lang.Exception; + + +/** + * CMS Test framework . + * Before createing an instance of this class make sure you havae set an environment variable TEST_CONFIG_FILE. + */ + + + +public class TestClient implements SSLCertificateApprovalCallback { + + public int port; + + // properties file parameters + public static String host, ports, adminid, adminpwd, propfileName, cdir; + public static String certnickname, keysize, keytype, tokenpwd; + public static String serverRoot, instanceRoot, ldaprootDN, ldaprootDNPW, caInstanceRoot, dataDirectory; + + // Program variables + public String STATUS; + public Properties props = null; + public String ACTION_STRING; + public String query; + public boolean debug = false; + // Certificate nicknames to be used by Test Clients + private int i; + private String testConfigFile; + + public String caAgentCertName = "ca-agent"; + public String raAgentCertName = "ra-agent"; + public String ocspAgentCertName = "ocsp-agent"; + public String kraAgentCertName = "kra-agent"; + public String tksAgentCertName = "tks-agent"; + public String singleSignOnPWD = "secret12"; + public String adminCertName = "cn=admin"; + private String ldapBaseSuffix = "dc=netscape,dc=com"; + private String admDN = "admin"; + private String admDNPW = "admin"; + private String TmpDir; + private String TestLogFile; + private String startupTests, cleanupTests; + + private X509Certificate SSLServerCert = null; + + // Cert Sub vart + public String UID, OU, O, DN, E, CN, C, GN, SN, L, MAIL; + // Enroll + String PWD; + // CRypto + public ComCrypto cCrypt = new ComCrypto(); + public String pkcs10request = null; + + // Error + + public String ErrorDetail; + + private String serverKeyType, serverKeySize, serverKeyAlgo; + + private String unauth[] = { + "Unauthorized Access", "Server Error", + "Not Found", "Generic Unauthorized"}; + + public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) { + SSLServerCert = x509; + return true; + } + + // Constructor + + + public TestClient() { + keysize = "1024"; + keytype = "RSA"; + } + + /** + * Constructor . Takes the parameter for keysize and keytype . + * Before creating a new instance of this class make sure you have set TEST_CONFIG_FILE variable in your environnemt. + * Reads the TEST_CONFIG_FILE . Initializes the certificate database. See engage.cfg file for example. + * @param keysize + * @param keytype + */ + + + public TestClient(String ks, String kt) { + + testConfigFile = ReadEnv("TEST_CONFIG_FILE"); + + System.out.println(testConfigFile); + readConfigFile(); + keysize = ks; + keytype = kt; + cCrypt.setCertDir(cdir); + cCrypt.setCertnickname(adminCertName); + cCrypt.setKeySize(keysize); + cCrypt.setKeyType(keytype); + cCrypt.setTokenPWD(tokenpwd); + cCrypt.setDebug(true); + cCrypt.CreateCertDB(); + + } + + /** + * Gets the SSLServer Certificate of the server + */ + + public X509Certificate getSSLServerCert() { + return SSLServerCert; + } + + /** + * finds the cert with nickname cname in the clients cert database + */ + + public X509Certificate findCertByNickname(String cname) { + + return cCrypt.findCert(cname); + + } + + /** + * Imports certificate to cert database.Takes parameters Certpackage and certnickname + */ + boolean importCert(String cp, String nickname) { + + return cCrypt.importCert(cp, nickname); + + } + + /** + * This function returns true if you choose to executeStartupTests + */ + + public boolean executeStartupTests() { + + if (startupTests == null) { + return false; + } else if (startupTests.equals("y")) { + return true; + } else { + return false; + } + + } + + /** + * This function returns true if you choose to executeCleanupTests + */ + + + public boolean executeCleanupTests() { + + if (cleanupTests == null) { + return false; + } else if (cleanupTests.equals("y")) { + return true; + } else { + return false; + } + + } + + public String GetServerRoot() { + return serverRoot; + } + + public String GetInstanceRoot() { + return instanceRoot; + } + + public String getErrorDetail() { + return ErrorDetail; + } + + public String GetAdminDN() { + return admDN; + } + + public String GetAdminDNPWD() { + return admDNPW; + } + + public String GetLDAPDN() { + return ldaprootDN; + } + + public String GetLDAPDNPW() { + return ldaprootDNPW; + } + + public String GetLDAPBASE() { + return ldapBaseSuffix; + } + + public String GetAdminCertName() { + return adminCertName; + } + + public String GetRAAgentCertName() { + return raAgentCertName; + } + + public String GetKRAAgentCertName() { + return kraAgentCertName; + } + + public String GetOCSPAgentCertName() { + return ocspAgentCertName; + } + + public String GetTKSAgentCertName() { + return tksAgentCertName; + } + + public String GetDataDirectory() { + return dataDirectory; + } + + public String GetClientCertDB() { + return cdir; + } + + public String GetClientCertDBPW() { + return tokenpwd; + } + + public String GetSingleSignOnPW() { + return singleSignOnPWD; + } + + public String GetCARoot() { + return caInstanceRoot; + } + + public String GetTmpDir() { + return TmpDir; + } + + public String GetServerKeySize() { + return serverKeySize; + } + + public String GetServerKeyType() { + return serverKeyType; + } + + public String GetServerKeyAlgorithm() { + return serverKeyAlgo; + } + + public void setStatusString(String ststr) { + STATUS = ststr; + } + + public void setDebug(boolean t) { + debug = t; + } + + public void setpkcs10Request(String t) { + pkcs10request = t; + } + + public void setHostName(String s) { + host = s; + } + + public void setCARoot(String s) { + caInstanceRoot = s; + } + + public void setTestLogFile(String s) { + TestLogFile = s; + } + + /** + * parses a http page and returns true if any error is returned by server + **/ + + public boolean getError(String line) { + + int ret; + + ret = line.indexOf("fixed.errorDetails"); + + if (line.indexOf("fixed.errorDetails") == 0) { + ErrorDetail = line.substring( + ret + ("fixed.errorDetails = ").length()); + return true; + } + + if (line.indexOf("fixed.errorDetails") >= 0) { + ErrorDetail = line.substring( + ret + ("fixed.errorDetails = ").length()); + return true; + } + + ret = line.indexOf("fixed.unexpectedError"); + + if (line.indexOf("fixed.unexpectedError") == 0) { + System.out.println("Processing unexpectedError"); + ErrorDetail = line.substring( + ret + ("fixed.unexpectedError = ").length()); + return true; + } + + if (line.indexOf(unauth[0]) > 0) { + ErrorDetail = unauth[0]; + return true; + } + if (line.indexOf(unauth[1]) > -1) { + ErrorDetail = unauth[1]; + return true; + } + if (line.indexOf(unauth[2]) > -1) { + ErrorDetail = unauth[2]; + return true; + } + if (line.indexOf(unauth[3]) > -1) { + ErrorDetail = unauth[3]; + return true; + } + + if (line.indexOf("errorReason") >= 0) { + ErrorDetail = line.substring(ret + ("errorReason=").length()); + return true; + } + + return false; + } + + /** + * Reads a properties file . Takes filename as input parameter. + */ + + public void getProperties(String fileName) throws Exception { + try { + FileInputStream fis = new FileInputStream(fileName); + + props = new Properties(); + props.load(fis); + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + } + + } + + public String ReadEnv(String str) { + try { + Process p = null; + Runtime r = Runtime.getRuntime(); + String OS = System.getProperty("os.name").toLowerCase(); + + if (OS.indexOf("windows") > 1) { + p = r.exec("cmd.exe /c set"); + } else { + p = r.exec("env"); + } + + BufferedReader br = new BufferedReader( + new InputStreamReader(p.getInputStream())); + String line; + + while ((line = br.readLine()) != null) { + int idx = line.indexOf('='); + String key = line.substring(0, idx); + String value = line.substring(idx + 1); + + // System.out.println(key + "=" + value); + if (key.startsWith(str)) { + return value; + } + } + return null; + } catch (Throwable e) { + e.printStackTrace(); + } + return null; + } + + private void readConfigFile() { + try { + getProperties(testConfigFile); + } catch (Exception e) { + System.out.println( + "exception reading TestConfigFile " + e.getMessage()); + } + + serverRoot = props.getProperty("SROOT"); + instanceRoot = props.getProperty("IROOT"); + dataDirectory = props.getProperty("DATA_DIR"); + ldapBaseSuffix = props.getProperty("LDAPBASESUFFIX"); + + if (ldapBaseSuffix.indexOf("\"") > -1) { + ldapBaseSuffix = ldapBaseSuffix.substring(1, + ldapBaseSuffix.length() - 1); + } + + ldaprootDN = props.getProperty("LDAPROOTDN"); + // Strip of th e quotes "cn=directory manager" string + if (ldaprootDN.indexOf("\"") > -1) { + ldaprootDN = ldaprootDN.substring(1, ldaprootDN.length() - 1); + } + System.out.println("ldaprootDN : " + ldaprootDN); + + ldaprootDNPW = props.getProperty("LDAPROOTDNPW"); + cdir = props.getProperty("CERTDB"); + tokenpwd = props.getProperty("CERTDBPW"); + caInstanceRoot = props.getProperty("CAIROOT"); + admDN = props.getProperty("ADMINDN"); + admDNPW = props.getProperty("ADMINDNPW"); + singleSignOnPWD = props.getProperty("SINGLESIGNONPW"); + serverKeySize = props.getProperty("KEYSIZE"); + serverKeyType = props.getProperty("KEYTYPE"); + serverKeyAlgo = props.getProperty("KEYALGORITHM"); + + TmpDir = props.getProperty("TMP_DIR"); + TestLogFile = props.getProperty("TEST_LOG_FILE"); + + String de = props.getProperty("DEBUG"); + + if (de == null) { + debug = false; + } else if (de.equals("true")) { + debug = true; + } else { + debug = false; + } + + } + + /** + * returns a String representation of an interger + */ + public String getString(int m) { + Integer x = new Integer(m); + String s = x.toString(); + + return s; + } + + private static boolean isSocketUnused(String h, int p) { + + try { + + Socket ss = new Socket(h, p); + + ss.close(); + return false; + + } catch (IOException e) { + return true; + } + } + + /** + * returns FreePort in this machine . Takes a parmater portnumber. For example getFreePort("4026"). + */ + public String getFreePort(String s) { + Integer x = new Integer(s); + int p = x.intValue(); + boolean st = true; + + // if p = 0, then the serversocket constructor get a free port by itself + p = 0; + try { + ServerSocket ss1 = new ServerSocket(p); + + p = ss1.getLocalPort(); + System.out.println("Obtained Free Port = " + p); + ss1.close(); + return (getString(p)); + } catch (Exception e) { + System.out.println("Unable to get Free Port"); + e.printStackTrace(); + p = 0; + return (getString(p)); + } + + // This following method doesn't Always get a free port. + // while (st) { + // if(isSocketUnused(host,p) ) + // st=false; + // p++; + // } + // return (getString(p)); + + } + + /** + * Reads a file and returns the cert request as string + **/ + + public String readRequest(String filename) { + try { + FileInputStream f1 = new FileInputStream(filename); + int size = f1.available(); + byte b[] = new byte[size]; + + if (f1.read(b) != b.length) { + return null; + } + + f1.close(); + String s = new String(b); + + return s; + } catch (Exception e) { + System.out.println("exception " + e.getMessage()); + return null; + } + } + + public static void main(String args[]) { + TestClient t = new TestClient("1024", "RSA"); + + /* + ******************************************************************* + * Sample programs to initialze calsses + ******************************************************************* + */ + + + /* + ******************************************************************** + * To Test AutoInstaller + ******************************************************************* + */ + + + /* + AutoInstaller a = new AutoInstaller(t.GetServerRoot()); + + ServerInfo s = new ServerInfo(t.GetServerRoot()); + System.out.println (" Admin Port : " + s.GetAdminPort()); + System.out.println (" LDAP Port : "+ s.GetConfigLDAPPort()); + System.out.println( "Hostname " + s.GetHostName()); + System.out.println(" doamin name : " + s.GetDomainName()); + + t.setHostName(s.GetHostName()); + // Set adminServer Info + a.setAdminInfo(s.GetHostName(),s.GetAdminPort(),s.GetDomainName(),"admin","admin"); + a.setAdminInfo(s.GetHostName(),s.GetAdminPort(),"mcom.com","admin","admin"); + + // setCAInfo + a.setCAInfo(s.GetHostName(),"1027","8100","admin","secret12"); + //setInternalDB info + String dp = t.getFreePort("38900"); + a.setInternalDBInfo(s.GetHostName(),"38907","ca-db","cn=directory manager","secret12" ); + + // set tokenInfo + + a.setTokenInfo("Internal","secret12"); + + // set Subsystem info + String agp = t.getFreePort("8100"); + String adp = t.getFreePort("8200"); + String eesp = t.getFreePort("1027"); + String eep = t.getFreePort("1100"); + + System.out.println(agp); + + a.setSubSystemInfo("testra",t.GetServerRoot(),"RSA","1024","MD5","365","cn=certificate manager,ou=test,o=test",adp,agp,eesp,eep); + + a.setClientDBInfo(t.GetClientCertDB(),"secret12",t.GetAdminCertName()); + + a.ConfigureCA("admin","admin","secret12","secret12"); + + // a.ConfigureRA("admin","admin","secret12","secret12"); + + */ + + /* + ****************************************************** + * Example to Get Server Details + ****************************************************** + */ + + + + ServerInfo s = new ServerInfo(t.GetServerRoot(), t.GetInstanceRoot()); + + t.setHostName(s.GetHostName()); + + System.out.println("AgentPort " + s.GetAgentPort()); + System.out.println("EESSLPort " + s.GetEESSLPort()); + System.out.println("EEPort " + s.GetEEPort()); + System.out.println("CMSAdminPort :" + s.GetCMSAdminPort()); + System.out.println("IDBPort : " + s.GetInternalDBPort()); + System.out.println("CAAuthority : " + s.GetCertAuthority()); + System.out.println("CASigningCert:" + s.GetCASigningCert()); + System.out.println("RASigningCert:" + s.GetRASigningCert()); + System.out.println("ServerCert" + s.GetServerCertNickName()); + System.out.println("------------------------------------------"); + System.out.println(" Internal Database Test:"); + System.out.println(" LDAP Port : " + s.GetConfigLDAPPort()); + System.out.println("Hostname " + s.GetHostName()); + + DirEnroll de = new DirEnroll(s.GetHostName(), s.GetEESSLPort()); + + de.setAuthenticator("Portal"); + de.setUIDInfo("caeetest110", "secret12"); + de.enroll(); + + /* **************************************************************** + * CMC Enroll + *************************************************************** + */ + + /* CMSUtils cmsutils = new CMSUtils(t.GetServerRoot()); + String requestfile="/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptance/data/basic/cmcreq/cmctest1.req"; + cmsutils.runCMCEnroll(t.GetClientCertDB(),"cn=admin",t.GetClientCertDBPW(),requestfile); + Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort()); + pr.setProfileType("caCMCUserCert"); + pr.setCertAuthority("ca"); + + String request = t.readRequest(requestfile+".out"); + String bstr = "-----BEGIN NEW CERTIFICATE REQUEST-----"; + String estr="-----END NEW CERTIFICATE REQUEST-----"; + String Blob1 = request.substring(bstr.length() + 1); + String Blob2 = Blob1.substring(0,Blob1.indexOf(estr)); + request=Blob2; + + + pr.setRequest(request); + + pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test","netscape","aol"); + pr.clientCertEnroll(); + */ + + + /* **************************************************************** + * OCSP Client stuff + ************************************************************ + */ + + /* + String ip= "10.169.25.26"; + OCSPClient ocspclient= new OCSPClient(s.GetHostName(),ip,s.GetEEPort(),t.GetClientCertDB(),t.GetClientCertDBPW(),"cn=admin" ,"/tmp/ocsp.out","4"); + ocspclient.setCert(t.findCertByNickname("ocsp-agent")); + + ocspclient.SendOCSPRequest(); + */ + + + /* + ***************************************************** + * Test CRMFcleint and KRA REcovery and Archival + ***************************************************** + */ + + /* + ********************************************************* + * OCSP Agent stuff + ********************************************************* + */ + + + /* Retrieval rtr = new Retrieval(s.GetHostName(),s.GetEESSLPort()); + rtr.getCACert(); + System.out.println("CA Cert chain" + rtr.getCert()); + + OcspAgent ocspAgent= new OcspAgent(s.GetHostName(),"8111"); + ocspAgent.setAgentCertName(t.GetOCSPAgentCertName()); + + String cert = "-----BEGIN CERTIFICATE-----"+"\n"+rtr.getCert()+"\n"+"-----END CERTIFICATE-----\n"; + + ocspAgent.setCACert(cert); + ocspAgent.addCA(); + */ + + + /* + *************************************************************** + Submit Profile based request + ********************************************************* + */ + + /* + Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort()); + pr.setProfileType("caUserCert"); + // pr.setProfileType("caDirUserCert"); + + pr.setCertAuthority("ca"); + pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test","netscape","aol"); + //pr.setDirUserInfo("test","netscape"); + pr.clientCertEnroll(); + System.out.println("Request ID is " + pr.getRequestID()); + + + Request re = new Request (s.GetHostName(),s.GetAgentPort(),"ca"); + re.setAgentCertName(t.GetAdminCertName()); + re.ApproveProfileRequests(pr.getRequestID()); + */ + + /* + String TransportCert="MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MjMyMTM3NTFaFw0wNDA0MjIwOTMzMzFaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANVW81T7GatHIB25kF0jdY4h4hOF1NAlAHE2YdN/UEyXuU22CfwrIltA3x/6sKFHhbbFysn6nGJlgKipPJqJDwyYTIv07hgoXqgcUu8fSYQg4BDHYhpHJxsUt3BSfADTjxAUHize7C2F8TVhBIcWW043FSkwvAiUjJb7uqQRKn7lAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBTqvc3UPGDSWq+21DZGSUABNGIUbDANBgkqhkiG9w0BAQQFAAOBgQCNLJivNDHTTmCb2vDefUwLMxXNjuHwrbjVqymHPFqUjredTq2Yp+Ed1zxj+mxRovzegd65Tbnx+MV84j8K3Qc1kWOC+kbohAY9svSPsN3o5Q5BB19+5nUPC5Gk/mxkWJWWJLOnpKJGiAHMZIr58TH7hF8KQWXWMN9ikSFkPj0a/g=="; + + + CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort()); + CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW()); + CrmfClient.setTransportCert(TransportCert); + CrmfClient.setUserInfo("user","netscape"); + CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW()); + CrmfClient.setDualKey(true); + + if(!CrmfClient.Enroll()) + {System.out.println("CRMFClient : could not submit request");} + + + checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),t.getString(CrmfClient.getRequestId()),"false"); + cr.checkRequestStatus(); + System.out.println("Serial num " + cr.getSerialNumber()); + System.out.println("cert pack " + cr.getCert()); + + KraAgent kraAgent = new KraAgent(s.GetHostName(),"8111"); + kraAgent.setAgentCertName("cn=admin"); + System.out.println("KRAAgent List archival"); + + Vector aReq= kraAgent.ListArchivalRequests(); + int i=0; + while(i < aReq.size() ) + { + System.out.print(aReq.elementAt(i) + " "); + i++; + } + + kraAgent.setCertificate(cr.getCert()); + kraAgent.setLocalAgent(false); + kraAgent.recoverKeys(); + */ + + /* + ************************************************************* + * Example to Connect oto Config Directory port + ************************************************************* + */ + + /* + CMSLDAP cmsldap = new CMSLDAP(s.GetHostName(),s.GetConfigLDAPPort(),t.GetLDAPDN(),t.GetLDAPDNPW()); + if(cmsldap.connect()) + System.out.println("LDAP Connection successful"); + else + System.out.println("Error Connecting to LDAPSERVER"); + + // Add user to config directoory + if (cmsldap.userAdd("ou=people,"+t.GetLDAPBASE(),"t2","t2","t2","netscape")) + System.out.println("Added user to Config directory"); + + */ + + + /* + ************************************************************* + * Example to Submit a CRMFCleint request to CA + ************************************************************* + */ + + String TransportCert = "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTgyMjMwMDhaFw0wNDA0MTcxMDI2MDhaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAN6sQ3mSU8mL6i6gTZIXDLzOZPhYOkQLpnJjit5hcPZ0JMn0CQVXo4QjKN1xvuZv8qVlZoQw9czmzp/knTa0sCDgFKd0r+u0TnLeZkJMSimgFnma9CnChlaDHnBd8Beu4vyaHmo7rJ0xA4etn7HjhmKbaQZOcv/aP0SW9JXRga7ZAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBSC3fsQHb7fddr2vL0UdkM2dAmUWzANBgkqhkiG9w0BAQQFAAOBgQBkAGbgd9HIqwoLKAr+V6bj9oWesDmDH80gPPxj10qyWSQYIs8PofOs/75yGS9nxhydtgSMFoBgCPdroUI31kZQQlFzxtudGoKD+5MWSXho79XzPwpjheOBYgpX6ch+L4tMLFDpqeraB1yZESO5EEeKm20DGVBOKVWxHhddO1BenA=="; + + /* + CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort()); + CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW()); + CrmfClient.setTransportCert(TransportCert); + CrmfClient.setUserInfo("user","netscape"); + CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW()); + CrmfClient.setDualKey(true); + + if(!CrmfClient.Enroll()) + {System.out.println("CRMFClient : could not submit request");} + */ + + /* KRA Agent list archived request */ + + /* ServerInfo KRAsvrInfo = new ServerInfo(t.GetServerRoot()); + String KRAinstanceRoot=t.GetServerRoot() + "/cert-" + "KRARSA1024" ; + KRAsvrInfo.setInstanceRoot(KRAinstanceRoot);*/ + + /* System.out.println("KRAAgent "); + KraAgent kraAgent = new KraAgent(s.GetHostName(),s.GetAgentPort()); + kraAgent.setAgentCertName(t.GetKRAAgentCertName()); + System.out.println("KRAAgent List archival"); + + Vector aReq= kraAgent.ListArchivalRequests(); + int i=0; + while(i < aReq.size() ) + { + System.out.print(aReq.elementAt(i) + " "); + i++; + } + + */ + + + // cmsldap.disconnect(); + + /* + ************************************************************* + * Example to submit manual user enrollment request + ************************************************************* + /* + + + /* + UserEnroll ue = new UserEnroll(s.GetHostName(),"1029"); + ue.setUserInfo("E=testman,CN=testman,OU=netscape,O=aol,UID=testman1,C=US","testman", "testman", "testman1", "netscape","t"); + + boolean flag = ue.clientCertEnroll(); + if(flag) + System.out.println("Success submitted request"); + */ + + /* + ************************************************************* + * Example to submit Directory based enroolemt request + ************************************************************* + /* + + /* + // Add user to config directoory + if (cmsldap.userAdd("dc=netscape,dc=com","t2","t2","t2","netscape")) + System.out.println("Success "); + + if(cmsldap.TurnOnSSL("slapd-jupiter2","Server-Cert cert-jupiter2","7000")) + System.out.println("Turned on ssl"); + else + return; + + cmsldap.TurnOffSSL(); + + cmsldap.disconnect(); + + DirEnroll de = new DirEnroll(s.GetHostName(),s.GetEESSLPort()); + de.setUIDInfo("t2","netscape"); + de.enroll(); + + */ + + /* + ************************************************************* + * Example to submit Admin Enrollment request + ************************************************************* + /* + + /* + + AdminEnroll ade = new AdminEnroll("jupiter2","8200","cn=CMS Administrator,UID=admin,C=US","admin", "secret12"); + flag = ade.Enroll(); + if (flag) + System.out.println("adminEnrolled Successfully"); + */ + + /* + ************************************************************* + * Example gent List Pending request + ************************************************************* + /* + + /* + + // Agent List and Approve Request + Request re = new Request (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority()); + re.setAgentCertName(t.GetAdminCertName()); + re.ListPendingRequests("2","70"); + re.ApproveRequests(t.getString(ue.getRequestId())); + */ + + /* + ************************************************************* + * Example for CheckRequest Status and add the certificate to internal db + ************************************************************* + /* + + /* + // check request status and Revoke cert + checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),t.getString(ue.getRequestId()),"false"); + checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),"1","false"); + + cr.checkRequestStatus(); + System.out.println("Serial num " + cr.getSerialNumber()); + System.out.println("cert pack " + cr.getCert()); + + String st= "-----BEGIN CERTIFICATE-----"+"\n"+cr.getCert()+"\n"+"-----END CERTIFICATE-----\n"; + System.out.println("cert pack " + st); + + cmsldap.getXCertificate(st.getBytes()); + + */ + + + /* + ************************************************************* + * Example agent ro revoke request + ************************************************************* + /* + + /* + Revoke rr = new Revoke (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority(),t.getString(cr.getSerialNumber())); + rr.revokeCerts(); + */ + + /* + ************************************************************* + * Example Agent update CRL + ************************************************************* + /* + + /* + // Update CRLand DISPLAY it + + System.out.println("Displayin CRL"); + CRL crl = new CRL (s.GetHostName(),s.GetAgentPort(),"/tmp/crlfile"); + crl.setAgentCertName(t.GetAdminCertName()); + crl.updateCRL(); + crl.displayCRL(); + crl.getRevokedCerts(); + */ + + // Update CRL in Directory + /* UpdateDir dcrl = new UpdateDir(s.GetHostName(),s.GetEESSLPort()); + dcrl.updateDir();*/ + + /* + ************************************************************* + * Example for stopping and starting servers + ************************************************************* + */ + + /* + DSTask idb = new DSTask(t.GetServerRoot()+"/slapd-jupiter2-db"); + if (idb.ldapStop()) System.out.println("IDB stopped"); + if(idb.ldapStart()) System.out.println("IDB Started"); + + System.out.println("------------------------------------------"); + System.out.println(" CMS Test:"); + CMSTask task = new CMSTask(t.GetInstanceRoot()); + task.CMSStop(); + task.CMSStart(); + */ + + + + }// end of function main + +} diff --git a/pki/base/silent/src/common/Utilities.java b/pki/base/silent/src/common/Utilities.java new file mode 100644 index 000000000..648fbb34d --- /dev/null +++ b/pki/base/silent/src/common/Utilities.java @@ -0,0 +1,351 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.io.*; +import java.net.*; + +import java.security.*; +import java.security.cert.*; +import sun.misc.*; +import netscape.security.x509.*; +import netscape.security.util.*; + + +public class Utilities { + private static final String keyValueSeparators = "=: \t\r\n\f"; + private static final String strictKeyValueSeparators = "=:"; + private static final String specialSaveChars = " \t\r\n\f"; + private static final String whiteSpaceChars = " \t\r\n\f"; + + public Utilities() {// Do nothing + } + + public String cleanupQuotes(String token) { + + StringBuffer buf = new StringBuffer(); + int length = token.length(); + int curIndex = 0; + + if (token.startsWith("\"") && token.endsWith("\"")) { + curIndex = 1; + length--; + } + + boolean oneQuoteFound = false; + boolean twoQuotesFound = false; + + while (curIndex < length) { + char curChar = token.charAt(curIndex); + + if (curChar == '"') { + twoQuotesFound = (oneQuoteFound) ? true : false; + oneQuoteFound = true; + } else { + oneQuoteFound = false; + twoQuotesFound = false; + } + + if (twoQuotesFound) { + twoQuotesFound = false; + oneQuoteFound = false; + curIndex++; + continue; + } + + buf.append(curChar); + curIndex++; + } + + return buf.toString(); + } + + public String removechar(String token) { + + StringBuffer buf = new StringBuffer(); + int end = token.length(); + int begin = 0; + + if (token.endsWith(";")) { + end--; + } + + while (begin < end) { + char curChar = token.charAt(begin); + + buf.append(curChar); + begin++; + } + return buf.toString(); + + } + + public String parse_httpresponse(String line) { + // look for name=value pair + // remove trailing white spaces + // remove trailing ; + // remove double quotes + + String temp = line.substring(line.indexOf("=") + 1); + + return cleanupQuotes(removechar(temp.trim())); + + } + + public String remove_newline(String s) { + if (s == null) { + return null; + } + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'n')) { + i++; + continue; + } else if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'r')) { + i++; + continue; + } else if (s.charAt(i) == '"') { + continue; + } + val += s.charAt(i); + } + return val; + + } + + public String normalize(String s) { + + if (s == null) { + return null; + } + + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'n')) { + val += '\n'; + i++; + continue; + } else if ((s.charAt(i) == '\\') && (s.charAt(i + 1) == 'r')) { + i++; + continue; + } else if (s.charAt(i) == '"') { + continue; + } + val += s.charAt(i); + } + return val; + } + + /* + * format of the file should be like this: + * -----BEGIN CERTIFICATE----- + * base64 encoded certificate + * -----END CERTIFICATE----- + */ + public String getcertfromfile(String filename) { + StringBuffer tempBuffer = new StringBuffer(); + + try { + FileInputStream fis = new FileInputStream(filename); + DataInputStream in = new DataInputStream(fis); + + while (in.available() != 0) { + String temp = in.readLine(); + + if (temp.equalsIgnoreCase("-----BEGIN CERTIFICATE-----") + || temp.equalsIgnoreCase("-----END CERTIFICATE-----")) { + continue; + } + tempBuffer.append(temp); + } + + return tempBuffer.toString(); + } catch (Exception e) { + System.out.println("ERROR: getcertfromfile" + e.toString()); + return null; + } + + } + + public String getcertfromfile_withheaders(String filename) { + StringBuffer tempBuffer = new StringBuffer(); + + try { + FileInputStream fis = new FileInputStream(filename); + DataInputStream in = new DataInputStream(fis); + + while (in.available() != 0) { + String temp = in.readLine(); + + tempBuffer.append(temp); + } + return tempBuffer.toString(); + } catch (Exception e) { + System.out.println( + "ERROR: getcertfromfile_withheaders" + e.toString()); + return null; + } + } + + /* + * format of the file should be like this: + * -----BEGIN CERTIFICATE REVOCATION LIST----- + * base64 encoded CRL + * -----END CERTIFICATE REVOCATION LIST----- + */ + public String getcrlfromfile(String filename) { + StringBuffer tempBuffer = new StringBuffer(); + + try { + FileInputStream fis = new FileInputStream(filename); + DataInputStream in = new DataInputStream(fis); + + while (in.available() != 0) { + String temp = in.readLine(); + + tempBuffer.append(temp); + } + + return tempBuffer.toString(); + } catch (Exception e) { + System.out.println("ERROR: getcrlfromfile" + e.toString()); + return null; + } + + } + + /* + * format of the file should be like this: + * -----BEGIN CERTIFICATE----- + * base64 encoded certificate + * -----END CERTIFICATE----- + */ + public String getcafromfile(String filename) { + StringBuffer tempBuffer = new StringBuffer(); + + try { + FileInputStream fis = new FileInputStream(filename); + DataInputStream in = new DataInputStream(fis); + + while (in.available() != 0) { + String temp = in.readLine(); + + tempBuffer.append(temp); + } + + return tempBuffer.toString(); + } catch (Exception e) { + System.out.println("ERROR: getcafromfile" + e.toString()); + return null; + } + + } + + /* + * function for RFC 2254. converts a x509 certificate given as + * a binary array[] to a Ldap filter string + */ + public static String escapeBinaryData(byte data[]) { + String result = ""; + + for (int i = 0; i < data.length; i++) { + String s = Integer.toHexString((int) (0xff & data[i])); + + if (s.length() == 1) { + s = "0" + s; + } + result = result + "\\" + s; + } + + System.out.println("LDAP_FILTER=" + result); + return result; + } + + /* + * function to decode base64 encoded certificate + */ + public Certificate_Record decode_cert(String cert) { + + String head = "-----BEGIN CERTIFICATE-----"; + String tail = "-----END CERTIFICATE-----"; + + Certificate_Record cr = new Certificate_Record(); + + int head_pos = cert.indexOf(head); + int tail_pos = cert.indexOf(tail); + + // String not found + if (head_pos == -1 || tail_pos == -1) { + return null; + } + + String temp = cert.substring(head_pos + head.length(), tail_pos); + + temp = temp.replaceAll("\\r", ""); + temp = temp.replaceAll("\\n", ""); + + try { + BASE64Decoder base64 = new BASE64Decoder(); + byte decodedBASE64Cert[] = base64.decodeBuffer(temp); + X509CertImpl x509_cert = new X509CertImpl(decodedBASE64Cert); + X509CertInfo certinfo = (X509CertInfo) x509_cert.get("x509.INFO"); + + /* Get Serial Number */ + CertificateSerialNumber csn = (CertificateSerialNumber) + certinfo.get(X509CertInfo.SERIAL_NUMBER); + SerialNumber sn = (SerialNumber) csn.get("NUMBER"); + + // just adding serialnumber for add. + // we can add mode here like subject name, extensions,issuer to this record. + cr.serialNumber = sn.getNumber().toString().trim(); + + /* Get Subject Name */ + + CertificateSubjectName csn1 = (CertificateSubjectName) + certinfo.get(X509CertInfo.SUBJECT); + + Enumeration en = csn1.getElements(); + + X500Name dname = (X500Name) csn1.get(CertificateSubjectName.DN_NAME); + + String pp = ""; + RDN[] rdns = dname.getNames(); + + for (int i = rdns.length - 1; i >= 0; i--) { + pp = pp + rdns[i] + "\n"; + } + + cr.subject = pp; + + } catch (Exception e) { + System.out.println("ERROR: Exception when decoding certificate=" + e); + e.printStackTrace(); + return null; + } + + return cr; + + } + +} + + +; // end class diff --git a/pki/base/silent/src/common/createinstance.java b/pki/base/silent/src/common/createinstance.java new file mode 100644 index 000000000..53ad7f022 --- /dev/null +++ b/pki/base/silent/src/common/createinstance.java @@ -0,0 +1,112 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.net.*; +import java.io.*; + + +public class createinstance { + + private static String host; + private static String port; + private static String AdminDN; + private static String AdminDNPW; + private static String serverRoot; + private static String instanceID; + private static String sieurl; + private static String adminDomain; + private static String first_arg; + + public createinstance() {// do nothing :) + } + + public void usage() { + System.out.println("Usage : "); + System.out.println(" createinstance -c host"); + System.out.println(" port"); + System.out.println(" AdminDN"); + System.out.println(" AdminDNPW"); + System.out.println(" adminDomain"); + System.out.println(" serverRoot"); + System.out.println(" instanceID"); + System.out.println(" machineName"); + System.out.println(" sieURL"); + System.out.println(" OR "); + System.out.println(" createinstance -h <to print this usage string>"); + + } + + public boolean CreateInstance() { + String startURL = "/cert/Tasks/Operation/Create"; + String myStringUrl = "http://" + host + "." + adminDomain + ":" + port + + startURL; + + System.out.println(myStringUrl); + + String query = "serverRoot=" + URLEncoder.encode(serverRoot); + + query += "&instanceID=" + URLEncoder.encode(instanceID); + query += "&adminDomain=" + URLEncoder.encode(adminDomain); + query += "&sieURL=" + URLEncoder.encode(sieurl); + query += "&adminUID=" + URLEncoder.encode(AdminDN); + query += "&adminPWD=" + URLEncoder.encode(AdminDNPW); + query += "&machineName=" + URLEncoder.encode(host + "." + adminDomain); + + PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query); + + return (sm.Send()); + + } + + public static void main(String args[]) { + createinstance newinstance = new createinstance(); + + // set variables + + first_arg = args[0]; + if (args[0].equals("-h")) { + newinstance.usage(); + System.exit(-1); + } else if (args[0].equals("-c")) { + host = args[1]; + port = args[2]; + AdminDN = args[3]; + AdminDNPW = args[4]; + serverRoot = args[5]; + instanceID = args[6]; + sieurl = args[7]; + adminDomain = args[8]; + + } + + boolean st = newinstance.CreateInstance(); + + if (!st) { + System.out.println("ERROR: Certficate System - Instance NOT created"); + System.exit(-1); + } + + System.out.println("Certficate System - Instance created"); + System.exit(0); + + } + +} + + +; diff --git a/pki/base/silent/src/drm/ConfigureDRM.java b/pki/base/silent/src/drm/ConfigureDRM.java new file mode 100644 index 000000000..fc2b41546 --- /dev/null +++ b/pki/base/silent/src/drm/ConfigureDRM.java @@ -0,0 +1,1152 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.osutil.*; + +public class ConfigureDRM +{ + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/kra/admin/console/config/login"; + public static String wizard_uri = "/kra/admin/console/config/wizard"; + public static String domain_uri = "/kra/ee/ca/domain"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + + public static String sd_login_uri = "/ca/ee/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/ee/ca/getCookie"; + public static String pkcs12_uri = "/kra/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = null; + + public static String ca_hostname = null; + public static String ca_port = null; + public static String ca_ssl_port = null; + public static String ca_agent_name = null; + public static String ca_agent_password = null; + + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String ldap_host = null; + public static String ldap_port = null; + public static String bind_dn = null; + public static String bind_password = null; + public static String base_dn = null; + public static String db_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String drm_transport_cert_name = null; + public static String drm_transport_cert_req = null; + public static String drm_transport_cert_pp = null; + public static String drm_transport_cert_cert = null; + + public static String drm_storage_cert_name = null; + public static String drm_storage_cert_req = null; + public static String drm_storage_cert_pp = null; + public static String drm_storage_cert_cert = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String drm_subsystem_cert_name = null; + public static String drm_subsystem_cert_req = null; + public static String drm_subsystem_cert_pp = null; + public static String drm_subsystem_cert_cert = null; + + public static String backup_pwd = null; + + // cert subject names + public static String drm_transport_cert_subject_name = null; + public static String drm_subsystem_cert_subject_name = null; + public static String drm_storage_cert_subject_name = null; + public static String drm_server_cert_subject_name = null; + + public static String subsystem_name = null; + + + public ConfigureDRM () + { + // do nothing :) + } + + public void sleep_time() + { + try + { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } + catch(Exception e) + { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // get cookie + String temp = hr.getCookieValue("JSESSIONID"); + + if(temp!=null) + { + int index = temp.indexOf(";"); + hc.j_session_id = temp.substring(0,index); + st = true; + } + + hr = null; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream( + hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return st; + } + + public boolean DomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String domain_url = "https://" + sd_hostname + ":" + sd_ssl_port ; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url) + + "&choice=existingdomain"+ + "&p=1" + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean DisplayChainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String query_string = null; + + query_string = "p=2" + "&op=next" + "&xml=true"; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean SecurityDomainLoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String kra_url = "https://" + cs_hostname + ":" + cs_port + + "/kra/admin/console/config/wizard" + + "?p=3&subsystem=KRA" ; + + String query_string = "url=" + URLEncoder.encode(kra_url); + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_login_uri,query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + sd_admin_password + + "&url=" + URLEncoder.encode(kra_url) ; + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + + String kra_session_id = hr.getContentValue("header.session_id"); + String kra_url_1 = hr.getContentValue("header.url"); + + System.out.println("KRA_SESSION_ID=" + kra_session_id ); + System.out.println("KRA_URL=" + kra_url_1 ); + + // use session id to connect back to KRA + + String query_string_2 = "p=3" + + "&subsystem=KRA" + + "&session_id=" + kra_session_id + + "&xml=true" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + query_string_2); + + // parse xml + // bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + // px.parse(bais); + // px.prettyprintxml(); + + return true; + + } + + public boolean SubsystemPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=3" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name) + + "&choice=newsubsystem" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean LdapConnectionPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=5" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host) + + "&port=" + URLEncoder.encode(ldap_port) + + "&binddn=" + URLEncoder.encode(bind_dn) + + "&__bindpwd=" + URLEncoder.encode(bind_password) + + "&basedn=" + URLEncoder.encode(base_dn) + + "&database=" + URLEncoder.encode(db_name) + + "&display=" + URLEncoder.encode("displayStr") + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if(token_name.equalsIgnoreCase("internal")) + { + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token") + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } + // HSM + else + { + // login to hsm first + query_string = "p=7" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name) + + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + return true; + } + + public boolean KeyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList al = null; + + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&transport_custom_size=" + key_size + + "&storage_custom_size=" + key_size + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + + "&custom_size=" + key_size + + "&transport_keytype=" + key_type + + "&storage_keytype=" + key_type + + "&subsystem_keytype=" + key_type + + "&sslserver_keytype=" + key_type + + "&keytype=" + key_type + + "&transport_choice=default"+ + "&storage_choice=default"+ + "&subsystem_choice=default"+ + "&sslserver_choice=default"+ + "&choice=default"+ + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + al = px.constructvaluelist("CertReqPair","DN"); + // get ca cert subject name + if(al != null) + { + for (int i=0; i < al.size(); i++) + { + String temp = (String) al.get(i); + if(temp.indexOf("DRM Transport") > 0 ) + { + drm_transport_cert_name = temp; + } + else if(temp.indexOf("DRM Storage") > 0 ) + { + drm_storage_cert_name = temp; + } + else if(temp.indexOf("DRM Subsystem") > 0 ) + { + drm_subsystem_cert_name = temp; + } + else + { + server_cert_name = temp; + } + } + } + + System.out.println("default: drm_transport_cert_name=" + + drm_transport_cert_name); + System.out.println("default: drm_storage_cert_name=" + + drm_storage_cert_name); + System.out.println("default: drm_subsystem_cert_name=" + + drm_subsystem_cert_name); + System.out.println("default: server_cert_name=" + + server_cert_name); + return true; + } + + public boolean CertSubjectPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + + + String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + /* + public static String drm_transport_cert_subject_name = null; + public static String drm_subsystem_cert_subject_name = null; + public static String drm_storage_cert_subject_name = null; + public static String drm_server_cert_subject_name = null; + */ + + String query_string = "p=9" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(drm_subsystem_cert_subject_name) + + "&transport=" + + URLEncoder.encode(drm_transport_cert_subject_name) + + "&storage=" + + URLEncoder.encode(drm_storage_cert_subject_name) + + "&sslserver=" + + URLEncoder.encode(drm_server_cert_subject_name) + + "&urls=" + + URLEncoder.encode(domain_url) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + req_list = px.constructvaluelist("CertReqPair","Request"); + cert_list = px.constructvaluelist("CertReqPair","Certificate"); + dn_list = px.constructvaluelist("CertReqPair","Nickname"); + + if(req_list != null && cert_list != null && dn_list != null) + { + for (int i=0; i < dn_list.size(); i++) + { + String temp = (String) dn_list.get(i); + + if(temp.indexOf("transportCert") >= 0 ) + { + drm_transport_cert_req = (String) req_list.get(i); + drm_transport_cert_cert = (String) cert_list.get(i); + } + else if(temp.indexOf("storageCert") >= 0 ) + { + drm_storage_cert_req = (String) req_list.get(i); + drm_storage_cert_cert = (String) cert_list.get(i); + } + else if(temp.indexOf("subsystemCert") >= 0 ) + { + drm_subsystem_cert_req = (String) req_list.get(i); + drm_subsystem_cert_cert = (String) cert_list.get(i); + } + else + { + server_cert_req = (String) req_list.get(i); + server_cert_cert = (String) cert_list.get(i); + } + } + } + + return true; + } + + public boolean CertificatePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(drm_subsystem_cert_cert) + + "&subsystem_cc=" + + "&transport=" + + URLEncoder.encode(drm_transport_cert_cert) + + "&transport_cc=" + + "&storage=" + + URLEncoder.encode(drm_storage_cert_cert) + + "&storage_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert) + + "&sslserver_cc=" + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean BackupPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + backup_pwd + + "&__pwdagain=" + backup_pwd + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean SavePKCS12Panel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = ""; + + hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string); + + // dump hr.getResponseData() to file + + try + { + FileOutputStream fos = new FileOutputStream("/tmp/tmp-kra.p12"); + fos.write(hr.getResponseData()); + fos.close(); + + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream("/tmp/tmp-kra.p12"); + PFX.Template pfxt = new PFX.Template(); + PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis, 2048)); + System.out.println("Decoded PFX"); + + // now peruse it for interesting info + System.out.println("Version: "+pfx.getVersion()); + AuthenticatedSafes authSafes = pfx.getAuthSafes(); + SEQUENCE asSeq = authSafes.getSequence(); + System.out.println("AuthSafes has "+ + asSeq.size()+" SafeContents"); + + fis.close(); + } + catch(Exception e) + { + System.out.println("ERROR: Exception=" + e.getMessage()); + return false; + } + + return true; + } + + public boolean AdminCertReqPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + agent_cert_subject, + agent_key_size, + agent_key_type); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if(crmf_request == null) + { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + + "&uid=" + admin_user + + "&name=" + admin_user + + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email) + + "&cert_request=" + + URLEncoder.encode(admin_cert_request) + + "&subject=" + URLEncoder.encode(agent_cert_subject) + + "&clone=new" + + "&import=true" + + "&securitydomain=" + domain_name + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(ca_hostname,ca_ssl_port,ee_uri,query_string); + + // get response data + String cert_to_import = + new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + System.out.println("Imported Cert=" + cert_to_import); + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n" ; + String end = "\r\n-----END CERTIFICATE-----" ; + + st = cCrypt.importCert(start+cert_to_import+end,agent_name); + if(!st) + { + System.out.println("ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert"); + return true; + } + + public boolean UpdateDomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=14" + "&op=next" + + "&caHost=" + URLEncoder.encode(ca_hostname) + + "&caPort=" + URLEncoder.encode(ca_ssl_port) + + "&pkcs7=" + URLEncoder.encode("/") + + "&serialNumber=" + URLEncoder.encode(admin_serial_number) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); +// px.parse(bais); +// px.prettyprintxml(); + + return true; + } + + public boolean ConfigureDRMInstance() + { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + hc = new HTTPClient(); + + // 1. Login panel + boolean log_st = LoginPanel(); + if(!log_st) + { + System.out.println("ERROR: ConfigureDRM: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if(!dom_st) + { + System.out.println("ERROR: ConfigureDRM: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureDRM: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // security domain login panel + boolean disp_sd = SecurityDomainLoginPanel(); + if(!disp_sd) + { + System.out.println("ERROR: ConfigureDRM: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // subsystem panel + boolean disp_ss = SubsystemPanel(); + if(!disp_ss) + { + System.out.println("ERROR: ConfigureDRM: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if(!disp_ldap) + { + System.out.println("ERROR: ConfigureDRM: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if(!disp_token) + { + System.out.println("ERROR: ConfigureDRM: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + if(!disp_key) + { + System.out.println("ERROR: ConfigureDRM: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if(!disp_csubj) + { + System.out.println("ERROR: ConfigureDRM: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + if(!disp_cp) + { + System.out.println("ERROR: ConfigureDRM: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // backup panel + boolean disp_back = BackupPanel(); + if(!disp_back) + { + System.out.println("ERROR: ConfigureDRM: BackupPanel() failure"); + return false; + } + + sleep_time(); + // save panel + boolean disp_save = SavePKCS12Panel(); + if(!disp_save) + { + System.out.println("ERROR: ConfigureDRM: SavePKCS12Panel() failure"); + return false; + } + + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if(!disp_adm) + { + System.out.println("ERROR: ConfigureDRM: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if(!disp_im) + { + System.out.println("ERROR: ConfigureDRM: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if(!disp_ud) + { + System.out.println("ERROR: ConfigureDRM: UpdateDomainPanel() failure"); + return false; + } + + sleep_time(); + return true; + } + + public static void main(String args[]) + { + ConfigureDRM ca = new ConfigureDRM(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = new StringHolder(); + + StringHolder x_ca_hostname = new StringHolder(); + StringHolder x_ca_port = new StringHolder(); + StringHolder x_ca_ssl_port = new StringHolder(); + + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // ldap + + StringHolder x_ldap_host = new StringHolder(); + StringHolder x_ldap_port = new StringHolder(); + StringHolder x_bind_dn = new StringHolder(); + StringHolder x_bind_password = new StringHolder(); + StringHolder x_base_dn = new StringHolder(); + StringHolder x_db_name = new StringHolder(); + + // key size + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + StringHolder x_backup_pwd = new StringHolder(); + + // drm cert subject name params + StringHolder x_drm_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_drm_server_cert_subject_name = new StringHolder(); + StringHolder x_drm_transport_cert_subject_name = new StringHolder(); + StringHolder x_drm_storage_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("ConfigureDRM"); + + parser.addOption ("-cs_hostname %s #CS Hostname", + x_cs_hostname); + parser.addOption ("-cs_port %s #CS SSL port", + x_cs_port); + + parser.addOption ("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption ("-sd_ssl_port %s #Security Domain SSL port", + x_sd_ssl_port); + parser.addOption ("-sd_admin_name %s #Security Domain username", + x_sd_admin_name); + parser.addOption ("-sd_admin_password %s #Security Domain password", + x_sd_admin_password); + + parser.addOption ("-ca_hostname %s #CA Hostname", + x_ca_hostname); + parser.addOption ("-ca_port %s #CA non SSL port", + x_ca_port); + parser.addOption ("-ca_ssl_port %s #CA SSL port", + x_ca_ssl_port); + + parser.addOption ("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption ("-preop_pin %s #pre op pin", + x_preop_pin); + parser.addOption ("-domain_name %s #domain name", + x_domain_name); + parser.addOption ("-admin_user %s #Admin User Name", + x_admin_user); + parser.addOption ("-admin_email %s #Admin email", + x_admin_email); + parser.addOption ("-admin_password %s #Admin password", + x_admin_password); + parser.addOption ("-agent_name %s #Agent Cert Nickname", + x_agent_name); + + parser.addOption ("-ldap_host %s #ldap host", + x_ldap_host); + parser.addOption ("-ldap_port %s #ldap port", + x_ldap_port); + parser.addOption ("-bind_dn %s #ldap bind dn", + x_bind_dn); + parser.addOption ("-bind_password %s #ldap bind password", + x_bind_password); + parser.addOption ("-base_dn %s #base dn", + x_base_dn); + parser.addOption ("-db_name %s #db name", + x_db_name); + + parser.addOption ("-key_size %s #Key Size", + x_key_size); + parser.addOption ("-key_type %s #Key type [RSA,ECC]", + x_key_type); + parser.addOption ("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption ("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + + parser.addOption ("-agent_key_size %s #Agent Cert Key Size", + x_agent_key_size); + parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]", + x_agent_key_type); + parser.addOption ("-agent_cert_subject %s #Agent Cert Subject ", + x_agent_cert_subject); + + parser.addOption ("-backup_pwd %s #PKCS12 password", + x_backup_pwd); + + parser.addOption ( + "-drm_transport_cert_subject_name %s #DRM transport cert subject name", + x_drm_transport_cert_subject_name); + parser.addOption ( + "-drm_subsystem_cert_subject_name %s #DRM subsystem cert subject name", + x_drm_subsystem_cert_subject_name); + parser.addOption ( + "-drm_storage_cert_subject_name %s #DRM storage cert subject name", + x_drm_storage_cert_subject_name); + parser.addOption ( + "-drm_server_cert_subject_name %s #DRM server cert subject name", + x_drm_server_cert_subject_name); + + parser.addOption ( + "-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + ca_hostname = x_ca_hostname.value; + ca_port = x_ca_port.value; + ca_ssl_port = x_ca_ssl_port.value; + + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + ldap_host = x_ldap_host.value; + ldap_port = x_ldap_port.value; + bind_dn = x_bind_dn.value; + bind_password = x_bind_password.value; + base_dn = x_base_dn.value; + db_name = x_db_name.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + backup_pwd = x_backup_pwd.value; + + drm_transport_cert_subject_name = + x_drm_transport_cert_subject_name.value ; + drm_subsystem_cert_subject_name = + x_drm_subsystem_cert_subject_name.value; + drm_storage_cert_subject_name = x_drm_storage_cert_subject_name.value ; + drm_server_cert_subject_name = x_drm_server_cert_subject_name.value ; + + subsystem_name = x_subsystem_name.value ; + + + + boolean st = ca.ConfigureDRMInstance(); + + if (!st) + { + System.out.println("ERROR: unable to create DRM"); + System.exit(-1); + } + + System.out.println("Certficate System - DRM Instance Configured"); + System.exit(0); + + } + +}; diff --git a/pki/base/silent/src/http/CertSelection.java b/pki/base/silent/src/http/CertSelection.java new file mode 100644 index 000000000..a83cb3af3 --- /dev/null +++ b/pki/base/silent/src/http/CertSelection.java @@ -0,0 +1,57 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.util.*; + +import org.mozilla.jss.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + + +public class CertSelection implements SSLClientCertificateSelectionCallback +{ + + // make the select() call to use this client cert + public static String client_cert = null; + + public void setClientCert(String nickname) + { + client_cert = nickname; + } + + public String select(Vector nicknames) + { + + // when this method is called by SSLSocket we get a vector + // of nicknames to select similar to the way the browser presents + // the list. + + // We will just use the one thats set by setClientCert() + + return client_cert; + } + +}; // end class diff --git a/pki/base/silent/src/http/HTMLDocument.java b/pki/base/silent/src/http/HTMLDocument.java new file mode 100644 index 000000000..5fcb5343b --- /dev/null +++ b/pki/base/silent/src/http/HTMLDocument.java @@ -0,0 +1,747 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.regex.*; + + + +public class HTMLDocument +{ + // Indicates whether this HTML document has been parsed. + boolean parsed; + + // A list of URLs of files that should be retrieved along with the main + // contents of the document. This may include any images contained in the + // document, and possibly any external stylesheets. + LinkedHashSet associatedFiles; + + // A list of URLs of frames that are contained in the document. + LinkedHashSet documentFrames; + + // A list of URLs of links that are contained in the document. + LinkedHashSet documentLinks; + + // A list of URLs of images that are contained in the document. + LinkedHashSet documentImages; + + // A regular expression pattern that can be used to extract a URI from an HREF + // tag. + Pattern hrefPattern; + + // A regular expression pattern that can be used to extract a URI from a SRC + // tag. + Pattern srcPattern; + + // The base URL for relative links in this document. + String baseURL; + + // The URL that may be used to access this document. + String documentURL; + + // The actual contents of the page. + String htmlData; + + // The contents of the page converted to lowercase for easier matching. + String lowerData; + + // The URL for this document with only protocol, host, and port (i.e., no + // file). + String protocolHostPort; + + // A string buffer containing the contents of the page with tags removed. + StringBuffer textData; + + + // A set of private variables used for internal processing. + private boolean lastElementIsAssociatedFile; + private boolean lastElementIsChunk; + private boolean lastElementIsComment; + private boolean lastElementIsFrame; + private boolean lastElementIsImage; + private boolean lastElementIsLink; + private boolean lastElementIsText; + private int lastElementEndPos; + private int lastElementStartPos; + private String lastURL; + + // constructor that helps to parse without url stuff + public HTMLDocument(String htmlData) + { + this.documentURL = null; + this.htmlData = htmlData; + lowerData = htmlData.toLowerCase(); + associatedFiles = null; + documentLinks = null; + documentImages = null; + textData = null; + parsed = false; + + + // Create the regex patterns that we will use for extracting URIs from tags. + hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" + + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL); + srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" + + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL); + } + + + /** + * Creates a new HTML document using the provided data. + * + * @param documentURL The URL for this document. + * @param htmlData The actual data contained in the HTML document. + */ + public HTMLDocument(String documentURL, String htmlData) + throws MalformedURLException + { + this.documentURL = documentURL; + this.htmlData = htmlData; + lowerData = htmlData.toLowerCase(); + associatedFiles = null; + documentLinks = null; + documentImages = null; + textData = null; + parsed = false; + + + // Create the regex patterns that we will use for extracting URIs from tags. + hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" + + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL); + srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" + + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL); + + URL url = new URL(documentURL); + String urlPath = url.getPath(); + if ((urlPath == null) || (urlPath.length() == 0)) + { + baseURL = documentURL; + protocolHostPort = documentURL; + } + else if (urlPath.equals("/")) + { + baseURL = documentURL; + protocolHostPort = documentURL.substring(0, documentURL.length()-1); + } + else if (urlPath.endsWith("/")) + { + baseURL = documentURL; + + int port = url.getPort(); + if (port > 0) + { + protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" + + port; + } + else + { + protocolHostPort = url.getProtocol() + "://" + url.getHost(); + } + } + else + { + int port = url.getPort(); + if (port > 0) + { + protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" + + port; + } + else + { + protocolHostPort = url.getProtocol() + "://" + url.getHost(); + } + + File urlFile = new File(urlPath); + String parentDirectory = urlFile.getParent(); + if ((parentDirectory == null) || (parentDirectory.length() == 0)) + { + parentDirectory = "/"; + } + else if (! parentDirectory.startsWith("/")) + { + parentDirectory = "/" + parentDirectory; + } + + baseURL = protocolHostPort + parentDirectory; + } + + if (! baseURL.endsWith("/")) + { + baseURL = baseURL + "/"; + } + } + + + + /** + * Actually parses the HTML document and extracts useful elements from it. + * + * @return <CODE>true</CODE> if the page could be parsed successfully, or + * <CODE>false</CODE> if not. + */ + public boolean parse() + { + if (parsed) + { + return true; + } + + + try + { + associatedFiles = new LinkedHashSet(); + documentFrames = new LinkedHashSet(); + documentLinks = new LinkedHashSet(); + documentImages = new LinkedHashSet(); + textData = new StringBuffer(); + + lastElementStartPos = 0; + lastElementEndPos = -1; + String element; + while ((element = nextDocumentElement()) != null) + { + if (element.length() == 0) + { + continue; + } + + if (lastElementIsText) + { + char lastChar; + if (textData.length() == 0) + { + lastChar = ' '; + } + else + { + lastChar = textData.charAt(textData.length()-1); + } + char firstChar = element.charAt(0); + if (! ((lastChar == ' ') || (lastChar == '\t') || + (lastChar == '\r') || (lastChar == '\n')) || + (firstChar == ' ') || (firstChar == '\t') || + (firstChar == '\r') || (firstChar == '\n')) + { + textData.append(" "); + } + + textData.append(element); + } + else if (lastElementIsImage) + { + if (lastURL != null) + { + documentImages.add(lastURL); + associatedFiles.add(lastURL); + } + } + else if (lastElementIsFrame) + { + if (lastURL != null) + { + documentFrames.add(lastURL); + associatedFiles.add(lastURL); + } + } + else if (lastElementIsLink) + { + if (lastURL != null) + { + documentLinks.add(lastURL); + } + } + else if (lastElementIsAssociatedFile) + { + if (lastURL != null) + { + associatedFiles.add(lastURL); + } + } + else if (lastElementIsChunk || lastElementIsComment) + { + // Don't need to do anything with this. + } + else + { + // Also don't need anything here. + } + } + + parsed = true; + } + catch (Exception e) + { + associatedFiles = null; + documentLinks = null; + documentImages = null; + textData = null; + parsed = false; + } + + return parsed; + } + + + + /** + * Retrieves the next element from the HTML document. An HTML element can + * include a string of plain text, a single HTML tag, or a larger chunk of + * HTML including a start and end tag, all of which should be considered a + * single element. + */ + private String nextDocumentElement() + { + // If we're at the end of the HTML, then return null. + if (lastElementEndPos >= htmlData.length()) + { + return null; + } + + + // Initialize the variables we will use for the search. + lastElementStartPos = lastElementEndPos+1; + lastElementIsAssociatedFile = false; + lastElementIsChunk = false; + lastElementIsComment = false; + lastElementIsFrame = false; + lastElementIsImage = false; + lastElementIsLink = false; + lastElementIsText = false; + lastURL = null; + + + // Find the location of the next open angle bracket. If there is none, then + // the rest of the document must be plain text. + int openPos = lowerData.indexOf('<', lastElementStartPos); + if (openPos < 0) + { + lastElementEndPos = htmlData.length(); + lastElementIsText = true; + return htmlData.substring(lastElementStartPos); + } + + + // If the location of the next open tag is not we started looking, then read + // everything up to that tag as text. + if (openPos > lastElementStartPos) + { + lastElementEndPos = openPos-1; + lastElementIsText = true; + return htmlData.substring(lastElementStartPos, openPos); + } + + + // The start position is an open tag. See if the tag is actually "<!--", + // which indicates an HTML comment. If that's the case, then find the + // closing "-->". + if (openPos == lowerData.indexOf("<!--", lastElementStartPos)) + { + int closePos = lowerData.indexOf("-->", openPos+1); + if (closePos < 0) + { + // This looks like an unterminated comment. We can't do much else + // here, so just stop parsing. + return null; + } + else + { + lastElementEndPos = closePos + 2; + lastElementIsComment = true; + return htmlData.substring(lastElementStartPos, lastElementEndPos+1); + } + } + + + // Find the location of the next close angle bracket. If there is none, + // then we have an unmatched open tag. What to do here? I guess just treat + // the rest of the document as text. + int closePos = lowerData.indexOf('>', openPos+1); + if (closePos < 0) + { + lastElementEndPos = htmlData.length(); + lastElementIsText = true; + return htmlData.substring(lastElementStartPos); + } + + + // Grab the contents of the tag in both normal and lowercase. + String tag = htmlData.substring(openPos, closePos+1); + String strippedTag = htmlData.substring(openPos+1, closePos).trim(); + StringTokenizer tokenizer = new StringTokenizer(strippedTag, " \t\r\n=\"'"); + lastElementEndPos = closePos; + + if (! tokenizer.hasMoreTokens()) + { + return tag; + } + + String token = tokenizer.nextToken(); + String lowerToken = token.toLowerCase(); + + if (lowerToken.equals("a") || lowerToken.equals("area")) + { + while (tokenizer.hasMoreTokens()) + { + token = tokenizer.nextToken(); + if (token.equalsIgnoreCase("href")) + { + try + { + Matcher matcher = hrefPattern.matcher(tag); + lastURL = uriToURL(matcher.replaceAll("$1")); + if (lastURL != null) + { + lastElementIsLink = true; + } + } catch (Exception e) {} + break; + } + } + } + else if (lowerToken.equals("base")) + { + while (tokenizer.hasMoreTokens()) + { + token = tokenizer.nextToken(); + if (token.equalsIgnoreCase("href")) + { + try + { + Matcher matcher = hrefPattern.matcher(tag); + String uri = matcher.replaceAll("$1"); + if (! uri.endsWith("/")) + { + uri = uri + "/"; + } + + baseURL = uri; + } catch (Exception e) {} + break; + } + } + } + else if (lowerToken.equals("frame") || lowerToken.equals("iframe") || + lowerToken.equals("input")) + { + while (tokenizer.hasMoreTokens()) + { + token = tokenizer.nextToken(); + if (token.equalsIgnoreCase("src")) + { + try + { + Matcher matcher = srcPattern.matcher(tag); + String uri = matcher.replaceAll("$1"); + lastURL = uriToURL(uri); + if (lastURL != null) + { + lastElementIsFrame = true; + lastElementIsAssociatedFile = true; + } + } catch (Exception e) {} + break; + } + } + } + else if (lowerToken.equals("img")) + { + while (tokenizer.hasMoreTokens()) + { + token = tokenizer.nextToken(); + if (token.equalsIgnoreCase("src")) + { + try + { + Matcher matcher = srcPattern.matcher(tag); + String uri = matcher.replaceAll("$1"); + lastURL = uriToURL(uri); + if (lastURL != null) + { + lastElementIsImage = true; + } + } catch (Exception e) {} + break; + } + } + } + else if (lowerToken.equals("link")) + { + boolean isStyleSheet = false; + + while (tokenizer.hasMoreTokens()) + { + token = tokenizer.nextToken(); + if (token.equalsIgnoreCase("href")) + { + try + { + Matcher matcher = hrefPattern.matcher(tag); + String uri = matcher.replaceAll("$1"); + lastURL = uriToURL(uri); + if (lastURL != null) + { + lastElementIsLink = true; + } + } catch (Exception e) {} + break; + } + else if (token.equalsIgnoreCase("rel")) + { + if (tokenizer.hasMoreTokens()) + { + String relType = tokenizer.nextToken(); + if (relType.equalsIgnoreCase("stylesheet")) + { + isStyleSheet = true; + } + } + } + } + + if (lastURL != null) + { + if (isStyleSheet) + { + lastElementIsAssociatedFile = true; + } + else + { + lastElementIsLink = true; + } + } + } + else if (lowerToken.equals("script")) + { + while (tokenizer.hasMoreTokens()) + { + token = tokenizer.nextToken(); + if (token.equalsIgnoreCase("src")) + { + try + { + Matcher matcher = srcPattern.matcher(tag); + String uri = matcher.replaceAll("$1"); + lastURL = uriToURL(uri); + } catch (Exception e) {} + break; + } + } + + if (lastURL == null) + { + int endScriptPos = lowerData.indexOf("</script>", lastElementEndPos+1); + if (endScriptPos > 0) + { + lastElementEndPos = endScriptPos + 8; + tag = htmlData.substring(lastElementStartPos, lastElementEndPos+1); + lastElementIsChunk = true; + } + } + else + { + lastElementIsAssociatedFile = true; + } + } + + return tag; + } + + + + /** + * Converts the provided URI to a URL. The provided URI may be a URL already, + * or it may also be an absolute path on the server or a path relative to the + * base URL. + * + * @param uri The URI to convert to a URL. + * + * @return The URL based on the provided URI. + */ + private String uriToURL(String uri) + { + String url = null; + + if (uri.indexOf("://") > 0) + { + if (uri.startsWith("http")) + { + url = uri; + } + } + else if (uri.startsWith("/")) + { + url = protocolHostPort + uri; + } + else + { + url = baseURL + uri; + } + + return url; + } + + + + /** + * Retrieves the URL of this HTML document. + * + * @return The URL of this HTML document. + */ + public String getDocumentURL() + { + return documentURL; + } + + + + /** + * Retrieves the original HTML data used to create this document. + * + * @return The orginal HTML data used to create this document. + */ + public String getHTMLData() + { + return htmlData; + } + + + + /** + * Retrieves the contents of the HTML document with all tags removed. + * + * @return The contents of the HTML document with all tags removed, or + * <CODE>null</CODE> if a problem occurs while trying to parse the + * HTML. + */ + public String getTextData() + { + if (! parsed) + { + if (! parse()) + { + return null; + } + } + + return textData.toString(); + } + + + + /** + * Retrieves an array containing a set of URLs parsed from the HTML document + * that reference files that would normally be downloaded as part of + * retrieving a page in a browser. This includes images and external style + * sheets. + * + * @return An array containing a set of URLs to files associated with the + * HTML document, or <CODE>null</CODE> if a problem occurs while + * trying to parse the HTML. + */ + public String[] getAssociatedFiles() + { + if (! parsed) + { + if (! parse()) + { + return null; + } + } + + String[] urlArray = new String[associatedFiles.size()]; + associatedFiles.toArray(urlArray); + return urlArray; + } + + + + /** + * Retrieves an array containing a set of URLs parsed from the HTML document + * that are in the form of links to other content. + * + * @return An array containing a set of URLs parsed from the HTML document + * that are in the form of links to other content, or + * <CODE>null</CODE> if a problem occurs while trying to parse the + * HTML. + */ + public String[] getDocumentLinks() + { + if (! parsed) + { + if (! parse()) + { + return null; + } + } + + String[] urlArray = new String[documentLinks.size()]; + documentLinks.toArray(urlArray); + return urlArray; + } + + + + /** + * Retrieves an array containing a set of URLs parsed from the HTML document + * that reference images used in the document. + * + * @return An array containing a set of URLs parsed from the HTML document + * that reference images used in the document. + */ + public String[] getDocumentImages() + { + if (! parsed) + { + if (! parse()) + { + return null; + } + } + + String[] urlArray = new String[documentImages.size()]; + documentImages.toArray(urlArray); + return urlArray; + } + + + + /** + * Retrieves an array containing a set of URLs parsed from the HTML document + * that reference frames used in the document. + * + * @return An array containing a set of URLs parsed from the HTML document + * that reference frames used in the document. + */ + public String[] getDocumentFrames() + { + if (! parsed) + { + if (! parse()) + { + return null; + } + } + + String[] urlArray = new String[documentFrames.size()]; + documentFrames.toArray(urlArray); + return urlArray; + } +} + diff --git a/pki/base/silent/src/http/HTTPClient.java b/pki/base/silent/src/http/HTTPClient.java new file mode 100644 index 000000000..4db3f4d18 --- /dev/null +++ b/pki/base/silent/src/http/HTTPClient.java @@ -0,0 +1,1391 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.io.*; +import java.net.*; +import java.nio.*; +import java.util.*; +import java.net.URLEncoder; + +import sun.misc.BASE64Encoder; +import sun.misc.BASE64Decoder; + + +import org.mozilla.jss.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + + +public class HTTPClient implements SSLCertificateApprovalCallback +{ + + public static final int BUFFER_SIZE = 4096; + public boolean debugMode = true; + + public static String basic_auth_header_value = null; + + public static String cs_hostname = null; + public static String cs_port = null; + public static String ssl = null; + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + public static String client_cert_nickname = null; + public static String uri = null; + public static String query = null; + public static String request_type = null; + public static String user_id = null; + public static String user_password = null; + public static String auth_type = null; + public static String debug = null; + + public static boolean parse_xml = false; + + public static X509Certificate server_cert = null; + + // cookie variable for CS install UI + public static String j_session_id = null; + public static boolean ecc_support = false; + + + + + public HTTPClient() + { + // constructor + // turn off ecc by default + ecc_support = true; + } + + + public HTTPClient(boolean ecc) + { + ecc_support = ecc; + } + + public boolean setCipherPref(SSLSocket socket) + { + + if(ecc_support) + { + int ecc_Ciphers[] = { + // ECC Ciphers - See JSSSocketFactory.java for more info + 0xC001, 0xC002, 0xC003, 0xC004, 0xC005, 0xC006, 0xC007, + 0xC008, 0xC009, 0xC00A, 0xC00B, 0xC00C, 0xC00E, 0xC00F, + 0xC010, 0xC011, 0xC012, 0xC013, 0xC014, 0 }; + + try + { + for (int i=0; i < ecc_Ciphers.length; i++) + { + if(ecc_Ciphers[i] > 0) + socket.setCipherPreference( + ecc_Ciphers[i],true); + } + } + catch(Exception e) + { + System.out.println("ERROR: unable to set Cipher List"); + System.out.println("ERROR: Exception = " + e.getMessage()); + } + + } + return true; + } + + public boolean disableSSL2(SSLSocket socket) + { + try + { + socket.enableSSL3Default(true); + socket.enableSSL3(true); + socket.enableSSL2(false); + socket.enableSSL2Default(false); + } + catch(Exception e) + { + System.out.println("ERROR: Exception = " + e.getMessage()); + } + return true; + } + + public X509Certificate getServerCert() + { + return server_cert; + } + + public void set_parse_xml(boolean b) + { + parse_xml = b; + } + + public boolean approve(X509Certificate cert, + SSLCertificateApprovalCallback.ValidityStatus status) + { + + // when this method is called by SSLSocket we get the server cert + // we can capture this for future use. + server_cert = cert; + return true; + } + + public boolean testsslConnect(String hostname, String portnumber) + { + boolean st = true; + + try + { + + System.out.println("#############################################"); + System.out.println("Attempting to connect to: " + hostname + ":" + + portnumber); + + Integer x = new Integer(portnumber); + int port = x.intValue(); + + + SSLClientCertificateSelectionCallback certSelectionCallback = + new TestClientCertificateSelectionCallback(); + + Socket js = new Socket(InetAddress.getByName(hostname), port); + SSLSocket socket = new SSLSocket(js, hostname, this, + certSelectionCallback ); + setCipherPref(socket); + disableSSL2(socket); + socket.forceHandshake(); + System.out.println("Connected."); + socket.setUseClientMode(true); + + // test connection to obtain server cert. close it. + socket.close(); + + + } + + catch(Exception e) + { + System.err.println("Exception: Unable to Send Request:" +e); + e.printStackTrace(); + st = false; + } + + if(!st) + return false; + else + return true; + } + + // performs ssl connect to given host/port requiring client auth + // posts the given query data + // returns HTTPResponse + public HTTPResponse sslConnectClientAuth(String hostname, String portnumber, + String client_cert,String url,String query) + { + + boolean st = true; + HTTPResponse hr = null; + + try + { + + System.out.println("#############################################"); + System.out.println("Attempting to connect to: " + hostname + ":" + + portnumber); + + Integer x = new Integer(portnumber); + int port = x.intValue(); + + + SSLCertificateApprovalCallback approvalCallback = + new TestCertApprovalCallback(); + CertSelection certSelectionCallback = + new CertSelection(); + + // Client Cert for Auth is set here + certSelectionCallback.setClientCert(client_cert); + + Socket js = new Socket(InetAddress.getByName(hostname), port); + SSLSocket socket = new SSLSocket(js, hostname, approvalCallback, + certSelectionCallback ); + disableSSL2(socket); + setCipherPref(socket); + socket.forceHandshake(); + System.out.println("Connected."); + socket.setUseClientMode(true); + + System.out.println("Posting Query = " + + "https://" + hostname + + ":" + portnumber + + "/" + url + + "?" + query); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + ps.println("POST " + url + " HTTP/1.0"); + ps.println("Connection: Keep-Alive"); + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " +query.length()); + ps.println(""); + ps.print(query); + ps.flush(); + os.flush(); + + try + { + hr = readResponse(socket.getInputStream()); + hr.parseContent(); + + } + catch (Exception e) + { + System.out.println("Exception"); + e.printStackTrace(); + st = false; + } + + socket.close(); + os.close(); + rawos.close(); + ps.close(); + + os=null; + rawos=null; + ps=null; + + } + + catch(Exception e) + { + System.err.println("Exception: Unable to Send Request:" +e); + e.printStackTrace(); + st = false; + } + + if(!st) + return null; + else + return hr; + } + + // performs ssl connect to given host/port + // posts the given query data + // returns HTTPResponse + public HTTPResponse sslConnect(String hostname, String portnumber, + String url, String query) + { + + boolean st = true; + HTTPResponse hr = null; + + try + { + + System.out.println("#############################################"); + System.out.println("Attempting to connect to: " + hostname + ":" + + portnumber); + + Integer x = new Integer(portnumber); + int port = x.intValue(); + + + SSLCertificateApprovalCallback approvalCallback = + new TestCertApprovalCallback(); + SSLClientCertificateSelectionCallback certSelectionCallback = + new TestClientCertificateSelectionCallback(); + + Socket js = new Socket(InetAddress.getByName(hostname), port); + SSLSocket socket = new SSLSocket(js, hostname, approvalCallback, + certSelectionCallback ); + setCipherPref(socket); + disableSSL2(socket); + socket.forceHandshake(); + System.out.println("Connected."); + socket.setUseClientMode(true); + + System.out.println("Posting Query = " + + "https://" + hostname + + ":" + portnumber + + "/" + url + + "?" + query); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + + ps.println("POST " + url + " HTTP/1.0"); + + // check to see if we have a cookie to send + if(j_session_id != null ) + ps.println("Cookie: " + j_session_id); + + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " +query.length()); + ps.println("Connection: Keep-Alive"); + + // special header posting if available + if(basic_auth_header_value != null) + { + System.out.println("basic_auth = " + basic_auth_header_value ); + ps.println("Authorization: Basic " + basic_auth_header_value ); + } + + ps.println(""); + ps.println(query); + ps.println("\r"); + ps.flush(); + os.flush(); + + try + { + hr = readResponse(socket.getInputStream()); + hr.parseContent(); + + } + catch (Exception e) + { + System.out.println("Exception"); + e.printStackTrace(); + st = false; + } + + socket.close(); + os.close(); + rawos.close(); + ps.close(); + + os=null; + rawos=null; + ps=null; + + } + + catch(Exception e) + { + System.err.println("Exception: Unable to Send Request:" +e); + e.printStackTrace(); + st = false; + } + + if(!st) + return null; + else + return hr; + } + + // performs non ssl connect to given host/port + // posts the given query data + // returns HTTPResponse + public HTTPResponse nonsslConnect(String hostname, String portnumber, + String url, String query) + { + + boolean st = true; + HTTPResponse hr = null; + + try + { + + System.out.println("#############################################"); + System.out.println("Attempting to connect to: " + hostname + ":" + + portnumber); + + Integer x = new Integer(portnumber); + int port = x.intValue(); + + Socket socket = new Socket(hostname, port); + + System.out.println("Posting Query = " + + "http://" + hostname + + ":" + portnumber + + "/" + url + + "?" + query); + + OutputStream rawos = socket.getOutputStream(); + BufferedOutputStream os = new BufferedOutputStream(rawos); + PrintStream ps = new PrintStream(os); + + System.out.println("Connected."); + + ps.println("POST " + url + " HTTP/1.0"); + + // check to see if we have a cookie to send + if(j_session_id != null ) + ps.println("Cookie: " + j_session_id); + + ps.println("Content-type: application/x-www-form-urlencoded"); + ps.println("Content-length: " +query.length()); + ps.println("Connection: Keep-Alive"); + + // special header posting if available + if(basic_auth_header_value != null) + { + System.out.println("basic_auth = " + basic_auth_header_value ); + ps.println("Authorization: Basic " + basic_auth_header_value ); + } + + ps.println(""); + ps.println(query); + ps.println("\r"); + ps.flush(); + os.flush(); + + try + { + hr = readResponse(socket.getInputStream()); + hr.parseContent(); + + } + catch (Exception e) + { + System.out.println("Exception"); + e.printStackTrace(); + st = false; + } + + socket.close(); + os.close(); + rawos.close(); + ps.close(); + + os=null; + rawos=null; + ps=null; + + } + + catch(Exception e) + { + System.err.println("Exception: Unable to Send Request:" +e); + e.printStackTrace(); + st = false; + } + + if(!st) + return null; + else + return hr; + } + + public HTTPResponse readResponse(InputStream inputStream) + throws Exception + { + // read response from http input stream and return HTTPResponse + byte[] buffer = new byte[BUFFER_SIZE]; + HTTPResponse response = null; + int statusCode = 0; + + // Read an initial chunk of the response from the server. + int bytesRead = inputStream.read(buffer); + if (bytesRead < 0) + { + throw new IOException("Unexpected end of input stream from server"); + } + + // Hopefully, this initial chunk will contain the entire header, so look for + // it. Technically, HTTP is supposed to use CRLF as the end-of-line + // character, so look for that first, but also check for LF by itself just + // in case. + int headerEndPos = -1; + int dataStartPos = -1; + for (int i=0; i < (bytesRead-3); i++) + { + if ((buffer[i] == '\r') && (buffer[i+1] == '\n') && + (buffer[i+2] == '\r') && (buffer[i+3] == '\n')) + { + headerEndPos = i; + dataStartPos = i+4; + break; + } + } + + if (headerEndPos < 0) + { + for (int i=0; i < (bytesRead-1); i++) + { + if ((buffer[i] == '\n') && (buffer[i+1] == '\n')) + { + headerEndPos = i; + dataStartPos = i+2; + break; + } + } + } + + + // In the event that we didn't get the entire header in the first pass, keep + // reading until we do have enough. + if (headerEndPos < 0) + { + byte[] buffer2 = new byte[BUFFER_SIZE]; + while (headerEndPos < 0) + { + int startPos = bytesRead; + int moreBytesRead = inputStream.read(buffer2); + if (moreBytesRead < 0) + { + throw new IOException("Unexpected end of input stream from server " + + "when reading more data from response"); + } + + byte[] newBuffer = new byte[bytesRead + moreBytesRead]; + System.arraycopy(buffer, 0, newBuffer, 0, bytesRead); + System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead); + buffer = newBuffer; + bytesRead += moreBytesRead; + + for (int i=startPos; i < (bytesRead-3); i++) + { + if ((buffer[i] == '\r') && (buffer[i+1] == '\n') && + (buffer[i+2] == '\r') && (buffer[i+3] == '\n')) + { + headerEndPos = i; + dataStartPos = i+4; + break; + } + } + + if (headerEndPos < 0) + { + for (int i=startPos; i < (bytesRead-1); i++) + { + if ((buffer[i] == '\n') && (buffer[i+1] == '\n')) + { + headerEndPos = i; + dataStartPos = i+2; + break; + } + } + } + } + } + + + // At this point, we should have the entire header, so read and analyze it. + String headerStr = new String(buffer, 0, headerEndPos); + StringTokenizer tokenizer = new StringTokenizer(headerStr, "\r\n"); + if (tokenizer.hasMoreTokens()) + { + String statusLine = tokenizer.nextToken(); + if (debugMode) + { + System.out.println("RESPONSE STATUS: " + statusLine); + } + + int spacePos = statusLine.indexOf(' '); + if (spacePos < 0) + { + System.out.println("ERROR: Unable to parse response header -- could " + + "not find protocol/version delimiter"); + return null; + + } + + String protocolVersion = statusLine.substring(0, spacePos); + int spacePos2 = statusLine.indexOf(' ', spacePos+1); + if (spacePos2 < 0) + { + System.out.println("ERROR: Unable to parse response header -- could " + + "not find response code delimiter"); + return null; + } + + try + { + statusCode = Integer.parseInt(statusLine.substring(spacePos+1, + spacePos2)); + } + catch (NumberFormatException nfe) + { + System.out.println("Unable to parse response header -- could " + + "not interpret status code as an integer"); + return null; + } + + String responseMessage = statusLine.substring(spacePos2+1); + response = new HTTPResponse(statusCode, protocolVersion, + responseMessage); + + while (tokenizer.hasMoreTokens()) + { + String headerLine = tokenizer.nextToken(); + if (debugMode) + { + System.out.println("RESPONSE HEADER: " + headerLine); + } + + int colonPos = headerLine.indexOf(':'); + if (colonPos < 0) + { + if (headerLine.toLowerCase().startsWith("http/")) + { + // This is a direct violation of RFC 2616, but certain HTTP servers + // seem to immediately follow a 100 continue with a 200 ok without + // the required CRLF in between. + System.out.println("ERROR: Found illegal status line '" + headerLine + + "'in the middle of a response -- attempting " + + "to deal with it as the start of a new " + + "response."); + statusLine = headerLine; + spacePos = statusLine.indexOf(' '); + if (spacePos < 0) + { + System.out.println("ERROR: Unable to parse response header -- " + + "could not find protocol/version " + + "delimiter"); + return null; + } + + protocolVersion = statusLine.substring(0, spacePos); + spacePos2 = statusLine.indexOf(' ', spacePos+1); + if (spacePos2 < 0) + { + System.out.println("ERROR: Unable to parse response header -- " + + "could not find response code delimiter"); + return null; + } + + try + { + statusCode = Integer.parseInt(statusLine.substring(spacePos+1, + spacePos2)); + } + catch (NumberFormatException nfe) + { + System.out.println("ERROR: Unable to parse response header -- " + + "could not interpret status code as an " + + "integer"); + return null; + } + + responseMessage = statusLine.substring(spacePos2+1); + response = new HTTPResponse(statusCode, protocolVersion, + responseMessage); + continue; + } + else + { + System.out.println("ERROR: Unable to parse response header -- no " + + "colon found on header line \"" + + headerLine + "\""); + } + } + + String headerName = headerLine.substring(0, colonPos); + String headerValue = headerLine.substring(colonPos+1).trim(); + response.addHeader(headerName, headerValue); + } + } + else + { + // This should never happen -- an empty response + System.out.println("Unable to parse response header -- empty " + + "header"); + } + + + // If the status code was 100 (continue), then it was an intermediate header + // and we need to keep reading until we get the real response header. + while (response.getStatusCode() == 100) + { + if (dataStartPos < bytesRead) + { + byte[] newBuffer = new byte[bytesRead - dataStartPos]; + System.arraycopy(buffer, dataStartPos, newBuffer, 0, newBuffer.length); + buffer = newBuffer; + bytesRead = buffer.length; + + headerEndPos = -1; + for (int i=0; i < (bytesRead-3); i++) + { + if ((buffer[i] == '\r') && (buffer[i+1] == '\n') && + (buffer[i+2] == '\r') && (buffer[i+3] == '\n')) + { + headerEndPos = i; + dataStartPos = i+4; + break; + } + } + + if (headerEndPos < 0) + { + for (int i=0; i < (bytesRead-1); i++) + { + if ((buffer[i] == '\n') && (buffer[i+1] == '\n')) + { + headerEndPos = i; + dataStartPos = i+2; + break; + } + } + } + } + else + { + buffer = new byte[0]; + bytesRead = 0; + headerEndPos = -1; + } + + + byte[] buffer2 = new byte[BUFFER_SIZE]; + while (headerEndPos < 0) + { + int startPos = bytesRead; + int moreBytesRead = inputStream.read(buffer2); + + if (moreBytesRead < 0) + { + throw new IOException("Unexpected end of input stream from server " + + "when reading more data from response"); + } + + byte[] newBuffer = new byte[bytesRead + moreBytesRead]; + System.arraycopy(buffer, 0, newBuffer, 0, bytesRead); + System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead); + buffer = newBuffer; + bytesRead += moreBytesRead; + + for (int i=startPos; i < (bytesRead-3); i++) + { + if ((buffer[i] == '\r') && (buffer[i+1] == '\n') && + (buffer[i+2] == '\r') && (buffer[i+3] == '\n')) + { + headerEndPos = i; + dataStartPos = i+4; + break; + } + } + + if (headerEndPos < 0) + { + for (int i=startPos; i < (bytesRead-1); i++) + { + if ((buffer[i] == '\n') && (buffer[i+1] == '\n')) + { + headerEndPos = i; + dataStartPos = i+2; + break; + } + } + } + } + + + // We should now have the next header, so examine it. + headerStr = new String(buffer, 0, headerEndPos); + tokenizer = new StringTokenizer(headerStr, "\r\n"); + if (tokenizer.hasMoreTokens()) + { + String statusLine = tokenizer.nextToken(); + if (debugMode) + { + System.out.println("RESPONSE STATUS: " + statusLine); + } + + int spacePos = statusLine.indexOf(' '); + if (spacePos < 0) + { + System.out.println("Unable to parse response header -- could " + + "not find protocol/version delimiter"); + } + + String protocolVersion = statusLine.substring(0, spacePos); + int spacePos2 = statusLine.indexOf(' ', spacePos+1); + if (spacePos2 < 0) + { + System.out.println("Unable to parse response header -- could " + + "not find response code delimiter"); + } + + try + { + statusCode = Integer.parseInt(statusLine.substring(spacePos+1, + spacePos2)); + } + catch (NumberFormatException nfe) + { + System.out.println("Unable to parse response header -- could " + + "not interpret status code as an integer"); + } + + String responseMessage = statusLine.substring(spacePos2+1); + response = new HTTPResponse(statusCode, protocolVersion, + responseMessage); + + while (tokenizer.hasMoreTokens()) + { + String headerLine = tokenizer.nextToken(); + if (debugMode) + { + System.out.println("RESPONSE HEADER: " + headerLine); + } + + int colonPos = headerLine.indexOf(':'); + if (colonPos < 0) + { + System.out.println("Unable to parse response header -- no " + + "colon found on header line \"" + + headerLine + "\""); + } + + String headerName = headerLine.substring(0, colonPos); + String headerValue = headerLine.substring(colonPos+1).trim(); + response.addHeader(headerName, headerValue); + } + } + else + { + // This should never happen -- an empty response + System.out.println("Unable to parse response header -- empty " + + "header"); + } + } + + + // Now that we have parsed the header, use it to determine how much data + // there is. If we're lucky, the server will have told us using the + // "Content-Length" header. + int contentLength = response.getContentLength(); + + + if (contentLength >= 0) + { + readContentDataUsingLength(response, inputStream, contentLength, buffer, + dataStartPos, bytesRead); + } + else + { + // It's not chunked encoding, so our last hope is that the connection + // will be closed when all the data has been sent. + String connectionStr = response.getHeader("connection"); + if ((connectionStr != null) && + (! connectionStr.equalsIgnoreCase("close"))) + { + System.out.println("ERROR:Unable to determine how to find when the " + + "end of the data has been reached (no " + + "content length, not chunked encoding, " + + "connection string is \"" + connectionStr + + "\" rather than \"close\")"); + } + else + { + readContentDataUsingConnectionClose(response, inputStream, buffer, + dataStartPos, bytesRead); + } + } + // Finally, return the response to the caller. + return response; + } + + /** + * Reads the actual data of the response based on the content length provided + * by the server in the response header. + * + * @param response The response with which the data is associated. + * @param inputStream The input stream from which to read the response. + * @param contentLength The number of bytes that the server said are in the + * response. + * @param dataRead The data that we have already read. This includes + * the header data, but may also include some or all of + * the content data as well. + * @param dataStartPos The position in the provided array at which the + * content data starts. + * @param dataBytesRead The total number of valid bytes in the provided + * array that should be considered part of the + * response (the number of header bytes is included in + * this count). + * + * @throws IOException If a problem occurs while reading data from the + * server. + */ + private void readContentDataUsingLength(HTTPResponse response, + InputStream inputStream, + int contentLength, byte[] dataRead, + int dataStartPos, int dataBytesRead) + throws IOException + { + if (contentLength <= 0) + { + response.setResponseData(new byte[0]); + return; + } + + + byte[] contentBytes = new byte[contentLength]; + int startPos = 0; + if (dataBytesRead > dataStartPos) + { + // We've already got some data to include in the header, so copy that into + // the content array. Make sure the server didn't do something stupid + // like return more data than it told us was in the response. + int bytesToCopy = Math.min(contentBytes.length, + (dataBytesRead - dataStartPos)); + System.arraycopy(dataRead, dataStartPos, contentBytes, 0, bytesToCopy); + startPos = bytesToCopy; + } + + byte[] buffer = new byte[BUFFER_SIZE]; + while (startPos < contentBytes.length) + { + int bytesRead = inputStream.read(buffer); + if (bytesRead < 0) + { + throw new IOException("Unexpected end of input stream reached when " + + "reading data from the server"); + } + + System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead); + startPos += bytesRead; + } + + + response.setResponseData(contentBytes); + } + + /** + * Reads the actual data of the response using chunked encoding, which is a + * way for the server to provide the data in several chunks rather than all at + * once. + * + * @param response The response with which the data is associated. + * @param inputStream The input stream from which to read the response. + * @param dataRead The data that we have already read. This includes + * the header data, but may also include some or all of + * the content data as well. + * @param dataStartPos The position in the provided array at which the + * content data starts. + * @param dataBytesRead The total number of valid bytes in the provided + * array that should be considered part of the + * response (the number of header bytes is included in + * this count). + * + * @throws IOException If a problem occurs while reading data from the + * server. + */ + private void readContentDataUsingConnectionClose(HTTPResponse response, + InputStream inputStream, + byte[] dataRead, + int dataStartPos, + int dataBytesRead) + throws IOException + { + // Create an array list that we will use to hold the chunks of information + // read from the server. + ArrayList bufferList = new ArrayList(); + + + // Create a variable to hold the total number of bytes in the data. + int totalBytes = 0; + + + // See if we have unread data in the array already provided. + int existingBytes = dataBytesRead - dataStartPos; + if (existingBytes > 0) + { + ByteBuffer byteBuffer = ByteBuffer.allocate(existingBytes); + byteBuffer.put(dataRead, dataStartPos, existingBytes); + bufferList.add(byteBuffer); + totalBytes += existingBytes; + } + + + // Keep reading until we hit the end of the input stream. + byte[] buffer = new byte[BUFFER_SIZE]; + while (true) + { + try + { + int bytesRead = inputStream.read(buffer); + if (bytesRead < 0) + { + // We've hit the end of the stream and therefore the end of the + // document. + break; + } + else if (bytesRead > 0) + { + ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead); + byteBuffer.put(buffer, 0, bytesRead); + bufferList.add(byteBuffer); + totalBytes += bytesRead; + } + } + catch (IOException ioe) + { + // In this case we'll assume that the end of the stream has been + // reached. It's possible that there was some other error, but we can't + // do anything about it so try to process what we've got so far. + System.out.println("ERROR: unable to read until end of stream"); + System.out.println("ERROR: "+ ioe.getMessage()); + break; + } + } + + + // Assemble the contents of all the buffers into a big array and store that + // array in the response. + int startPos = 0; + byte[] contentData = new byte[totalBytes]; + for (int i=0; i < bufferList.size(); i++) + { + ByteBuffer byteBuffer = (ByteBuffer) bufferList.get(i); + byteBuffer.flip(); + byteBuffer.get(contentData, startPos, byteBuffer.limit()); + startPos += byteBuffer.limit(); + } + response.setResponseData(contentData); + } + + // performs ssl connect to given host/port + // posts the given query data - format - a byte array + // returns HTTPResponse + + public HTTPResponse sslConnect(String hostname, String portnumber, + String url, byte[] data) + { + + boolean st = true; + HTTPResponse hr = null; + + try + { + + System.out.println("#############################################"); + System.out.println("Attempting to connect to: " + hostname + ":" + + portnumber); + + Integer x = new Integer(portnumber); + int port = x.intValue(); + + + SSLCertificateApprovalCallback approvalCallback = + new TestCertApprovalCallback(); + SSLClientCertificateSelectionCallback certSelectionCallback = + new TestClientCertificateSelectionCallback(); + + Socket js = new Socket(InetAddress.getByName(hostname), port); + SSLSocket socket = new SSLSocket(js, hostname, approvalCallback, + certSelectionCallback ); + setCipherPref(socket); + disableSSL2(socket); + socket.forceHandshake(); + System.out.println("Connected."); + socket.setUseClientMode(true); + + DataOutputStream dos = + new DataOutputStream(socket.getOutputStream()); + dos.writeBytes("POST /ocsp HTTP/1.0\r\n"); + dos.writeBytes("Content-length: " + data.length + "\r\n"); + dos.writeBytes("\r\n"); + dos.write(data); + dos.writeBytes("\r\n"); + dos.flush(); + + try + { + hr = readResponse(socket.getInputStream()); + hr.parseContent(); + } + catch (Exception e) + { + System.out.println("Exception"); + e.printStackTrace(); + st = false; + } + + socket.close(); + dos.close(); + + } + + catch(Exception e) + { + System.err.println("Exception: Unable to Send Request:" +e); + e.printStackTrace(); + st = false; + } + + if(!st) + return null; + else + return hr; + } + + // performs non ssl connect to given host/port + // posts the given query data + // returns HTTPResponse + public HTTPResponse nonsslConnect(String hostname, String portnumber, + String url, byte[] data) + { + + boolean st = true; + HTTPResponse hr = null; + + try + { + + System.out.println("#############################################"); + System.out.println("Attempting to connect to: " + hostname + ":" + + portnumber); + + Integer x = new Integer(portnumber); + int port = x.intValue(); + + Socket socket = new Socket(hostname, port); + + System.out.println("Posting Query = " + + "http://" + hostname + + ":" + portnumber + + "/" + url ); + + System.out.println("Connected."); + + DataOutputStream dos = + new DataOutputStream(socket.getOutputStream()); + dos.writeBytes("POST " + url + " HTTP/1.0\r\n"); + dos.writeBytes("Content-length: " + data.length + "\r\n"); + dos.writeBytes("\r\n"); + dos.write(data); + dos.writeBytes("\r\n"); + dos.flush(); + + try + { + hr = readResponse(socket.getInputStream()); + hr.parseContent(); + } + catch (Exception e) + { + System.out.println("Exception"); + e.printStackTrace(); + st = false; + } + + socket.close(); + dos.close(); + + } + + catch(Exception e) + { + System.err.println("Exception: Unable to Send Request:" +e); + e.printStackTrace(); + st = false; + } + + if(!st) + return null; + else + return hr; + } + + public static boolean init_nss() + { + try + { + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(false); + cCrypt.loginDB(); + } + catch(Exception e) + { + System.out.println("ERROR: unable to login to : " + + client_certdb_dir ); + return false; + } + + return true; + } + + public static void main(String args[]) + { + HTTPClient hc = new HTTPClient(); + HTTPResponse hr = null; + byte[] responseData = null; + + // parse args + StringHolder x_hostname = new StringHolder(); + StringHolder x_port = new StringHolder(); + StringHolder x_ssl = new StringHolder(); + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_client_cert_nickname = new StringHolder(); + StringHolder x_uri = new StringHolder(); + StringHolder x_query = new StringHolder(); + StringHolder x_request_type = new StringHolder(); + StringHolder x_auth_type = new StringHolder(); + StringHolder x_user_id = new StringHolder(); + StringHolder x_user_password = new StringHolder(); + StringHolder x_debug = new StringHolder(); + StringHolder x_decode = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("HTTPClient"); + + parser.addOption ("-hostname %s #Hostname", + x_hostname); + parser.addOption ("-port %s #port number", + x_port); + parser.addOption ("-ssl %s #HTTP or HTTPS[true or false]", + x_ssl); + parser.addOption ("-client_certdb_dir %s #CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #CertDB password", + x_client_certdb_pwd); + parser.addOption ("-client_cert_nickname %s #client cert nickname", + x_client_cert_nickname); + parser.addOption ("-uri %s #URI", + x_uri); + parser.addOption ("-query %s #URL encoded query string[note: url encode value part only for CS operations]", + x_query); + parser.addOption ("-request_type %s #Request Type [ post ]", + x_request_type); + parser.addOption ("-user_id %s #user id for authorization", + x_user_id); + parser.addOption ("-user_password %s #password for authorization", + x_user_password); + parser.addOption ("-auth_type %s #type of authorization [ BASIC ]", + x_auth_type); + parser.addOption ("-debug %s #enables display of debugging info", + x_debug); + parser.addOption ("-decode %s #URL Decode the resulting output" , + x_decode); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_hostname.value; + cs_port = x_port.value; + ssl = x_ssl.value; + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + client_cert_nickname = x_client_cert_nickname.value; + uri = x_uri.value; + query = x_query.value; + request_type = x_request_type.value; + user_id = x_user_id.value; + user_password = x_user_password.value; + auth_type = x_auth_type.value; + debug = x_debug.value; + + String decode = x_decode.value; + + // init_nss if needed + boolean st = init_nss(); + if(!st) + System.exit(-1); + + // set basic auth if needed + if(auth_type != null && auth_type.equalsIgnoreCase("BASIC")) + { + BASE64Encoder encoder = new BASE64Encoder(); + + String temp = encoder.encodeBuffer((user_id + + ":" + user_password).getBytes()); + + // note: temp already contains \r and \n. + // remove \r and \n from the base64 encoded string. + // causes problems when sending http post requests + // using PrintStream.println() + + temp = temp.replaceAll("\\r" , ""); + temp = temp.replaceAll("\\n" , ""); + + basic_auth_header_value = temp; + } + + // route to proper function + + if(ssl != null && ssl.equalsIgnoreCase("true")) + { + if(client_cert_nickname != null && + !client_cert_nickname.equalsIgnoreCase("null")) + { + // ssl client auth call + + hr = hc.sslConnectClientAuth(cs_hostname,cs_port, + client_cert_nickname, + uri,query); + } + + else + { + // ssl client call + hr = hc.sslConnect(cs_hostname,cs_port,uri,query); + } + } + else if(ssl!=null && ssl.equalsIgnoreCase("false")) + { + // non ssl connect + hr = hc.nonsslConnect(cs_hostname,cs_port,uri,query); + } + else + { + System.out.println("ERROR: ssl parameter is null"); + System.exit(-1); + } + + + // collect and print response + + responseData = hr.getResponseData(); + + if(hr.getStatusCode() == 200) + System.out.println("Response from Host:" + cs_hostname + " OK"); + else + { + System.out.println("ERROR: unable to get response from host:" + + cs_hostname); + System.exit(-1); + } + + String responseValue = null; + if(decode.equalsIgnoreCase("true")) + responseValue = URLDecoder.decode(hr.getHTML()); + else + responseValue = hr.getHTML(); + + + System.out.println("###############################"); + System.out.println("RESULT=" + responseValue); + System.out.println("###############################"); + + } + +}; diff --git a/pki/base/silent/src/http/HTTPResponse.java b/pki/base/silent/src/http/HTTPResponse.java new file mode 100644 index 000000000..f4d66adb5 --- /dev/null +++ b/pki/base/silent/src/http/HTTPResponse.java @@ -0,0 +1,382 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + + +import java.net.*; +import java.util.*; + + +public class HTTPResponse +{ + // The set of cookie values included in this response. + ArrayList cookieValueList; + + // The names of the headers included in this response. + ArrayList headerNameList; + + // The values of the headers included in this response. + ArrayList headerValueList; + + // The actual data associated with this response. + byte[] responseData; + + // The HTML document included in the response, if appropriate. + HTMLDocument htmlDocument; + + // The number of bytes contained in the content of the response. + int contentLength; + + // The HTTP status code for the response. + int statusCode; + + // The MIME type of the response. + String contentType; + + // The protocol version string for this response. + String protolVersion; + + // The response message for this response. + String responseMessage; + + // Parsed Content Name/Value pair info + ArrayList contentName; + ArrayList contentValue; + + + + /** + * Creates a new HTTP response with the provided status code. + * + * @param statusCode The HTTP status code for this response. + * @param protocolVersion The protocol and version for this response. + * @param responseMessage The message associated with this response. + */ + public HTTPResponse(int statusCode, String protocolVersion, + String responseMessage) + { + this.statusCode = statusCode; + this.protolVersion = protocolVersion; + this.responseMessage = responseMessage; + + htmlDocument = null; + contentType = null; + contentLength = -1; + responseData = new byte[0]; + cookieValueList = new ArrayList(); + headerNameList = new ArrayList(); + headerValueList = new ArrayList(); + contentName = new ArrayList(); + contentValue = new ArrayList(); + } + + + + /** + * Retrieves the status code for this HTTP response. + * + * @return The status code for this HTTP response. + */ + public int getStatusCode() + { + return statusCode; + } + + + + /** + * Retrieves the protocol version for this HTTP response. + * + * @return The protocol version for this HTTP response. + */ + public String getProtocolVersion() + { + return protolVersion; + } + + + + /** + * Retrieves the response message for this HTTP response. + * + * @return The response message for this HTTP response. + */ + public String getResponseMessage() + { + return responseMessage; + } + + + + /** + * Retrieves the value of the header with the specified name. If the + * specified header has more than one value, then only the first will be + * retrieved. + * + * @return The value of the header with the specified name, or + * <CODE>null</CODE> if no such header is available. + */ + public String getHeader(String headerName) + { + String lowerName = headerName.toLowerCase(); + + for (int i=0; i < headerNameList.size(); i++) + { + if (lowerName.equals(headerNameList.get(i))) + { + return (String) headerValueList.get(i); + } + } + + return null; + } + + + + /** + * Retrieves the set of values for the specified header. + * + * @return The set of values for the specified header. + */ + public String[] getHeaderValues(String headerName) + { + ArrayList valueList = new ArrayList(); + String lowerName = headerName.toLowerCase(); + + for (int i=0; i < headerNameList.size(); i++) + { + if (lowerName.equals(headerNameList.get(i))) + { + valueList.add(headerValueList.get(i)); + } + } + + String[] values = new String[valueList.size()]; + valueList.toArray(values); + return values; + } + + + + /** + * Adds a header with the given name and value to this response. + * + * @param headerName The name of the header to add to this response. + * @param headerValue The value of the header to add to this response. + */ + public void addHeader(String headerName, String headerValue) + { + String lowerName = headerName.toLowerCase(); + headerNameList.add(lowerName); + headerValueList.add(headerValue); + + if (lowerName.equals("content-length")) + { + try + { + contentLength = Integer.parseInt(headerValue); + } catch (NumberFormatException nfe) {} + } + else if (lowerName.equals("content-type")) + { + contentType = headerValue; + } + else if (lowerName.equals("set-cookie")) + { + cookieValueList.add(headerValue); + } + } + + + + /** + * Retrieves a two-dimensional array containing the header data for this + * response, with each element being an array containing a name/value pair. + * + * @return A two-dimensional array containing the header data for this + * response. + */ + public String[][] getHeaderElements() + { + String[][] headerElements = new String[headerNameList.size()][2]; + for (int i=0; i < headerNameList.size(); i++) + { + headerElements[i][0] = (String) headerNameList.get(i); + headerElements[i][1] = (String) headerValueList.get(i); + } + + return headerElements; + } + + + + /** + * Retrieves the raw data included in this HTTP response. If the response did + * not include any data, an empty array will be returned. + * + * @return The raw data included in this HTTP response. + */ + public byte[] getResponseData() + { + return responseData; + } + + + public String getHTML() + { + String htmlString = new String(responseData); + return htmlString; + } + + public String getHTMLwithoutTags() + { + String htmlString = new String(responseData); + HTMLDocument htmldocument = new HTMLDocument(htmlString); + return htmldocument.getTextData(); + } + public void parseContent() + { + // parse the responseData byte[] buffer and split content into name + // value pair + String htmlString = new String(responseData); + StringTokenizer st = new StringTokenizer(htmlString, "\n"); + Utilities ut = new Utilities(); + + while(st.hasMoreTokens()) + { + String line = st.nextToken(); + // format for line assumed to be name="value"; format + + int eqPos = line.indexOf('=') ; + if(eqPos != -1) + { + String name = line.substring(0,eqPos); + String tempval = line.substring(eqPos+1).trim(); + String value = ut.cleanupQuotes(ut.removechar(tempval)); + + // add to array + this.contentName.add(name.trim()); + this.contentValue.add(value); + } + + } + + } + + + + public String getContentValue(String headerName) + { + for (int i=0; i < contentName.size(); i++) + { + if (headerName.equals(contentName.get(i))) + { + return (String) contentValue.get(i); + } + } + + return null; + } + + public ArrayList getContentNames() + { + return contentName; + } + + public ArrayList getContentValues() + { + return contentValue; + } + + /** + * Sets the actual data associated with this response. + * + * @param responseData The actual data associated with this response. + */ + public void setResponseData(byte[] responseData) + { + if (responseData == null) + { + this.responseData = new byte[0]; + } + else + { + this.responseData = responseData; + } + } + + + + /** + * Retrieves the content length associated with this response. + * + * @return The content length associated with this response, or -1 if no + * content length is available. + */ + public int getContentLength() + { + return contentLength; + } + + + + /** + * Retrieves the content type associated with this response. + * + * @return The content type associated with this response, or + * <CODE>null</CODE> if no content type is available. + */ + public String getContentType() + { + return contentType; + } + + + + /** + * Retrieves an array containing the values of the cookies that should be set + * based on the information in this response. + * + * @return An array containing the values of the cookies that should be set + * based on the information in this response. + */ + public String[] getCookieValues() + { + String[] cookieValues = new String[cookieValueList.size()]; + cookieValueList.toArray(cookieValues); + return cookieValues; + } + + public String getCookieValue(String headerName) + { + for (int i=0; i < cookieValueList.size(); i++) + { + System.out.println("cookie list: " + cookieValueList.get(i)); + + String temp = (String) cookieValueList.get(i); + if (temp.startsWith(headerName)) + { + return (String) cookieValueList.get(i); + } + } + + return null; + } + + +} + diff --git a/pki/base/silent/src/ocsp/ConfigureOCSP.java b/pki/base/silent/src/ocsp/ConfigureOCSP.java new file mode 100644 index 000000000..09c0c9e06 --- /dev/null +++ b/pki/base/silent/src/ocsp/ConfigureOCSP.java @@ -0,0 +1,1110 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.osutil.*; + +public class ConfigureOCSP +{ + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/ocsp/admin/console/config/login"; + public static String wizard_uri = "/ocsp/admin/console/config/wizard"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + + public static String sd_login_uri = "/ca/ee/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/ee/ca/getCookie"; + public static String pkcs12_uri = "/ocsp/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = null; + + public static String ca_hostname = null; + public static String ca_port = null; + public static String ca_ssl_port = null; + + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String ldap_host = null; + public static String ldap_port = null; + public static String bind_dn = null; + public static String bind_password = null; + public static String base_dn = null; + public static String db_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String ocsp_signing_cert_name = null; + public static String ocsp_signing_cert_req = null; + public static String ocsp_signing_cert_pp = null; + public static String ocsp_signing_cert_cert = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String ocsp_subsystem_cert_name = null; + public static String ocsp_subsystem_cert_req = null; + public static String ocsp_subsystem_cert_pp = null; + public static String ocsp_subsystem_cert_cert = null; + + public static String backup_pwd = null; + + // cert subject names + public static String ocsp_sign_cert_subject_name = null; + public static String ocsp_subsystem_cert_subject_name = null; + public static String ocsp_server_cert_subject_name = null; + + public static String subsystem_name = null; + public ConfigureOCSP () + { + // do nothing :) + } + + public void sleep_time() + { + try + { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } + catch(Exception e) + { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // get cookie + String temp = hr.getCookieValue("JSESSIONID"); + + if(temp!=null) + { + int index = temp.indexOf(";"); + hc.j_session_id = temp.substring(0,index); + st = true; + } + + hr = null; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream( + hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return st; + } + + public boolean DomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String domain_url = "https://" + sd_hostname + ":" + sd_ssl_port ; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url) + + "&choice=existingdomain"+ + "&p=1" + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean DisplayChainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String query_string = null; + + query_string = "p=2" + "&op=next" + "&xml=true"; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean SecurityDomainLoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String ocsp_url = "https://" + cs_hostname + ":" + cs_port + + "/ocsp/admin/console/config/wizard" + + "?p=3&subsystem=OCSP" ; + + String query_string = "url=" + URLEncoder.encode(ocsp_url); + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_login_uri,query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + sd_admin_password + + "&url=" + URLEncoder.encode(ocsp_url) ; + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + + String ocsp_session_id = hr.getContentValue("header.session_id"); + String ocsp_url_1 = hr.getContentValue("header.url"); + + System.out.println("OCSP_SESSION_ID=" + ocsp_session_id ); + System.out.println("OCSP_URL=" + ocsp_url_1 ); + + // use session id to connect back to OCSP + + String query_string_2 = "p=3" + + "&subsystem=OCSP" + + "&session_id=" + ocsp_session_id + + "&xml=true" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + query_string_2); + + // parse xml + // bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + // px.parse(bais); + // px.prettyprintxml(); + + return true; + + } + + public boolean SubsystemPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=3" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name) + + "&choice=newsubsystem" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean LdapConnectionPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=5" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host) + + "&port=" + URLEncoder.encode(ldap_port) + + "&binddn=" + URLEncoder.encode(bind_dn) + + "&__bindpwd=" + URLEncoder.encode(bind_password) + + "&basedn=" + URLEncoder.encode(base_dn) + + "&database=" + URLEncoder.encode(db_name) + + "&display=" + URLEncoder.encode("displayStr") + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if(token_name.equalsIgnoreCase("internal")) + { + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token") + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } + // HSM + else + { + // login to hsm first + query_string = "p=7" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name) + + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + + return true; + } + + public boolean KeyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList al = null; + + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&signing_custom_size=" + key_size + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + + "&custom_size=" + key_size + + "&signing_keytype=" + key_type + + "&subsystem_keytype=" + key_type + + "&sslserver_keytype=" + key_type + + "&keytype=" + key_type + + "&signing_choice=default"+ + "&subsystem_choice=default"+ + "&sslserver_choice=default"+ + "&choice=default"+ + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + al = px.constructvaluelist("CertReqPair","DN"); + // get ca cert subject name + if(al != null) + { + for (int i=0; i < al.size(); i++) + { + String temp = (String) al.get(i); + if(temp.indexOf("OCSP Signing") > 0 ) + { + ocsp_signing_cert_name = temp; + } + else if(temp.indexOf("OCSP Subsystem") > 0 ) + { + ocsp_subsystem_cert_name = temp; + } + else + { + server_cert_name = temp; + } + } + } + + System.out.println("default: ocsp_signing_cert_name=" + ocsp_signing_cert_name); + System.out.println("default: ocsp_subsystem_cert_name=" + ocsp_subsystem_cert_name); + System.out.println("default: server_cert_name=" + server_cert_name); + return true; + } + + public boolean CertSubjectPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + + String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + String query_string = "p=9" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(ocsp_subsystem_cert_subject_name) + + "&signing=" + + URLEncoder.encode(ocsp_sign_cert_subject_name) + + "&sslserver=" + + URLEncoder.encode(ocsp_server_cert_subject_name) + + "&urls=" + + URLEncoder.encode(domain_url) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + req_list = px.constructvaluelist("CertReqPair","Request"); + cert_list = px.constructvaluelist("CertReqPair","Certificate"); + dn_list = px.constructvaluelist("CertReqPair","Nickname"); + + if(req_list != null && cert_list != null && dn_list != null) + { + for (int i=0; i < dn_list.size(); i++) + { + String temp = (String) dn_list.get(i); + + if(temp.indexOf("ocspSigningCert") >= 0 ) + { + ocsp_signing_cert_req = (String) req_list.get(i); + ocsp_signing_cert_cert = (String) cert_list.get(i); + } + else if(temp.indexOf("subsystemCert") >= 0 ) + { + ocsp_subsystem_cert_req = (String) req_list.get(i); + ocsp_subsystem_cert_cert = (String) cert_list.get(i); + } + else + { + server_cert_req = (String) req_list.get(i); + server_cert_cert = (String) cert_list.get(i); + } + } + } + + return true; + } + + public boolean CertificatePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(ocsp_subsystem_cert_cert) + + "&subsystem_cc=" + + "&signing=" + + URLEncoder.encode(ocsp_signing_cert_cert) + + "&signing_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert) + + "&sslserver_cc=" + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + + System.out.println("html returned=" + hr.getHTML()); + + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean BackupPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + backup_pwd + + "&__pwdagain=" + backup_pwd + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean SavePKCS12Panel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = ""; + + hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string); + + // dump hr.getResponseData() to file + + try + { + FileOutputStream fos = new FileOutputStream("/tmp/tmp-ocsp.p12"); + fos.write(hr.getResponseData()); + fos.close(); + + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream("/tmp/tmp-ocsp.p12"); + PFX.Template pfxt = new PFX.Template(); + PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis, 2048)); + System.out.println("Decoded PFX"); + + // now peruse it for interesting info + System.out.println("Version: "+pfx.getVersion()); + AuthenticatedSafes authSafes = pfx.getAuthSafes(); + SEQUENCE asSeq = authSafes.getSequence(); + System.out.println("AuthSafes has "+ + asSeq.size()+" SafeContents"); + + fis.close(); + } + catch(Exception e) + { + System.out.println("ERROR: Exception=" + e.getMessage()); + return false; + } + + return true; + } + + public boolean AdminCertReqPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + + String cert_subject = "CN=ocsp-" + admin_user; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + agent_cert_subject, + agent_key_size, + agent_key_type); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if(crmf_request == null) + { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + + "&uid=" + admin_user + + "&name=" + admin_user + + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email) + + "&cert_request=" + + URLEncoder.encode(admin_cert_request) + + "&subject=" + agent_cert_subject + + "&clone=new" + + "&import=true" + + "&securitydomain=" + domain_name + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(ca_hostname,ca_ssl_port,ee_uri,query_string); + + // get response data + String cert_to_import = + new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + System.out.println("Imported Cert=" + cert_to_import); + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n" ; + String end = "\r\n-----END CERTIFICATE-----" ; + + st = cCrypt.importCert(start+cert_to_import+end,agent_name); + if(!st) + { + System.out.println("ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert"); + return true; + } + + public boolean UpdateDomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=14" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(ca_hostname) + + "&caPort=" + URLEncoder.encode(ca_port) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + + public boolean ConfigureOCSPInstance() + { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + hc = new HTTPClient(); + + // 1. Login panel + boolean log_st = LoginPanel(); + if(!log_st) + { + System.out.println("ERROR: ConfigureOCSP: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if(!dom_st) + { + System.out.println("ERROR: ConfigureOCSP: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureOCSP: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // security domain login panel + boolean disp_sd = SecurityDomainLoginPanel(); + if(!disp_sd) + { + System.out.println("ERROR: ConfigureOCSP: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // subsystem panel + boolean disp_ss = SubsystemPanel(); + if(!disp_ss) + { + System.out.println("ERROR: ConfigureOCSP: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if(!disp_ldap) + { + System.out.println("ERROR: ConfigureOCSP: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if(!disp_token) + { + System.out.println("ERROR: ConfigureOCSP: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + if(!disp_key) + { + System.out.println("ERROR: ConfigureOCSP: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if(!disp_csubj) + { + System.out.println("ERROR: ConfigureOCSP: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + if(!disp_cp) + { + System.out.println("ERROR: ConfigureOCSP: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // backup panel + boolean disp_back = BackupPanel(); + if(!disp_back) + { + System.out.println("ERROR: ConfigureOCSP: BackupPanel() failure"); + return false; + } + + sleep_time(); + // save panel + boolean disp_save = SavePKCS12Panel(); + if(!disp_save) + { + System.out.println("ERROR: ConfigureOCSP: SavePKCS12Panel() failure"); + return false; + } + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if(!disp_adm) + { + System.out.println("ERROR: ConfigureOCSP: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if(!disp_im) + { + System.out.println("ERROR: ConfigureOCSP: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if(!disp_ud) + { + System.out.println("ERROR: ConfigureOCSP: UpdateDomainPanel() failure"); + return false; + } + + sleep_time(); + return true; + } + + public static void main(String args[]) + { + ConfigureOCSP ca = new ConfigureOCSP(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = new StringHolder(); + + StringHolder x_ca_hostname = new StringHolder(); + StringHolder x_ca_port = new StringHolder(); + StringHolder x_ca_ssl_port = new StringHolder(); + + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // ldap + + StringHolder x_ldap_host = new StringHolder(); + StringHolder x_ldap_port = new StringHolder(); + StringHolder x_bind_dn = new StringHolder(); + StringHolder x_bind_password = new StringHolder(); + StringHolder x_base_dn = new StringHolder(); + StringHolder x_db_name = new StringHolder(); + + // key size + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + StringHolder x_backup_pwd = new StringHolder(); + + // ca cert subject name params + StringHolder x_ocsp_sign_cert_subject_name = new StringHolder(); + StringHolder x_ocsp_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_ocsp_server_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("ConfigureOCSP"); + + parser.addOption ("-cs_hostname %s #CS Hostname", + x_cs_hostname); + parser.addOption ("-cs_port %s #CS SSL port", + x_cs_port); + + parser.addOption ("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption ("-sd_ssl_port %s #Security Domain SSL port", + x_sd_ssl_port); + parser.addOption ("-sd_admin_name %s #Security Domain Admin Name", + x_sd_admin_name); + parser.addOption ("-sd_admin_password %s #Security Domain Admin password", + x_sd_admin_password); + + parser.addOption ("-ca_hostname %s #CA Hostname", + x_ca_hostname); + parser.addOption ("-ca_port %s #CA non SSL port", + x_ca_port); + parser.addOption ("-ca_ssl_port %s #CA SSL port", + x_ca_ssl_port); + + parser.addOption ("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption ("-preop_pin %s #pre op pin", + x_preop_pin); + parser.addOption ("-domain_name %s #domain name", + x_domain_name); + parser.addOption ("-admin_user %s #Admin User Name", + x_admin_user); + parser.addOption ("-admin_email %s #Admin email", + x_admin_email); + parser.addOption ("-admin_password %s #Admin password", + x_admin_password); + parser.addOption ("-agent_name %s #Agent Cert Nickname", + x_agent_name); + + parser.addOption ("-ldap_host %s #ldap host", + x_ldap_host); + parser.addOption ("-ldap_port %s #ldap port", + x_ldap_port); + parser.addOption ("-bind_dn %s #ldap bind dn", + x_bind_dn); + parser.addOption ("-bind_password %s #ldap bind password", + x_bind_password); + parser.addOption ("-base_dn %s #base dn", + x_base_dn); + parser.addOption ("-db_name %s #db name", + x_db_name); + + parser.addOption ("-key_size %s #Key Size", + x_key_size); + parser.addOption ("-key_type %s #Key type [RSA,ECC]", + x_key_type); + parser.addOption ("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption ("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + + parser.addOption ("-agent_key_size %s #Agent Cert Key Size", + x_agent_key_size); + parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]", + x_agent_key_type); + parser.addOption ("-agent_cert_subject %s #Agent Cert Subject", + x_agent_cert_subject); + + parser.addOption ("-backup_pwd %s #PKCS12 password", + x_backup_pwd); + + parser.addOption ( + "-ocsp_sign_cert_subject_name %s #OCSP cert subject name", + x_ocsp_sign_cert_subject_name); + parser.addOption ( + "-ocsp_subsystem_cert_subject_name %s #OCSP subsystem cert subject name", + x_ocsp_subsystem_cert_subject_name); + parser.addOption ( + "-ocsp_server_cert_subject_name %s #OCSP server cert subject name", + x_ocsp_server_cert_subject_name); + + parser.addOption ( + "-subsystem_name %s #OCSP subsystem name", + x_subsystem_name); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + ca_hostname = x_ca_hostname.value; + ca_port = x_ca_port.value; + ca_ssl_port = x_ca_ssl_port.value; + + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + ldap_host = x_ldap_host.value; + ldap_port = x_ldap_port.value; + bind_dn = x_bind_dn.value; + bind_password = x_bind_password.value; + base_dn = x_base_dn.value; + db_name = x_db_name.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + backup_pwd = x_backup_pwd.value; + + ocsp_sign_cert_subject_name = x_ocsp_sign_cert_subject_name.value ; + ocsp_subsystem_cert_subject_name = + x_ocsp_subsystem_cert_subject_name.value; + ocsp_server_cert_subject_name = x_ocsp_server_cert_subject_name.value ; + + subsystem_name = x_subsystem_name.value ; + + + boolean st = ca.ConfigureOCSPInstance(); + + if (!st) + { + System.out.println("ERROR: unable to create OCSP"); + System.exit(-1); + } + + System.out.println("Certficate System - OCSP Instance Configured"); + System.exit(0); + + } + +}; diff --git a/pki/base/silent/src/ra/ConfigureRA.java b/pki/base/silent/src/ra/ConfigureRA.java new file mode 100644 index 000000000..06e4f0883 --- /dev/null +++ b/pki/base/silent/src/ra/ConfigureRA.java @@ -0,0 +1,923 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.osutil.*; + +public class ConfigureRA +{ + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/ra/admin/console/config/login"; + public static String wizard_uri = "/ra/admin/console/config/wizard"; + public static String domain_uri = "/ra/ee/ca/domain"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + + public static String sd_login_uri = "/ca/ee/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/ee/ca/getCookie"; + public static String pkcs12_uri = "/ra/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = null; + + public static String ca_hostname = null; + public static String ca_port = null; + public static String ca_ssl_port = null; + + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String ra_subsystem_cert_name = null; + public static String ra_subsystem_cert_req = null; + public static String ra_subsystem_cert_pp = null; + public static String ra_subsystem_cert_cert = null; + + // names + public static String ra_subsystem_cert_subject_name = null; + public static String ra_server_cert_subject_name = null; + public static String subsystem_name = null; + + + public ConfigureRA () + { + // do nothing :) + } + + public void sleep_time() + { + try + { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } + catch(Exception e) + { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.nonsslConnect(cs_hostname,cs_port,login_uri,query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // no cookie for tps + // get cookie + String temp = hr.getCookieValue("pin"); + + if(temp!=null) + { + int index = temp.indexOf(";"); + hc.j_session_id = temp.substring(0,index); + st = true; + } + + hr = null; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream( + hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + st = true; + return st; + } + + public boolean DomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String domain_url = "https://" + sd_hostname + ":" + sd_ssl_port ; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url) + + "&choice=existingdomain"+ + "&p=1" + + "&op=next" + + "&xml=true"; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean DisplayChainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String query_string = null; + + query_string = "p=2" + "&op=next" + "&xml=true"; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + return true; + + } + + public boolean SecurityDomainLoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String ra_url = "https://" + cs_hostname + ":" + cs_port + + "/ra/admin/console/config/wizard" + + "?p=3&subsystem=RA" ; + + String query_string = "url=" + URLEncoder.encode(ra_url); + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_login_uri,query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + sd_admin_password + + "&url=" + URLEncoder.encode(ra_url) ; + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + sleep_time(); + + String ra_session_id = hr.getContentValue("header.session_id"); + String ra_url_1 = hr.getContentValue("header.url"); + + System.out.println("RA_SESSION_ID=" + ra_session_id ); + System.out.println("RA_URL=" + ra_url_1 ); + + // use session id to connect back to RA + + String query_string_2 = "p=3" + + "&session_id=" + ra_session_id + + "&subsystem=RA" + + "&xml=true" ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri, + query_string_2); + + // parse xml - no parsing + + return true; + + } + + public boolean SubsystemPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + sleep_time(); + String query_string = "p=3" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name) + + "&choice=newsubsystem" ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + sleep_time(); + String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + // CA choice panel + query_string = "p=4" + "&op=next" + "&xml=true" + + "&urls=" + + URLEncoder.encode(ca_url) ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean DBPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + // SQL LITE PANEL + + String query_string = "p=5" + "&op=next" + "&xml=true" ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + //////////////////////////////////////////////////////// + String query_string = null; + + // Software Token + if(token_name.equalsIgnoreCase("internal")) + { + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("NSS Certificate DB") + + ""; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } + // HSM + else + { + // login to hsm first + query_string = "p=7" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name) + + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + + ""; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name) + + ""; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + + return true; + } + + public boolean KeyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList friendly_list = null; + ArrayList dn_list = null; + + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + + "&custom_size=" + key_size + + "&subsystem_keytype=" + key_type + + "&sslserver_keytype=" + key_type + + "&keytype=" + key_type + + "&subsystem_choice=custom"+ + "&sslserver_choice=custom"+ + "&choice=custom"+ + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean CertSubjectPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList friendly_list = null; + + String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + String query_string = "p=9" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(ra_subsystem_cert_subject_name) + + "&sslserver=" + + URLEncoder.encode(ra_server_cert_subject_name) + + "&urls=" + + URLEncoder.encode(ca_url) + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // parse the certs if needed + + return true; + } + + public boolean CertificatePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + "&subsystem_cc=" + + "&sslserver=" + + "&sslserver_cc=" + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean AdminCertReqPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + // not used + String cert_subject = "CN=" + "ra-" + admin_user; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + agent_cert_subject, + agent_key_size, + agent_key_type); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if(crmf_request == null) + { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + + "&uid=" + admin_user + + "&name=" + admin_user + + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email) + + "&cert_request=" + + URLEncoder.encode(admin_cert_request) + + "&subject=" + agent_cert_subject + + "&clone=0" + + "&import=true" + + "&securitydomain=" + domain_name + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(ca_hostname,ca_ssl_port,ee_uri,query_string); + String cert_to_import = null; + + try + { + cert_to_import = + new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + + } + catch (Exception e) + { + System.out.println("ERROR: failed to retrieve cert"); + } + + System.out.println("Imported Cert=" + cert_to_import); + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n" ; + String end = "\r\n-----END CERTIFICATE-----" ; + + st = cCrypt.importCert(start+cert_to_import+end,agent_name); + if(!st) + { + System.out.println("ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert"); + return true; + } + + public boolean UpdateDomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=12" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(ca_hostname) + + "&caPort=" + URLEncoder.encode(ca_ssl_port) + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + // px.parse(bais); + // px.prettyprintxml(); + + return true; + } + + public boolean ConfigureRAInstance() + { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + hc = new HTTPClient(); + + sleep_time(); + // 1. Login panel + boolean log_st = LoginPanel(); + if(!log_st) + { + System.out.println("ERROR: JSESSIONID not found."); + System.out.println("ERROR: ConfigureRA: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if(!dom_st) + { + System.out.println("ERROR: ConfigureRA: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureRA: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // security domain login panel + boolean disp_sd = SecurityDomainLoginPanel(); + if(!disp_sd) + { + System.out.println("ERROR: ConfigureRA: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // subsystem panel + boolean disp_ss = SubsystemPanel(); + if(!disp_ss) + { + System.out.println("ERROR: ConfigureRA: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = DBPanel(); + if(!disp_ldap) + { + System.out.println("ERROR: ConfigureRA: DBPanel() failure"); + return false; + } + + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if(!disp_token) + { + System.out.println("ERROR: ConfigureRA: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + if(!disp_key) + { + System.out.println("ERROR: ConfigureRA: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if(!disp_csubj) + { + System.out.println("ERROR: ConfigureRA: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + if(!disp_cp) + { + System.out.println("ERROR: ConfigureRA: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if(!disp_adm) + { + System.out.println("ERROR: ConfigureRA: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if(!disp_im) + { + System.out.println("ERROR: ConfigureRA: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if(!disp_ud) + { + System.out.println("ERROR: ConfigureRA: UpdateDomainPanel() failure"); + return false; + } + + return true; + } + + public static void main(String args[]) + { + ConfigureRA ca = new ConfigureRA(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = new StringHolder(); + + StringHolder x_ca_hostname = new StringHolder(); + StringHolder x_ca_port = new StringHolder(); + StringHolder x_ca_ssl_port = new StringHolder(); + + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // key size + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + + // ra cert subject name params + StringHolder x_ra_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_ra_server_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + + // parse the args + ArgParser parser = new ArgParser("ConfigureRA"); + + parser.addOption ("-cs_hostname %s #CS Hostname", + x_cs_hostname); + parser.addOption ("-cs_port %s #CS SSL port", + x_cs_port); + + parser.addOption ("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption ("-sd_ssl_port %s #Security Domain SSL port", + x_sd_ssl_port); + parser.addOption ("-sd_admin_name %s #Security Domain username", + x_sd_admin_name); + parser.addOption ("-sd_admin_password %s #Security Domain password", + x_sd_admin_password); + + parser.addOption ("-ca_hostname %s #CA Hostname", + x_ca_hostname); + parser.addOption ("-ca_port %s #CA non SSL port", + x_ca_port); + parser.addOption ("-ca_ssl_port %s #CA SSL port", + x_ca_ssl_port); + + parser.addOption ("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption ("-preop_pin %s #pre op pin", + x_preop_pin); + parser.addOption ("-domain_name %s #domain name", + x_domain_name); + parser.addOption ("-admin_user %s #Admin User Name", + x_admin_user); + parser.addOption ("-admin_email %s #Admin email", + x_admin_email); + parser.addOption ("-admin_password %s #Admin password", + x_admin_password); + parser.addOption ("-agent_name %s #Agent Cert Nickname", + x_agent_name); + + parser.addOption ("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption ("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + parser.addOption ("-key_size %s #Key Size", + x_key_size); + parser.addOption ("-key_type %s #Key type [rsa,ecc]", + x_key_type); + + parser.addOption ("-agent_key_size %s #Agent Cert Key Size", + x_agent_key_size); + parser.addOption ("-agent_key_type %s #Agent cert Key type [rsa]", + x_agent_key_type); + parser.addOption ("-agent_cert_subject %s #Agent cert Subject", + x_agent_cert_subject); + + parser.addOption ( + "-ra_subsystem_cert_subject_name %s #RA subsystem cert subject name", + x_ra_subsystem_cert_subject_name); + parser.addOption ( + "-ra_server_cert_subject_name %s #RA server cert subject name", + x_ra_server_cert_subject_name); + + parser.addOption ( + "-subsystem_name %s #RA subsystem name", + x_subsystem_name); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + ca_hostname = x_ca_hostname.value; + ca_port = x_ca_port.value; + ca_ssl_port = x_ca_ssl_port.value; + + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + ra_subsystem_cert_subject_name = + x_ra_subsystem_cert_subject_name.value; + ra_server_cert_subject_name = + x_ra_server_cert_subject_name.value ; + + subsystem_name = x_subsystem_name.value ; + + + + boolean st = ca.ConfigureRAInstance(); + + if (!st) + { + System.out.println("ERROR: unable to create RA"); + System.exit(-1); + } + + System.out.println("Certficate System - RA Instance Configured"); + System.exit(0); + + } + +}; diff --git a/pki/base/silent/src/subca/ConfigureSubCA.java b/pki/base/silent/src/subca/ConfigureSubCA.java new file mode 100644 index 000000000..a9530be6c --- /dev/null +++ b/pki/base/silent/src/subca/ConfigureSubCA.java @@ -0,0 +1,1171 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import com.netscape.osutil.*; + +public class ConfigureSubCA +{ + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/ca/admin/console/config/login"; + public static String wizard_uri = "/ca/admin/console/config/wizard"; + public static String domain_uri = "/ca/ee/ca/domain"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + public static String sd_login_uri = "/ca/ee/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/ee/ca/getCookie"; + public static String pkcs12_uri = "/ca/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = null; + + public static String ca_hostname = null; + public static String ca_port = null; + public static String ca_ssl_port = null; + + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String ldap_host = null; + public static String ldap_port = null; + public static String bind_dn = null; + public static String bind_password = null; + public static String base_dn = null; + public static String db_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String ca_cert_name = null; + public static String ca_cert_req = null; + public static String ca_cert_pp = null; + public static String ca_cert_cert = null; + + public static String ocsp_cert_name = null; + public static String ocsp_cert_req = null; + public static String ocsp_cert_pp = null; + public static String ocsp_cert_cert = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String ca_subsystem_cert_name = null; + public static String ca_subsystem_cert_req = null; + public static String ca_subsystem_cert_pp = null; + public static String ca_subsystem_cert_cert = null; + + public static String backup_pwd = null; + + public static String subsystem_name = null; + + // names + public static String subca_sign_cert_subject_name = null; + public static String subca_subsystem_cert_subject_name = null; + public static String subca_ocsp_cert_subject_name = null; + public static String subca_server_cert_subject_name = null; + + public ConfigureSubCA () + { + // do nothing :) + } + + public void sleep_time() + { + try + { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } + catch(Exception e) + { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // get cookie + String temp = hr.getCookieValue("JSESSIONID"); + + if(temp!=null) + { + int index = temp.indexOf(";"); + hc.j_session_id = temp.substring(0,index); + st = true; + } + + hr = null; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream( + hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return st; + } + + public boolean DomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String domain_url = "https://" + sd_hostname + ":" + sd_ssl_port ; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url) + + "&sdomainName="+ + "&choice=existingdomain"+ + "&p=1" + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + String query_string_1 = "p=2" + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string_1); + + return true; + + } + + public boolean SecurityDomainLoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String subca_url = "https://" + cs_hostname + ":" + cs_port + + "/ca/admin/console/config/wizard" + + "?p=3&subsystem=CA" ; + + String query_string = "url=" + URLEncoder.encode(subca_url); + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_login_uri,query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + sd_admin_password + + "&url=" + URLEncoder.encode(subca_url) ; + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + + String subca_session_id = hr.getContentValue("header.session_id"); + String subca_url_1 = hr.getContentValue("header.url"); + + System.out.println("SUBCA_SESSION_ID=" + subca_session_id ); + System.out.println("SUBCA_URL=" + subca_url_1 ); + + // use session id to connect back to subCA + + String query_string_2 = "p=3" + + "&subsystem=CA" + + "&session_id=" + subca_session_id + + "&xml=true" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + query_string_2); + + return true; + + } + + public boolean DisplayChainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string; + + hr = null; + query_string = "p=3" + "&op=next" + "&xml=true" + + "&choice=newsubsystem" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name) + + "&urls=0" ; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean HierarchyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=join" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + + return true; + + } + + public boolean LdapConnectionPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=7" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host) + + "&port=" + URLEncoder.encode(ldap_port) + + "&binddn=" + URLEncoder.encode(bind_dn) + + "&__bindpwd=" + URLEncoder.encode(bind_password) + + "&basedn=" + URLEncoder.encode(base_dn) + + "&database=" + URLEncoder.encode(db_name) + + "&display=" + URLEncoder.encode("displayStr") + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + /////////////////////////////////////////////////////// + String query_string = null; + + // Software Token + if(token_name.equalsIgnoreCase("internal")) + { + query_string = "p=8" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token") + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } + // HSM + else + { + // login to hsm first + query_string = "p=9" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name) + + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=8" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + return true; + } + + public boolean KeyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList al = null; + + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + + "&signing_keytype=" + key_type + + "&keytype=" + key_type + + "&choice=default"+ + "&op=next"+ + "&custom_size=" + key_size + + "&ocsp_signing_keytype=" + key_type + + "&subsystem_keytype=" + key_type + + "&ocsp_signing_custom_size=" + key_size + + "&signing_custom_size=" + key_size + + "&ocsp_signing_choice=default"+ + "&signing_choice=default"+ + "&subsystem_choice=default"+ + "&sslserver_keytype=" + key_type + + "&sslserver_choice=default"+ + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + al = px.constructvaluelist("CertReqPair","DN"); + // get ca cert subject name + if(al != null) + { + for (int i=0; i < al.size(); i++) + { + String temp = (String) al.get(i); + if(temp.indexOf("Certificate Authority") > 0 ) + { + ca_cert_name = temp; + } + else if(temp.indexOf("OCSP Signing Certificate") > 0 ) + { + ocsp_cert_name = temp; + } + else if(temp.indexOf("Subsystem Certificate") > 0 ) + { + ca_subsystem_cert_name = temp; + } + else + { + server_cert_name = temp; + } + } + } + + System.out.println("default: ca_cert_name=" + ca_cert_name); + System.out.println("default: ocsp_cert_name=" + ocsp_cert_name); + System.out.println("default: ca_subsystem_cert_name=" + + ca_subsystem_cert_name); + System.out.println("default: server_cert_name=" + server_cert_name); + return true; + } + + public boolean CertSubjectPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + + String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(subca_subsystem_cert_subject_name) + + "&ocsp_signing=" + + URLEncoder.encode(subca_ocsp_cert_subject_name) + + "&signing=" + + URLEncoder.encode(subca_sign_cert_subject_name) + + "&sslserver=" + + URLEncoder.encode(subca_server_cert_subject_name) + + "&urls=" + + URLEncoder.encode(domain_url) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + req_list = px.constructvaluelist("CertReqPair","Request"); + cert_list = px.constructvaluelist("CertReqPair","Certificate"); + dn_list = px.constructvaluelist("CertReqPair","Nickname"); + + System.out.println("req_list_size=" + req_list.size()); + System.out.println("cert_list_size=" + cert_list.size()); + System.out.println("dn_list_size=" + dn_list.size()); + + if(req_list != null && cert_list != null && dn_list != null) + { + for (int i=0; i < dn_list.size(); i++) + { + String temp = (String) dn_list.get(i); + + if(temp.indexOf("caSigningCert") >= 0 ) + { + ca_cert_req = (String) req_list.get(i); + ca_cert_cert = (String) cert_list.get(i); + } + else if(temp.indexOf("ocspSigningCert") >= 0 ) + { + ocsp_cert_req = (String) req_list.get(i); + ocsp_cert_cert = (String) cert_list.get(i); + } + else if(temp.indexOf("subsystemCert") >= 0 ) + { + ca_subsystem_cert_req = (String) req_list.get(i); + ca_subsystem_cert_cert = (String) cert_list.get(i); + } + else + { + server_cert_req = (String) req_list.get(i); + server_cert_cert = (String) cert_list.get(i); + } + } + } + + System.out.println("ca_cert_name=" + subca_sign_cert_subject_name); + System.out.println("ocsp_cert_name=" + subca_ocsp_cert_subject_name); + System.out.println("ca_subsystem_cert_name=" + + subca_subsystem_cert_subject_name); + System.out.println("server_cert_name=" + + subca_server_cert_subject_name); + + System.out.println("ca_cert_req=" + ca_cert_req); + System.out.println("ocsp_cert_req=" + ocsp_cert_req); + System.out.println("ca_subsystem_cert_req=" + ca_subsystem_cert_req); + System.out.println("server_cert_req=" + server_cert_req); + + System.out.println("ca_cert_cert=" + ca_cert_cert); + System.out.println("ocsp_cert_cert=" + ocsp_cert_cert); + System.out.println("ca_subsystem_cert_cert=" + ca_subsystem_cert_cert); + System.out.println("server_cert_cert=" + server_cert_cert); + + return true; + } + + public boolean CertificatePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + + String query_string = "p=12" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(ca_subsystem_cert_cert) + + "&subsystem_cc=" + + "&ocsp_signing=" + + URLEncoder.encode(ocsp_cert_cert) + + "&ocsp_signing_cc=" + + "&signing=" + + URLEncoder.encode(ca_cert_cert) + + "&signing_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert) + + "&sslserver_cc=" + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean BackupPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + backup_pwd + + "&__pwdagain=" + backup_pwd + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean SavePKCS12Panel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = ""; + + hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string); + + // dump hr.getResponseData() to file + + try + { + FileOutputStream fos = new FileOutputStream("/tmp/tmp-subca.p12"); + fos.write(hr.getResponseData()); + fos.close(); + + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream("/tmp/tmp-subca.p12"); + PFX.Template pfxt = new PFX.Template(); + PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis, 2048)); + System.out.println("Decoded PFX"); + + // now peruse it for interesting info + System.out.println("Version: "+pfx.getVersion()); + AuthenticatedSafes authSafes = pfx.getAuthSafes(); + SEQUENCE asSeq = authSafes.getSequence(); + System.out.println("AuthSafes has "+ + asSeq.size()+" SafeContents"); + + fis.close(); + } + catch(Exception e) + { + return false; + } + + return true; + } + + public boolean AdminCertReqPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + + String cert_subject = "CN=" + "subca-" + admin_user; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + agent_cert_subject, + agent_key_size, + agent_key_type); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if(crmf_request == null) + { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=15" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + + "&uid=" + admin_user + + "&name=" + admin_user + + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email) + + "&cert_request=" + + URLEncoder.encode(admin_cert_request) + + "&subject=" + agent_cert_subject + + "&clone=new" + + "&import=true" + + "&securitydomain=" + domain_name + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,ee_uri,query_string); + + // get response data + String cert_to_import = + new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + + System.out.println("Imported Cert=" + cert_to_import); + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n" ; + String end = "\r\n-----END CERTIFICATE-----" ; + + st = cCrypt.importCert(start+cert_to_import+end,agent_name); + if(!st) + { + System.out.println("ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert:" + agent_name); + return true; + } + + public boolean UpdateDomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=16" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode("/") + + "&caPort=" + URLEncoder.encode("/") + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + String caHost = px.getvalue("host"); + String caPort = px.getvalue("port"); + String systemType = px.getvalue("systemType"); + + System.out.println("caHost=" + caHost); + System.out.println("caPort=" + caPort); + System.out.println("systemType=" + systemType); + + return true; + } + + public boolean ConfigureCAInstance() + { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + hc = new HTTPClient(); + + sleep_time(); + // 1. Login panel + boolean log_st = LoginPanel(); + if(!log_st) + { + System.out.println("ERROR: ConfigureCA: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if(!dom_st) + { + System.out.println("ERROR: ConfigureCA: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 2a. domain panel + boolean sd_st = SecurityDomainLoginPanel(); + if(!sd_st) + { + System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureCA: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // 5. hierarchy panel + boolean disp_h = HierarchyPanel(); + if(!disp_h) + { + System.out.println("ERROR: ConfigureCA: HierarchyPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if(!disp_ldap) + { + System.out.println("ERROR: ConfigureCA: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if(!disp_token) + { + System.out.println("ERROR: ConfigureCA: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + if(!disp_key) + { + System.out.println("ERROR: ConfigureCA: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if(!disp_csubj) + { + System.out.println("ERROR: ConfigureCA: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + if(!disp_cp) + { + System.out.println("ERROR: ConfigureCA: CertificatePanel() failure"); + return false; + } + + sleep_time(); + boolean disp_back = BackupPanel(); + if(!disp_back) + { + System.out.println("ERROR: ConfigureCA: BackupPanel() failure"); + return false; + } + + sleep_time(); + boolean disp_save = SavePKCS12Panel(); + if(!disp_save) + { + System.out.println("ERROR: ConfigureCA: SavePKCS12Panel() failure"); + return false; + } + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if(!disp_adm) + { + System.out.println("ERROR: ConfigureCA: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if(!disp_im) + { + System.out.println("ERROR: ConfigureCA: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if(!disp_ud) + { + System.out.println("ERROR: ConfigureCA: UpdateDomainPanel() failure"); + return false; + } + + + return true; + } + + public static void main(String args[]) + { + ConfigureSubCA ca = new ConfigureSubCA(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = new StringHolder(); + + StringHolder x_ca_hostname = new StringHolder(); + StringHolder x_ca_port = new StringHolder(); + StringHolder x_ca_ssl_port = new StringHolder(); + + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // ldap + StringHolder x_ldap_host = new StringHolder(); + StringHolder x_ldap_port = new StringHolder(); + StringHolder x_bind_dn = new StringHolder(); + StringHolder x_bind_password = new StringHolder(); + StringHolder x_base_dn = new StringHolder(); + StringHolder x_db_name = new StringHolder(); + + // key size + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + StringHolder x_backup_pwd = new StringHolder(); + + // subsystem name + StringHolder x_subsystem_name = new StringHolder(); + + // subject names + StringHolder x_subca_sign_cert_subject_name = new StringHolder(); + StringHolder x_subca_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_subca_ocsp_cert_subject_name = new StringHolder(); + StringHolder x_subca_server_cert_subject_name = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("ConfigureSubCA"); + + parser.addOption ("-cs_hostname %s #CS Hostname", + x_cs_hostname); + parser.addOption ("-cs_port %s #CS SSL port", + x_cs_port); + + parser.addOption ("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption ("-sd_ssl_port %s #Security Domain SSL port", + x_sd_ssl_port); + parser.addOption ("-sd_admin_name %s #Security Domain admin name", + x_sd_admin_name); + parser.addOption ("-sd_admin_password %s #Security Domain admin password", + x_sd_admin_password); + + parser.addOption ("-ca_hostname %s #CA Hostname", + x_ca_hostname); + parser.addOption ("-ca_port %s #CA non SSL port", + x_ca_port); + parser.addOption ("-ca_ssl_port %s #CA SSL port", + x_ca_ssl_port); + + parser.addOption ("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption ("-preop_pin %s #pre op pin", + x_preop_pin); + parser.addOption ("-domain_name %s #domain name", + x_domain_name); + parser.addOption ("-admin_user %s #Admin User Name", + x_admin_user); + parser.addOption ("-admin_email %s #Admin email", + x_admin_email); + parser.addOption ("-admin_password %s #Admin password", + x_admin_password); + parser.addOption ("-agent_name %s #Agent Cert Nickname", + x_agent_name); + + parser.addOption ("-ldap_host %s #ldap host", + x_ldap_host); + parser.addOption ("-ldap_port %s #ldap port", + x_ldap_port); + parser.addOption ("-bind_dn %s #ldap bind dn", + x_bind_dn); + parser.addOption ("-bind_password %s #ldap bind password", + x_bind_password); + parser.addOption ("-base_dn %s #base dn", + x_base_dn); + parser.addOption ("-db_name %s #db name", + x_db_name); + + parser.addOption ("-key_size %s #Key Size", + x_key_size); + parser.addOption ("-key_type %s #Key type [RSA,ECC]", + x_key_type); + parser.addOption ("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption ("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + + parser.addOption ("-agent_key_size %s #Agent Cert Key Size", + x_agent_key_size); + parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]", + x_agent_key_type); + parser.addOption ("-agent_cert_subject %s #Agent Cert Subject", + x_agent_cert_subject); + + parser.addOption ("-backup_pwd %s #PKCS12 backup password", + x_backup_pwd); + + parser.addOption ("-subsystem_name %s #Subsystem name", + x_subsystem_name); + + parser.addOption ( + "-subca_sign_cert_subject_name %s #subCA cert subject name", + x_subca_sign_cert_subject_name); + parser.addOption ( + "-subca_subsystem_cert_subject_name %s #subCA subsystem cert subject name", + x_subca_subsystem_cert_subject_name); + parser.addOption ( + "-subca_ocsp_cert_subject_name %s #subCA ocsp cert subject name", + x_subca_ocsp_cert_subject_name); + parser.addOption ( + "-subca_server_cert_subject_name %s #subCA server cert subject name", + x_subca_server_cert_subject_name); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + ca_hostname = x_ca_hostname.value; + ca_port = x_ca_port.value; + ca_ssl_port = x_ca_ssl_port.value; + + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + ldap_host = x_ldap_host.value; + ldap_port = x_ldap_port.value; + bind_dn = x_bind_dn.value; + bind_password = x_bind_password.value; + base_dn = x_base_dn.value; + db_name = x_db_name.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + backup_pwd = x_backup_pwd.value; + subsystem_name = x_subsystem_name.value; + + subca_sign_cert_subject_name = x_subca_sign_cert_subject_name.value ; + subca_subsystem_cert_subject_name = + x_subca_subsystem_cert_subject_name.value; + subca_ocsp_cert_subject_name = x_subca_ocsp_cert_subject_name.value ; + subca_server_cert_subject_name = x_subca_server_cert_subject_name.value ; + + + boolean st = ca.ConfigureCAInstance(); + + if (!st) + { + System.out.println("ERROR: unable to create CA"); + System.exit(-1); + } + + System.out.println("Certficate System - CA Instance Configured."); + System.exit(0); + + } + +}; diff --git a/pki/base/silent/src/tks/ConfigureTKS.java b/pki/base/silent/src/tks/ConfigureTKS.java new file mode 100644 index 000000000..624d5bd43 --- /dev/null +++ b/pki/base/silent/src/tks/ConfigureTKS.java @@ -0,0 +1,1083 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.osutil.*; + +public class ConfigureTKS +{ + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/tks/admin/console/config/login"; + public static String wizard_uri = "/tks/admin/console/config/wizard"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + + public static String sd_login_uri = "/ca/ee/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/ee/ca/getCookie"; + public static String pkcs12_uri = "/tks/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + + public static String ca_hostname = null; + public static String ca_port = null; + public static String ca_ssl_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = null; + + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String ldap_host = null; + public static String ldap_port = null; + public static String bind_dn = null; + public static String bind_password = null; + public static String base_dn = null; + public static String db_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String tks_subsystem_cert_name = null; + public static String tks_subsystem_cert_req = null; + public static String tks_subsystem_cert_pp = null; + public static String tks_subsystem_cert_cert = null; + + public static String backup_pwd = null; + + // names + public static String tks_subsystem_cert_subject_name = null; + public static String tks_server_cert_subject_name = null; + public static String subsystem_name = null; + + public ConfigureTKS () + { + // do nothing :) + } + + public void sleep_time() + { + try + { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } + catch(Exception e) + { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // get cookie + String temp = hr.getCookieValue("JSESSIONID"); + + if(temp!=null) + { + int index = temp.indexOf(";"); + hc.j_session_id = temp.substring(0,index); + st = true; + } + + hr = null; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream( + hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return st; + } + + public boolean DomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String domain_url = "https://" + sd_hostname + ":" + sd_ssl_port ; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url) + + "&choice=existingdomain"+ + "&p=1" + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean DisplayChainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String query_string = null; + + query_string = "p=2" + "&op=next" + "&xml=true"; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean SecurityDomainLoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String tks_url = "https://" + cs_hostname + ":" + cs_port + + "/tks/admin/console/config/wizard" + + "?p=3&subsystem=TKS" ; + + String query_string = "url=" + URLEncoder.encode(tks_url); + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_login_uri,query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + sd_admin_password + + "&url=" + URLEncoder.encode(tks_url) ; + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + + String tks_session_id = hr.getContentValue("header.session_id"); + String tks_url_1 = hr.getContentValue("header.url"); + + System.out.println("TKS_SESSION_ID=" + tks_session_id ); + System.out.println("TKS_URL=" + tks_url_1 ); + + // use session id to connect back to TKS + + String query_string_2 = "p=3" + + "&subsystem=TKS" + + "&session_id=" + tks_session_id + + "&xml=true" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, + query_string_2); + + // parse xml + // bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + // px.parse(bais); + // px.prettyprintxml(); + + return true; + + } + + public boolean SubsystemPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=3" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name) + + "&choice=newsubsystem" ; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean LdapConnectionPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=5" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host) + + "&port=" + URLEncoder.encode(ldap_port) + + "&binddn=" + URLEncoder.encode(bind_dn) + + "&__bindpwd=" + URLEncoder.encode(bind_password) + + "&basedn=" + URLEncoder.encode(base_dn) + + "&database=" + URLEncoder.encode(db_name) + + "&display=" + URLEncoder.encode("displayStr") + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if(token_name.equalsIgnoreCase("internal")) + { + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token") + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } + // HSM + else + { + // login to hsm first + query_string = "p=7" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name) + + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=6" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name) + + ""; + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + return true; + } + + public boolean KeyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList al = null; + + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + + "&custom_size=" + key_size + + "&subsystem_keytype=" + key_type + + "&sslserver_keytype=" + key_type + + "&keytype=" + key_type + + "&subsystem_choice=default"+ + "&sslserver_choice=default"+ + "&choice=default"+ + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + al = px.constructvaluelist("CertReqPair","DN"); + // get ca cert subject name + if(al != null) + { + for (int i=0; i < al.size(); i++) + { + String temp = (String) al.get(i); + if(temp.indexOf("TKS Subsystem") > 0 ) + { + tks_subsystem_cert_name = temp; + } + else + { + server_cert_name = temp; + } + } + } + + System.out.println("default: tks_subsystem_cert_name=" + + tks_subsystem_cert_name); + System.out.println("default: server_cert_name=" + + server_cert_name); + return true; + } + + public boolean CertSubjectPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + + String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + String query_string = "p=9" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(tks_subsystem_cert_subject_name) + + "&sslserver=" + + URLEncoder.encode(tks_server_cert_subject_name) + + "&urls=" + + URLEncoder.encode(domain_url) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + req_list = px.constructvaluelist("CertReqPair","Request"); + cert_list = px.constructvaluelist("CertReqPair","Certificate"); + dn_list = px.constructvaluelist("CertReqPair","Nickname"); + + if(req_list != null && cert_list != null && dn_list != null) + { + for (int i=0; i < dn_list.size(); i++) + { + String temp = (String) dn_list.get(i); + + if(temp.indexOf("subsystemCert") >= 0 ) + { + tks_subsystem_cert_req = (String) req_list.get(i); + tks_subsystem_cert_cert = (String) cert_list.get(i); + } + else + { + server_cert_req = (String) req_list.get(i); + server_cert_cert = (String) cert_list.get(i); + } + } + } + + return true; + } + + public boolean CertificatePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(tks_subsystem_cert_cert) + + "&subsystem_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert) + + "&sslserver_cc=" + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean BackupPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + backup_pwd + + "&__pwdagain=" + backup_pwd + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean SavePKCS12Panel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = ""; + + hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string); + + // dump hr.getResponseData() to file + + try + { + FileOutputStream fos = new FileOutputStream("/tmp/tmp-tks.p12"); + fos.write(hr.getResponseData()); + fos.close(); + + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream("/tmp/tmp-tks.p12"); + PFX.Template pfxt = new PFX.Template(); + PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis, 2048)); + System.out.println("Decoded PFX"); + + // now peruse it for interesting info + System.out.println("Version: "+pfx.getVersion()); + AuthenticatedSafes authSafes = pfx.getAuthSafes(); + SEQUENCE asSeq = authSafes.getSequence(); + System.out.println("AuthSafes has "+ + asSeq.size()+" SafeContents"); + + fis.close(); + } + catch(Exception e) + { + System.out.println("ERROR: Exception=" + e.getMessage()); + return false; + } + + return true; + } + + public boolean AdminCertReqPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + + String cert_subject = "CN=tks-" + admin_user; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + agent_cert_subject, + agent_key_size, + agent_key_type); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if(crmf_request == null) + { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + + "&uid=" + admin_user + + "&name=" + admin_user + + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email) + + "&cert_request=" + + URLEncoder.encode(admin_cert_request) + + "&subject=" + agent_cert_subject + + "&clone=new" + + "&import=true" + + "&securitydomain=" + domain_name + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(ca_hostname,ca_ssl_port,ee_uri,query_string); + + // get response data + String cert_to_import = + new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + System.out.println("Imported Cert=" + cert_to_import); + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n" ; + String end = "\r\n-----END CERTIFICATE-----" ; + + st = cCrypt.importCert(start+cert_to_import+end,agent_name); + if(!st) + { + System.out.println("ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert"); + return true; + } + + public boolean UpdateDomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=14" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(ca_hostname) + + "&caPort=" + URLEncoder.encode(ca_port) + + ""; + + hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + + public boolean ConfigureTKSInstance() + { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + hc = new HTTPClient(); + + sleep_time(); + // 1. Login panel + boolean log_st = LoginPanel(); + if(!log_st) + { + System.out.println("ERROR: ConfigureTKS: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if(!dom_st) + { + System.out.println("ERROR: ConfigureTKS: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureTKS: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // security domain login panel + boolean disp_sd = SecurityDomainLoginPanel(); + if(!disp_sd) + { + System.out.println("ERROR: ConfigureTKS: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // subsystem panel + boolean disp_ss = SubsystemPanel(); + if(!disp_ss) + { + System.out.println("ERROR: ConfigureTKS: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if(!disp_ldap) + { + System.out.println("ERROR: ConfigureTKS: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if(!disp_token) + { + System.out.println("ERROR: ConfigureTKS: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + if(!disp_key) + { + System.out.println("ERROR: ConfigureTKS: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if(!disp_csubj) + { + System.out.println("ERROR: ConfigureTKS: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + if(!disp_cp) + { + System.out.println("ERROR: ConfigureTKS: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // backup panel + boolean disp_back = BackupPanel(); + if(!disp_back) + { + System.out.println("ERROR: ConfigureTKS: BackupPanel() failure"); + return false; + } + + sleep_time(); + // save panel + boolean disp_save = SavePKCS12Panel(); + if(!disp_save) + { + System.out.println("ERROR: ConfigureTKS: SavePKCS12Panel() failure"); + return false; + } + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if(!disp_adm) + { + System.out.println("ERROR: ConfigureTKS: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if(!disp_im) + { + System.out.println("ERROR: ConfigureTKS: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if(!disp_ud) + { + System.out.println("ERROR: ConfigureTKS: UpdateDomainPanel() failure"); + return false; + } + + sleep_time(); + return true; + } + + public static void main(String args[]) + { + ConfigureTKS ca = new ConfigureTKS(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = new StringHolder(); + + StringHolder x_ca_hostname = new StringHolder(); + StringHolder x_ca_port = new StringHolder(); + StringHolder x_ca_ssl_port = new StringHolder(); + + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // ldap + + StringHolder x_ldap_host = new StringHolder(); + StringHolder x_ldap_port = new StringHolder(); + StringHolder x_bind_dn = new StringHolder(); + StringHolder x_bind_password = new StringHolder(); + StringHolder x_base_dn = new StringHolder(); + StringHolder x_db_name = new StringHolder(); + + // key size + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + StringHolder x_backup_pwd = new StringHolder(); + + // tks cert subject name params + StringHolder x_tks_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_tks_server_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + // parse the args + ArgParser parser = new ArgParser("ConfigureTKS"); + + parser.addOption ("-cs_hostname %s #CS Hostname", + x_cs_hostname); + parser.addOption ("-cs_port %s #CS SSL port", + x_cs_port); + + parser.addOption ("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption ("-sd_ssl_port %s #Security Domain SSL port", + x_sd_ssl_port); + parser.addOption ("-sd_admin_name %s #Security Domain Admin Name", + x_sd_admin_name); + parser.addOption ("-sd_admin_password %s #Security Domain Admin password", + x_sd_admin_password); + + parser.addOption ("-ca_hostname %s #CA Hostname", + x_ca_hostname); + parser.addOption ("-ca_port %s #CA non SSL port", + x_ca_port); + parser.addOption ("-ca_ssl_port %s #CA SSL port", + x_ca_ssl_port); + + parser.addOption ("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption ("-preop_pin %s #pre op pin", + x_preop_pin); + parser.addOption ("-domain_name %s #domain name", + x_domain_name); + parser.addOption ("-admin_user %s #Admin User Name", + x_admin_user); + parser.addOption ("-admin_email %s #Admin email", + x_admin_email); + parser.addOption ("-admin_password %s #Admin password", + x_admin_password); + parser.addOption ("-agent_name %s #Agent Cert Nickname", + x_agent_name); + + parser.addOption ("-ldap_host %s #ldap host", + x_ldap_host); + parser.addOption ("-ldap_port %s #ldap port", + x_ldap_port); + parser.addOption ("-bind_dn %s #ldap bind dn", + x_bind_dn); + parser.addOption ("-bind_password %s #ldap bind password", + x_bind_password); + parser.addOption ("-base_dn %s #base dn", + x_base_dn); + parser.addOption ("-db_name %s #db name", + x_db_name); + + parser.addOption ("-key_size %s #Key Size", + x_key_size); + parser.addOption ("-key_type %s #Key type [RSA,ECC]", + x_key_type); + parser.addOption ("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption ("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + + parser.addOption ("-agent_key_size %s #Agent Cert Key Size", + x_agent_key_size); + parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]", + x_agent_key_type); + parser.addOption ("-agent_cert_subject %s #Agent Cert Subject", + x_agent_cert_subject); + + parser.addOption ("-backup_pwd %s #PKCS12 password", + x_backup_pwd); + + parser.addOption ( + "-tks_subsystem_cert_subject_name %s #TKS subsystem cert subject name", + x_tks_subsystem_cert_subject_name); + parser.addOption ( + "-tks_server_cert_subject_name %s #TKS server cert subject name", + x_tks_server_cert_subject_name); + + parser.addOption ( + "-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + + ca_hostname = x_ca_hostname.value; + ca_port = x_ca_port.value; + ca_ssl_port = x_ca_ssl_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + ldap_host = x_ldap_host.value; + ldap_port = x_ldap_port.value; + bind_dn = x_bind_dn.value; + bind_password = x_bind_password.value; + base_dn = x_base_dn.value; + db_name = x_db_name.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + backup_pwd = x_backup_pwd.value; + + tks_subsystem_cert_subject_name = + x_tks_subsystem_cert_subject_name.value; + tks_server_cert_subject_name = + x_tks_server_cert_subject_name.value ; + + subsystem_name = x_subsystem_name.value ; + + + + boolean st = ca.ConfigureTKSInstance(); + + if (!st) + { + System.out.println("ERROR: unable to create TKS"); + System.exit(-1); + } + + System.out.println("Certficate System - TKS Instance Configured."); + System.exit(0); + + } + +}; diff --git a/pki/base/silent/src/tps/ConfigureTPS.java b/pki/base/silent/src/tps/ConfigureTPS.java new file mode 100644 index 000000000..0f588f477 --- /dev/null +++ b/pki/base/silent/src/tps/ConfigureTPS.java @@ -0,0 +1,1099 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +import java.util.*; +import java.net.*; +import java.io.*; + +import com.netscape.cmsutil.ocsp.*; +import com.netscape.cmsutil.ocsp.Request; + +import org.mozilla.jss.*; +import org.mozilla.jss.pkcs12.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.CertDatabaseException; +import sun.misc.*; +import java.lang.Exception; + +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.pkcs11.PK11Token; + +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509Key; +import netscape.security.x509.X500Name; + +import com.netscape.osutil.*; + +public class ConfigureTPS +{ + + public static Hashtable mUsedPort = new Hashtable(); + + // define global variables + + public static HTTPClient hc = null; + + public static String login_uri = "/tps/admin/console/config/login"; + public static String wizard_uri = "/tps/admin/console/config/wizard"; + public static String domain_uri = "/tps/ee/ca/domain"; + public static String ee_uri = "/ca/ee/ca/getBySerial"; + + public static String sd_login_uri = "/ca/ee/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/ee/ca/getCookie"; + public static String pkcs12_uri = "/tps/admin/console/config/savepkcs12"; + + public static String cs_hostname = null; + public static String cs_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = null; + + public static String ca_hostname = null; + public static String ca_port = null; + public static String ca_ssl_port = null; + + public static String drm_hostname = null; + public static String drm_ssl_port = null; + + public static String tks_hostname = null; + public static String tks_ssl_port = null; + + public static String client_certdb_dir = null; + public static String client_certdb_pwd = null; + + // Login Panel + public static String pin = null; + + public static String domain_name = null; + + public static String admin_user = null; + public static String admin_email = null; + public static String admin_password = null; + public static String admin_serial_number = null; + public static String agent_name = null; + + public static String ldap_auth_host = null; + public static String ldap_auth_port = null; + public static String ldap_auth_base_dn = null; + + public static String ldap_host = null; + public static String ldap_port = null; + public static String bind_dn = null; + public static String bind_password = null; + public static String base_dn = null; + public static String db_name = null; + + public static String key_size = null; + public static String key_type = null; + public static String token_name = null; + public static String token_pwd = null; + + public static String agent_key_size = null; + public static String agent_key_type = null; + public static String agent_cert_subject = null; + + public static String tps_transport_cert_name = null; + public static String tps_transport_cert_req = null; + public static String tps_transport_cert_pp = null; + public static String tps_transport_cert_cert = null; + + public static String tps_storage_cert_name = null; + public static String tps_storage_cert_req = null; + public static String tps_storage_cert_pp = null; + public static String tps_storage_cert_cert = null; + + public static String server_cert_name = null; + public static String server_cert_req = null; + public static String server_cert_pp = null; + public static String server_cert_cert = null; + + public static String tps_subsystem_cert_name = null; + public static String tps_subsystem_cert_req = null; + public static String tps_subsystem_cert_pp = null; + public static String tps_subsystem_cert_cert = null; + + public static String ss_keygen = null; + + // names + public static String tps_subsystem_cert_subject_name = null; + public static String tps_server_cert_subject_name = null; + public static String subsystem_name = null; + + + public ConfigureTPS () + { + // do nothing :) + } + + public void sleep_time() + { + try + { + System.out.println("Sleeping for 5 secs.."); + Thread.sleep(5000); + } + catch(Exception e) + { + System.out.println("ERROR: sleep problem"); + } + + } + + public boolean LoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "pin=" + pin + "&xml=true"; + + hr = hc.nonsslConnect(cs_hostname,cs_port,login_uri,query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // no cookie for tps + // get cookie + String temp = hr.getCookieValue("pin"); + + if(temp!=null) + { + int index = temp.indexOf(";"); + hc.j_session_id = temp.substring(0,index); + st = true; + } + + hr = null; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri, + "p=0&op=next&xml=true"); + + // parse xml here + + bais = new ByteArrayInputStream( + hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + st = true; + return st; + } + + public boolean DomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String domain_url = "https://" + sd_hostname + ":" + sd_ssl_port ; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url) + + "&choice=existingdomain"+ + "&p=1" + + "&op=next" + + "&xml=true"; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + + } + + public boolean DisplayChainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String query_string = null; + + query_string = "p=2" + "&op=next" + "&xml=true"; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + return true; + + } + + public boolean SecurityDomainLoginPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String tps_url = "https://" + cs_hostname + ":" + cs_port + + "/tps/admin/console/config/wizard" + + "?p=3&subsystem=TPS" ; + + String query_string = "url=" + URLEncoder.encode(tps_url); + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_login_uri,query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + sd_admin_password + + "&url=" + URLEncoder.encode(tps_url) ; + + hr = hc.sslConnect(sd_hostname,sd_ssl_port,sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + sleep_time(); + + String tps_session_id = hr.getContentValue("header.session_id"); + String tps_url_1 = hr.getContentValue("header.url"); + + System.out.println("TPS_SESSION_ID=" + tps_session_id ); + System.out.println("TPS_URL=" + tps_url_1 ); + + // use session id to connect back to TPS + + String query_string_2 = "p=3" + + "&session_id=" + tps_session_id + + "&subsystem=TPS" + + "&xml=true" ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri, + query_string_2); + + // parse xml - no parsing + + return true; + + } + + public boolean SubsystemPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + sleep_time(); + String query_string = "p=3" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name) + + "&choice=newsubsystem" ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + sleep_time(); + String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + // CA choice panel + query_string = "p=4" + "&op=next" + "&xml=true" + + "&urls=" + + URLEncoder.encode(ca_url) ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + sleep_time(); + // TKS choice panel + String tks_url = "https://" + tks_hostname + ":" + tks_ssl_port ; + query_string = "p=5" + "&op=next" + "&xml=true" + + "&urls=" + + URLEncoder.encode(tks_url) ; + + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // DRM / server side keygen panel + + sleep_time(); + if(ss_keygen.equalsIgnoreCase("true")) + { + ss_keygen = "keygen"; + } + + String drm_url = "https://" + drm_hostname + ":" + drm_ssl_port ; + + query_string = "p=6" + "&op=next" + "&xml=true" + + "&urls=" + + URLEncoder.encode(drm_url) + + "&choice=" + ss_keygen ; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean LdapAuthConnectionPanel() + { + // auth db + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=7" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_auth_host) + + "&port=" + URLEncoder.encode(ldap_auth_port) + + "&basedn=" + URLEncoder.encode(ldap_auth_base_dn) + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean LdapConnectionPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host) + + "&port=" + URLEncoder.encode(ldap_port) + + "&binddn=" + URLEncoder.encode(bind_dn) + + "&__bindpwd=" + URLEncoder.encode(bind_password) + + "&basedn=" + URLEncoder.encode(base_dn) + + "&database=" + URLEncoder.encode(db_name) + + "&display=" + URLEncoder.encode("") + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean TokenChoicePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + //////////////////////////////////////////////////////// + String query_string = null; + + // Software Token + if(token_name.equalsIgnoreCase("internal")) + { + query_string = "p=9" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("NSS Certificate DB") + + ""; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } + // HSM + else + { + // login to hsm first + query_string = "p=10" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name) + + "&__uPasswd=" + + URLEncoder.encode(token_pwd) + + ""; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // choice with token name now + query_string = "p=9" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name) + + ""; + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + } + + + return true; + } + + public boolean KeyPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList friendly_list = null; + ArrayList dn_list = null; + + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + key_size + + "&sslserver_custom_size=" + key_size + + "&custom_size=" + key_size + + "&subsystem_keytype=" + key_type + + "&sslserver_keytype=" + key_type + + "&keytype=" + key_type + + "&subsystem_choice=custom"+ + "&sslserver_choice=custom"+ + "&choice=custom"+ + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean CertSubjectPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList friendly_list = null; + + String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ; + + String query_string = "p=12" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(tps_subsystem_cert_subject_name) + + "&sslserver=" + + URLEncoder.encode(tps_server_cert_subject_name) + + "&urls=" + + URLEncoder.encode(ca_url) + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + // parse the certs if needed + + return true; + } + + public boolean CertificatePanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList req_list = null; + ArrayList cert_list = null; + ArrayList dn_list = null; + ArrayList pp_list = null; + + + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&subsystem=" + + "&subsystem_cc=" + + "&sslserver=" + + "&sslserver_cc=" + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean AdminCertReqPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + String cert_subject = "CN=" + "tps-" + admin_user; + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + agent_cert_subject, + agent_key_size, + agent_key_type); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.setTransportCert(null); + cCrypt.setDualKey(false); + cCrypt.loginDB(); + + String crmf_request = cCrypt.generateCRMFrequest(); + + if(crmf_request == null) + { + System.out.println("ERROR: AdminCertReqPanel() cert req gen failed"); + return false; + } + + admin_cert_request = crmf_request; + + String query_string = "p=14" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + + "&uid=" + admin_user + + "&name=" + admin_user + + "&__pwd=" + admin_password + + "&__admin_password_again=" + admin_password + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email) + + "&cert_request=" + + URLEncoder.encode(admin_cert_request) + + "&subject=" + agent_cert_subject + + "&clone=0" + + "&import=true" + + "&securitydomain=" + domain_name + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(ca_hostname,ca_ssl_port,ee_uri,query_string); + String cert_to_import = null; + + try + { + cert_to_import = + new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + + } + catch (Exception e) + { + System.out.println("ERROR: failed to retrieve cert"); + } + + System.out.println("Imported Cert=" + cert_to_import); + + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + String start = "-----BEGIN CERTIFICATE-----\r\n" ; + String end = "\r\n-----END CERTIFICATE-----" ; + + st = cCrypt.importCert(start+cert_to_import+end,agent_name); + if(!st) + { + System.out.println("ERROR: AdminCertImportPanel() during cert import"); + return false; + } + + System.out.println("SUCCESS: imported admin user cert"); + return true; + } + + public boolean UpdateDomainPanel() + { + boolean st = false; + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=15" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(ca_hostname) + + "&caPort=" + URLEncoder.encode(ca_ssl_port) + + ""; + + hr = hc.nonsslConnect(cs_hostname,cs_port,wizard_uri,query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + // px.parse(bais); + // px.prettyprintxml(); + + return true; + } + + public boolean ConfigureTPSInstance() + { + // 0. login to cert db + ComCrypto cCrypt = new ComCrypto(client_certdb_dir, + client_certdb_pwd, + null, + null, + null); + cCrypt.setDebug(true); + cCrypt.setGenerateRequest(true); + cCrypt.loginDB(); + + // instantiate http client + hc = new HTTPClient(); + + sleep_time(); + // 1. Login panel + boolean log_st = LoginPanel(); + if(!log_st) + { + System.out.println("ERROR: JSESSIONID not found."); + System.out.println("ERROR: ConfigureTPS: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if(!dom_st) + { + System.out.println("ERROR: ConfigureTPS: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 3. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if(!disp_st) + { + System.out.println("ERROR: ConfigureTPS: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // security domain login panel + boolean disp_sd = SecurityDomainLoginPanel(); + if(!disp_sd) + { + System.out.println("ERROR: ConfigureTPS: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // subsystem panel + boolean disp_ss = SubsystemPanel(); + if(!disp_ss) + { + System.out.println("ERROR: ConfigureTPS: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // ldap auth connection panel + boolean disp_ldap_auth = LdapAuthConnectionPanel(); + if(!disp_ldap_auth) + { + System.out.println("ERROR: ConfigureTPS: LdapAuthConnectionPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if(!disp_ldap) + { + System.out.println("ERROR: ConfigureTPS: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + // 8. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if(!disp_token) + { + System.out.println("ERROR: ConfigureTPS: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 9. Key Panel + boolean disp_key = KeyPanel(); + if(!disp_key) + { + System.out.println("ERROR: ConfigureTPS: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if(!disp_csubj) + { + System.out.println("ERROR: ConfigureTPS: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 11. Certificate Panel + boolean disp_cp = CertificatePanel(); + if(!disp_cp) + { + System.out.println("ERROR: ConfigureTPS: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // 13. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if(!disp_adm) + { + System.out.println("ERROR: ConfigureTPS: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if(!disp_im) + { + System.out.println("ERROR: ConfigureTPS: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if(!disp_ud) + { + System.out.println("ERROR: ConfigureTPS: UpdateDomainPanel() failure"); + return false; + } + + return true; + } + + public static void main(String args[]) + { + ConfigureTPS ca = new ConfigureTPS(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = new StringHolder(); + + StringHolder x_ca_hostname = new StringHolder(); + StringHolder x_ca_port = new StringHolder(); + StringHolder x_ca_ssl_port = new StringHolder(); + + StringHolder x_drm_hostname = new StringHolder(); + StringHolder x_drm_ssl_port = new StringHolder(); + + StringHolder x_tks_hostname = new StringHolder(); + StringHolder x_tks_ssl_port = new StringHolder(); + + StringHolder x_client_certdb_dir = new StringHolder(); + StringHolder x_client_certdb_pwd = new StringHolder(); + StringHolder x_preop_pin = new StringHolder(); + + StringHolder x_domain_name = new StringHolder(); + + StringHolder x_admin_user = new StringHolder(); + StringHolder x_admin_email = new StringHolder(); + StringHolder x_admin_password = new StringHolder(); + + // ldap + + StringHolder x_ldap_host = new StringHolder(); + StringHolder x_ldap_port = new StringHolder(); + StringHolder x_bind_dn = new StringHolder(); + StringHolder x_bind_password = new StringHolder(); + StringHolder x_base_dn = new StringHolder(); + StringHolder x_db_name = new StringHolder(); + + StringHolder x_ldap_auth_host = new StringHolder(); + StringHolder x_ldap_auth_port = new StringHolder(); + StringHolder x_ldap_auth_base_dn = new StringHolder(); + + // key size + StringHolder x_token_name = new StringHolder(); + StringHolder x_token_pwd = new StringHolder(); + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + + StringHolder x_agent_key_size = new StringHolder(); + StringHolder x_agent_key_type = new StringHolder(); + StringHolder x_agent_cert_subject = new StringHolder(); + + StringHolder x_agent_name = new StringHolder(); + + StringHolder x_ss_keygen = new StringHolder(); + + // tps cert subject name params + StringHolder x_tps_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_tps_server_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + + // parse the args + ArgParser parser = new ArgParser("ConfigureTPS"); + + parser.addOption ("-cs_hostname %s #CS Hostname", + x_cs_hostname); + parser.addOption ("-cs_port %s #CS SSL port", + x_cs_port); + + parser.addOption ("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption ("-sd_ssl_port %s #Security Domain SSL port", + x_sd_ssl_port); + parser.addOption ("-sd_admin_name %s #Security Domain username", + x_sd_admin_name); + parser.addOption ("-sd_admin_password %s #Security Domain password", + x_sd_admin_password); + + parser.addOption ("-ca_hostname %s #CA Hostname", + x_ca_hostname); + parser.addOption ("-ca_port %s #CA non SSL port", + x_ca_port); + parser.addOption ("-ca_ssl_port %s #CA SSL port", + x_ca_ssl_port); + + parser.addOption ("-drm_hostname %s #DRM Hostname", + x_drm_hostname); + parser.addOption ("-drm_ssl_port %s #DRM SSL port", + x_drm_ssl_port); + parser.addOption ("-ss_keygen %s #Enable Server Side Keygen [true,false]", + x_ss_keygen); + + parser.addOption ("-tks_hostname %s #TKS Hostname", + x_tks_hostname); + parser.addOption ("-tks_ssl_port %s #TKS SSL port", + x_tks_ssl_port); + + parser.addOption ("-client_certdb_dir %s #Client CertDB dir", + x_client_certdb_dir); + parser.addOption ("-client_certdb_pwd %s #client certdb password", + x_client_certdb_pwd); + parser.addOption ("-preop_pin %s #pre op pin", + x_preop_pin); + parser.addOption ("-domain_name %s #domain name", + x_domain_name); + parser.addOption ("-admin_user %s #Admin User Name", + x_admin_user); + parser.addOption ("-admin_email %s #Admin email", + x_admin_email); + parser.addOption ("-admin_password %s #Admin password", + x_admin_password); + parser.addOption ("-agent_name %s #Agent Cert Nickname", + x_agent_name); + + parser.addOption ("-ldap_host %s #ldap host", + x_ldap_host); + parser.addOption ("-ldap_port %s #ldap port", + x_ldap_port); + parser.addOption ("-bind_dn %s #ldap bind dn", + x_bind_dn); + parser.addOption ("-bind_password %s #ldap bind password", + x_bind_password); + parser.addOption ("-base_dn %s #base dn", + x_base_dn); + parser.addOption ("-db_name %s #db name", + x_db_name); + + parser.addOption ("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption ("-token_pwd %s #HSM/Software Token password", + x_token_pwd); + parser.addOption ("-key_size %s #Key Size", + x_key_size); + parser.addOption ("-key_type %s #Key type [rsa,ecc]", + x_key_type); + + parser.addOption ("-agent_key_size %s #Agent Cert Key Size", + x_agent_key_size); + parser.addOption ("-agent_key_type %s #Agent cert Key type [rsa]", + x_agent_key_type); + parser.addOption ("-agent_cert_subject %s #Agent cert Subject", + x_agent_cert_subject); + + + parser.addOption ("-ldap_auth_host %s #ldap auth host", + x_ldap_auth_host); + parser.addOption ("-ldap_auth_port %s #ldap auth port", + x_ldap_auth_port); + parser.addOption ("-ldap_auth_base_dn %s #ldap auth base dn", + x_ldap_auth_base_dn); + + parser.addOption ( + "-tps_subsystem_cert_subject_name %s #TPS subsystem cert subject name", + x_tps_subsystem_cert_subject_name); + parser.addOption ( + "-tps_server_cert_subject_name %s #TPS server cert subject name", + x_tps_server_cert_subject_name); + + parser.addOption ( + "-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + // and then match the arguments + String [] unmatched = null; + unmatched = parser.matchAllArgs (args,0,parser.EXIT_ON_UNMATCHED); + + if(unmatched!=null) + { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + ca_hostname = x_ca_hostname.value; + ca_port = x_ca_port.value; + ca_ssl_port = x_ca_ssl_port.value; + + tks_hostname = x_tks_hostname.value; + tks_ssl_port = x_tks_ssl_port.value; + + drm_hostname = x_drm_hostname.value; + drm_ssl_port = x_drm_ssl_port.value; + + client_certdb_dir = x_client_certdb_dir.value; + client_certdb_pwd = x_client_certdb_pwd.value; + pin = x_preop_pin.value; + domain_name = x_domain_name.value; + + admin_user = x_admin_user.value; + admin_email = x_admin_email.value; + admin_password = x_admin_password.value; + agent_name = x_agent_name.value; + + ldap_host = x_ldap_host.value; + ldap_port = x_ldap_port.value; + bind_dn = x_bind_dn.value; + bind_password = x_bind_password.value; + base_dn = x_base_dn.value; + db_name = x_db_name.value; + + ldap_auth_host = x_ldap_auth_host.value; + ldap_auth_port = x_ldap_auth_port.value; + ldap_auth_base_dn = x_ldap_auth_base_dn.value; + + key_size = x_key_size.value; + key_type = x_key_type.value; + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + + agent_key_size = x_agent_key_size.value; + agent_key_type = x_agent_key_type.value; + agent_cert_subject = x_agent_cert_subject.value; + + ss_keygen = x_ss_keygen.value; + + tps_subsystem_cert_subject_name = + x_tps_subsystem_cert_subject_name.value; + tps_server_cert_subject_name = + x_tps_server_cert_subject_name.value ; + + subsystem_name = x_subsystem_name.value ; + + + + boolean st = ca.ConfigureTPSInstance(); + + if (!st) + { + System.out.println("ERROR: unable to create TPS"); + System.exit(-1); + } + + System.out.println("Certficate System - TPS Instance Configured"); + System.exit(0); + + } + +}; |