diff options
author | Endi Sukma Dewata <edewata@redhat.com> | 2012-03-24 02:27:47 -0500 |
---|---|---|
committer | Endi Sukma Dewata <edewata@redhat.com> | 2012-03-26 11:43:54 -0500 |
commit | 621d9e5c413e561293d7484b93882d985b3fe15f (patch) | |
tree | 638f3d75761c121d9a8fb50b52a12a6686c5ac5c /base/silent | |
parent | 40d3643b8d91886bf210aa27f711731c81a11e49 (diff) | |
download | pki-621d9e5c413e561293d7484b93882d985b3fe15f.tar.gz pki-621d9e5c413e561293d7484b93882d985b3fe15f.tar.xz pki-621d9e5c413e561293d7484b93882d985b3fe15f.zip |
Removed unnecessary pki folder.
Previously the source code was located inside a pki folder.
This folder was created during svn migration and is no longer
needed. This folder has now been removed and the contents have
been moved up one level.
Ticket #131
Diffstat (limited to 'base/silent')
50 files changed, 26368 insertions, 0 deletions
diff --git a/base/silent/CMakeLists.txt b/base/silent/CMakeLists.txt new file mode 100644 index 000000000..8f71375dc --- /dev/null +++ b/base/silent/CMakeLists.txt @@ -0,0 +1,17 @@ +project(silent Java) + +add_subdirectory(src) +add_subdirectory(scripts) + +install( + FILES + templates/pki_silent.template + templates/subca_silent.template + DESTINATION + ${DATA_INSTALL_DIR}/silent/ + PERMISSIONS + OWNER_EXECUTE OWNER_WRITE OWNER_READ + GROUP_EXECUTE GROUP_READ + WORLD_EXECUTE WORLD_READ +) + diff --git a/base/silent/LICENSE b/base/silent/LICENSE new file mode 100644 index 000000000..e281f4362 --- /dev/null +++ b/base/silent/LICENSE @@ -0,0 +1,291 @@ +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. + + 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/base/silent/scripts/CMakeLists.txt b/base/silent/scripts/CMakeLists.txt new file mode 100644 index 000000000..df4dfc469 --- /dev/null +++ b/base/silent/scripts/CMakeLists.txt @@ -0,0 +1,10 @@ +install( + FILES + pkisilent + DESTINATION + ${BIN_INSTALL_DIR} + PERMISSIONS + OWNER_EXECUTE OWNER_WRITE OWNER_READ + GROUP_EXECUTE GROUP_READ + WORLD_EXECUTE WORLD_READ +) diff --git a/base/silent/scripts/pkisilent b/base/silent/scripts/pkisilent new file mode 100755 index 000000000..c5be67855 --- /dev/null +++ b/base/silent/scripts/pkisilent @@ -0,0 +1,117 @@ +#!/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="pki"; +my $libpath=""; + + +############################################################################### +## (2) Define helper functions. ## +############################################################################### + +sub invalid_architecture() +{ + print "\n"; + print "ERROR: pkisilent does not execute on this architecture\n"; + print "ERROR: check to make sure pki-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 $ARCHITECTURE=`uname -i`; +chop( $ARCHITECTURE ); + +if( $ARCHITECTURE eq "i386" ) { + $libpath="/usr/lib"; + + $ENV{LD_LIBRARY_PATH} = "/usr/lib/jss:" + . "/usr/lib:/lib"; +} elsif($ARCHITECTURE eq "x86_64") { + $libpath="/usr/lib64"; + + $ENV{LD_LIBRARY_PATH} = "/usr/lib64/jss:" + . "/usr/lib64:/lib64:" + . "/usr/lib/jss:" + . "/usr/lib:/lib"; +} else { + invalid_architecture(); + 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/${PRODUCT}/pki-silent.jar:" + . "/usr/share/java/${PRODUCT}/pki-certsrv.jar:" + . "/usr/share/java/${PRODUCT}/pki-cmscore.jar:" + . "/usr/share/java/${PRODUCT}/pki-nsutil.jar:" + . "/usr/share/java/${PRODUCT}/pki-cmsutil.jar:" + . "/usr/share/java/${PRODUCT}/pki-tools.jar:" + . "/usr/share/java/ldapjdk.jar:" + . "/usr/share/java/commons-codec.jar:" + . "/usr/share/java/xerces-j2.jar:" + . "/usr/share/java/xml-commons-apis.jar:" + . "/usr/share/java/xml-commons-resolver.jar:"; +if( $ARCHITECTURE eq "x86_64" ) { + $ENV{CLASSPATH} = $ENV{CLASSPATH} + . "/usr/lib64/java/jss4.jar:" + . "/usr/lib/java/jss4.jar:"; +} else { + $ENV{CLASSPATH} = $ENV{CLASSPATH} + . "/usr/lib/java/jss4.jar:"; +} + + +############################################################################### +## (5) Execute the java command specified by this java command wrapper ## +## based upon the preset LD_LIBRARY_PATH and CP environment variables. ## +############################################################################### + +my @args = (); +foreach (@ARGV) { + push(@args, quotemeta($_)); +} +my $output = `java -cp $ENV{CLASSPATH} com.netscape.pkisilent.PKISilent @args`; +my $status = $?; + +print "#######################################################################\n"; +print "$output\n"; +print "#######################################################################\n"; + +if ($status != 0) { + exit(255); +} else { + exit(0); +} diff --git a/base/silent/src/CMakeLists.txt b/base/silent/src/CMakeLists.txt new file mode 100644 index 000000000..a3e6034f8 --- /dev/null +++ b/base/silent/src/CMakeLists.txt @@ -0,0 +1,82 @@ +project(pki-silent_java Java) + +find_file(JSS_JAR + NAMES + jss4.jar + PATHS + ${JAVA_LIB_INSTALL_DIR} + /usr/share/java +) + +find_file(LDAPJDK_JAR + NAMES + ldapjdk.jar + PATHS + ${JAVA_LIB_INSTALL_DIR} + /usr/share/java +) + +find_file(XERCES_JAR + NAMES + xerces-j2.jar + PATHS + ${JAVA_LIB_INSTALL_DIR} + /usr/share/java +) + +set(pki-silent_java_SRCS + com/netscape/pkisilent/ConfigureTKS.java + com/netscape/pkisilent/ConfigureCA.java + com/netscape/pkisilent/argparser/CharHolder.java + com/netscape/pkisilent/argparser/ArgParseException.java + com/netscape/pkisilent/argparser/StringHolder.java + com/netscape/pkisilent/argparser/SimpleExample.java + com/netscape/pkisilent/argparser/ArgParser.java + com/netscape/pkisilent/argparser/DoubleHolder.java + com/netscape/pkisilent/argparser/ObjectHolder.java + com/netscape/pkisilent/argparser/FloatHolder.java + com/netscape/pkisilent/argparser/BooleanHolder.java + com/netscape/pkisilent/argparser/StringScanException.java + com/netscape/pkisilent/argparser/StringScanner.java + com/netscape/pkisilent/argparser/LongHolder.java + com/netscape/pkisilent/argparser/IntHolder.java + com/netscape/pkisilent/ConfigureTPS.java + com/netscape/pkisilent/http/HTTPClient.java + com/netscape/pkisilent/http/HTMLDocument.java + com/netscape/pkisilent/http/HTTPResponse.java + com/netscape/pkisilent/http/CertSelection.java + com/netscape/pkisilent/common/Request.java + com/netscape/pkisilent/common/CertificateRecord.java + com/netscape/pkisilent/common/Utilities.java + com/netscape/pkisilent/common/ComCrypto.java + com/netscape/pkisilent/common/BaseState.java + com/netscape/pkisilent/common/CMSLDAP.java + com/netscape/pkisilent/common/CMSConfig.java + com/netscape/pkisilent/common/PostQuery.java + com/netscape/pkisilent/common/ServerInfo.java + com/netscape/pkisilent/common/UserEnroll.java + com/netscape/pkisilent/common/ParseXML.java + com/netscape/pkisilent/common/CMSProperties.java + com/netscape/pkisilent/common/DirEnroll.java + com/netscape/pkisilent/common/Con2Agent.java + com/netscape/pkisilent/common/TestClient.java + com/netscape/pkisilent/common/CMSTask.java + com/netscape/pkisilent/ConfigureOCSP.java + com/netscape/pkisilent/ConfigureRA.java + com/netscape/pkisilent/ConfigureSubCA.java + com/netscape/pkisilent/ConfigureDRM.java + com/netscape/pkisilent/PKISilent.java +) + +set(CMAKE_JAVA_INCLUDE_PATH + ${PKI_CERTSRV_JAR} ${PKI_CMS_JAR} + ${PKI_CMSUTIL_JAR} ${PKI_NSUTIL_JAR} + ${LDAPJDK_JAR} ${XERCES_JAR} + ${JSS_JAR} ${COMMONS_CODEC_JAR} ${SYMKEY_JAR}) + +set(CMAKE_JAVA_TARGET_VERSION ${APPLICATION_VERSION}) + +add_jar(pki-silent ${pki-silent_java_SRCS}) +add_dependencies(pki-silent symkey pki-cmsutil pki-nsutil pki-certsrv pki-cms) +install_jar(pki-silent ${JAVA_JAR_INSTALL_DIR}/pki) +set(PKI_SILENT_JAR ${pki-silent_JAR_FILE} CACHE INTERNAL "pki-silent jar file") diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureCA.java b/base/silent/src/com/netscape/pkisilent/ConfigureCA.java new file mode 100644 index 000000000..3c498febe --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureCA.java @@ -0,0 +1,1698 @@ +package com.netscape.pkisilent; + +// --- 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.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.URLEncoder; +import java.util.ArrayList; + +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.pkcs12.AuthenticatedSafes; +import org.mozilla.jss.pkcs12.PFX; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureCA { + + // global constants + public static final String DEFAULT_KEY_TYPE = "RSA"; + public static final String DEFAULT_KEY_SIZE = "2048"; + public static final String DEFAULT_KEY_CURVENAME = "nistp256"; + public static final String DEFAULT_KEY_ALGORITHM_RSA = "SHA256withRSA"; + public static final String DEFAULT_KEY_ALGORITHM_ECC = "SHA256withEC"; + public static final String SUCCESS = "success"; + public static final String FAILURE = "failure"; + + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + public static String pkcs12_uri = "/ca/admin/console/config/savepkcs12"; + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie"; + + 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; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_agent_port = null; + public static String sd_admin_port = null; + public static String sd_admin_name = null; + public static String sd_admin_password = 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 secure_conn = null; + public static String remove_data = null; + + public static String key_type = null; + public static String key_size = null; + public static String key_curvename = null; + public static String key_algorithm = null; + public static String signing_algorithm = null; + + public static String signing_key_type = null; + public static String signing_key_size = null; + public static String signing_key_curvename = null; + public static String signing_signingalgorithm = null; + + public static String ocsp_signing_key_type = null; + public static String ocsp_signing_key_size = null; + public static String ocsp_signing_key_curvename = null; + public static String ocsp_signing_signingalgorithm = null; + + public static String subsystem_key_type = null; + public static String subsystem_key_size = null; + public static String subsystem_key_curvename = null; + + public static String audit_signing_key_type = null; + public static String audit_signing_key_size = null; + public static String audit_signing_key_curvename = null; + + public static String sslserver_key_type = null; + public static String sslserver_key_size = null; + public static String sslserver_key_curvename = 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 backup_fname = 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 ca_audit_signing_cert_name = null; + public static String ca_audit_signing_cert_req = null; + public static String ca_audit_signing_cert_pp = null; + public static String ca_audit_signing_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 ca_audit_signing_cert_subject_name = null; + + public static String subsystem_name = null; + + public static String external_ca = null; + public static String ext_ca_cert_file = null; + public static String ext_ca_cert_chain_file = null; + public static String ext_csr_file = null; + public static String signing_cc = null; + + public static boolean clone = false; + public static String clone_uri = null; + public static String clone_p12_passwd = null; + public static String clone_p12_file = null; + public static String clone_master_port = null; + public static String clone_replica_port = null; + public static String clone_replication_security = null; + + //for correct selection of CA to be cloned + public static String urls; + + public ConfigureCA() {// do nothing :) + } + + public String getStatus(HTTPResponse hr, String name) { + ByteArrayInputStream bais = null; + String status = null; + try { + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + ParseXML px = new ParseXML(); + px.parse(bais); + px.prettyprintxml(); + status = px.getvalue(name); + } catch (Exception e) { + System.out.println("Exception in getStatus(): " + e.toString()); + } + return status; + } + + public boolean checkStatus(HTTPResponse hr, String name, + String expected, String location) { + return checkStatus(hr, name, new String[] { expected }, location); + } + + public boolean checkStatus(HTTPResponse hr, String name, + String[] expected, String location) { + String status = getStatus(hr, name); + if (status == null) { + System.out.println("Error in " + location + ": " + name + + " value is null"); + return false; + } + for (int i = 0; i < expected.length; i++) { + if (status.equals(expected[i])) { + return true; + } + } + System.out.println("Error in " + location + ": " + name + + " returns " + status); + return false; + } + + public boolean LoginPanel() { + try { + boolean st = false; + HTTPResponse hr = null; + + 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(";"); + + HTTPClient.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"); + if (!checkStatus(hr, "status", "display", "LoginPanel()")) { + return false; + } + + return st; + } catch (Exception e) { + System.out.println("Exception in LoginPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean TokenChoicePanel() { + try { + HTTPResponse hr = null; + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=1" + "&op=next" + "&xml=true" + "&choice=" + + URLEncoder.encode("Internal Key Storage Token", "UTF-8") + ""; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) { + return false; + } + } // HSM + else { + // login to hsm first + query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8") + ""; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) { + return false; + } + + // choice with token name now + query_string = "p=1" + "&op=next" + "&xml=true" + "&choice=" + + URLEncoder.encode(token_name, "UTF-8") + ""; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) { + return false; + } + } + return true; + } catch (Exception e) { + System.out.println("Exception in TokenChoicePanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean DomainPanel() { + try { + HTTPResponse hr = null; + String domain_url = "https://" + cs_hostname + ":" + cs_port; + String query_string = null; + + if (!clone) { + query_string = "sdomainURL=" + URLEncoder.encode(domain_url, "UTF-8") + + "&sdomainName=" + URLEncoder.encode(domain_name, "UTF-8") + + "&choice=newdomain" + "&p=3" + "&op=next" + "&xml=true"; + } else { + domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + query_string = "sdomainURL=" + URLEncoder.encode(domain_url, "UTF-8") + + "&sdomainName=" + + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true"; + } + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "DomainPanel()")) { + return false; + } + + return true; + } catch (Exception e) { + System.out.println("Exception in DomainPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean DisplayCertChainPanel() { + try { + String query_string = "p=4" + "&op=next" + "&xml=true"; + hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + return true; + } catch (Exception e) { + System.out.println("Exception in DisplayCertChainPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean SecurityDomainLoginPanel() { + try { + HTTPResponse hr = null; + + String subca_url = "https://" + cs_hostname + ":" + cs_port + + "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA"; + + String query_string = "url=" + URLEncoder.encode(subca_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(subca_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_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=5" + "&subsystem=CA" + + "&session_id=" + subca_session_id + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2); + urls = hr.getHTML(); + int indx = urls.indexOf(clone_uri); + if (indx < 0) { + throw new Exception("Invalid clone_uri"); + } + urls = urls.substring(urls.lastIndexOf("<option", indx), indx); + urls = urls.split("\"")[1]; + + System.out.println("urls =" + urls); + return true; + } catch (Exception e) { + System.out.println("Exception in SecurityDomainLoginPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean CreateCAPanel() { + try { + HTTPResponse hr = null; + String query_string = null; + + if (!clone) { + query_string = "p=5" + "&op=next" + "&xml=true" + + "&choice=newsubsystem" + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8"); + } else { + query_string = "p=5" + "&op=next" + "&xml=true" + + "&choice=clonesubsystem" + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&urls=" + urls + ""; + } + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel()")) { + return false; + } + + if (clone) { + + hr = null; + query_string = "p=6" + "&op=next" + "&xml=true"; + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel(2)")) { + return false; + } + } + + return true; + } catch (Exception e) { + System.out.println("Exception in CreateCAPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean RestoreKeyCertPanel() { + try { + HTTPResponse hr = null; + + String query_string = "p=7" + "&op=next" + "&xml=true" + + "&__password=" + URLEncoder.encode(clone_p12_passwd, "UTF-8") + + "&path=" + URLEncoder.encode(clone_p12_file, "UTF-8") + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "RestoreKeyCertPanel()")) { + return false; + } + return true; + } catch (Exception e) { + System.out.println("Exception in RestoreKeyCertPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean HierarchyPanel() { + try { + HTTPResponse hr = null; + + String query_string = "p=8" + "&op=next" + "&xml=true"; + if (external_ca.equalsIgnoreCase("true")) + query_string += "&choice=join"; + else + query_string += "&choice=root"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "HierarchyPanel()")) { + return false; + } + + return true; + } catch (Exception e) { + System.out.println("Exception in HierarchyPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + + } + + public boolean LdapConnectionPanel() { + try { + HTTPResponse hr = null; + + String query_string = "p=9" + "&op=next" + "&xml=true" + "&host=" + + URLEncoder.encode(ldap_host,"UTF-8") + "&port=" + + URLEncoder.encode(ldap_port,"UTF-8") + "&binddn=" + + URLEncoder.encode(bind_dn, "UTF-8") + "&__bindpwd=" + + URLEncoder.encode(bind_password, "UTF-8") + "&basedn=" + + URLEncoder.encode(base_dn, "UTF-8") + "&database=" + + URLEncoder.encode(db_name, "UTF-8") + "&display=" + + URLEncoder.encode("$displayStr", "UTF-8") + + (secure_conn.equals("true") ? "&secureConn=on" : "") + + "&masterReplicationPort=" + URLEncoder.encode(clone_master_port, "UTF-8") + + "&cloneReplicationPort=" + URLEncoder.encode(clone_replica_port, "UTF-8") + + "&replicationSecurity=" + URLEncoder.encode(clone_replication_security, "UTF-8") + + (remove_data.equals("true") ? "&removeData=true" : ""); + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "LdapConnectionPanel()")) { + return false; + } + + return true; + } catch (Exception e) { + System.out.println("Exception in LdapConnectionPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean KeyPanel() { + try { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> al = null; + String query_string = null; + if (clone) { + query_string = "p=10" + "&op=next" + "&xml=true" + + "&sslserver_custom_size=" + sslserver_key_size + + "&sslserver_custom_curvename=" + sslserver_key_curvename + + "&sslserver_choice=custom" + + "&sslserver_keytype=" + sslserver_key_type + + "&choice=custom" + "&keytype=" + key_type + + "&custom_size=" + key_size; + } else { + query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + subsystem_key_size + + "&subsystem_custom_curvename=" + subsystem_key_curvename + + "&subsystem_keytype=" + subsystem_key_type + + "&subsystem_choice=custom" + + "&sslserver_custom_size=" + sslserver_key_size + + "&sslserver_custom_curvename=" + sslserver_key_curvename + + "&sslserver_keytype=" + sslserver_key_type + + "&sslserver_choice=custom" + + "&signing_custom_size=" + signing_key_size + + "&signing_custom_curvename=" + signing_key_curvename + + "&signing_keytype=" + signing_key_type + + "&signing_choice=custom" + + "&signing_keyalgorithm=" + key_algorithm + + "&signing_signingalgorithm=" + signing_signingalgorithm + + "&ocsp_signing_custom_size=" + ocsp_signing_key_size + + "&ocsp_signing_custom_curvename=" + ocsp_signing_key_curvename + + "&ocsp_signing_keytype=" + ocsp_signing_key_type + + "&ocsp_signing_choice=custom" + + "&ocsp_signing_signingalgorithm=" + ocsp_signing_signingalgorithm + + "&audit_signing_custom_size=" + audit_signing_key_size + + "&audit_signing_custom_curvename=" + audit_signing_key_curvename + + "&audit_signing_keytype=" + audit_signing_key_type + + "&audit_signing_choice=custom" + + "&custom_size=" + key_size + + "&custom_curvename=" + key_curvename + + "&keytype=" + key_type + + "&choice=custom" + + "&signingalgorithm=" + signing_algorithm + + "&keyalgorithm=" + key_algorithm; + } + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "KeyPanel()")) { + return false; + } + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + + al = px.constructValueList("CertReqPair", "DN"); + // get ca cert subject name + if (al != null) { + for (int i = 0; i < al.size(); i++) { + String temp = 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 if (temp.indexOf("Audit Signing Certificate") > 0) { + ca_audit_signing_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: ca_audit_signing_cert_name=" + ca_audit_signing_cert_name); + System.out.println("default: server_cert_name=" + server_cert_name); + return true; + } catch (Exception e) { + System.out.println("Exception in KeyPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean CertSubjectPanel() { + try { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> req_list = null; + ArrayList<String> cert_list = null; + ArrayList<String> dn_list = null; + String query_string = null; + + // use subject names provided as input + + if (!clone) { + query_string = "p=11" + "&op=next" + "&xml=true" + "&subsystem=" + + URLEncoder.encode(ca_subsystem_cert_subject_name, "UTF-8") + + "&ocsp_signing=" + + URLEncoder.encode(ca_ocsp_cert_subject_name, "UTF-8") + "&signing=" + + URLEncoder.encode(ca_sign_cert_subject_name, "UTF-8") + "&sslserver=" + + URLEncoder.encode(ca_server_cert_subject_name, "UTF-8") + "&audit_signing=" + + URLEncoder.encode(ca_audit_signing_cert_subject_name, "UTF-8") + "&urls=0" + + ""; + } else { + query_string = "p=11" + "&op=next" + "&xml=true" + "&sslserver=" + + URLEncoder.encode(ca_server_cert_subject_name, "UTF-8") + "&urls=0" + + ""; + } + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "CertSubjectPanel()")) { + return false; + } + + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + + 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 (external_ca.equalsIgnoreCase("true")) { + if ((req_list != null) && (dn_list != null)) { + for (int i = 0; i < dn_list.size(); i++) { + String temp = dn_list.get(i); + if (temp.indexOf("caSigningCert") >= 0) { + ca_cert_req = req_list.get(i); + } + } + } + + if (ext_ca_cert_file == null) { + try { + FileOutputStream fos = new FileOutputStream(ext_csr_file); + PrintStream p = new PrintStream(fos); + p.println(ca_cert_req); + p.close(); + return true; + } catch (Exception e) { + System.out.println("CertSubjectPanel: Unable to write CSR for external CA to " + ext_csr_file); + System.out.println(e.toString()); + return false; + } + } else { + try { + ca_cert_cert = ""; + FileInputStream fis = new FileInputStream(ext_ca_cert_file); + DataInputStream in = new DataInputStream(fis); + while (in.available() != 0) { + ca_cert_cert += in.readLine(); + } + in.close(); + + signing_cc = ""; + fis = new FileInputStream(ext_ca_cert_chain_file); + in = new DataInputStream(fis); + while (in.available() != 0) { + signing_cc += in.readLine(); + } + in.close(); + return true; + } catch (Exception e) { + System.out.println( + "CertSubjectPanel: Unable to read in external approved CA cert or certificate chain."); + System.out.println(e.toString()); + return false; + } + } + } + + if (req_list != null && cert_list != null && dn_list != null) { + for (int i = 0; i < dn_list.size(); i++) { + String temp = dn_list.get(i); + + if (temp.indexOf("caSigningCert") >= 0) { + ca_cert_req = req_list.get(i); + ca_cert_cert = cert_list.get(i); + } else if (temp.indexOf("ocspSigningCert") >= 0) { + ocsp_cert_req = req_list.get(i); + ocsp_cert_cert = cert_list.get(i); + } else if (temp.indexOf("subsystemCert") >= 0) { + ca_subsystem_cert_req = req_list.get(i); + ca_subsystem_cert_cert = cert_list.get(i); + } else if (temp.indexOf("auditSigningCert") >= 0) { + ca_audit_signing_cert_req = req_list.get(i); + ca_audit_signing_cert_cert = cert_list.get(i); + } else { + server_cert_req = req_list.get(i); + server_cert_cert = cert_list.get(i); + } + } + } + + // print out subject names + 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("audit_signing_cert_name=" + ca_audit_signing_cert_subject_name); + + // print out requests + 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_audit_siging_cert_req=" + ca_audit_signing_cert_req); + + // print out certs + 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); + System.out.println("ca_audit_signing_cert_cert=" + ca_audit_signing_cert_cert); + + return true; + } catch (Exception e) { + System.out.println("Exception in CertSubjectPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + + } + + public boolean CertificatePanel() { + try { + HTTPResponse hr = null; + + String query_string = "p=12" + "&op=next" + "&xml=true" + "&subsystem=" + + URLEncoder.encode(ca_subsystem_cert_cert, "UTF-8") + "&subsystem_cc=" + + "&ocsp_signing=" + URLEncoder.encode(ocsp_cert_cert, "UTF-8") + + "&ocsp_signing_cc=" + "&signing=" + + URLEncoder.encode(ca_cert_cert, "UTF-8") + "&signing_cc=" + + "&audit_signing=" + URLEncoder.encode(ca_audit_signing_cert_cert, "UTF-8") + + "&audit_signing_cc=" + + "&sslserver=" + URLEncoder.encode(server_cert_cert, "UTF-8") + + "&sslserver_cc=" + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanel()")) { + return false; + } + + return true; + } catch (Exception e) { + System.out.println("Exception in CertificatePanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + + } + + public boolean CertificatePanelExternal() { + try { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> req_list = null; + ArrayList<String> cert_list = null; + ArrayList<String> dn_list = null; + String genString = "...certificate be generated internally..."; + + String query_string = "p=12" + "&op=apply" + "&xml=true" + "&subsystem=" + + URLEncoder.encode(genString, "UTF-8") + "&subsystem_cc=" + + "&ocsp_signing=" + URLEncoder.encode(genString, "UTF-8") + + "&ocsp_signing_cc=" + "&signing=" + + URLEncoder.encode(ca_cert_cert, "UTF-8") + "&signing_cc=" + + URLEncoder.encode(signing_cc, "UTF-8") + + "&audit_signing=" + URLEncoder.encode(genString, "UTF-8") + + "&audit_signing_cc=" + + "&sslserver=" + URLEncoder.encode(genString, "UTF-8") + + "&sslserver_cc=" + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanelExternal()")) { + return false; + } + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + + 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 = dn_list.get(i); + + if (temp.indexOf("caSigningCert") >= 0) { + ca_cert_req = req_list.get(i); + ca_cert_cert = cert_list.get(i); + } else if (temp.indexOf("ocspSigningCert") >= 0) { + ocsp_cert_req = req_list.get(i); + ocsp_cert_cert = cert_list.get(i); + } else if (temp.indexOf("subsystemCert") >= 0) { + ca_subsystem_cert_req = req_list.get(i); + ca_subsystem_cert_cert = cert_list.get(i); + } else if (temp.indexOf("auditSigningCert") >= 0) { + ca_audit_signing_cert_req = req_list.get(i); + ca_audit_signing_cert_cert = cert_list.get(i); + } else { + server_cert_req = req_list.get(i); + server_cert_cert = cert_list.get(i); + } + } + } + + // print out subject name + 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_audit_signing_cert_name=" + ca_audit_signing_cert_subject_name); + + // print out requests + 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_audit_signing_cert_req=" + ca_audit_signing_cert_req); + + // print out certs + 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); + System.out.println("ca_audit_signing_cert_cert=" + ca_audit_signing_cert_cert); + + return true; + } catch (Exception e) { + System.out.println("Exception in CertificatePanelExternal(): " + e.toString()); + e.printStackTrace(); + return false; + } + + } + + public boolean BackupPanel() { + try { + HTTPResponse hr = null; + + if (save_p12.equalsIgnoreCase("true")) { + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&choice=backupkey" + "&__pwd=" + URLEncoder.encode(backup_pwd, "UTF-8") + + "&__pwdagain=" + URLEncoder.encode(backup_pwd, "UTF-8"); + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "BackupPanel()")) { + return false; + } + + query_string = ""; + + hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string); + + // dump hr.getResponseData() to file + + try { + FileOutputStream fos = new FileOutputStream(backup_fname); + + fos.write(hr.getResponseData()); + fos.close(); + + // set file to permissions 600 + String rtParams[] = { "chmod", "600", backup_fname }; + Process proc = Runtime.getRuntime().exec(rtParams); + + BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream())); + String line = null; + while ((line = br.readLine()) != null) + System.out.println("Error: " + line); + proc.waitFor(); + + // verify p12 file + // Decode the P12 file + FileInputStream fis = new FileInputStream(backup_fname); + 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; + } catch (Exception e) { + System.out.println("Exception in BackupPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean BackupContinuePanel() { + try { + HTTPResponse hr = null; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + "p=14&op=next&xml=true"); + if (!checkStatus(hr, "updateStatus", SUCCESS, "BackupContinuePanel()")) { + return false; + } + + return true; + } catch (Exception e) { + System.out.println("Exception in BackupContinuePanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean ImportCACertPanel() { + try { + HTTPResponse hr = null; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + "p=15&op=next&xml=true"); + if (!checkStatus(hr, "updateStatus", SUCCESS, "ImportCACertPanel()")) { + return false; + } + + return true; + } catch (Exception e) { + System.out.println("Exception in ImportCACertPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean AdminCertReqPanel() { + try { + 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=16" + "&op=next" + "&xml=true" + + "&cert_request_type=" + "crmf" + "&uid=" + admin_user + + "&name=" + admin_user + "&__pwd=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + "&profileId=" + + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email, "UTF-8") + + "&cert_request=" + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&subject=" + URLEncoder.encode(agent_cert_subject, "UTF-8") + + "&clone=new" + + "&import=true" + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8") + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "AdminCertReqPanel()")) { + return false; + } + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } catch (Exception e) { + System.out.println("Exception in AdminCertReqPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + + } + + public boolean AdminCertImportPanel() { + try { + boolean st = false; + HTTPResponse hr = null; + String cert_to_import = null; + + String query_string = "&serialNumber=" + admin_serial_number + + "&importCert=true" + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string); + + try { + // get response data + // Convert a byte array to base64 string + // cert_to_import = new sun.misc.BASE64Encoder().encode( + // hr.getResponseData()); + cert_to_import = Utils.base64encode(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; + } catch (Exception e) { + System.out.println("Exception in AdminCertImportPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean UpdateDomainPanel() { + try { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=17" + "&op=next" + "&xml=true" + "&caHost=" + + URLEncoder.encode("/", "UTF-8") + "&caPort=" + URLEncoder.encode("/", "UTF-8") + + ""; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + if (!checkStatus(hr, "updateStatus", SUCCESS, "UpdateDomainPanel()")) { + return false; + } + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + + 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; + } catch (Exception e) { + System.out.println("Exception in UpdateDomainPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + + } + + 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")) { + hc = new HTTPClient(true); + } else { + hc = new HTTPClient(false); + } + + // 1. Login panel + boolean log_st = LoginPanel(); + + if (!log_st) { + System.out.println("ERROR: ConfigureCA: LoginPanel() failure"); + return false; + } + + // 2. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + + if (!disp_token) { + System.out.println("ERROR: ConfigureCA: TokenChoicePanel() failure"); + return false; + } + + // 3. domain panel + boolean dom_st = DomainPanel(); + + if (!dom_st) { + System.out.println("ERROR: ConfigureCA: DomainPanel() failure"); + return false; + } + + // 4. display cert chain panel and security domain login + if (clone) { + boolean disp_st = DisplayCertChainPanel(); + if (!disp_st) { + System.out.println("ERROR: ConfigureCA: DisplayCertChainPanel() failure"); + return false; + } + + boolean sd_st = SecurityDomainLoginPanel(); + if (!sd_st) { + System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure"); + return false; + } + + } + + // 5. display create CA panel + boolean disp_cert = CreateCAPanel(); + + if (!disp_cert) { + System.out.println("ERROR: ConfigureCA: CreateCAPanel() failure"); + return false; + } + + // 6. display restore key cert panel + if (clone) { + boolean restore_st = RestoreKeyCertPanel(); + if (!restore_st) { + System.out.println("ERROR: ConfigureCA: RestoreKeyCertPanel() failure"); + return false; + } + } + + // 7. hierarchy panel + if (!clone) { + boolean disp_h = HierarchyPanel(); + + if (!disp_h) { + System.out.println("ERROR: ConfigureCA: HierarchyPanel() failure"); + return false; + } + } + + // 8. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + + if (!disp_ldap) { + System.out.println( + "ERROR: ConfigureCA: LdapConnectionPanel() failure"); + return false; + } + + // 9. Key Panel + boolean disp_key = KeyPanel(); + + if (!disp_key) { + System.out.println("ERROR: ConfigureCA: KeyPanel() failure"); + return false; + } + + // 10. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + + if (!disp_csubj) { + System.out.println("ERROR: ConfigureCA: CertSubjectPanel() failure"); + return false; + } + + // 11. Certificate Panel + boolean disp_cp; + + if (external_ca.equalsIgnoreCase("true")) { + if (ext_ca_cert_file != null) { + // second pass - cacert file defined + disp_cp = CertificatePanelExternal(); + + if (!disp_cp) { + System.out.println("ERROR: ConfigureCA: CertificatePanelExternal() failure"); + return false; + } + } else { + // first pass - cacert file not defined + System.out.println("A Certificate Request has been generated and stored in " + ext_csr_file); + System.out.println( + "Please submit this CSR to your external CA and obtain the CA Cert and CA Cert Chain"); + return true; + } + } + + disp_cp = CertificatePanel(); + + if (!disp_cp) { + System.out.println("ERROR: ConfigureCA: CertificatePanel() failure"); + return false; + } + + // 13. Backup Panel + boolean disp_back = BackupPanel(); + + if (!disp_back) { + System.out.println("ERROR: ConfigureCA: BackupPanel() failure"); + return false; + } + + // 14. Backup Continue Panel + boolean disp_back_cont = BackupContinuePanel(); + + if (!disp_back_cont) { + System.out.println("ERROR: ConfigureCA: BackupContinuePanel() failure"); + return false; + } + + // 15. Import CA Cert panel + boolean disp_import_cacert = ImportCACertPanel(); + + if (!disp_import_cacert) { + System.out.println("ERROR: ConfigureCA: ImportCACertPanel() failure"); + return false; + } + + if (clone) { + // no other panels required for clone + return true; + } + + // 16. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + + if (!disp_adm) { + System.out.println("ERROR: ConfigureCA: AdminCertReqPanel() failure"); + return false; + } + + // 14. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + + if (!disp_im) { + System.out.println( + "ERROR: ConfigureCA: AdminCertImportPanel() failure"); + return false; + } + + // 15. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + + if (!disp_ud) { + System.out.println("ERROR: ConfigureCA: UpdateDomainPanel() failure"); + return false; + } + + return true; + } + + private static String set_default(String val, String def) { + if ((val == null) || (val.equals(""))) { + return def; + } else { + return val; + } + } + + 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(); + StringHolder x_secure_conn = new StringHolder(); + StringHolder x_remove_data = new StringHolder(); + + // key properties (defaults) + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_key_curvename = new StringHolder(); + StringHolder x_key_algorithm = new StringHolder(); + StringHolder x_signing_algorithm = new StringHolder(); + + // key properties (custom - signing) + StringHolder x_signing_key_size = new StringHolder(); + StringHolder x_signing_key_type = new StringHolder(); + StringHolder x_signing_key_curvename = new StringHolder(); + StringHolder x_signing_signingalgorithm = new StringHolder(); + + // key properties (custom - ocsp_signing) + StringHolder x_ocsp_signing_key_size = new StringHolder(); + StringHolder x_ocsp_signing_key_type = new StringHolder(); + StringHolder x_ocsp_signing_key_curvename = new StringHolder(); + StringHolder x_ocsp_signing_signingalgorithm = new StringHolder(); + + // key properties (custom - audit_signing) + StringHolder x_audit_signing_key_size = new StringHolder(); + StringHolder x_audit_signing_key_type = new StringHolder(); + StringHolder x_audit_signing_key_curvename = new StringHolder(); + + // key properties (custom - subsystem) + StringHolder x_subsystem_key_size = new StringHolder(); + StringHolder x_subsystem_key_type = new StringHolder(); + StringHolder x_subsystem_key_curvename = new StringHolder(); + + // key properties (custom - sslserver) + StringHolder x_sslserver_key_size = new StringHolder(); + StringHolder x_sslserver_key_type = new StringHolder(); + StringHolder x_sslserver_key_curvename = 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(); + StringHolder x_backup_fname = 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(); + StringHolder x_ca_audit_signing_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + // external CA cert + StringHolder x_external_ca = new StringHolder(); + StringHolder x_ext_ca_cert_file = new StringHolder(); + StringHolder x_ext_ca_cert_chain_file = new StringHolder(); + StringHolder x_ext_csr_file = new StringHolder(); + + //clone parameters + StringHolder x_clone = new StringHolder(); + StringHolder x_clone_uri = new StringHolder(); + StringHolder x_clone_p12_file = new StringHolder(); + StringHolder x_clone_p12_passwd = new StringHolder(); + StringHolder x_clone_master_port = new StringHolder(); + StringHolder x_clone_replica_port = new StringHolder(); + StringHolder x_clone_replication_security = new StringHolder(); + + //security domain + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_agent_port = new StringHolder(); + StringHolder x_sd_admin_port = new StringHolder(); + StringHolder x_sd_admin_name = new StringHolder(); + StringHolder x_sd_admin_password = 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 Admin 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("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn); + parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", + x_remove_data); + + // key and algorithm options (default) + parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type); + parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size); + parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename); + parser.addOption( + "-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", + x_key_algorithm); + parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)", + x_signing_algorithm); + + // key and algorithm options for signing certificate (overrides default) + parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type); + parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size); + parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_signing_key_curvename); + parser.addOption( + "-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)", + x_signing_signingalgorithm); + + // key and algorithm options for ocsp_signing certificate (overrides default) + parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_ocsp_signing_key_type); + parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_ocsp_signing_key_size); + parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_ocsp_signing_key_curvename); + parser.addOption( + "-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)", + x_ocsp_signing_signingalgorithm); + + // key and algorithm options for audit_signing certificate (overrides default) + parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_audit_signing_key_type); + parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_audit_signing_key_size); + parser.addOption( + "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_audit_signing_key_curvename); + + // key and algorithm options for subsystem certificate (overrides default) + parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_subsystem_key_type); + parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", + x_subsystem_key_size); + parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_subsystem_key_curvename); + + // key and algorithm options for sslserver certificate (overrides default) + parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_sslserver_key_type); + parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", + x_sslserver_key_size); + parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_sslserver_key_curvename); + + parser.addOption("-token_name %s #HSM/Software Token name", x_token_name); + parser.addOption("-token_pwd %s #HSM/Software Token password (optional - only required for HSM)", + 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 (optional, only required if -save_p12 = true)", + x_backup_pwd); + parser.addOption("-backup_fname %s #Backup File for p12, (optional, default is /root/tmp-ca.p12)", + x_backup_fname); + + 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( + "-ca_audit_signing_cert_subject_name %s #CA audit signing cert subject name", + x_ca_audit_signing_cert_subject_name); + + parser.addOption("-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + parser.addOption("-external %s #Subordinate to external CA [true,false] (optional, default false)", + x_external_ca); + parser.addOption("-ext_ca_cert_file %s #File with CA cert from external CA (optional)", + x_ext_ca_cert_file); + parser.addOption("-ext_ca_cert_chain_file %s #File with CA cert from external CA (optional)", + x_ext_ca_cert_chain_file); + parser.addOption("-ext_csr_file %s #File to save the CSR for submission to an external CA (optional)", + x_ext_csr_file); + + parser.addOption("-clone %s #Clone of another CA [true, false] (optional, default false)", x_clone); + parser.addOption( + "-clone_uri %s #URL of Master CA to clone. It must have the form https://<hostname>:<EE port> (optional, required if -clone=true)", + x_clone_uri); + parser.addOption( + "-clone_p12_file %s #File containing pk12 keys of Master CA (optional, required if -clone=true)", + x_clone_p12_file); + parser.addOption("-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)", + x_clone_p12_passwd); + + // replication agreement options + parser.addOption("-clone_master_port %s #Master Port to be used in replication agreement (optional)", + x_clone_master_port); + parser.addOption("-clone_replica_port %s #Replica Port to be used in replication agreement (optional)", + x_clone_replica_port); + parser.addOption("-clone_replication_security %s #Type of security in replication agreement (optional)", + x_clone_replication_security); + + parser.addOption("-sd_hostname %s #Security Domain Hostname (optional, required if -clone=true)", x_sd_hostname); + parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port (optional, required if -clone=true)", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port (optional, required if -clone=true)", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port (optional, required if -clone=true)", + x_sd_admin_port); + parser.addOption("-sd_admin_name %s #Security Domain admin name (optional, required if -clone=true)", + x_sd_admin_name); + parser.addOption("-sd_admin_password %s #Security Domain admin password (optional, required if -clone=true)", + x_sd_admin_password); + + // and then match the arguments + String[] unmatched = null; + + unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + parser.checkRequiredArgs(); + + // 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; + secure_conn = set_default(x_secure_conn.value, "false"); + remove_data = set_default(x_remove_data.value, "false"); + + key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE); + signing_key_type = set_default(x_signing_key_type.value, key_type); + ocsp_signing_key_type = set_default(x_ocsp_signing_key_type.value, key_type); + audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type); + subsystem_key_type = set_default(x_subsystem_key_type.value, key_type); + sslserver_key_type = set_default(x_sslserver_key_type.value, key_type); + + key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE); + signing_key_size = set_default(x_signing_key_size.value, key_size); + ocsp_signing_key_size = set_default(x_ocsp_signing_key_size.value, key_size); + audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size); + subsystem_key_size = set_default(x_subsystem_key_size.value, key_size); + sslserver_key_size = set_default(x_sslserver_key_size.value, key_size); + + key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME); + signing_key_curvename = set_default(x_signing_key_curvename.value, key_curvename); + ocsp_signing_key_curvename = set_default(x_ocsp_signing_key_curvename.value, key_curvename); + audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename); + subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename); + sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename); + + if (signing_key_type.equalsIgnoreCase("RSA")) { + key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA); + } else { + key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC); + } + + signing_algorithm = set_default(x_signing_algorithm.value, key_algorithm); + signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm); + ocsp_signing_signingalgorithm = set_default(x_ocsp_signing_signingalgorithm.value, signing_algorithm); + + token_name = x_token_name.value; + token_pwd = x_token_pwd.value; + save_p12 = x_save_p12.value; + backup_pwd = x_backup_pwd.value; + backup_fname = set_default(x_backup_fname.value, "/root/tmp-ca.p12"); + + 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; + ca_audit_signing_cert_subject_name = x_ca_audit_signing_cert_subject_name.value; + + subsystem_name = x_subsystem_name.value; + + external_ca = set_default(x_external_ca.value, "false"); + ext_ca_cert_file = x_ext_ca_cert_file.value; + ext_ca_cert_chain_file = x_ext_ca_cert_chain_file.value; + ext_csr_file = set_default(x_ext_csr_file.value, "/tmp/ext_ca.csr"); + + if ((x_clone.value != null) && (x_clone.value.equalsIgnoreCase("true"))) { + clone = true; + } else { + clone = false; + } + clone_uri = x_clone_uri.value; + clone_p12_file = x_clone_p12_file.value; + clone_p12_passwd = x_clone_p12_passwd.value; + clone_master_port = set_default(x_clone_master_port.value, ""); + clone_replica_port = set_default(x_clone_replica_port.value, ""); + clone_replication_security = set_default(x_clone_replication_security.value, "None"); + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_port.value; + sd_admin_name = x_sd_admin_name.value; + sd_admin_password = x_sd_admin_password.value; + + boolean st = ca.ConfigureCAInstance(); + + if (!st) { + System.out.println("ERROR: unable to create CA"); + System.exit(-1); + } + + System.out.println("Certificate System - CA Instance Configured."); + System.exit(0); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java b/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java new file mode 100644 index 000000000..7d548ddf3 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java @@ -0,0 +1,1374 @@ +package com.netscape.pkisilent; + +// --- 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.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; + +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.pkcs12.AuthenticatedSafes; +import org.mozilla.jss.pkcs12.PFX; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureDRM { + + // global constants + public static final String DEFAULT_KEY_TYPE = "RSA"; + public static final String DEFAULT_KEY_SIZE = "2048"; + public static final String DEFAULT_KEY_CURVENAME = "nistp256"; + public static final String DEFAULT_KEY_ALGORITHM_RSA = "SHA256withRSA"; + public static final String DEFAULT_KEY_ALGORITHM_ECC = "SHA256withEC"; + + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/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_agent_port = null; + public static String sd_admin_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 secure_conn = null; + public static String remove_data = null; + + public static String key_type = null; + public static String key_size = null; + public static String key_curvename = null; + public static String signing_algorithm = null; + + public static String transport_key_type = null; + public static String transport_key_size = null; + public static String transport_key_curvename = null; + public static String transport_signingalgorithm = null; + + public static String storage_key_type = null; + public static String storage_key_size = null; + public static String storage_key_curvename = null; + + public static String subsystem_key_type = null; + public static String subsystem_key_size = null; + public static String subsystem_key_curvename = null; + + public static String audit_signing_key_type = null; + public static String audit_signing_key_size = null; + public static String audit_signing_key_curvename = null; + + public static String sslserver_key_type = null; + public static String sslserver_key_size = null; + public static String sslserver_key_curvename = 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 drm_audit_signing_cert_name = null; + public static String drm_audit_signing_cert_req = null; + public static String drm_audit_signing_cert_pp = null; + public static String drm_audit_signing_cert_cert = null; + + public static String backup_pwd = null; + public static String backup_fname = 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 drm_audit_signing_cert_subject_name = null; + + public static String subsystem_name = null; + + // cloning + public static boolean clone = false; + public static String clone_uri = null; + public static String clone_p12_passwd = null; + public static String clone_p12_file = null; + public static String clone_master_port = null; + public static String clone_replica_port = null; + public static String clone_replication_security = null; + + //for correct selection of CA to be cloned + public static String urls; + + 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(";"); + HTTPClient.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 TokenChoicePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token", "UTF-8"); + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + } else { + // login to hsm first + query_string = "p=2" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8"); + 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=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name, "UTF-8"); + 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 DomainPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url, "UTF-8") + + "&choice=existingdomain" + + "&p=3" + + "&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() { + String query_string = "p=4" + "&op=next" + "&xml=true"; + hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + return true; + + } + + public boolean SecurityDomainLoginPanel() { + try { + HTTPResponse hr = null; + + String kra_url = "https://" + cs_hostname + ":" + cs_port + + "/kra/admin/console/config/wizard" + + "?p=5&subsystem=KRA"; + + String query_string = "url=" + URLEncoder.encode(kra_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(kra_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_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=5" + + "&subsystem=KRA" + + "&session_id=" + kra_session_id + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + query_string_2); + + if (clone) { + // parse urls + urls = hr.getHTML(); + int indx = urls.indexOf(clone_uri); + if (indx < 0) { + throw new Exception("Invalid clone_uri"); + } + urls = urls.substring(urls.lastIndexOf("<option", indx), indx); + urls = urls.split("\"")[1]; + + System.out.println("urls =" + urls); + } + + return true; + } catch (Exception e) { + System.out.println("Exception in SecurityDomainLoginPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean SubsystemPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String query_string = null; + if (!clone) { + query_string = "p=5" + "&op=next" + "&xml=true" + + "&choice=newsubsystem" + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8"); + } else { + query_string = "p=5" + "&op=next" + "&xml=true" + + "&choice=clonesubsystem" + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&urls=" + urls; + } + + 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 RestoreKeyCertPanel() { + try { + ByteArrayInputStream bais = null; + HTTPResponse hr = null; + ParseXML px = new ParseXML(); + + String query_string = "p=6" + "&op=next" + "&xml=true" + + "&__password=" + URLEncoder.encode(clone_p12_passwd, "UTF-8") + + "&path=" + URLEncoder.encode(clone_p12_file, "UTF-8") + ""; + + 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; + } catch (Exception e) { + System.out.println("Exception in RestoreKeyCertPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean LdapConnectionPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=7" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host, "UTF-8") + + "&port=" + URLEncoder.encode(ldap_port, "UTF-8") + + "&binddn=" + URLEncoder.encode(bind_dn, "UTF-8") + + "&__bindpwd=" + URLEncoder.encode(bind_password, "UTF-8") + + "&basedn=" + URLEncoder.encode(base_dn, "UTF-8") + + "&database=" + URLEncoder.encode(db_name, "UTF-8") + + "&display=" + URLEncoder.encode("$displayStr", "UTF-8") + + (secure_conn.equals("true") ? "&secureConn=on" : "") + + "&masterReplicationPort=" + URLEncoder.encode(clone_master_port, "UTF-8") + + "&cloneReplicationPort=" + URLEncoder.encode(clone_replica_port, "UTF-8") + + "&replicationSecurity=" + URLEncoder.encode(clone_replication_security, "UTF-8") + + (remove_data.equals("true") ? "&removeData=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 KeyPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> al = null; + + String query_string = null; + + if (!clone) { + query_string = "p=8" + "&op=next" + "&xml=true" + + "&transport_custom_size=" + transport_key_size + + "&storage_custom_size=" + storage_key_size + + "&subsystem_custom_size=" + subsystem_key_size + + "&sslserver_custom_size=" + sslserver_key_size + + "&audit_signing_custom_size=" + key_size + + "&custom_size=" + key_size + + "&transport_custom_curvename=" + transport_key_curvename + + "&storage_custom_curvename=" + storage_key_curvename + + "&subsystem_custom_curvename=" + subsystem_key_curvename + + "&sslserver_custom_curvename=" + sslserver_key_curvename + + "&audit_signing_custom_curvename=" + audit_signing_key_curvename + + "&custom_curvename=" + key_curvename + + "&transport_keytype=" + transport_key_type + + "&storage_keytype=" + storage_key_type + + "&subsystem_keytype=" + subsystem_key_type + + "&sslserver_keytype=" + sslserver_key_type + + "&audit_signing_keytype=" + audit_signing_key_type + + "&keytype=" + key_type + + "&transport_choice=custom" + + "&storage_choice=custom" + + "&subsystem_choice=custom" + + "&sslserver_choice=custom" + + "&choice=custom" + + "&audit_signing_choice=custom" + + "&signingalgorithm=" + signing_algorithm + + "&transport_signingalgorithm=" + transport_signingalgorithm; + + } else { + query_string = "p=8" + "&op=next" + "&xml=true" + + "&sslserver_custom_size=" + sslserver_key_size + + "&sslserver_keytype=" + sslserver_key_type + + "&sslserver_choice=custom" + + "&custom_size=" + key_size + + "&keytype=" + key_type + + "&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 = 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 if (temp.indexOf("DRM Audit Signing Certificate") > 0) { + drm_audit_signing_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: drm_audit_signing_cert_name=" + + drm_audit_signing_cert_name); + + System.out.println("default: server_cert_name=" + + server_cert_name); + return true; + } + + public boolean CertSubjectPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> req_list = null; + ArrayList<String> cert_list = null; + ArrayList<String> dn_list = null; + String query_string = null; + + String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port; + + if (!clone) { + query_string = "p=9" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(drm_subsystem_cert_subject_name, "UTF-8") + + "&transport=" + + URLEncoder.encode(drm_transport_cert_subject_name, "UTF-8") + + "&storage=" + + URLEncoder.encode(drm_storage_cert_subject_name, "UTF-8") + + "&sslserver=" + + URLEncoder.encode(drm_server_cert_subject_name, "UTF-8") + + "&audit_signing=" + + URLEncoder.encode(drm_audit_signing_cert_subject_name, "UTF-8") + + "&urls=" + + URLEncoder.encode(domain_url, "UTF-8"); + } else { + query_string = "p=9" + "&op=next" + "&xml=true" + + "&sslserver=" + + URLEncoder.encode(drm_server_cert_subject_name, "UTF-8") + + "&urls=" + + URLEncoder.encode(domain_url, "UTF-8"); + } + + 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 = dn_list.get(i); + + if (temp.indexOf("transportCert") >= 0) { + drm_transport_cert_req = req_list.get(i); + drm_transport_cert_cert = cert_list.get(i); + } else if (temp.indexOf("storageCert") >= 0) { + drm_storage_cert_req = req_list.get(i); + drm_storage_cert_cert = cert_list.get(i); + } else if (temp.indexOf("subsystemCert") >= 0) { + drm_subsystem_cert_req = req_list.get(i); + drm_subsystem_cert_cert = cert_list.get(i); + } else if (temp.indexOf("auditSigningCert") >= 0) { + drm_audit_signing_cert_req = req_list.get(i); + drm_audit_signing_cert_cert = cert_list.get(i); + } else { + server_cert_req = req_list.get(i); + server_cert_cert = cert_list.get(i); + } + } + } + + return true; + } + + public boolean CertificatePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(drm_subsystem_cert_cert, "UTF-8") + + "&subsystem_cc=" + + "&transport=" + + URLEncoder.encode(drm_transport_cert_cert, "UTF-8") + + "&transport_cc=" + + "&storage=" + + URLEncoder.encode(drm_storage_cert_cert, "UTF-8") + + "&storage_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert, "UTF-8") + + "&sslserver_cc=" + + "&audit_signing=" + + URLEncoder.encode(drm_audit_signing_cert_cert, "UTF-8") + + "&audit_signing_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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + URLEncoder.encode(backup_pwd, "UTF-8") + + "&__pwdagain=" + URLEncoder.encode(backup_pwd, "UTF-8"); + + 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() { + 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(backup_fname); + fos.write(hr.getResponseData()); + fos.close(); + + // set file to permissions 600 + String rtParams[] = { "chmod", "600", backup_fname }; + Process proc = Runtime.getRuntime().exec(rtParams); + + BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream())); + String line = null; + while ((line = br.readLine()) != null) + System.out.println("Error: " + line); + proc.waitFor(); + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream(backup_fname); + 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(); + + if (clone) { + query_string = "p=12" + "&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(); + } + } catch (Exception e) { + System.out.println("ERROR: Exception=" + e.getMessage()); + return false; + } + + return true; + } + + public boolean AdminCertReqPanel() throws UnsupportedEncodingException { + 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=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email, "UTF-8") + + "&cert_request=" + + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&subject=" + + URLEncoder.encode(agent_cert_subject, "UTF-8") + + "&clone=new" + + "&import=true" + + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8"); + + 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; + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true"; + + hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string); + + // get response data + // String cert_to_import = + // new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + String cert_to_import = + Utils.base64encode(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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=14" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(sd_hostname, "UTF-8") + + "&caPort=" + URLEncoder.encode(sd_agent_port, "UTF-8"); + + 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() throws UnsupportedEncodingException { + // 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. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if (!disp_token) { + System.out.println("ERROR: ConfigureDRM: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 3. domain panel + boolean dom_st = DomainPanel(); + if (!dom_st) { + System.out.println("ERROR: ConfigureDRM: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 4. 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(); + // 6. display restore key cert panel + if (clone) { + boolean restore_st = RestoreKeyCertPanel(); + if (!restore_st) { + System.out.println("ERROR: ConfigureCA: RestoreKeyCertPanel() 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(); + // 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; + } + + if (clone) { + // no other panels required for clone + return true; + } + + 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; + } + + private static String set_default(String val, String def) { + if ((val == null) || (val.equals(""))) { + return def; + } else { + return val; + } + } + + public static void main(String args[]) throws UnsupportedEncodingException { + 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_agent_port = new StringHolder(); + StringHolder x_sd_admin_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(); + StringHolder x_secure_conn = new StringHolder(); + StringHolder x_remove_data = new StringHolder(); + + // key properties (defaults) + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_key_curvename = new StringHolder(); + StringHolder x_signing_algorithm = new StringHolder(); + + // key properties (custom - transport) + StringHolder x_transport_key_size = new StringHolder(); + StringHolder x_transport_key_type = new StringHolder(); + StringHolder x_transport_key_curvename = new StringHolder(); + StringHolder x_transport_signingalgorithm = new StringHolder(); + + // key properties (custom - storage) + StringHolder x_storage_key_size = new StringHolder(); + StringHolder x_storage_key_type = new StringHolder(); + StringHolder x_storage_key_curvename = new StringHolder(); + + // key properties (custom - audit_signing) + StringHolder x_audit_signing_key_size = new StringHolder(); + StringHolder x_audit_signing_key_type = new StringHolder(); + StringHolder x_audit_signing_key_curvename = new StringHolder(); + + // key properties (custom - subsystem) + StringHolder x_subsystem_key_size = new StringHolder(); + StringHolder x_subsystem_key_type = new StringHolder(); + StringHolder x_subsystem_key_curvename = new StringHolder(); + + // key properties (custom - sslserver) + StringHolder x_sslserver_key_size = new StringHolder(); + StringHolder x_sslserver_key_type = new StringHolder(); + StringHolder x_sslserver_key_curvename = 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(); + StringHolder x_backup_fname = 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(); + StringHolder x_drm_audit_signing_cert_subject_name = new StringHolder(); + + // subsystemName + StringHolder x_subsystem_name = new StringHolder(); + + //clone parameters + StringHolder x_clone = new StringHolder(); + StringHolder x_clone_uri = new StringHolder(); + StringHolder x_clone_p12_file = new StringHolder(); + StringHolder x_clone_p12_passwd = new StringHolder(); + StringHolder x_clone_master_port = new StringHolder(); + StringHolder x_clone_replica_port = new StringHolder(); + StringHolder x_clone_replication_security = 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 Admin port", + x_cs_port); + + parser.addOption("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port", + x_sd_admin_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 EE port", + x_ca_port); + parser.addOption("-ca_ssl_port %s #CA SSL EE 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("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn); + parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", + x_remove_data); + + // key and algorithm options (default) + parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type); + parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size); + parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename); + parser.addOption( + "-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", + x_signing_algorithm); + + // key and algorithm options for transport certificate (overrides default) + parser.addOption("-transport_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_transport_key_type); + parser.addOption("-transport_key_size %s #Key Size (optional, for RSA default is key_size)", + x_transport_key_size); + parser.addOption("-transport_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_transport_key_curvename); + parser.addOption( + "-transport_signingalgorithm %s #Algorithm used by the transport cert to sign objects (optional, default is signing_algorithm)", + x_transport_signingalgorithm); + + // key and algorithm options for storage certificate (overrides default) + parser.addOption("-storage_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_storage_key_type); + parser.addOption("-storage_key_size %s #Key Size (optional, for RSA default is key_size)", x_storage_key_size); + parser.addOption("-storage_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_storage_key_curvename); + + // key and algorithm options for audit_signing certificate (overrides default) + parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_audit_signing_key_type); + parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_audit_signing_key_size); + parser.addOption( + "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_audit_signing_key_curvename); + + // key and algorithm options for subsystem certificate (overrides default) + parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_subsystem_key_type); + parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", + x_subsystem_key_size); + parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_subsystem_key_curvename); + + // key and algorithm options for sslserver certificate (overrides default) + parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_sslserver_key_type); + parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", + x_sslserver_key_size); + parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_sslserver_key_curvename); + + parser.addOption("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)", + 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("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-kra.p12)", + x_backup_fname); + + 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); + + parser.addOption( + "-drm_audit_signing_cert_subject_name %s #DRM audit signing cert subject name", + x_drm_audit_signing_cert_subject_name); + + parser.addOption("-clone %s #Clone of another KRA [true, false] (optional, default false)", x_clone); + parser.addOption( + "-clone_uri %s #URL of Master KRA to clone. It must have the form https://<hostname>:<EE port> (optional, required if -clone=true)", + x_clone_uri); + parser.addOption( + "-clone_p12_file %s #File containing pk12 keys of Master KRA (optional, required if -clone=true)", + x_clone_p12_file); + parser.addOption("-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)", + x_clone_p12_passwd); + + // replication agreement options + parser.addOption("-clone_master_port %s #Master Port to be used in replication agreement (optional)", + x_clone_master_port); + parser.addOption("-clone_replica_port %s #Replica Port to be used in replication agreement (optional)", + x_clone_replica_port); + parser.addOption("-clone_replication_security %s #Type of security in replication agreement (optional)", + x_clone_replication_security); + + + // and then match the arguments + String[] unmatched = null; + unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + parser.checkRequiredArgs(); + + // 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_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_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; + secure_conn = set_default(x_secure_conn.value, "false"); + remove_data = set_default(x_remove_data.value, "false"); + + key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE); + transport_key_type = set_default(x_transport_key_type.value, key_type); + storage_key_type = set_default(x_storage_key_type.value, key_type); + audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type); + subsystem_key_type = set_default(x_subsystem_key_type.value, key_type); + sslserver_key_type = set_default(x_sslserver_key_type.value, key_type); + + key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE); + transport_key_size = set_default(x_transport_key_size.value, key_size); + storage_key_size = set_default(x_storage_key_size.value, key_size); + audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size); + subsystem_key_size = set_default(x_subsystem_key_size.value, key_size); + sslserver_key_size = set_default(x_sslserver_key_size.value, key_size); + + key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME); + transport_key_curvename = set_default(x_transport_key_curvename.value, key_curvename); + storage_key_curvename = set_default(x_storage_key_curvename.value, key_curvename); + audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename); + subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename); + sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename); + + if (transport_key_type.equalsIgnoreCase("RSA")) { + signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA); + } else { + signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC); + } + + transport_signingalgorithm = set_default(x_transport_signingalgorithm.value, signing_algorithm); + + 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; + backup_fname = set_default(x_backup_fname.value, "/root/tmp-kra.p12"); + + 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; + drm_audit_signing_cert_subject_name = x_drm_audit_signing_cert_subject_name.value; + + subsystem_name = x_subsystem_name.value; + + if ((x_clone.value != null) && (x_clone.value.equalsIgnoreCase("true"))) { + clone = true; + } else { + clone = false; + } + clone_uri = x_clone_uri.value; + clone_p12_file = x_clone_p12_file.value; + clone_p12_passwd = x_clone_p12_passwd.value; + clone_master_port = set_default(x_clone_master_port.value, ""); + clone_replica_port = set_default(x_clone_replica_port.value, ""); + clone_replication_security = set_default(x_clone_replication_security.value, "None"); + + boolean st = ca.ConfigureDRMInstance(); + + if (!st) { + System.out.println("ERROR: unable to create DRM"); + System.exit(-1); + } + + System.out.println("Certificate System - DRM Instance Configured"); + System.exit(0); + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java b/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java new file mode 100644 index 000000000..53c014b74 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java @@ -0,0 +1,1181 @@ +package com.netscape.pkisilent; + +// --- 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.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; + +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.pkcs12.AuthenticatedSafes; +import org.mozilla.jss.pkcs12.PFX; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureOCSP { + public static final String DEFAULT_KEY_TYPE = "RSA"; + public static final String DEFAULT_KEY_SIZE = "2048"; + public static final String DEFAULT_KEY_CURVENAME = "nistp256"; + public static final String DEFAULT_KEY_ALGORITHM_RSA = "SHA256withRSA"; + public static final String DEFAULT_KEY_ALGORITHM_ECC = "SHA256withEC"; + + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/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_agent_port = null; + public static String sd_admin_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 secure_conn = null; + public static String remove_data = null; + + public static String key_type = null; + public static String key_size = null; + public static String key_curvename = null; + public static String signing_algorithm = null; + + public static String signing_key_type = null; + public static String signing_key_size = null; + public static String signing_key_curvename = null; + public static String signing_signingalgorithm = null; + + public static String subsystem_key_type = null; + public static String subsystem_key_size = null; + public static String subsystem_key_curvename = null; + + public static String audit_signing_key_type = null; + public static String audit_signing_key_size = null; + public static String audit_signing_key_curvename = null; + + public static String sslserver_key_type = null; + public static String sslserver_key_size = null; + public static String sslserver_key_curvename = 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 ocsp_audit_signing_cert_name = null; + public static String ocsp_audit_signing_cert_req = null; + public static String ocsp_audit_signing_cert_pp = null; + public static String ocsp_audit_signing_cert_cert = null; + + public static String backup_pwd = null; + public static String backup_fname = 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 ocsp_audit_signing_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(";"); + HTTPClient.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 TokenChoicePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=1" + "&op=next" + "&xml=true" + + "&choice=" + URLEncoder.encode("Internal Key Storage Token", "UTF-8"); + 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=2" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8"); + 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=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name, "UTF-8"); + 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 DomainPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url, "UTF-8") + + "&choice=existingdomain" + + "&p=3" + + "&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() { + String query_string = null; + + query_string = "p=4" + "&op=next" + "&xml=true"; + 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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + + String ocsp_url = "https://" + cs_hostname + ":" + cs_port + + "/ocsp/admin/console/config/wizard" + + "?p=5&subsystem=OCSP"; + + String query_string = "url=" + URLEncoder.encode(ocsp_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(ocsp_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_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=5" + + "&subsystem=OCSP" + + "&session_id=" + ocsp_session_id + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + query_string_2); + + return true; + + } + + public boolean SubsystemPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=5" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=7" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host, "UTF-8") + + "&port=" + URLEncoder.encode(ldap_port, "UTF-8") + + "&binddn=" + URLEncoder.encode(bind_dn, "UTF-8") + + "&__bindpwd=" + URLEncoder.encode(bind_password, "UTF-8") + + "&basedn=" + URLEncoder.encode(base_dn, "UTF-8") + + "&database=" + URLEncoder.encode(db_name, "UTF-8") + + "&display=" + URLEncoder.encode("$displayStr", "UTF-8") + + (secure_conn.equals("true") ? "&secureConn=on" : "") + + (remove_data.equals("true") ? "&removeData=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 KeyPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> al = null; + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&signing_custom_size=" + signing_key_size + + "&subsystem_custom_size=" + subsystem_key_size + + "&sslserver_custom_size=" + sslserver_key_size + + "&audit_signing_custom_size=" + audit_signing_key_size + + "&custom_size=" + key_size + + "&signing_custom_curvename=" + signing_key_curvename + + "&subsystem_custom_curvename=" + subsystem_key_curvename + + "&sslserver_custom_curvename=" + sslserver_key_curvename + + "&audit_signing_custom_curvename=" + audit_signing_key_curvename + + "&custom_curvename=" + key_curvename + + "&signing_keytype=" + signing_key_type + + "&subsystem_keytype=" + subsystem_key_type + + "&sslserver_keytype=" + sslserver_key_type + + "&audit_signing_keytype=" + audit_signing_key_type + + "&keytype=" + key_type + + "&signing_choice=custom" + + "&subsystem_choice=custom" + + "&sslserver_choice=custom" + + "&audit_signing_choice=custom" + + "&signingalgorithm=" + signing_algorithm + + "&signing_signingalgorithm=" + signing_signingalgorithm + + "&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 = 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 if (temp.indexOf("Audit Signing Certificate") > 0) { + ocsp_audit_signing_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); + System.out.println("default: oscp_audit_signing_cert_name=" + ocsp_audit_signing_cert_name); + + return true; + } + + public boolean CertSubjectPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> req_list = null; + ArrayList<String> cert_list = null; + ArrayList<String> 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, "UTF-8") + + "&signing=" + + URLEncoder.encode(ocsp_sign_cert_subject_name, "UTF-8") + + "&sslserver=" + + URLEncoder.encode(ocsp_server_cert_subject_name, "UTF-8") + + "&audit_signing=" + + URLEncoder.encode(ocsp_audit_signing_cert_subject_name, "UTF-8") + + "&urls=" + + URLEncoder.encode(domain_url, "UTF-8") + + ""; + + 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 = dn_list.get(i); + + if (temp.indexOf("ocspSigningCert") >= 0) { + ocsp_signing_cert_req = req_list.get(i); + ocsp_signing_cert_cert = cert_list.get(i); + } else if (temp.indexOf("subsystemCert") >= 0) { + ocsp_subsystem_cert_req = req_list.get(i); + ocsp_subsystem_cert_cert = cert_list.get(i); + } else if (temp.indexOf("auditSigningCert") >= 0) { + ocsp_audit_signing_cert_req = req_list.get(i); + ocsp_audit_signing_cert_cert = cert_list.get(i); + } else { + server_cert_req = req_list.get(i); + server_cert_cert = cert_list.get(i); + } + } + } + + return true; + } + + public boolean CertificatePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(ocsp_subsystem_cert_cert, "UTF-8") + + "&subsystem_cc=" + + "&signing=" + + URLEncoder.encode(ocsp_signing_cert_cert, "UTF-8") + + "&signing_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert, "UTF-8") + + "&sslserver_cc=" + + "&audit_signing=" + + URLEncoder.encode(ocsp_audit_signing_cert_cert, "UTF-8") + + "&audit_signing_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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + URLEncoder.encode(backup_pwd, "UTF-8") + + "&__pwdagain=" + URLEncoder.encode(backup_pwd, "UTF-8"); + + 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() { + HTTPResponse hr = null; + + String query_string = ""; + + hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string); + + // dump hr.getResponseData() to file + + try { + FileOutputStream fos = new FileOutputStream(backup_fname); + fos.write(hr.getResponseData()); + fos.close(); + + // set file to permissions 600 + String rtParams[] = { "chmod", "600", backup_fname }; + Process proc = Runtime.getRuntime().exec(rtParams); + + BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream())); + String line = null; + while ((line = br.readLine()) != null) + System.out.println("Error: " + line); + proc.waitFor(); + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream(backup_fname); + 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() throws UnsupportedEncodingException { + 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=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email, "UTF-8") + + "&cert_request=" + + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&subject=" + + URLEncoder.encode(agent_cert_subject, "UTF-8") + + "&clone=new" + + "&import=true" + + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8"); + + 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; + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string); + + // get response data + // String cert_to_import = + // new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + String cert_to_import = + Utils.base64encode(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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=14" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(sd_hostname, "UTF-8") + + "&caPort=" + URLEncoder.encode(sd_agent_port, "UTF-8"); + + 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() throws UnsupportedEncodingException { + // 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. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if (!disp_token) { + System.out.println("ERROR: ConfigureOCSP: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 3. domain panel + boolean dom_st = DomainPanel(); + if (!dom_st) { + System.out.println("ERROR: ConfigureOCSP: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 4. 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(); + // 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; + } + + private static String set_default(String val, String def) { + if ((val == null) || (val.equals(""))) { + return def; + } else { + return val; + } + } + + public static void main(String args[]) throws UnsupportedEncodingException { + 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_agent_port = new StringHolder(); + StringHolder x_sd_admin_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(); + StringHolder x_secure_conn = new StringHolder(); + StringHolder x_remove_data = new StringHolder(); + + // key properties (defaults) + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_key_curvename = new StringHolder(); + StringHolder x_signing_algorithm = new StringHolder(); + + // key properties (custom - signing) + StringHolder x_signing_key_size = new StringHolder(); + StringHolder x_signing_key_type = new StringHolder(); + StringHolder x_signing_key_curvename = new StringHolder(); + StringHolder x_signing_signingalgorithm = new StringHolder(); + + // key properties (custom - audit_signing) + StringHolder x_audit_signing_key_size = new StringHolder(); + StringHolder x_audit_signing_key_type = new StringHolder(); + StringHolder x_audit_signing_key_curvename = new StringHolder(); + + // key properties (custom - subsystem) + StringHolder x_subsystem_key_size = new StringHolder(); + StringHolder x_subsystem_key_type = new StringHolder(); + StringHolder x_subsystem_key_curvename = new StringHolder(); + + // key properties (custom - sslserver) + StringHolder x_sslserver_key_size = new StringHolder(); + StringHolder x_sslserver_key_type = new StringHolder(); + StringHolder x_sslserver_key_curvename = 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(); + StringHolder x_backup_fname = 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(); + StringHolder x_ocsp_audit_signing_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 Admin port", + x_cs_port); + + parser.addOption("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port", + x_sd_admin_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 EE port", + x_ca_port); + parser.addOption("-ca_ssl_port %s #CA SSL EE 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("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn); + parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", + x_remove_data); + + // key and algorithm options (default) + parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type); + parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size); + parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename); + parser.addOption( + "-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", + x_signing_algorithm); + + // key and algorithm options for signing certificate (overrides default) + parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type); + parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size); + parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_signing_key_curvename); + parser.addOption( + "-signing_signingalgorithm %s #Algorithm used be ocsp signing cert to sign objects (optional, default is signing_algorithm)", + x_signing_signingalgorithm); + + // key and algorithm options for audit_signing certificate (overrides default) + parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_audit_signing_key_type); + parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_audit_signing_key_size); + parser.addOption( + "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_audit_signing_key_curvename); + + // key and algorithm options for subsystem certificate (overrides default) + parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_subsystem_key_type); + parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", + x_subsystem_key_size); + parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_subsystem_key_curvename); + + // key and algorithm options for sslserver certificate (overrides default) + parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_sslserver_key_type); + parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", + x_sslserver_key_size); + parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_sslserver_key_curvename); + + parser.addOption("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)", + 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("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-ocsp.p12", + x_backup_fname); + + parser.addOption( + "-subsystem_name %s #OCSP subsystem name", + x_subsystem_name); + + parser.addOption( + "-ocsp_audit_signing_cert_subject_name %s #OCSP audit signing cert subject name", + x_ocsp_audit_signing_cert_subject_name); + + // and then match the arguments + String[] unmatched = null; + unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + parser.checkRequiredArgs(); + + // 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_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_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; + secure_conn = set_default(x_secure_conn.value, "false"); + remove_data = set_default(x_remove_data.value, "false"); + + key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE); + signing_key_type = set_default(x_signing_key_type.value, key_type); + audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type); + subsystem_key_type = set_default(x_subsystem_key_type.value, key_type); + sslserver_key_type = set_default(x_sslserver_key_type.value, key_type); + + key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE); + signing_key_size = set_default(x_signing_key_size.value, key_size); + audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size); + subsystem_key_size = set_default(x_subsystem_key_size.value, key_size); + sslserver_key_size = set_default(x_sslserver_key_size.value, key_size); + + key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME); + signing_key_curvename = set_default(x_signing_key_curvename.value, key_curvename); + audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename); + subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename); + sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename); + + if (signing_key_type.equalsIgnoreCase("RSA")) { + signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA); + } else { + signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC); + } + signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm); + + 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; + backup_fname = set_default(x_backup_fname.value, "/root/tmp-ocsp.p12"); + + 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; + ocsp_audit_signing_cert_subject_name = x_ocsp_audit_signing_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("Certificate System - OCSP Instance Configured"); + System.exit(0); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureRA.java b/base/silent/src/com/netscape/pkisilent/ConfigureRA.java new file mode 100644 index 000000000..3de70a067 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureRA.java @@ -0,0 +1,881 @@ +package com.netscape.pkisilent; + +// --- 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.ByteArrayInputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureRA { + + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie"; + public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML"; + 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 cs_clientauth_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_agent_port = null; + public static String sd_admin_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_admin_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_server_cert_subject_name = null; + public static String ra_server_cert_nickname = null; + public static String ra_subsystem_cert_subject_name = null; + public static String ra_subsystem_cert_nickname = null; + public static String subsystem_name = null; + + // Security Domain Login Panel + public static String ra_session_id = null; + + // Admin Certificate Request Panel + public static String requestor_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.sslConnect(cs_hostname, cs_port, login_uri, query_string); + System.out.println("xml returned: " + hr.getHTML()); + + // parse xml here - nothing to parse + + // no cookie for ra + // get cookie + String temp = hr.getCookieValue("pin"); + + if (temp != null) { + int index = temp.indexOf(";"); + HTTPClient.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(); + + st = true; + return st; + } + + public boolean DomainPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + + String query_string = "p=1" + + "&choice=existingdomain" + + "&sdomainURL=" + + URLEncoder.encode(domain_url, "UTF-8") + + "&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() { + String query_string = "p=2" + "&op=next" + "&xml=true"; + hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + return true; + + } + + public boolean SecurityDomainLoginPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + + 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, "UTF-8") + ""; + + hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(ra_url, "UTF-8") + + ""; + + hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + sleep_time(); + + 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" + + "&subsystem=RA" + + "&session_id=" + ra_session_id + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + query_string_2); + + // parse xml - no parsing + + return true; + + } + + public boolean SubsystemPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + sleep_time(); + String query_string = "p=3" + + "&choice=newsubsystem" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&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(); + + sleep_time(); + + // CA choice panel + query_string = "p=4" + + "&urls=0" + + "&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 DBPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + // SQL LITE PANEL + + String query_string = "p=5" + "&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 TokenChoicePanel() throws UnsupportedEncodingException { + 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" + + "&choice=" + + URLEncoder.encode("NSS Certificate DB", "UTF-8") + + "&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(); + } + // HSM + else { + // login to hsm first + query_string = "p=7" + + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8") + + "&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(); + + // choice with token name now + query_string = "p=6" + + "&choice=" + + URLEncoder.encode(token_name, "UTF-8") + + "&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 KeyPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=8" + + "&keytype=" + key_type + + "&choice=default" + + "&custom_size=" + key_size + + "&sslserver_keytype=" + key_type + + "&sslserver_choice=custom" + + "&sslserver_custom_size=" + key_size + + "&subsystem_keytype=" + key_type + + "&subsystem_choice=custom" + + "&subsystem_custom_size=" + key_size + + "&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 CertSubjectPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=9" + + "&sslserver=" + + URLEncoder.encode(ra_server_cert_subject_name, "UTF-8") + + "&sslserver_nick=" + + URLEncoder.encode(ra_server_cert_nickname, "UTF-8") + + "&subsystem=" + + URLEncoder.encode(ra_subsystem_cert_subject_name, "UTF-8") + + "&subsystem_nick=" + + URLEncoder.encode(ra_subsystem_cert_nickname, "UTF-8") + + "&urls=0" + + "&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 CertificatePanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=10" + + "&sslserver=" + + "&sslserver_cc=" + + "&subsystem=" + + "&subsystem_cc=" + + "&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 AdminCertReqPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + requestor_name = "RA-" + cs_hostname + "-" + cs_clientauth_port; + + 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" + + "&uid=" + admin_user + + "&name=" + + URLEncoder.encode("RA Administrator", "UTF-8") + + "&email=" + + URLEncoder.encode(admin_email, "UTF-8") + + "&__pwd=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + + "&cert_request=" + + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&display=0" + + "&profileId=" + "caAdminCert" + + "&cert_request_type=" + "crmf" + + "&import=true" + + "&uid=" + admin_user + + "&clone=0" + + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8") + + "&subject=" + + URLEncoder.encode(agent_cert_subject, "UTF-8") + + "&requestor_name=" + + URLEncoder.encode(requestor_name, "UTF-8") + + "&sessionID=" + ra_session_id + + "&auth_hostname=" + ca_hostname + + "&auth_port=" + ca_ssl_port + + "&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(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() throws UnsupportedEncodingException { + 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" + + ""; + + // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port; + // whereas RA and TPS use the CA Admin Port associated with + // the 'CA choice panel' as invoked from the SubsystemPanel() + // which MAY or MAY NOT be the same CA as the CA specified + // by the Security Domain. + hr = hc.sslConnect(ca_hostname, ca_admin_port, admin_uri, query_string); + + try { + // cert_to_import = + // new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + cert_to_import = + Utils.base64encode(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"); + + String query_string_1 = "p=12" + + "&serialNumber=" + admin_serial_number + + "&caHost=" + + URLEncoder.encode(ca_hostname, "UTF-8") + + "&caPort=" + ca_admin_port + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean ConfigureRAInstance() throws UnsupportedEncodingException { + // 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(); + // 4. subsystem panel + boolean disp_ss = SubsystemPanel(); + if (!disp_ss) { + System.out.println("ERROR: ConfigureRA: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // 5. ldap connection panel + boolean disp_ldap = DBPanel(); + if (!disp_ldap) { + System.out.println("ERROR: ConfigureRA: DBPanel() failure"); + return false; + } + + sleep_time(); + // 6. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if (!disp_token) { + System.out.println("ERROR: ConfigureRA: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 8. Key Panel + boolean disp_key = KeyPanel(); + if (!disp_key) { + System.out.println("ERROR: ConfigureRA: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 9. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if (!disp_csubj) { + System.out.println("ERROR: ConfigureRA: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 10. Certificate Panel + boolean disp_cp = CertificatePanel(); + if (!disp_cp) { + System.out.println("ERROR: ConfigureRA: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // 11. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if (!disp_adm) { + System.out.println("ERROR: ConfigureRA: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 12. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if (!disp_im) { + System.out.println("ERROR: ConfigureRA: AdminCertImportPanel() failure"); + return false; + } + + return true; + } + + public static void main(String args[]) throws UnsupportedEncodingException { + ConfigureRA ca = new ConfigureRA(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + StringHolder x_cs_clientauth_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_agent_port = new StringHolder(); + StringHolder x_sd_admin_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_ca_admin_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_server_cert_subject_name = new StringHolder(); + StringHolder x_ra_server_cert_nickname = new StringHolder(); + StringHolder x_ra_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_ra_subsystem_cert_nickname = 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("-cs_clientauth_port %s #CS SSL port", + x_cs_clientauth_port); + + parser.addOption("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port", + x_sd_admin_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("-ca_admin_port %s #CA SSL Admin port", + x_ca_admin_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_server_cert_subject_name %s #RA server cert subject name", + x_ra_server_cert_subject_name); + parser.addOption( + "-ra_server_cert_nickname %s #RA server cert nickname", + x_ra_server_cert_nickname); + parser.addOption( + "-ra_subsystem_cert_subject_name %s #RA subsystem cert subject name", + x_ra_subsystem_cert_subject_name); + parser.addOption( + "-ra_subsystem_cert_nickname %s #RA subsystem cert nickname", + x_ra_subsystem_cert_nickname); + + parser.addOption( + "-subsystem_name %s #RA subsystem name", + x_subsystem_name); + + // and then match the arguments + String[] unmatched = null; + unmatched = parser.matchAllArgs(args, 0, ArgParser.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; + cs_clientauth_port = x_cs_clientauth_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_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; + ca_admin_port = x_ca_admin_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_server_cert_subject_name = + x_ra_server_cert_subject_name.value; + ra_server_cert_nickname = + x_ra_server_cert_nickname.value; + ra_subsystem_cert_subject_name = + x_ra_subsystem_cert_subject_name.value; + ra_subsystem_cert_nickname = + x_ra_subsystem_cert_nickname.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("Certificate System - RA Instance Configured"); + System.exit(0); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java b/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java new file mode 100644 index 000000000..706827c74 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java @@ -0,0 +1,1249 @@ +package com.netscape.pkisilent; + +// --- 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.ByteArrayInputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureSubCA { + + // global constants + public static final String DEFAULT_KEY_TYPE = "RSA"; + public static final String DEFAULT_KEY_SIZE = "2048"; + public static final String DEFAULT_KEY_CURVENAME = "nistp256"; + public static final String DEFAULT_KEY_ALGORITHM_RSA = "SHA256withRSA"; + public static final String DEFAULT_KEY_ALGORITHM_ECC = "SHA256withEC"; + + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/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_agent_port = null; + public static String sd_admin_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 secure_conn = null; + public static String remove_data = null; + + public static String key_type = null; + public static String key_size = null; + public static String key_curvename = null; + public static String key_algorithm = null; + public static String signing_algorithm = null; + + public static String signing_key_type = null; + public static String signing_key_size = null; + public static String signing_key_curvename = null; + public static String signing_signingalgorithm = null; + + public static String ocsp_signing_key_type = null; + public static String ocsp_signing_key_size = null; + public static String ocsp_signing_key_curvename = null; + public static String ocsp_signing_signingalgorithm = null; + + public static String subsystem_key_type = null; + public static String subsystem_key_size = null; + public static String subsystem_key_curvename = null; + + public static String audit_signing_key_type = null; + public static String audit_signing_key_size = null; + public static String audit_signing_key_curvename = null; + + public static String sslserver_key_type = null; + public static String sslserver_key_size = null; + public static String sslserver_key_curvename = 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 ca_audit_signing_cert_name = null; + public static String ca_audit_signing_cert_req = null; + public static String ca_audit_signing_cert_pp = null; + public static String ca_audit_signing_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 static String subca_audit_signing_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(";"); + HTTPClient.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 TokenChoicePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + /////////////////////////////////////////////////////// + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token", "UTF-8") + + ""; + 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=2" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8") + + ""; + 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=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name, "UTF-8") + + ""; + 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 DomainPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url, "UTF-8") + + "&sdomainName=" + + URLEncoder.encode(domain_name, "UTF-8") + + "&choice=existingdomain" + + "&p=3" + + "&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=4" + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1); + + return true; + + } + + public boolean SecurityDomainLoginPanel() throws UnsupportedEncodingException { + String subca_url = "https://" + cs_hostname + ":" + cs_port + + "/ca/admin/console/config/wizard" + + "?p=5&subsystem=CA"; + + String query_string = "url=" + URLEncoder.encode(subca_url, "UTF-8"); + + HTTPResponse hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(subca_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_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=5" + + "&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() throws UnsupportedEncodingException { + String query_string = "p=5" + "&op=next" + "&xml=true" + + "&choice=newsubsystem" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&urls=0"; + 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() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=8" + "&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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=9" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host, "UTF-8") + + "&port=" + URLEncoder.encode(ldap_port, "UTF-8") + + "&basedn=" + URLEncoder.encode(base_dn, "UTF-8") + + "&database=" + URLEncoder.encode(db_name, "UTF-8") + + "&binddn=" + URLEncoder.encode(bind_dn, "UTF-8") + + "&__bindpwd=" + URLEncoder.encode(bind_password, "UTF-8") + + "&display=" + URLEncoder.encode("$displayStr", "UTF-8") + + (secure_conn.equals("true") ? "&secureConn=on" : "") + + (remove_data.equals("true") ? "&removeData=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 KeyPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> al = null; + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + subsystem_key_size + + "&subsystem_custom_curvename=" + subsystem_key_curvename + + "&subsystem_keytype=" + subsystem_key_type + + "&subsystem_choice=custom" + + "&sslserver_custom_size=" + sslserver_key_size + + "&sslserver_custom_curvename=" + sslserver_key_curvename + + "&sslserver_keytype=" + sslserver_key_type + + "&sslserver_choice=custom" + + "&signing_custom_size=" + signing_key_size + + "&signing_custom_curvename=" + signing_key_curvename + + "&signing_keytype=" + signing_key_type + + "&signing_choice=custom" + + "&signing_keyalgorithm=" + key_algorithm + + "&signing_signingalgorithm=" + signing_signingalgorithm + + "&ocsp_signing_custom_size=" + ocsp_signing_key_size + + "&ocsp_signing_custom_curvename=" + ocsp_signing_key_curvename + + "&ocsp_signing_keytype=" + ocsp_signing_key_type + + "&ocsp_signing_choice=custom" + + "&ocsp_signing_signingalgorithm=" + ocsp_signing_signingalgorithm + + "&audit_signing_custom_size=" + audit_signing_key_size + + "&audit_signing_custom_curvename=" + audit_signing_key_curvename + + "&audit_signing_keytype=" + audit_signing_key_type + + "&audit_signing_choice=custom" + + "&custom_size=" + key_size + + "&custom_curvename=" + key_curvename + + "&keytype=" + key_type + + "&choice=custom" + + "&signingalgorithm=" + signing_algorithm + + "&keyalgorithm=" + key_algorithm; + + 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 = 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 if (temp.indexOf("Audit Signing Certificate") > 0) { + ca_audit_signing_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); + System.out.println("default: ca_audit_signing_cert_name=" + + ca_audit_signing_cert_name); + return true; + } + + public boolean CertSubjectPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> req_list = null; + ArrayList<String> cert_list = null; + ArrayList<String> dn_list = null; + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&signing=" + + URLEncoder.encode(subca_sign_cert_subject_name, "UTF-8") + + "&ocsp_signing=" + + URLEncoder.encode(subca_ocsp_cert_subject_name, "UTF-8") + + "&sslserver=" + + URLEncoder.encode(subca_server_cert_subject_name, "UTF-8") + + "&subsystem=" + + URLEncoder.encode(subca_subsystem_cert_subject_name, "UTF-8") + + "&audit_signing=" + + URLEncoder.encode(subca_audit_signing_cert_subject_name, "UTF-8") + + "&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 = dn_list.get(i); + + if (temp.indexOf("caSigningCert") >= 0) { + ca_cert_req = req_list.get(i); + ca_cert_cert = cert_list.get(i); + } else if (temp.indexOf("ocspSigningCert") >= 0) { + ocsp_cert_req = req_list.get(i); + ocsp_cert_cert = cert_list.get(i); + } else if (temp.indexOf("subsystemCert") >= 0) { + ca_subsystem_cert_req = req_list.get(i); + ca_subsystem_cert_cert = cert_list.get(i); + } else if (temp.indexOf("auditSigningCert") >= 0) { + ca_audit_signing_cert_req = req_list.get(i); + ca_audit_signing_cert_cert = cert_list.get(i); + } else { + server_cert_req = req_list.get(i); + server_cert_cert = 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("audit_signing_cert_name=" + + subca_audit_signing_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_audit_siging_cert_req=" + + ca_audit_signing_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); + System.out.println("ca_audit_signing_cert_cert=" + + ca_audit_signing_cert_cert); + + return true; + } + + public boolean CertificatePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=12" + "&op=next" + "&xml=true" + + "&signing=" + + URLEncoder.encode(ca_cert_cert, "UTF-8") + + "&signing_cc=" + + "&ocsp_signing=" + + URLEncoder.encode(ocsp_cert_cert, "UTF-8") + + "&ocsp_signing_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert, "UTF-8") + + "&sslserver_cc=" + + "&subsystem=" + + URLEncoder.encode(ca_subsystem_cert_cert, "UTF-8") + + "&subsystem_cc=" + + "&audit_signing=" + + URLEncoder.encode(ca_audit_signing_cert_cert, "UTF-8") + + "&audit_signing_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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=13" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + URLEncoder.encode(backup_pwd, "UTF-8") + + "&__pwdagain=" + URLEncoder.encode(backup_pwd, "UTF-8"); + + 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 ImportCACertPanel() { + try { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + "p=15&op=next&xml=true"); + + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } catch (Exception e) { + System.out.println("Exception in ImportCACertPanel(): " + e.toString()); + e.printStackTrace(); + return false; + } + } + + public boolean AdminCertReqPanel() throws UnsupportedEncodingException { + 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=16" + "&op=next" + "&xml=true" + + "&uid=" + admin_user + + "&name=" + URLEncoder.encode(agent_name, "UTF-8") + + "&email=" + + URLEncoder.encode(admin_email, "UTF-8") + + "&__pwd=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + + "&cert_request=" + + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&display=" + URLEncoder.encode("$displayStr", "UTF-8") + + "&profileId=" + "caAdminCert" + + "&cert_request_type=" + "crmf" + + "&import=true" + + "&uid=" + admin_user + + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8") + + "&subject=" + + URLEncoder.encode(agent_cert_subject, "UTF-8") + + ""; + + 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; + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + HTTPResponse hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string); + + // get response data + // String cert_to_import = + // new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + String cert_to_import = + Utils.base64encode(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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=17" + + "&serialNumber=" + admin_serial_number + + "&caHost=" + URLEncoder.encode(sd_hostname, "UTF-8") + + "&caPort=" + URLEncoder.encode(sd_admin_port, "UTF-8") + + "&importCert=" + "true" + + "&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 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 ConfigureSubCAInstance() throws UnsupportedEncodingException { + // 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(); + // 0. Login panel + boolean log_st = LoginPanel(); + if (!log_st) { + System.out.println("ERROR: ConfigureSubCA: LoginPanel() failure"); + return false; + } + + sleep_time(); + // 1. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if (!disp_token) { + System.out.println("ERROR: ConfigureSubCA: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 2. domain panel + boolean dom_st = DomainPanel(); + if (!dom_st) { + System.out.println("ERROR: ConfigureSubCA: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 3. domain panel + boolean sd_st = SecurityDomainLoginPanel(); + if (!sd_st) { + System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // 4. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if (!disp_st) { + System.out.println("ERROR: ConfigureSubCA: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // 6. hierarchy panel + boolean disp_h = HierarchyPanel(); + if (!disp_h) { + System.out.println("ERROR: ConfigureSubCA: HierarchyPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if (!disp_ldap) { + System.out.println("ERROR: ConfigureSubCA: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + sleep_time(); + // 10. Key Panel + boolean disp_key = KeyPanel(); + if (!disp_key) { + System.out.println("ERROR: ConfigureSubCA: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 11. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if (!disp_csubj) { + System.out.println("ERROR: ConfigureSubCA: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 12. Certificate Panel + boolean disp_cp = CertificatePanel(); + if (!disp_cp) { + System.out.println("ERROR: ConfigureSubCA: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // 13. Backup Panel + boolean disp_back = BackupPanel(); + if (!disp_back) { + System.out.println("ERROR: ConfigureSubCA: BackupPanel() failure"); + return false; + } + + sleep_time(); + // 15. Import CA Certificate Panel + boolean disp_cert = ImportCACertPanel(); + if (!disp_cert) { + System.out.println("ERROR: ConfigureSubCA: ImportCACertPanel() failure"); + return false; + } + + sleep_time(); + // 16. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if (!disp_adm) { + System.out.println("ERROR: ConfigureSubCA: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + boolean disp_im = AdminCertImportPanel(); + if (!disp_im) { + System.out.println("ERROR: ConfigureSubCA: AdminCertImportPanel() failure"); + return false; + } + + sleep_time(); + // 17. Update Domain Panel + boolean disp_ud = UpdateDomainPanel(); + if (!disp_ud) { + System.out.println("ERROR: ConfigureSubCA: UpdateDomainPanel() failure"); + return false; + } + + return true; + } + + private static String set_default(String val, String def) { + if ((val == null) || (val.equals(""))) { + return def; + } else { + return val; + } + } + + public static void main(String args[]) throws UnsupportedEncodingException { + 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_agent_port = new StringHolder(); + StringHolder x_sd_admin_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(); + StringHolder x_secure_conn = new StringHolder(); + StringHolder x_remove_data = new StringHolder(); + + // key properties (defaults) + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_key_curvename = new StringHolder(); + StringHolder x_key_algorithm = new StringHolder(); + StringHolder x_signing_algorithm = new StringHolder(); + + // key properties (custom - signing) + StringHolder x_signing_key_size = new StringHolder(); + StringHolder x_signing_key_type = new StringHolder(); + StringHolder x_signing_key_curvename = new StringHolder(); + StringHolder x_signing_signingalgorithm = new StringHolder(); + + // key properties (custom - ocsp_signing) + StringHolder x_ocsp_signing_key_size = new StringHolder(); + StringHolder x_ocsp_signing_key_type = new StringHolder(); + StringHolder x_ocsp_signing_key_curvename = new StringHolder(); + StringHolder x_ocsp_signing_signingalgorithm = new StringHolder(); + + // key properties (custom - audit_signing) + StringHolder x_audit_signing_key_size = new StringHolder(); + StringHolder x_audit_signing_key_type = new StringHolder(); + StringHolder x_audit_signing_key_curvename = new StringHolder(); + + // key properties (custom - subsystem) + StringHolder x_subsystem_key_size = new StringHolder(); + StringHolder x_subsystem_key_type = new StringHolder(); + StringHolder x_subsystem_key_curvename = new StringHolder(); + + // key properties (custom - sslserver) + StringHolder x_sslserver_key_size = new StringHolder(); + StringHolder x_sslserver_key_type = new StringHolder(); + StringHolder x_sslserver_key_curvename = 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(); + StringHolder x_subca_audit_signing_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 EE port", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port", + x_sd_admin_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("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn); + parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", + x_remove_data); + + // key and algorithm options (default) + parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type); + parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size); + parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename); + parser.addOption( + "-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", + x_key_algorithm); + parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)", + x_signing_algorithm); + + // key and algorithm options for signing certificate (overrides default) + parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type); + parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size); + parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_signing_key_curvename); + parser.addOption( + "-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)", + x_signing_signingalgorithm); + + // key and algorithm options for ocsp_signing certificate (overrides default) + parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_ocsp_signing_key_type); + parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_ocsp_signing_key_size); + parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_ocsp_signing_key_curvename); + parser.addOption( + "-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)", + x_ocsp_signing_signingalgorithm); + + // key and algorithm options for audit_signing certificate (overrides default) + parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_audit_signing_key_type); + parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_audit_signing_key_size); + parser.addOption( + "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_audit_signing_key_curvename); + + // key and algorithm options for subsystem certificate (overrides default) + parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_subsystem_key_type); + parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", + x_subsystem_key_size); + parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_subsystem_key_curvename); + + // key and algorithm options for sslserver certificate (overrides default) + parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_sslserver_key_type); + parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", + x_sslserver_key_size); + parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_sslserver_key_curvename); + + parser.addOption("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption("-token_pwd %s #HSM/Software Token password (optional - required for HSM)", + 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); + parser.addOption( + "-subca_audit_signing_cert_subject_name %s #CA audit signing cert subject name", + x_subca_audit_signing_cert_subject_name); + + // and then match the arguments + String[] unmatched = null; + unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + parser.checkRequiredArgs(); + + // 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_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_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; + secure_conn = set_default(x_secure_conn.value, "false"); + remove_data = set_default(x_remove_data.value, "false"); + + key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE); + signing_key_type = set_default(x_signing_key_type.value, key_type); + ocsp_signing_key_type = set_default(x_ocsp_signing_key_type.value, key_type); + audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type); + subsystem_key_type = set_default(x_subsystem_key_type.value, key_type); + sslserver_key_type = set_default(x_sslserver_key_type.value, key_type); + + key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE); + signing_key_size = set_default(x_signing_key_size.value, key_size); + ocsp_signing_key_size = set_default(x_ocsp_signing_key_size.value, key_size); + audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size); + subsystem_key_size = set_default(x_subsystem_key_size.value, key_size); + sslserver_key_size = set_default(x_sslserver_key_size.value, key_size); + + key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME); + signing_key_curvename = set_default(x_signing_key_curvename.value, key_curvename); + ocsp_signing_key_curvename = set_default(x_ocsp_signing_key_curvename.value, key_curvename); + audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename); + subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename); + sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename); + + if (signing_key_type.equalsIgnoreCase("RSA")) { + key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA); + } else { + key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC); + } + + signing_algorithm = set_default(x_signing_algorithm.value, key_algorithm); + signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm); + ocsp_signing_signingalgorithm = set_default(x_ocsp_signing_signingalgorithm.value, signing_algorithm); + + 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; + subca_audit_signing_cert_subject_name = x_subca_audit_signing_cert_subject_name.value; + + boolean st = ca.ConfigureSubCAInstance(); + + if (!st) { + System.out.println("ERROR: unable to create Subordinate CA"); + System.exit(-1); + } + + System.out.println("Certificate System - Subordinate CA Instance Configured."); + System.exit(0); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java b/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java new file mode 100644 index 000000000..760690888 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java @@ -0,0 +1,1121 @@ +package com.netscape.pkisilent; + +// --- 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.BufferedInputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; + +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.pkcs12.AuthenticatedSafes; +import org.mozilla.jss.pkcs12.PFX; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureTKS { + + public static final String DEFAULT_KEY_TYPE = "RSA"; + public static final String DEFAULT_KEY_SIZE = "2048"; + public static final String DEFAULT_KEY_CURVENAME = "nistp256"; + + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/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 sd_agent_port = null; + public static String sd_admin_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 secure_conn = null; + public static String remove_data = null; + + public static String key_type = null; + public static String key_size = null; + public static String key_curvename = null; + + public static String subsystem_key_type = null; + public static String subsystem_key_size = null; + public static String subsystem_key_curvename = null; + + public static String audit_signing_key_type = null; + public static String audit_signing_key_size = null; + public static String audit_signing_key_curvename = null; + + public static String sslserver_key_type = null; + public static String sslserver_key_size = null; + public static String sslserver_key_curvename = 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 tks_audit_signing_cert_name = null; + public static String tks_audit_signing_cert_req = null; + public static String tks_audit_signing_cert_pp = null; + public static String tks_audit_signing_cert_cert = null; + + public static String backup_pwd = null; + public static String backup_fname = 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 static String tks_audit_signing_cert_subject_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(";"); + HTTPClient.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 TokenChoicePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode("Internal Key Storage Token", "UTF-8") + + ""; + 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=2" + "&op=next" + "&xml=true" + + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8") + + ""; + 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=1" + "&op=next" + "&xml=true" + + "&choice=" + + URLEncoder.encode(token_name, "UTF-8") + + ""; + 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 DomainPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + + String query_string = "sdomainURL=" + + URLEncoder.encode(domain_url, "UTF-8") + + "&choice=existingdomain" + + "&p=3" + + "&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() { + String query_string = "p=4" + "&op=next" + "&xml=true"; + 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() throws UnsupportedEncodingException { + String tks_url = "https://" + cs_hostname + ":" + cs_port + + "/tks/admin/console/config/wizard" + + "?p=5&subsystem=TKS"; + + String query_string = "url=" + URLEncoder.encode(tks_url, "UTF-8"); + + HTTPResponse hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(tks_url, "UTF-8"); + + hr = hc.sslConnect(sd_hostname, sd_admin_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=5" + + "&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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=5" + "&op=next" + "&xml=true" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=7" + "&op=next" + "&xml=true" + + "&host=" + URLEncoder.encode(ldap_host, "UTF-8") + + "&port=" + URLEncoder.encode(ldap_port, "UTF-8") + + "&binddn=" + URLEncoder.encode(bind_dn, "UTF-8") + + "&__bindpwd=" + URLEncoder.encode(bind_password, "UTF-8") + + "&basedn=" + URLEncoder.encode(base_dn, "UTF-8") + + "&database=" + URLEncoder.encode(db_name, "UTF-8") + + "&display=" + URLEncoder.encode("$displayStr", "UTF-8") + + (secure_conn.equals("true") ? "&secureConn=on" : "") + + (remove_data.equals("true") ? "&removeData=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 KeyPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> al = null; + + String query_string = "p=8" + "&op=next" + "&xml=true" + + "&subsystem_custom_size=" + subsystem_key_size + + "&sslserver_custom_size=" + sslserver_key_size + + "&audit_signing_custom_size=" + audit_signing_key_size + + "&custom_size=" + key_size + + "&subsystem_custom_curvename=" + subsystem_key_curvename + + "&sslserver_custom_curvename=" + sslserver_key_curvename + + "&audit_signing_custom_curvename=" + audit_signing_key_curvename + + "&custom_curvename=" + key_curvename + + "&subsystem_keytype=" + subsystem_key_type + + "&sslserver_keytype=" + sslserver_key_type + + "&audit_signing_keytype=" + audit_signing_key_type + + "&keytype=" + key_type + + "&subsystem_choice=custom" + + "&sslserver_choice=custom" + + "&audit_signing_choice=custom" + + "&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 = al.get(i); + if (temp.indexOf("TKS Subsystem") > 0) { + tks_subsystem_cert_name = temp; + } else if (temp.indexOf("Audit Signing Certificate") > 0) { + tks_audit_signing_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); + System.out.println("default: tks_audit_signing_cert_name=" + tks_audit_signing_cert_name); + return true; + } + + public boolean CertSubjectPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + ArrayList<String> req_list = null; + ArrayList<String> cert_list = null; + ArrayList<String> 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, "UTF-8") + + "&sslserver=" + + URLEncoder.encode(tks_server_cert_subject_name, "UTF-8") + + "&audit_signing=" + + URLEncoder.encode(tks_audit_signing_cert_subject_name, "UTF-8") + + "&urls=" + + URLEncoder.encode(domain_url, "UTF-8") + + ""; + + 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 = dn_list.get(i); + + if (temp.indexOf("subsystemCert") >= 0) { + tks_subsystem_cert_req = req_list.get(i); + tks_subsystem_cert_cert = cert_list.get(i); + } else if (temp.indexOf("auditSigningCert") >= 0) { + tks_audit_signing_cert_req = req_list.get(i); + tks_audit_signing_cert_cert = cert_list.get(i); + } else { + server_cert_req = req_list.get(i); + server_cert_cert = cert_list.get(i); + } + } + } + + return true; + } + + public boolean CertificatePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=10" + "&op=next" + "&xml=true" + + "&subsystem=" + + URLEncoder.encode(tks_subsystem_cert_cert, "UTF-8") + + "&subsystem_cc=" + + "&sslserver=" + + URLEncoder.encode(server_cert_cert, "UTF-8") + + "&sslserver_cc=" + + "&audit_signing=" + + URLEncoder.encode(tks_audit_signing_cert_cert, "UTF-8") + + "&audit_signing_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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=11" + "&op=next" + "&xml=true" + + "&choice=backupkey" + + "&__pwd=" + URLEncoder.encode(backup_pwd, "UTF-8") + + "&__pwdagain=" + URLEncoder.encode(backup_pwd, "UTF-8"); + + 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() { + String query_string = ""; + + HTTPResponse hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string); + + // dump hr.getResponseData() to file + + try { + FileOutputStream fos = new FileOutputStream(backup_fname); + fos.write(hr.getResponseData()); + fos.close(); + + // set file to permissions 600 + String rtParams[] = { "chmod", "600", backup_fname }; + Process proc = Runtime.getRuntime().exec(rtParams); + + BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream())); + String line = null; + while ((line = br.readLine()) != null) + System.out.println("Error: " + line); + proc.waitFor(); + + // verify p12 file + + // Decode the P12 file + FileInputStream fis = new FileInputStream(backup_fname); + 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() throws UnsupportedEncodingException { + 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=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + + "&profileId=" + "caAdminCert" + + "&email=" + + URLEncoder.encode(admin_email, "UTF-8") + + "&cert_request=" + + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&subject=" + + URLEncoder.encode(agent_cert_subject, "UTF-8") + + "&clone=new" + + "&import=true" + + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8") + + ""; + + 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; + + String query_string = "serialNumber=" + admin_serial_number + + "&importCert=" + "true" + + ""; + + HTTPResponse hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string); + + // get response data + // String cert_to_import = + // new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + String cert_to_import = + Utils.base64encode(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() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=14" + "&op=next" + "&xml=true" + + "&caHost=" + URLEncoder.encode(sd_hostname, "UTF-8") + + "&caPort=" + URLEncoder.encode(sd_agent_port, "UTF-8") + + ""; + + 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() throws UnsupportedEncodingException { + // 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. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if (!disp_token) { + System.out.println("ERROR: ConfigureTKS: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 3. domain panel + boolean dom_st = DomainPanel(); + if (!dom_st) { + System.out.println("ERROR: ConfigureTKS: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 4. 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(); + // 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; + } + + private static String set_default(String val, String def) { + if ((val == null) || (val.equals(""))) { + return def; + } else { + return val; + } + } + + public static void main(String args[]) throws UnsupportedEncodingException { + 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_agent_port = new StringHolder(); + StringHolder x_sd_admin_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(); + StringHolder x_secure_conn = new StringHolder(); + StringHolder x_remove_data = new StringHolder(); + + // key properties (defaults) + StringHolder x_key_size = new StringHolder(); + StringHolder x_key_type = new StringHolder(); + StringHolder x_key_curvename = new StringHolder(); + + // key properties (custom - audit_signing) + StringHolder x_audit_signing_key_size = new StringHolder(); + StringHolder x_audit_signing_key_type = new StringHolder(); + StringHolder x_audit_signing_key_curvename = new StringHolder(); + + // key properties (custom - subsystem) + StringHolder x_subsystem_key_size = new StringHolder(); + StringHolder x_subsystem_key_type = new StringHolder(); + StringHolder x_subsystem_key_curvename = new StringHolder(); + + // key properties (custom - sslserver) + StringHolder x_sslserver_key_size = new StringHolder(); + StringHolder x_sslserver_key_type = new StringHolder(); + StringHolder x_sslserver_key_curvename = 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(); + StringHolder x_backup_fname = 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(); + StringHolder x_tks_audit_signing_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 Admin port", + x_cs_port); + + parser.addOption("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port", + x_sd_admin_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 EE port", + x_ca_port); + parser.addOption("-ca_ssl_port %s #CA SSL EE 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("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn); + parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", + x_remove_data); + + // key and algorithm options (default) + parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type); + parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size); + parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename); + + // key and algorithm options for audit_signing certificate (overrides default) + parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_audit_signing_key_type); + parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", + x_audit_signing_key_size); + parser.addOption( + "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_audit_signing_key_curvename); + + // key and algorithm options for subsystem certificate (overrides default) + parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_subsystem_key_type); + parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", + x_subsystem_key_size); + parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_subsystem_key_curvename); + + // key and algorithm options for sslserver certificate (overrides default) + parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", + x_sslserver_key_type); + parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", + x_sslserver_key_size); + parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", + x_sslserver_key_curvename); + + parser.addOption("-token_name %s #HSM/Software Token name", + x_token_name); + parser.addOption("-token_pwd %s #HSM/Software Token password (optional, required for HSM)", + 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("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-tks.p12", + x_backup_fname); + + parser.addOption( + "-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + parser.addOption( + "-tks_audit_signing_cert_subject_name %s #TKS audit signing cert subject name", + x_tks_audit_signing_cert_subject_name); + + // and then match the arguments + String[] unmatched = null; + unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + parser.checkRequiredArgs(); + + // 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_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_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; + secure_conn = set_default(x_secure_conn.value, "false"); + remove_data = set_default(x_remove_data.value, "false"); + + key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE); + audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type); + subsystem_key_type = set_default(x_subsystem_key_type.value, key_type); + sslserver_key_type = set_default(x_sslserver_key_type.value, key_type); + + key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE); + audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size); + subsystem_key_size = set_default(x_subsystem_key_size.value, key_size); + sslserver_key_size = set_default(x_sslserver_key_size.value, key_size); + + key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME); + audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename); + subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename); + sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename); + + 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; + backup_fname = set_default(x_backup_fname.value, "/root/tmp-tks.p12"); + + 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; + tks_audit_signing_cert_subject_name = x_tks_audit_signing_cert_subject_name.value; + + boolean st = ca.ConfigureTKSInstance(); + + if (!st) { + System.out.println("ERROR: unable to create TKS"); + System.exit(-1); + } + + System.out.println("Certificate System - TKS Instance Configured."); + System.exit(0); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java b/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java new file mode 100644 index 000000000..366fb57b6 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java @@ -0,0 +1,1088 @@ +package com.netscape.pkisilent; + +// --- 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.ByteArrayInputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.pkisilent.common.ParseXML; +import com.netscape.pkisilent.http.HTTPClient; +import com.netscape.pkisilent.http.HTTPResponse; +import com.netscape.cmsutil.util.Utils; + +public class ConfigureTPS { + // 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 admin_uri = "/ca/admin/ca/getBySerial"; + + public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin"; + public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie"; + public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML"; + 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 cs_clientauth_port = null; + + public static String sd_hostname = null; + public static String sd_ssl_port = null; + public static String sd_agent_port = null; + public static String sd_admin_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_admin_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 tps_audit_signing_cert_name = null; + public static String tps_audit_signing_cert_req = null; + public static String tps_audit_signing_cert_pp = null; + public static String tps_audit_signing_cert_cert = null; + + public static String ss_keygen = null; + + // names + public static String tps_server_cert_subject_name = null; + public static String tps_server_cert_nickname = null; + public static String tps_subsystem_cert_subject_name = null; + public static String tps_subsystem_cert_nickname = null; + public static String tps_audit_signing_cert_subject_name = null; + public static String tps_audit_signing_cert_nickname = null; + public static String subsystem_name = null; + + // Security Domain Login Panel + public static String tps_session_id = null; + + // Admin Certificate Request Panel + public static String requestor_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.sslConnect(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(";"); + HTTPClient.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(); + + st = true; + return st; + } + + public boolean DomainPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String domain_url = "https://" + sd_hostname + ":" + sd_admin_port; + + String query_string = "p=3" + + "&choice=existingdomain" + + "&sdomainURL=" + + URLEncoder.encode(domain_url, "UTF-8") + + "&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() { + String query_string = "p=4" + "&op=next" + "&xml=true"; + hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string); + + return true; + + } + + public boolean SecurityDomainLoginPanel() throws UnsupportedEncodingException { + 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, "UTF-8") + ""; + + HTTPResponse hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri, query_string); + + String query_string_1 = "uid=" + sd_admin_name + + "&pwd=" + URLEncoder.encode(sd_admin_password, "UTF-8") + + "&url=" + URLEncoder.encode(tps_url, "UTF-8") + + ""; + + hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri, + query_string_1); + + // get session id from security domain + sleep_time(); + + 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=5" + + "&subsystem=TPS" + + "&session_id=" + tps_session_id + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, + query_string_2); + + // parse xml - no parsing + + return true; + + } + + public boolean SubsystemPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + sleep_time(); + String query_string = "p=5" + + "&choice=newsubsystem" + + "&subsystemName=" + + URLEncoder.encode(subsystem_name, "UTF-8") + + "&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(); + + sleep_time(); + + // CA choice panel + query_string = "p=6" + + "&urls=0" + + "&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(); + + sleep_time(); + query_string = "p=7" + + "&urls=0" + + "&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(); + + // DRM / server side keygen panel + + sleep_time(); + if (ss_keygen.equalsIgnoreCase("true")) { + ss_keygen = "keygen"; + } + + query_string = "p=8" + + "&choice=" + ss_keygen + + "&urls=0" + + "&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 LdapAuthConnectionPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=9" + + "&host=" + + URLEncoder.encode(ldap_auth_host, "UTF-8") + + "&port=" + + URLEncoder.encode(ldap_auth_port, "UTF-8") + + "&basedn=" + + URLEncoder.encode(ldap_auth_base_dn, "UTF-8") + + "&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 LdapConnectionPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=10" + + "&host=" + + URLEncoder.encode(ldap_host, "UTF-8") + + "&port=" + + URLEncoder.encode(ldap_port, "UTF-8") + + "&binddn=" + + URLEncoder.encode(bind_dn, "UTF-8") + + "&__bindpwd=" + + URLEncoder.encode(bind_password, "UTF-8") + + "&basedn=" + + URLEncoder.encode(base_dn, "UTF-8") + + "&database=" + + URLEncoder.encode(db_name, "UTF-8") + + "&display=" + + "&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 TokenChoicePanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + //////////////////////////////////////////////////////// + String query_string = null; + + // Software Token + if (token_name.equalsIgnoreCase("internal")) { + query_string = "p=1" + + "&choice=" + + URLEncoder.encode("NSS Certificate DB", "UTF-8") + + "&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(); + } + // HSM + else { + // login to hsm first + query_string = "p=2" + + "&uTokName=" + + URLEncoder.encode(token_name, "UTF-8") + + "&__uPasswd=" + + URLEncoder.encode(token_pwd, "UTF-8") + + "&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(); + + // choice with token name now + query_string = "p=1" + + "&choice=" + + URLEncoder.encode(token_name, "UTF-8") + + "&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 KeyPanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=11" + + "&keytype=" + key_type + + "&choice=default" + + "&custom_size=" + key_size + + "&sslserver_keytype=" + key_type + + "&sslserver_choice=custom" + + "&sslserver_custom_size=" + key_size + + "&subsystem_keytype=" + key_type + + "&subsystem_choice=custom" + + "&subsystem_custom_size=" + key_size + + "&audit_signing_keytype=" + key_type + + "&audit_signing_choice=default" + + "&audit_signing_custom_size=" + key_size + + "&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 CertSubjectPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=12" + + "&sslserver=" + + URLEncoder.encode(tps_server_cert_subject_name, "UTF-8") + + "&sslserver_nick=" + + URLEncoder.encode(tps_server_cert_nickname, "UTF-8") + + "&subsystem=" + + URLEncoder.encode(tps_subsystem_cert_subject_name, "UTF-8") + + "&subsystem_nick=" + + URLEncoder.encode(tps_subsystem_cert_nickname, "UTF-8") + + "&audit_signing=" + + URLEncoder.encode(tps_audit_signing_cert_subject_name, "UTF-8") + + "&audit_signing_nick=" + + URLEncoder.encode(tps_audit_signing_cert_nickname, "UTF-8") + + "&urls=0" + + "&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(); + + // parse the certs if needed + + return true; + } + + public boolean CertificatePanel() { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + + String query_string = "p=13" + + "&sslserver=" + + "&sslserver_cc=" + + "&subsystem=" + + "&subsystem_cc=" + + "&audit_signing=" + + "&audit_signing_cc=" + + "&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 AdminCertReqPanel() throws UnsupportedEncodingException { + HTTPResponse hr = null; + ByteArrayInputStream bais = null; + ParseXML px = new ParseXML(); + String admin_cert_request = null; + + requestor_name = "TPS-" + cs_hostname + "-" + cs_clientauth_port; + + 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" + + "&uid=" + admin_user + + "&name=" + + URLEncoder.encode("TPS Administrator", "UTF-8") + + "&email=" + + URLEncoder.encode(admin_email, "UTF-8") + + "&__pwd=" + URLEncoder.encode(admin_password, "UTF-8") + + "&__admin_password_again=" + URLEncoder.encode(admin_password, "UTF-8") + + "&cert_request=" + + URLEncoder.encode(admin_cert_request, "UTF-8") + + "&display=0" + + "&profileId=" + "caAdminCert" + + "&cert_request_type=" + "crmf" + + "&import=true" + + "&uid=" + admin_user + + "&clone=0" + + "&securitydomain=" + + URLEncoder.encode(domain_name, "UTF-8") + + "&subject=" + + URLEncoder.encode(agent_cert_subject, "UTF-8") + + "&requestor_name=" + + URLEncoder.encode(requestor_name, "UTF-8") + + "&sessionID=" + tps_session_id + + "&auth_hostname=" + ca_hostname + + "&auth_port=" + ca_ssl_port + + "&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(); + + admin_serial_number = px.getvalue("serialNumber"); + + return true; + } + + public boolean AdminCertImportPanel() throws UnsupportedEncodingException { + 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" + + ""; + + // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port; + // whereas RA and TPS use the CA Admin Port associated with + // the 'CA choice panel' as invoked from the SubsystemPanel() + // which MAY or MAY NOT be the same CA as the CA specified + // by the Security Domain. + hr = hc.sslConnect(ca_hostname, ca_admin_port, admin_uri, query_string); + + try { + // cert_to_import = + // new sun.misc.BASE64Encoder().encode(hr.getResponseData()); + cert_to_import = + Utils.base64encode(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"); + + String query_string_1 = "p=15" + + "&serialNumber=" + admin_serial_number + + "&caHost=" + + URLEncoder.encode(ca_hostname, "UTF-8") + + "&caPort=" + ca_admin_port + + "&op=next" + + "&xml=true"; + + hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1); + + // parse xml + bais = new ByteArrayInputStream(hr.getHTML().getBytes()); + px.parse(bais); + px.prettyprintxml(); + + return true; + } + + public boolean ConfigureTPSInstance() throws UnsupportedEncodingException { + // 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. Token Choice Panel + boolean disp_token = TokenChoicePanel(); + if (!disp_token) { + System.out.println("ERROR: ConfigureTPS: TokenChoicePanel() failure"); + return false; + } + + sleep_time(); + // 3. domain panel + boolean dom_st = DomainPanel(); + if (!dom_st) { + System.out.println("ERROR: ConfigureTPS: DomainPanel() failure"); + return false; + } + + sleep_time(); + // 4. display cert chain panel + boolean disp_st = DisplayChainPanel(); + if (!disp_st) { + System.out.println("ERROR: ConfigureTPS: DisplayChainPanel() failure"); + return false; + } + + sleep_time(); + // 5. security domain login panel + boolean disp_sd = SecurityDomainLoginPanel(); + if (!disp_sd) { + System.out.println("ERROR: ConfigureTPS: SecurityDomainLoginPanel() failure"); + return false; + } + + sleep_time(); + // 6. subsystem panel + boolean disp_ss = SubsystemPanel(); + if (!disp_ss) { + System.out.println("ERROR: ConfigureTPS: SubsystemPanel() failure"); + return false; + } + + sleep_time(); + // 7. ldap auth connection panel + boolean disp_ldap_auth = LdapAuthConnectionPanel(); + if (!disp_ldap_auth) { + System.out.println("ERROR: ConfigureTPS: LdapAuthConnectionPanel() failure"); + return false; + } + + sleep_time(); + // 8. ldap connection panel + boolean disp_ldap = LdapConnectionPanel(); + if (!disp_ldap) { + System.out.println("ERROR: ConfigureTPS: LdapConnectionPanel() failure"); + return false; + } + + sleep_time(); + // 11. Key Panel + boolean disp_key = KeyPanel(); + if (!disp_key) { + System.out.println("ERROR: ConfigureTPS: KeyPanel() failure"); + return false; + } + + sleep_time(); + // 12. Cert Subject Panel + boolean disp_csubj = CertSubjectPanel(); + if (!disp_csubj) { + System.out.println("ERROR: ConfigureTPS: CertSubjectPanel() failure"); + return false; + } + + sleep_time(); + // 13. Certificate Panel + boolean disp_cp = CertificatePanel(); + if (!disp_cp) { + System.out.println("ERROR: ConfigureTPS: CertificatePanel() failure"); + return false; + } + + sleep_time(); + // 14. Admin Cert Req Panel + boolean disp_adm = AdminCertReqPanel(); + if (!disp_adm) { + System.out.println("ERROR: ConfigureTPS: AdminCertReqPanel() failure"); + return false; + } + + sleep_time(); + // 15. Admin Cert import Panel + boolean disp_im = AdminCertImportPanel(); + if (!disp_im) { + System.out.println("ERROR: ConfigureTPS: AdminCertImportPanel() failure"); + return false; + } + + return true; + } + + public static void main(String args[]) throws UnsupportedEncodingException { + ConfigureTPS ca = new ConfigureTPS(); + + // set variables + StringHolder x_cs_hostname = new StringHolder(); + StringHolder x_cs_port = new StringHolder(); + StringHolder x_cs_clientauth_port = new StringHolder(); + + StringHolder x_sd_hostname = new StringHolder(); + StringHolder x_sd_ssl_port = new StringHolder(); + StringHolder x_sd_agent_port = new StringHolder(); + StringHolder x_sd_admin_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_ca_admin_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_server_cert_subject_name = new StringHolder(); + StringHolder x_tps_server_cert_nickname = new StringHolder(); + StringHolder x_tps_subsystem_cert_subject_name = new StringHolder(); + StringHolder x_tps_subsystem_cert_nickname = new StringHolder(); + StringHolder x_tps_audit_signing_cert_subject_name = new StringHolder(); + StringHolder x_tps_audit_signing_cert_nickname = 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("-cs_clientauth_port %s #CS SSL port", + x_cs_clientauth_port); + + parser.addOption("-sd_hostname %s #Security Domain Hostname", + x_sd_hostname); + parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port", + x_sd_ssl_port); + parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port", + x_sd_agent_port); + parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port", + x_sd_admin_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("-ca_admin_port %s #CA SSL Admin port", + x_ca_admin_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 (optional, required for HSM)", + 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_server_cert_subject_name %s #TPS server cert subject name", + x_tps_server_cert_subject_name); + parser.addOption( + "-tps_server_cert_nickname %s #TPS server cert nickname", + x_tps_server_cert_nickname); + parser.addOption( + "-tps_subsystem_cert_subject_name %s #TPS subsystem cert subject name", + x_tps_subsystem_cert_subject_name); + parser.addOption( + "-tps_subsystem_cert_nickname %s #TPS subsystem cert nickname", + x_tps_subsystem_cert_nickname); + parser.addOption( + "-tps_audit_signing_cert_subject_name %s #TPS audit signing cert subject name", + x_tps_audit_signing_cert_subject_name); + parser.addOption( + "-tps_audit_signing_cert_nickname %s #TPS audit signing cert nickname", + x_tps_audit_signing_cert_nickname); + + parser.addOption( + "-subsystem_name %s #CA subsystem name", + x_subsystem_name); + + // and then match the arguments + String[] unmatched = null; + unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED); + + if (unmatched != null) { + System.out.println("ERROR: Argument Mismatch"); + System.exit(-1); + } + + parser.checkRequiredArgs(); + + // set variables + cs_hostname = x_cs_hostname.value; + cs_port = x_cs_port.value; + cs_clientauth_port = x_cs_clientauth_port.value; + + sd_hostname = x_sd_hostname.value; + sd_ssl_port = x_sd_ssl_port.value; + sd_agent_port = x_sd_agent_port.value; + sd_admin_port = x_sd_admin_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; + ca_admin_port = x_ca_admin_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_server_cert_subject_name = + x_tps_server_cert_subject_name.value; + tps_server_cert_nickname = + x_tps_server_cert_nickname.value; + tps_subsystem_cert_subject_name = + x_tps_subsystem_cert_subject_name.value; + tps_subsystem_cert_nickname = + x_tps_subsystem_cert_nickname.value; + tps_audit_signing_cert_subject_name = + x_tps_audit_signing_cert_subject_name.value; + tps_audit_signing_cert_nickname = + x_tps_audit_signing_cert_nickname.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("Certificate System - TPS Instance Configured"); + System.exit(0); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/PKISilent.java b/base/silent/src/com/netscape/pkisilent/PKISilent.java new file mode 100644 index 000000000..f90832481 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/PKISilent.java @@ -0,0 +1,59 @@ +package com.netscape.pkisilent; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; + +public class PKISilent { + private static void usage() { + System.out.print("usage: java " + PKISilent.class.getCanonicalName()); + boolean first = true; + for (Class<?> c : classes) { + if (first) { + System.out.println(" [ "); + } else { + System.out.println(" | "); + } + first = false; + System.out.print(" " + c.getSimpleName()); + } + System.out.println(" ] "); + } + + static Class<?>[] classes = { ConfigureCA.class, ConfigureDRM.class, + ConfigureOCSP.class, ConfigureRA.class, ConfigureSubCA.class, + ConfigureTKS.class, ConfigureTPS.class, }; + + public static final void main(String[] args) { + HashMap<String, Method> classMap = new HashMap<String, Method>(); + for (Class<?> c : classes) { + try { + classMap.put(c.getSimpleName(), + c.getMethod("main", String[].class)); + } catch (Exception e) { + // The set of classes listed above is guaranteed to have a + // method 'main' + e.printStackTrace(); + } + } + if (args.length == 0) { + usage(); + System.exit(-1); + } + Method mainMethod = classMap.get(args[0]); + if (mainMethod == null) { + usage(); + System.exit(-1); + } + String[] innerArgs = {}; + if (args.length > 1) { + innerArgs = Arrays.copyOfRange(args, 1, args.length); + } + + try { + mainMethod.invoke(null, (Object) innerArgs); + } catch (Exception e) { + // exception is guaranteed to have the static main method + } + } +} diff --git a/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java b/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java new file mode 100644 index 000000000..de3c58bd4 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = -604960834535589460L; + + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java b/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java new file mode 100755 index 000000000..ed5f98b1d --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java @@ -0,0 +1,2085 @@ +package com.netscape.pkisilent.argparser; + +// --- 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.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.PrintStream; +import java.io.Reader; +import java.lang.reflect.Array; +import java.util.Vector; + +/** + * 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<Record> 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; + boolean required = true; + + 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) { + 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<Record>(128); + this.synopsisString = synopsisString; + if (defaultHelp) { + addOption("-help,-? %h #displays help information", null); + defaultHelpOption = firstHelpOption = 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); + 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.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 = ""; + } + + // parse helpMsg for required/optional information if present + // default to required + if (rec.helpMsg.indexOf("(optional") != -1) { + rec.required = false; + } + + // 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; + } + + public void checkRequiredArgs() { + for (int i = 1; i < matchList.size(); i++) { + Record rec = (Record) matchList.get(i); + StringHolder myString = (StringHolder) rec.resHolder; + if (((myString.value == null) || (myString.value.equals(""))) && (rec.required)) { + printErrorAndExit("Required parameter " + rec.nameList.name + " is not specified."); + } + } + } + + 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<String> 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<String> vec = new Vector<String>(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<String> unmatched = new Vector<String>(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 + */ + @SuppressWarnings("unchecked") + 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<Object>) 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/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java b/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java new file mode 100644 index 000000000..9ddb80778 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java @@ -0,0 +1,1514 @@ +package com.netscape.pkisilent.argparser; + +// --- 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.ByteArrayOutputStream; +import java.io.PrintStream; +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<String> vec = new Vector<String>(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<String> vec = new Vector<String>(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/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java new file mode 100644 index 000000000..ba10022b5 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = -2863748864787121510L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java new file mode 100644 index 000000000..453cac8b2 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = 7340010668929015745L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java new file mode 100644 index 000000000..13012a641 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = 5461991811517552431L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java new file mode 100644 index 000000000..b8474b535 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = -7962968109874934361L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java new file mode 100644 index 000000000..a94ceea1e --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = -5303361328570056819L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java new file mode 100644 index 000000000..5656d8b86 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = 1559599139421340971L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java new file mode 100644 index 000000000..70e050fde --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = 1825881254530066307L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java b/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java new file mode 100644 index 000000000..6970d318d --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java @@ -0,0 +1,53 @@ +package com.netscape.pkisilent.argparser; + +// --- 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/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java b/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java new file mode 100644 index 000000000..937360346 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java @@ -0,0 +1,54 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = -3184348746223759310L; + /** + * 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/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java b/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java new file mode 100644 index 000000000..bf3ea6dc3 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java @@ -0,0 +1,56 @@ +package com.netscape.pkisilent.argparser; + +// --- 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 { + /** + * + */ + private static final long serialVersionUID = 4923445904507805754L; + 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/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java b/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java new file mode 100644 index 000000000..271dd0c62 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java @@ -0,0 +1,567 @@ +package com.netscape.pkisilent.argparser; + +// --- 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; + double value = 0; + + skipWhiteSpace(); + if (idx == len) { + exception = new StringScanException("end of input"); + } else { + if ((c = buf[idx]) == '-' || c == '+') { + // signed + 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 + 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++; + } + } + + 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/base/silent/src/com/netscape/pkisilent/common/BaseState.java b/base/silent/src/com/netscape/pkisilent/common/BaseState.java new file mode 100644 index 000000000..0d5e9cfc6 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/BaseState.java @@ -0,0 +1,118 @@ +package com.netscape.pkisilent.common; + +// --- 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 --- + +/** + * 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/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java b/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java new file mode 100644 index 000000000..3e4f0bfa2 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java @@ -0,0 +1,569 @@ +package com.netscape.pkisilent.common; + +// --- 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.FileInputStream; +import java.io.FileOutputStream; + +/** + * 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 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"); + } + + // 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/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java b/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java new file mode 100644 index 000000000..91a273df6 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java @@ -0,0 +1,609 @@ +package com.netscape.pkisilent.common; + +// --- 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.ByteArrayInputStream; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +import netscape.ldap.LDAPAttribute; +import netscape.ldap.LDAPAttributeSet; +import netscape.ldap.LDAPConnection; +import netscape.ldap.LDAPEntry; +import netscape.ldap.LDAPException; +import netscape.ldap.LDAPModification; +import netscape.ldap.LDAPModificationSet; +import netscape.ldap.LDAPSearchResults; +import netscape.ldap.LDAPv2; + +/** + * 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()); + } + + } + + } + + /** + * 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 certificate 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 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 { + 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 { + conn.search( + "cn=RSA,cn=encryption,cn=config", searchScope, null, + getAttrs, false); // check for errors + + 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/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java b/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java new file mode 100644 index 000000000..a4ba55d29 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java @@ -0,0 +1,679 @@ +package com.netscape.pkisilent.common; + +// --- 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.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.util.Date; +import java.util.Enumeration; +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<String, String> { + + /** + * 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<String> e = keys(); e.hasMoreElements();) { + String key = e.nextElement(); + String val = 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) { + String oval = super.get(key); + String sval = (oval instanceof 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<String> propertyNames() { + Hashtable<String, String> h = new Hashtable<String, String>(); + + 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<String, String> h = new Hashtable<String, String>(); + + enumerate(h); + for (Enumeration<String> e = h.keys(); e.hasMoreElements();) { + String key = e.nextElement(); + String val = 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<String, String> h = new Hashtable<String, String>(); + + enumerate(h); + for (Enumeration<String> e = h.keys(); e.hasMoreElements();) { + String key = e.nextElement(); + String val = 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<String, String> h) { + if (defaults != null) { + defaults.enumerate(h); + } + for (Enumeration<String> e = keys(); e.hasMoreElements();) { + String key = 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/base/silent/src/com/netscape/pkisilent/common/CMSTask.java b/base/silent/src/com/netscape/pkisilent/common/CMSTask.java new file mode 100644 index 000000000..4b6c75ba3 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/CMSTask.java @@ -0,0 +1,190 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; + +/** + * 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, ArgParser.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/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java b/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java new file mode 100644 index 000000000..9599eb6dd --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java @@ -0,0 +1,44 @@ +package com.netscape.pkisilent.common; + +// --- 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 --- + +public class CertificateRecord { + + 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 CertificateRecord() {// Do nothing + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java b/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java new file mode 100644 index 000000000..d629030f2 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java @@ -0,0 +1,767 @@ +package com.netscape.pkisilent.common; + +// --- 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.ByteArrayInputStream; +import java.security.KeyPair; + +import netscape.security.x509.X500Name; + +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.asn1.ASN1Util; +import org.mozilla.jss.asn1.BIT_STRING; +import org.mozilla.jss.asn1.INTEGER; +import org.mozilla.jss.asn1.OBJECT_IDENTIFIER; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.crypto.AlreadyInitializedException; +import org.mozilla.jss.crypto.CryptoStore; +import org.mozilla.jss.crypto.CryptoToken; +import org.mozilla.jss.crypto.IVParameterSpec; +import org.mozilla.jss.crypto.InternalCertificate; +import org.mozilla.jss.crypto.KeyGenAlgorithm; +import org.mozilla.jss.crypto.KeyGenerator; +import org.mozilla.jss.crypto.KeyPairAlgorithm; +import org.mozilla.jss.crypto.KeyPairGenerator; +import org.mozilla.jss.crypto.KeyWrapAlgorithm; +import org.mozilla.jss.crypto.KeyWrapper; +import org.mozilla.jss.crypto.PrivateKey; +import org.mozilla.jss.crypto.SymmetricKey; +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.pkcs11.PK11Token; +import org.mozilla.jss.pkix.crmf.CertReqMsg; +import org.mozilla.jss.pkix.crmf.CertRequest; +import org.mozilla.jss.pkix.crmf.CertTemplate; +import org.mozilla.jss.pkix.crmf.EncryptedKey; +import org.mozilla.jss.pkix.crmf.EncryptedValue; +import org.mozilla.jss.pkix.crmf.PKIArchiveOptions; +import org.mozilla.jss.pkix.crmf.POPOPrivKey; +import org.mozilla.jss.pkix.crmf.ProofOfPossession; +import org.mozilla.jss.pkix.primitive.AVA; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; +import org.mozilla.jss.pkix.primitive.Name; +import org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo; +import org.mozilla.jss.util.Password; +import com.netscape.cmsutil.util.Utils; + +/** + * 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; + + 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"); + } + + 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"); + } + + 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. + */ + + public 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 String generateCRMFrequest() { + 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)); + + if (certnickname != null) { + X500Name name = new X500Name(certnickname); + ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded()); + Name n = (Name) Name.getTemplate().decode(cs); + 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); + String Req1 = Utils.base64encode(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() { + + 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); + byte transport[] = Utils.base64decode(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)); + + if (certnickname != null) { + X500Name name = new X500Name(certnickname); + ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded()); + Name n = (Name) Name.getTemplate().decode(cs); + 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); + CRMF_REQUEST = Utils.base64encode(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/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java b/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java new file mode 100644 index 000000000..61305305e --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java @@ -0,0 +1,318 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.Vector; + +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.crypto.AlreadyInitializedException; +import org.mozilla.jss.crypto.CryptoToken; +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.pkcs11.PK11Token; +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; +import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback; +import org.mozilla.jss.ssl.SSLSocket; +import org.mozilla.jss.util.Password; + +/** + * 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(@SuppressWarnings("rawtypes") Vector nicknames) { + + System.out.println("nicknames size = " + nicknames.size()); + int i = nicknames.size(); + + 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() { + 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; + + 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() { + + 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/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java b/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java new file mode 100644 index 000000000..019b75825 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java @@ -0,0 +1,470 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.mozilla.jss.ssl.SSLSocket; + +/** + * 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() throws UnsupportedEncodingException { + 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() throws UnsupportedEncodingException { + + 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, "UTF-8")); + queryStrBuf.append("&pwd="); + queryStrBuf.append(URLEncoder.encode(PWD, "UTF-8")); + 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, "UTF-8")); + queryStrBuf.append("&userPassword="); + queryStrBuf.append(URLEncoder.encode(PWD, "UTF-8")); + GN = "test"; + SN = "test"; + CN = "test"; + MAIL = "test@netscape.com"; + OU = "aol"; + O = "aol"; + L = "MV"; + queryStrBuf.append("&givenname="); + queryStrBuf.append(URLEncoder.encode(GN, "UTF-8")); + + queryStrBuf.append("&sn="); + queryStrBuf.append(URLEncoder.encode(SN, "UTF-8")); + queryStrBuf.append("&cn="); + queryStrBuf.append(URLEncoder.encode(CN, "UTF-8")); + + queryStrBuf.append("&mail="); + queryStrBuf.append(URLEncoder.encode(MAIL, "UTF-8")); + queryStrBuf.append("&ou="); + queryStrBuf.append(URLEncoder.encode(OU, "UTF-8")); + queryStrBuf.append("&o="); + queryStrBuf.append(URLEncoder.encode(O, "UTF-8")); + queryStrBuf.append("&l="); + queryStrBuf.append(URLEncoder.encode(L, "UTF-8")); + + queryStrBuf.append("&email=true"); + + } + + if (Authenticator.equals("NIS")) { + queryStrBuf.append("&authenticator=NISAuth"); + queryStrBuf.append("&requestFormat=keygen"); + queryStrBuf.append("&uid="); + queryStrBuf.append(URLEncoder.encode(UID, "UTF-8")); + queryStrBuf.append("&pwd="); + queryStrBuf.append(URLEncoder.encode(PWD, "UTF-8")); + queryStrBuf.append("&email=true"); + + } + + queryStrBuf.append("&pkcs10Request="); + queryStrBuf.append(URLEncoder.encode(pkcs10request, "UTF-8")); + 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/base/silent/src/com/netscape/pkisilent/common/ParseXML.java b/base/silent/src/com/netscape/pkisilent/common/ParseXML.java new file mode 100644 index 000000000..de1b38172 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/ParseXML.java @@ -0,0 +1,170 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +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<String> constructValueList(String first, String second) { + ArrayList<String> al = new ArrayList<String>(); + + 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/base/silent/src/com/netscape/pkisilent/common/PostQuery.java b/base/silent/src/com/netscape/pkisilent/common/PostQuery.java new file mode 100644 index 000000000..31fb07b3e --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/PostQuery.java @@ -0,0 +1,141 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import com.netscape.cmsutil.util.Utils; + +/** + * 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 { + + 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()); + String encoding = Utils.base64encode( + 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); + + 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/base/silent/src/com/netscape/pkisilent/common/Request.java b/base/silent/src/com/netscape/pkisilent/common/Request.java new file mode 100644 index 000000000..3dffc929c --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/Request.java @@ -0,0 +1,1138 @@ +package com.netscape.pkisilent.common; + +// --- 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.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Vector; + +/** + * 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<String> seqNum = new Vector<String>(); + 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. + * @throws UnsupportedEncodingException + */ + + public Vector<String> ListPendingRequests(String fromRequestNumber, String toRequestNumber) throws UnsupportedEncodingException { + 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. + * @throws UnsupportedEncodingException + */ + + public Vector<String> ListAllRequests(String fromRequestNumber, String toRequestNumber) throws UnsupportedEncodingException { + reqState = "showAll"; + reqType = "enrollment"; + approveseqnumFrom = fromRequestNumber; + approveseqnumTo = toRequestNumber; + listRequest(approveseqnumFrom, approveseqnumTo); + return seqNum; + } + + /** + * Approve pending enrollment request. Takes parameters RequestNumber + * + * @param request number + * @throws UnsupportedEncodingException + */ + + public int ApproveRequests(String requestNumber) throws UnsupportedEncodingException { + 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 + * @throws UnsupportedEncodingException + */ + + public int ApproveProfileRequests(String RequestNumber) throws UnsupportedEncodingException { + + 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) throws UnsupportedEncodingException { + + 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 + * @throws UnsupportedEncodingException + */ + + public int RejectProfileRequests(String RequestNumber) throws UnsupportedEncodingException { + + 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 + * @throws UnsupportedEncodingException + */ + + public int CancelProfileRequests(String RequestNumber) throws UnsupportedEncodingException { + + 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"; + + 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(); + + 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() throws UnsupportedEncodingException { + + 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, "UTF-8"); + } else if (subject != null) { + query += "&subject=" + URLEncoder.encode(subject, "UTF-8"); + } + + 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", "UTF-8"); + 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", "UTF-8"); + 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, "UTF-8") + "¬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) throws UnsupportedEncodingException { + + Integer x = new Integer(from); + + seqNumFrom = x.intValue(); + + Integer y = new Integer(To); + + 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() throws UnsupportedEncodingException { + + 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. + * @throws UnsupportedEncodingException + */ + + public int processRequest() throws UnsupportedEncodingException { + 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]); + + try { + st = t.processRequest(); + } catch (UnsupportedEncodingException e) { + System.out.println(e); + e.printStackTrace(); + } + if (st == -1) { + System.exit(0); + } else { + System.exit(st); + } + + }// end of function main + +} // end of class + diff --git a/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java b/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java new file mode 100644 index 000000000..f63456b4d --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java @@ -0,0 +1,355 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedReader; +import java.io.FileInputStream; +import java.io.FileReader; +import java.net.InetAddress; +import java.util.StringTokenizer; + +/** + * 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) { + // <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=")) { + // token contains the ip value + } 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 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/base/silent/src/com/netscape/pkisilent/common/TestClient.java b/base/silent/src/com/netscape/pkisilent/common/TestClient.java new file mode 100644 index 000000000..0e4ed9cdd --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/TestClient.java @@ -0,0 +1,941 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.net.ServerSocket; +import java.util.Properties; + +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; + +/** + * 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 + protected 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; + } + + /** + * 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(); + + // 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/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java b/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java new file mode 100644 index 000000000..c55088bc6 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java @@ -0,0 +1,536 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.mozilla.jss.ssl.SSLSocket; + +/** + * 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; + } + + public boolean enroll_load() throws UnsupportedEncodingException { + 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() throws UnsupportedEncodingException { + + 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, "UTF-8")); + if (requestorEmail.length() > 0) { + queryStrBuf.append("&csrRequestorEmail="); + queryStrBuf.append(URLEncoder.encode(requestorEmail, "UTF-8")); + queryStrBuf.append("&email=true"); + + } else { + queryStrBuf.append("&email=false"); + } + + if (requestorPhone.length() > 0) { + queryStrBuf.append("&csrRequestorPhone="); + queryStrBuf.append(URLEncoder.encode(requestorPhone, "UTF-8")); + } + if (requestorComments.length() > 0) { + queryStrBuf.append("&csrRequestorComments="); + queryStrBuf.append(URLEncoder.encode(requestorComments, "UTF-8")); + } + 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, "UTF-8")); + } + + 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, "UTF-8")); + 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 + + 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/base/silent/src/com/netscape/pkisilent/common/Utilities.java b/base/silent/src/com/netscape/pkisilent/common/Utilities.java new file mode 100644 index 000000000..3e5d6fb4c --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/Utilities.java @@ -0,0 +1,347 @@ +package com.netscape.pkisilent.common; + +// --- 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.DataInputStream; +import java.io.FileInputStream; + +import netscape.security.x509.CertificateSerialNumber; +import netscape.security.x509.CertificateSubjectName; +import netscape.security.x509.RDN; +import netscape.security.x509.SerialNumber; +import netscape.security.x509.X500Name; +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509CertInfo; + +import com.netscape.cmsutil.util.Utils; + +public class Utilities { + + 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 CertificateRecord decode_cert(String cert) { + + String head = "-----BEGIN CERTIFICATE-----"; + String tail = "-----END CERTIFICATE-----"; + + CertificateRecord cr = new CertificateRecord(); + + 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); + byte decodedBASE64Cert[] = Utils.base64decode(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); + + 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/base/silent/src/com/netscape/pkisilent/common/checkRequest.java b/base/silent/src/com/netscape/pkisilent/common/checkRequest.java new file mode 100644 index 000000000..c4599ffde --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/common/checkRequest.java @@ -0,0 +1,617 @@ +package com.netscape.pkisilent.common; + +// --- 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.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.mozilla.jss.ssl.SSLSocket; + +/** + * 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; + } + + /** + * 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 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")) { + 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/base/silent/src/com/netscape/pkisilent/http/CertSelection.java b/base/silent/src/com/netscape/pkisilent/http/CertSelection.java new file mode 100644 index 000000000..ff541b6c6 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/http/CertSelection.java @@ -0,0 +1,45 @@ +package com.netscape.pkisilent.http; + +// --- 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.Vector; + +import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback; + +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(@SuppressWarnings("rawtypes") 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/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java b/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java new file mode 100644 index 000000000..e8de29081 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java @@ -0,0 +1,595 @@ +package com.netscape.pkisilent.http; + +// --- 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.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.LinkedHashSet; +import java.util.StringTokenizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +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<String> associatedFiles; + + // A list of URLs of frames that are contained in the document. + LinkedHashSet<String> documentFrames; + + // A list of URLs of links that are contained in the document. + LinkedHashSet<String> documentLinks; + + // A list of URLs of images that are contained in the document. + LinkedHashSet<String> 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<String>(); + documentFrames = new LinkedHashSet<String>(); + documentLinks = new LinkedHashSet<String>(); + documentImages = new LinkedHashSet<String>(); + 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/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java b/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java new file mode 100644 index 000000000..f3980c0ed --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java @@ -0,0 +1,1231 @@ +package com.netscape.pkisilent.http; + +// --- 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.BufferedOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.net.Socket; +import java.net.URLDecoder; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.StringTokenizer; + +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; +import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback; +import org.mozilla.jss.ssl.SSLSocket; +import org.mozilla.jss.ssl.TestCertApprovalCallback; +import org.mozilla.jss.ssl.TestClientCertificateSelectionCallback; + +import com.netscape.pkisilent.argparser.ArgParser; +import com.netscape.pkisilent.argparser.StringHolder; +import com.netscape.pkisilent.common.ComCrypto; +import com.netscape.cmsutil.util.Utils; + +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[] = { + SSLSocket.TLS_ECDH_ECDSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_RC4_128_SHA, + SSLSocket.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, + SSLSocket.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_NULL_SHA, + SSLSocket.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, + SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + SSLSocket.TLS_ECDH_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_RSA_WITH_RC4_128_SHA, + SSLSocket.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, + SSLSocket.TLS_ECDHE_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_RC4_128_SHA, + SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + 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 ECC Cipher List"); + System.out.println("ERROR: Exception = " + e.getMessage()); + } + + } + return true; + } + + public boolean disableSSL2(SSLSocket socket) { + try { + SSLSocket.enableSSL3Default(true); + socket.enableSSL3(true); + socket.enableSSL2(false); + SSLSocket.enableSSL2Default(false); + socket.enableV2CompatibleHello(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<ByteBuffer> bufferList = new ArrayList<ByteBuffer>(); + + // 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[]) throws UnsupportedEncodingException { + HTTPClient hc = new HTTPClient(); + HTTPResponse hr = 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, ArgParser.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()); + String temp = Utils.base64encode((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 + + 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(), "UTF-8"); + else + responseValue = hr.getHTML(); + + System.out.println("###############################"); + System.out.println("RESULT=" + responseValue); + System.out.println("###############################"); + + } + +}; diff --git a/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java b/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java new file mode 100644 index 000000000..9ade1c133 --- /dev/null +++ b/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java @@ -0,0 +1,314 @@ +package com.netscape.pkisilent.http; + +// --- 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.ArrayList; +import java.util.StringTokenizer; + +import com.netscape.pkisilent.common.Utilities; + +public class HTTPResponse { + // The set of cookie values included in this response. + ArrayList<String> cookieValueList; + + // The names of the headers included in this response. + ArrayList<String> headerNameList; + + // The values of the headers included in this response. + ArrayList<String> 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<String> contentName; + ArrayList<String> 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<String>(); + headerNameList = new ArrayList<String>(); + headerValueList = new ArrayList<String>(); + contentName = new ArrayList<String>(); + contentValue = new ArrayList<String>(); + } + + /** + * 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 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<String> valueList = new ArrayList<String>(); + 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] = headerNameList.get(i); + headerElements[i][1] = 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 contentValue.get(i); + } + } + + return null; + } + + public ArrayList<String> getContentNames() { + return contentName; + } + + public ArrayList<String> 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 = cookieValueList.get(i); + if (temp.startsWith(headerName)) { + return cookieValueList.get(i); + } + } + + return null; + } + +} diff --git a/base/silent/templates/pki_silent.template b/base/silent/templates/pki_silent.template new file mode 100755 index 000000000..93ff5849a --- /dev/null +++ b/base/silent/templates/pki_silent.template @@ -0,0 +1,1732 @@ +#!/bin/bash +## BEGIN COPYRIGHT BLOCK +## (C) 2009 Red Hat, Inc. +## All rights reserved. +## END COPYRIGHT BLOCK + + +## Always switch into this base directory +## prior to script execution so that all +## of its output is written to this directory + +cd `dirname $0` + + +## Disallow script to be run as the name of this template +pki_silent_script=`basename $0` +if [ "${pki_silent_script}" = "pki_silent.template" ] ; then + printf "\n" + printf "Usage: (1) Install AND configure a directory server instance.\n\n" + printf " (2) Install, but do NOT configure ALL six\n" + printf " 'default' PKI subsystem instances.\n\n" + printf " (3) Install the 'pki-silent' package.\n\n" + printf " (4) Copy '$0' to a new script name\n" + printf " without the '.template' extension.\n" + printf " (e .g. - 'configure_default_pki_instances')\n\n" + printf " (5) Fill in all MANDATORY user-defined variables\n" + printf " in the new script.\n\n" + printf " (6) Change any OPTIONAL user-defined variables\n" + printf " in the new script as desired.\n\n" + printf " (7) Become the 'root' user, and execute the new script to\n" + printf " configure ALL six 'default' PKI subsystem instances.\n\n" + exit 255 +fi + + +## +## This script MUST be run as root! +## + +ROOTUID=0 + +OS=`uname` +if [ "${OS}" = "Linux" ] ; then + MY_EUID=`/usr/bin/id -u` + MY_UID=`/usr/bin/id -ur` + USERNAME=`/usr/bin/id -un` +else + printf "ERROR: Unsupported operating system '${OS}'!\n" + exit 255 +fi + +if [ "${MY_UID}" != "${ROOTUID}" ] && + [ "${MY_EUID}" != "${ROOTUID}" ] ; then + printf "ERROR: The '$0' script must be run as root!\n" + exit 255 +fi + + + +############################################################################## +############################################################################## +## ## +## P K I S I L E N T - V A R I A B L E D E C L A R A T I O N ## +## ## +############################################################################## +############################################################################## + +############################################################################## +## U S E R - D E F I N E D V A R I A B L E S ( M A N D A T O R Y ) ## +############################################################################## + +## +## IMPORTANT: 'Escape' ALL spaces in EACH variable specified below! +## +## For Example: +## +## pki_security_domain_name="My\ Security\ Domain" +## + +## PKI Silent Security Database Variables +## (e. g. - PKI Silent "browser" database) +pki_silent_security_database_repository="/tmp" +pki_silent_security_database_password= + +## PKI Security Domain Variables +## (e. g. - Security Domain Login Panel) +pki_security_domain_name= +pki_security_domain_host=`hostname` +pki_security_domain_admin_name=admin +pki_security_domain_admin_password= + +## PKI Internal LDAP Database Variables +## (e. g. - Database Panel) +pki_ldap_host=localhost +pki_ldap_port=389 +pki_bind_dn="cn=Directory\ Manager" +pki_bind_password= + +## PKI Instance-Specific Token Variables +## (e. g. - Module Panel) +ca_token_name=internal +ca_token_password= + +kra_token_name=internal +kra_token_password= + +ocsp_token_name=internal +ocsp_token_password= + +tks_token_name=internal +tks_token_password= + +ra_token_name=internal +ra_token_password= + +tps_token_name=internal +tps_token_password= + +## PKI Instance-Specific Backup Variables +## (e. g. - Backup Key and Certificates Panel) +ca_backup_password= +kra_backup_password= +ocsp_backup_password= +tks_backup_password= + +## PKI Email Variables +## +## For example, to specify 'pkitest@example.com': +## +## pki_email_name=pkitest +## pki_email_company=example +## pki_email_domain=com +## +pki_email_name= +pki_email_company= +pki_email_domain= + +## PKI Silent Admin Variables +## (e. g. - Import Admin Certificate into PKI Silent "browser" database) +pki_silent_admin_user=admin +pki_silent_admin_password= +pki_silent_admin_email="${pki_email_name}\@${pki_email_company}\.${pki_email_domain}" + + + +############################################################################## +## P R E - D E F I N E D " D E F A U L T " V A R I A B L E S ## +############################################################################## + +## PKI Subsystem Host (computed by default) +pki_host=`hostname` + +## PKI Subsystem Names +ca_subsystem_name="Certificate\ Authority" +kra_subsystem_name="Data\ Recovery\ Manager" +ocsp_subsystem_name="OCSP\ Responder" +tks_subsystem_name="Token\ Key\ Service" +ra_subsystem_name="Registration\ Authority" +tps_subsystem_name="Token\ Processing\ System" + +## PKI Subsystem Instance Names +ca_instance_name="pki-ca" +kra_instance_name="pki-kra" +ocsp_instance_name="pki-ocsp" +tks_instance_name="pki-tks" +ra_instance_name="pki-ra" +tps_instance_name="pki-tps" + +## PKI Subsystem Init Script Names +ca_init_script="pki-cad" +kra_init_script="pki-krad" +ocsp_init_script="pki-ocspd" +tks_init_script="pki-tksd" +ra_init_script="pki-rad" +tps_init_script="pki-tpsd" + +## +## NOTE: Default PKI Instance Ports +## +## CA, DRM, OCSP, TKS: +## +## *180 - non-secure port (not role specific) +## *701 - non-secure Tomcat port +## *443 - secure EE port +## *444 - secure Agent port +## *445 - secure Admin port +## +## RA, TPS: +## +## *888 - non-secure port +## *889 - secure port (clientauth) +## *890 - secure port (non-clientauth) +## +## +## For Example: +## +## semanage port -l | grep pki +## +## pki_ca_port_t tcp 9180, 9701, 9443, 9444, 9445 +## pki_kra_port_t tcp 10180, 10701, 10443, 10444, 10445 +## pki_ocsp_port_t tcp 11180, 11701, 11443, 11444, 11445 +## pki_ra_port_t tcp 12890, 12888, 12889 +## pki_tks_port_t tcp 13180, 13701, 13443, 13444, 13445 +## pki_tps_port_t tcp 7890, 7888, 7889 +## + +## CA ports +ca_nonssl_port=9180 +ca_agent_port=9443 +ca_ee_port=9444 +ca_admin_port=9445 + +## DRM ports +kra_nonssl_port=10180 +kra_agent_port=10443 +kra_ee_port=10444 +kra_admin_port=10445 + +## OCSP ports +ocsp_nonssl_port=11180 +ocsp_agent_port=11443 +ocsp_ee_port=11444 +ocsp_admin_port=11445 + +## TKS ports +tks_nonssl_port=13180 +tks_agent_port=13443 +tks_ee_port=13444 +tks_admin_port=13445 + +## RA ports +ra_nonssl_port=12888 +ra_clientauth_port=12889 +ra_nonclientauth_port=12890 + +## TPS ports +tps_nonssl_port=7888 +tps_clientauth_port=7889 +tps_nonclientauth_port=7890 + + + +############################################################################## +## U S E R - D E F I N E D V A R I A B L E S ( O P T I O N A L ) ## +############################################################################## + +## PKI Silent Log Files +pki_silent_ca_log=/tmp/ca.log +pki_silent_kra_log=/tmp/kra.log +pki_silent_ocsp_log=/tmp/ocsp.log +pki_silent_ra_log=/tmp/ra.log +pki_silent_tks_log=/tmp/tks.log +pki_silent_tps_log=/tmp/tps.log + + +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## Firefox browser's security libraries would be something similar +## to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## Certificate Authority - ${pki_security_domain_name} CT,C,C +## CA Administrator of Instance ${ca_instance_name}'s +## ${pki_security_domain_name} ID u,u,u +## KRA Administrator of Instance ${kra_instance_name}'s +## ${pki_security_domain_name} ID u,u,u +## OCSP Administrator of Instance ${ocsp_instance_name}'s +## ${pki_security_domain_name} ID u,u,u +## TKS Administrator of Instance ${tks_instance_name}'s +## ${pki_security_domain_name} ID u,u,u +## RA Administrator's ${pki_security_domain_name} ID u,u,u +## TPS Administrator's ${pki_security_domain_name} ID u,u,u +## +## where: +## +## Nickname: "Certificate Authority - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "CA Administrator of Instance " +## + "${ca_instance_name}'s " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=CA Administrator of Instance " +## + "${ca_instance_name}," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "KRA Administrator of Instance " +## + "${kra_instance_name}'s " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=KRA Administrator of Instance " +## + "${kra_instance_name}," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "OCSP Administrator of Instance " +## + "${ocsp_instance_name}'s " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=OCSP Administrator of Instance " +## + "${ocsp_instance_name}," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "TKS Administrator of Instance " +## + "${tks_instance_name}'s " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=TKS Administrator of Instance " +## + "${tks_instance_name}," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "RA Administrator's " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=RA Administrator," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "TPS Administrator's " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=TPS Administrator," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## + + +## Miscellaneous CA Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${ca_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## ocspSigningCert cert-${ca_instance_name} u,u,u +## subsystemCert cert-${ca_instance_name} u,u,u +## caSigningCert cert-${ca_instance_name} CTu,Cu,Cu +## Server-Cert cert-${ca_instance_name} u,u,u +## auditSigningCert cert-${ca_instance_name} u,u,u +## +## where: +## +## Nickname: "caSigningCert cert-${ca_instance_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "subsystemCert cert-${ca_instance_name}" +## Subject Name: "cn=CA Subsystem Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "ocspSigningCert cert-${ca_instance_name}" +## Subject Name: "cn=OCSP Signing Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${ca_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "auditSigningCert cert-${ca_instance_name}" +## Subject Name: "cn=CA Audit Signing Certificate," +## + "o=${pki_security_domain_name}" +## +## NOTE: The parameters for the signing and key algorithms have the following meaning: +## ca_key_algorithm - signature algorithm used to sign the CA certificate +## ca_signing_algorithm - signature algorithm used by the CA and OCSP signing certs to sign objects. +## ca_signing_signingalgorithm - optionally specify the algorithm used by the CA signing cert to sign objects +## ca_ocsp_signing_signingalgorithm - optionally specify the algorithm used by the CA ocsp signing cert to sign objects +## +## NOTE: Additional variables to specify the LDAP connection are as follows: +## remove_data - set to true/false. Remove any existing data found under the baseDN +## secure_conn - use the ldaps port +ca_agent_name="CA\ Administrator\ of\ Instance\ ${ca_instance_name}\'s\ ${pki_security_domain_name}\ ID" +ca_agent_key_size=2048 +ca_agent_key_type=rsa +ca_agent_cert_subject="cn=CA\ Administrator\ of\ Instance\ ${ca_instance_name},uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +ca_base_dn="dc=${pki_host}-${ca_instance_name}" +ca_db_name="${pki_host}-${ca_instance_name}" +ca_key_size=2048 +ca_key_type=rsa +ca_key_algorithm=SHA256withRSA +ca_signing_algorithm=SHA256withRSA +ca_signing_signingalgorithm=SHA256withRSA +ca_ocsp_signing_signingalgorithm=SHA256withRSA +ca_save_p12=false +ca_sign_cert_subject_name="cn=Certificate\ Authority,o=${pki_security_domain_name}" +ca_subsystem_cert_subject_name="cn=CA\ Subsystem\ Certificate,o=${pki_security_domain_name}" +ca_ocsp_cert_subject_name="cn=OCSP\ Signing\ Certificate,o=${pki_security_domain_name}" +ca_server_cert_subject_name="cn=${pki_host},o=${pki_security_domain_name}" +ca_audit_signing_cert_subject_name="cn=CA\ Audit\ Signing\ Certificate,o=${pki_security_domain_name}" + +## Optional CA Variables for creating a clone CA +## +## It is possible for pkisilent to create a CA that is a clone of a previously +## installed CA (the master CA). To do so, the keys of the master CA must +## first be backed up in a pk12 file, and this file should be copied to the +## alias directory of the clone CA. This file should have read permission for +## the PKI user (pkisuer). +## +## An example file would be /var/lib/ca-clone/alias/ca-master.p12. +## +## The following variables should then be uncommented and defined for the clone CA. +## ca_clone=true +## ca_clone_p12_file= +## ca_clone_p12_password= +## clone_uri= +## sd_hostname= +## sd_admin_port= +## sd_admin_name= +## sd_admin_password= +## clone_start_tls=false +## +## NOTES: +## 1. ca_clone_p12_file must be just the filename relative to the alias directory. +## So in the example above, ca_clone_p12_file="ca-master.p12" +## 2. sd_* refer to the CA where the security domain is hosted. +## 3. clone_uri has the following format: https://<hostname>:<EE port> fo the CA to be cloned +## 4. clone_start_tls can be set to true if we require replication between the master and clone databases +## to be encrypted using startTLS on the standard (non-ldaps) port. The databases must +## be ssl enabled first or the replication will fail. +## +## ADDITIONAL NOTES: +## 1. The clone CA and master CA cannot share the same database instance. A new +## instance should be created for the clone CA. +## 2. The variables ca_base_dn and ca_db_name defined above MUST be identical to the +## ca_base_dn and ca_db_name of the master CA. The following assignments attempt +## to ensure this is correct. +## +## ca_master_instance_name= +## ca_base_dn="dc=${pki_host}-${ca_master_instance_name}" +## ca_db_name="${pki_host}-${ca_master_instance_name}" + +## Optional CA variables for creating a CA using an external CA +## +## It is possible to configure a CA that has its certificates signed by an external CA. +## This is a two step process. +## +## In the first step, pkisilent will create a CSR to be signed by the external CA +## and write it to the file specified. If this file is not specified, the default +## location /tmp/ext_ca.csr is used. +## +## The following parameters are required: +## ca_external=true +## ca_ext_csr_file= +## +## Once the CSR is approved by the external CA, the resulting certificate and CA +## cert chain are copied into files on the system. +## +## pkisilent is then rerun for the second step, providing the cert and cert chain files as +## parameters. For the second step, the following parameters are then required: +## +## ca_external=true +## ca_ext_cert_file= +## ca_ext_cert_chain_file= + +## Miscellaneous DRM Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${kra_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## transportCert cert-${kra_instance_name} u,u,u +## Server-Cert cert-${kra_instance_name} u,u,u +## auditSigningCert cert-${kra_instance_name} u,u,u +## Certificate Authority - ${pki_security_domain_name} CT,c, +## storageCert cert-${kra_instance_name} u,u,u +## subsystemCert cert-${kra_instance_name} u,u,u +## +## where: +## +## Nickname: "transportCert cert-${kra_instance_name}" +## Subject Name: "cn=DRM Transport Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${kra_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "auditSigningCert cert-${kra_instance_name}" +## Subject Name: "cn=DRM Audit Signing Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Certificate Authority - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "storageCert cert-${kra_instance_name}" +## Subject Name: "cn=DRM Storage Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "subsystemCert cert-${kra_instance_name}" +## Subject Name: "cn=DRM Subsystem Certificate," +## + "o=${pki_security_domain_name}" +## + +## Optional CA Variables for creating a clone DRM +## +## It is possible for pkisilent to create a DRM that is a clone of a previously +## installed DRM (the master DRM). To do so, the keys of the master DRM must +## first be backed up in a pk12 file, and this file should be copied to the +## alias directory of the clone DRM. This file should have read permission for +## the PKI user (pkiuser). +## +## An example file would be /var/lib/drm-clone/alias/drm-master.p12. +## +## The following variables should then be uncommented and defined for the clone CA. +## kra_clone=true +## kra_clone_p12_file= +## kra_clone_p12_password= +## kra_clone_uri= +## clone_start_tls=false +## +## NOTES: +## 1. drm_clone_p12_file must be just the filename relative to the alias directory. +## So in the example above, drm_clone_p12_file="drm-master.p12" +## 2. drm_clone_uri has the following format: https://<hostname>:<EE port> of the DRM to be cloned +## 3. clone_start_tls can be set to true if we require replication between the master and clone databases +## to be encrypted using startTLS on the standard (non-ldaps) port. The databases must +## be ssl enabled first or the replication will fail. +## +## ADDITIONAL NOTES: +## 1. The clone DRM and master DRM cannot share the same database instance. A new +## instance should be created for the clone DRM. +## 2. The variables kra_base_dn and kra_db_name defined above MUST be identical to the +## kra_base_dn and kra_name of the master CA. The following assignments attempt +## to ensure this is correct. +## +## kra_master_instance_name= +## kra_base_dn="dc=${pki_host}-${kra_master_instance_name}" +## kra_db_name="${pki_host}-${kra_master_instance_name}" + +kra_agent_name="KRA\ Administrator\ of\ Instance\ ${kra_instance_name}\'s\ ${pki_security_domain_name}\ ID" +kra_agent_key_size=2048 +kra_agent_key_type=rsa +kra_agent_cert_subject="cn=KRA\ Administrator\ of\ Instance\ ${kra_instance_name},uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +kra_base_dn="dc=${pki_host}-${kra_instance_name}" +kra_db_name="${pki_host}-${kra_instance_name}" +kra_key_size=2048 +kra_key_type=rsa +kra_transport_cert_subject_name="cn=DRM\ Transport\ Certificate,o=${pki_security_domain_name}" +kra_subsystem_cert_subject_name="cn=DRM\ Subsystem\ Certificate,o=${pki_security_domain_name}" +kra_storage_cert_subject_name="cn=DRM\ Storage\ Certificate,o=${pki_security_domain_name}" +kra_server_cert_subject_name="cn=${pki_host},o=${pki_security_domain_name}" +kra_audit_signing_cert_subject_name="cn=DRM\ Audit\ Signing\ Certificate,o=${pki_security_domain_name}" + + +## Miscellaneous OCSP Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${ocsp_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## ocspSigningCert cert-${ocsp_instance_name} CTu,Cu,Cu +## subsystemCert cert-${ocsp_instance_name} u,u,u +## Certificate Authority - ${pki_security_domain_name} CT,c, +## Server-Cert cert-${ocsp_instance_name} u,u,u +## auditSigningCert cert-${ocsp_instance_name} u,u,u +## +## where: +## +## Nickname: "ocspSigningCert cert-${ocsp_instance_name}" +## Subject Name: "cn=OCSP Signing Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "subsystemCert cert-${ocsp_instance_name}" +## Subject Name: "cn=OCSP Subsystem Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Certificate Authority - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${ocsp_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "auditSigningCert cert-${ocsp_instance_name}" +## Subject Name: "cn=OCSP Audit Signing Certificate," +## + "o=${pki_security_domain_name}" +## + +ocsp_agent_name="OCSP\ Administrator\ of\ Instance\ ${ocsp_instance_name}\'s\ ${pki_security_domain_name}\ ID" +ocsp_agent_key_size=2048 +ocsp_agent_key_type=rsa +ocsp_agent_cert_subject="cn=OCSP\ Administrator\ of\ Instance\ ${ocsp_instance_name},uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +ocsp_base_dn="dc=${pki_host}-${ocsp_instance_name}" +ocsp_db_name="${pki_host}-${ocsp_instance_name}" +ocsp_key_size=2048 +ocsp_key_type=rsa +ocsp_sign_cert_subject_name="cn=OCSP\ Signing\ Certificate,o=${pki_security_domain_name}" +ocsp_subsystem_cert_subject_name="cn=OCSP\ Subsystem\ Certificate,o=${pki_security_domain_name}" +ocsp_server_cert_subject_name="cn=${pki_host},o=${pki_security_domain_name}" +ocsp_audit_signing_cert_subject_name="cn=OCSP\ Audit\ Signing\ Certificate,o=${pki_security_domain_name}" + + +## Miscellaneous TKS Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${tks_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## subsystemCert cert-${tks_instance_name} u,u,u +## DRM Transport Certificate - ${pki_security_domain_name} c,c,c +## Certificate Authority - ${pki_security_domain_name} CT,c, +## Server-Cert cert-${tks_instance_name} u,u,u +## auditSigningCert cert-${tks_instance_name} u,u,u +## +## where: +## +## Nickname: "subsystemCert cert-${tks_instance_name}" +## Subject Name: "cn=TKS Subsystem Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "DRM Transport Certificate - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=DRM Transport Certificate," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Certificate Authority - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${tks_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "auditSigningCert cert-${tks_instance_name}" +## Subject Name: "cn=TKS Audit Signing Certificate," +## + "o=${pki_security_domain_name}" +## + +tks_agent_name="TKS\ Administrator\ of\ Instance\ ${tks_instance_name}\'s\ ${pki_security_domain_name}\ ID" +tks_agent_key_size=2048 +tks_agent_key_type=rsa +tks_agent_cert_subject="cn=TKS\ Administrator\ of\ Instance\ ${tks_instance_name},uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +tks_base_dn="dc=${pki_host}-${tks_instance_name}" +tks_db_name="${pki_host}-${tks_instance_name}" +tks_key_size=2048 +tks_key_type=rsa +tks_subsystem_cert_subject_name="cn=TKS\ Subsystem\ Certificate,o=${pki_security_domain_name}" +tks_server_cert_subject_name="cn=${pki_host},o=${pki_security_domain_name}" +tks_audit_signing_cert_subject_name="cn=TKS\ Audit\ Signing\ Certificate,o=${pki_security_domain_name}" + + +## Miscellaneous RA Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${ra_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## subsystemCert cert-${ra_instance_name} u,u,u +## caCert CT,C,C +## Server-Cert cert-${ra_instance_name} u,u,u +## +## where: +## +## Nickname: "subsystemCert cert-${ra_instance_name}" +## Subject Name: "cn=RA Subsystem Certificate," +## + "ou=${ra_instance_name}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "caCert" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${ra_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "ou=${ra_instance_name}," +## + "o=${pki_security_domain_name}" +## + +ra_chosen_ca_hostname=${pki_security_domain_host} +ra_chosen_ca_nonssl_port=${ca_nonssl_port} +ra_chosen_ca_ssl_port=${ca_ee_port} +ra_chosen_ca_admin_port=${ca_admin_port} +ra_agent_name="RA\ Administrator\'s\ ${pki_security_domain_name}\ ID" +ra_agent_key_size=2048 +ra_agent_key_type=rsa +ra_agent_cert_subject="cn=RA\ Administrator,uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +ra_key_size=2048 +ra_key_type=rsa +ra_server_cert_nickname="Server-Cert\ cert-${ra_instance_name}" +ra_server_cert_subject_name="cn=${pki_host},ou=${ra_instance_name},o=${pki_security_domain_name}" +ra_subsystem_cert_nickname="subsystemCert\ cert-${ra_instance_name}" +ra_subsystem_cert_subject_name="cn=RA\ Subsystem\ Certificate,ou=${ra_instance_name},o=${pki_security_domain_name}" + + +## Miscellaneous TPS Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${tps_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## subsystemCert cert-${tps_instance_name} u,u,u +## caCert CT,C,C +## Server-Cert cert-${tps_instance_name} u,u,u +## auditSigningCert cert-${tps_instance_name} u,u,u +## +## where: +## +## Nickname: "subsystemCert cert-${tps_instance_name}" +## Subject Name: "cn=TPS Subsystem Certificate," +## + "ou=${tps_instance_name}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "caCert" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${tps_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "ou=${tps_instance_name}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "auditSigningCert cert-${tps_instance_name}" +## Subject Name: "cn=TPS Audit Signing Certificate," +## + "ou=${tps_instance_name}," +## + "o=${pki_security_domain_name}" +## + +tps_chosen_ca_hostname=${pki_security_domain_host} +tps_chosen_ca_nonssl_port=${ca_nonssl_port} +tps_chosen_ca_ssl_port=${ca_ee_port} +tps_chosen_ca_admin_port=${ca_admin_port} +tps_chosen_tks_hostname=${pki_host} +tps_chosen_tks_ssl_port=${tks_ee_port} +tps_chosen_drm_hostname=${pki_host} +tps_chosen_drm_ssl_port=${kra_ee_port} +tps_agent_name="TPS\ Administrator\'s\ ${pki_security_domain_name}\ ID" +tps_agent_key_size=2048 +tps_agent_key_type=rsa +tps_agent_cert_subject="cn=TPS\ Administrator,uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +tps_ldap_auth_host=localhost +tps_ldap_auth_port=389 +tps_ldap_auth_base_dn="dc=${pki_email_company},dc=${pki_email_domain}" +tps_base_dn="dc=${pki_host}-${tps_instance_name}" +tps_db_name="${pki_host}-${tps_instance_name}" +tps_key_size=2048 +tps_key_type=rsa +tps_ss_keygen=true +tps_server_cert_subject_name="cn=${pki_host},ou=${tps_instance_name},o=${pki_security_domain_name}" +tps_server_cert_nickname="Server-Cert\ cert-${tps_instance_name}" +tps_subsystem_cert_subject_name="cn=TPS\ Subsystem\ Certificate,ou=${tps_instance_name},o=${pki_security_domain_name}" +tps_subsystem_cert_nickname="subsystemCert\ cert-${tps_instance_name}" +tps_audit_signing_cert_subject_name="cn=TPS\ Audit\ Signing\ Certificate,ou=${tps_instance_name},o=${pki_security_domain_name}" +tps_audit_signing_cert_nickname="auditSigningCert\ cert-${tps_instance_name}" + + + +############################################################################## +############################################################################## +## ## +## P K I S I L E N T - S U B S Y S T E M C O N F I G U R A T I O N ## +## ## +############################################################################## +############################################################################## + +############################################################################## +## P K I S I L E N T I N I T I A L I Z A T I O N ## +############################################################################## + +## (1) Make certain that user has defined all MANDATORY user-defined variables! +usage_errors=0 +usage_error_preamble="ERROR: User MUST define a value for" + +if [ "${pki_silent_security_database_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_silent_security_database_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_security_domain_name}" = "" ] ; then + printf "${usage_error_preamble} 'pki_security_domain_name'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_security_domain_admin_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_security_domain_admin_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_bind_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_bind_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${ca_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'ca_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${kra_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'kra_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${ocsp_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'ocsp_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${tks_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'tks_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${ra_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'ra_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${tps_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'tps_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${ca_backup_password}" = "" ] ; then + printf "${usage_error_preamble} 'ca_backup_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${kra_backup_password}" = "" ] ; then + printf "${usage_error_preamble} 'kra_backup_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${ocsp_backup_password}" = "" ] ; then + printf "${usage_error_preamble} 'ocsp_backup_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${tks_backup_password}" = "" ] ; then + printf "${usage_error_preamble} 'tks_backup_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_email_name}" = "" ] ; then + printf "${usage_error_preamble} 'pki_email_name'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_email_company}" = "" ] ; then + printf "${usage_error_preamble} 'pki_email_company'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_email_domain}" = "" ] ; then + printf "${usage_error_preamble} 'pki_email_domain'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_silent_admin_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_silent_admin_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi + + +## (2) Make certain that a PKI instance of the specified name EXISTS, +## but has NOT been previously CONFIGURED! +existence_errors=0 +existence_error_preamble="ERROR: No PKI Instance named" +configuration_errors=0 +configuration_error_preamble="ERROR: A PKI Instance named" +configuration_error_postamble="EXISTS,\n but has PREVIOUSLY been CONFIGURED!" + +if [ ! -f "/var/lib/${ca_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${ca_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + ca_configuration_check=`grep -c preop /var/lib/${ca_instance_name}/conf/CS.cfg` + if [ ${ca_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${ca_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi +if [ ! -f "/var/lib/${kra_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${kra_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + kra_configuration_check=`grep -c preop /var/lib/${kra_instance_name}/conf/CS.cfg` + if [ ${kra_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${kra_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi +if [ ! -f "/var/lib/${ocsp_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${ocsp_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + ocsp_configuration_check=`grep -c preop /var/lib/${ocsp_instance_name}/conf/CS.cfg` + if [ ${ocsp_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${ocsp_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi +if [ ! -f "/var/lib/${tks_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${tks_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + tks_configuration_check=`grep -c preop /var/lib/${tks_instance_name}/conf/CS.cfg` + if [ ${tks_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${tks_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi +if [ ! -f "/var/lib/${ra_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${ra_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + ra_configuration_check=`grep -c preop /var/lib/${ra_instance_name}/conf/CS.cfg` + if [ ${ra_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${ra_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi +if [ ! -f "/var/lib/${tps_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${tps_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + tps_configuration_check=`grep -c preop /var/lib/${tps_instance_name}/conf/CS.cfg` + if [ ${tps_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${tps_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi + + +if [ ${usage_errors} -ne 0 ] || + [ ${existence_errors} -ne 0 ] || + [ ${configuration_errors} -ne 0 ] ; then + printf "\n" + printf "Please correct ALL errors listed above and re-run\n" + printf "the '$0' script!\n\n" + exit 255 +fi + + +## (3) Make certain that 'pkisilent' exists and is executable on this system. +if [ ! -x "/usr/bin/pkisilent" ] ; then + printf "\n" + printf "ERROR: Please install the 'pki-silent' package and re-run\n" + printf "the '$0' script!\n\n" + exit 255 +fi + + +## (4) Check for old PKI Silent Security Databases, but DO NOT remove them! +## Instead, inform the user and exit this script. +if [ -f "${pki_silent_security_database_repository}/cert8.db" ] || + [ -f "${pki_silent_security_database_repository}/key3.db" ] || + [ -f "${pki_silent_security_database_repository}/secmod.db" ] ; then + printf "\n" + printf "WARNING: At least one of the security databases\n" + printf " (i. e. - 'cert8.db', 'key3.db', and/or 'secmod.db')\n" + printf " required by '${pki_silent_script}' exists at the\n" + printf " specified location '${pki_silent_security_database_repository}'.\n" + printf "\n" + printf " Please MANUALLY move or erase these security database(s),\n" + printf " or specify a different location before re-running this script.\n\n" + exit 255 +fi + + +## (5) Remove ALL old PKI Silent log files +printf "Removing old PKI Silent log files:\n" +if [ -f ${pki_silent_ca_log} ] ; then + printf " Removing old '${pki_silent_ca_log}' . . . " + rm ${pki_silent_ca_log} + printf "done.\n" +fi +if [ -f ${pki_silent_kra_log} ] ; then + printf " Removing old '${pki_silent_kra_log}' . . . " + rm ${pki_silent_kra_log} + printf "done.\n" +fi +if [ -f ${pki_silent_ocsp_log} ] ; then + printf " Removing old '${pki_silent_ocsp_log}' . . . " + rm ${pki_silent_ocsp_log} + printf "done.\n" +fi +if [ -f ${pki_silent_tks_log} ] ; then + printf " Removing old '${pki_silent_tks_log}' . . . " + rm ${pki_silent_tks_log} + printf "done.\n" +fi +if [ -f ${pki_silent_ra_log} ] ; then + printf " Removing old '${pki_silent_ra_log}' . . . " + rm ${pki_silent_ra_log} + printf "done.\n" +fi +if [ -f ${pki_silent_tps_log} ] ; then + printf " Removing old '${pki_silent_tps_log}' . . . " + rm ${pki_silent_tps_log} + printf "done.\n" +fi +printf "Done.\n\n" + + + +############################################################################## +## C A L C U L A T E P K I I N S T A N C E P I N S ## +############################################################################## + +## PKI Subsystem Instance PINS +ca_preop_pin=`cat /var/lib/${ca_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` +kra_preop_pin=`cat /var/lib/${kra_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` +ocsp_preop_pin=`cat /var/lib/${ocsp_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` +tks_preop_pin=`cat /var/lib/${tks_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` +ra_preop_pin=`cat /var/lib/${ra_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` +tps_preop_pin=`cat /var/lib/${tps_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` + + + +############################################################################## +## C E R T I F I C A T E A U T H O R I T Y ## +############################################################################## +## +## For example, upon completion, +## execute '/sbin/service ${ca_init_script} status ${ca_instance_name}': +## +## ${ca_instance_name} (pid 7843) is running ... +## +## Unsecure Port = http://${pki_host}:9180/ca/ee/ca +## Secure Agent Port = https://${pki_host}:9443/ca/agent/ca +## Secure EE Port = https://${pki_host}:9444/ca/ee/ca +## Secure Admin Port = https://${pki_host}:9445/ca/services +## PKI Console Port = pkiconsole https://${pki_host}:9445/ca +## Tomcat Port = 9701 (for shutdown) +## +## +## Security Domain URL: +## ================================================================== +## https://${pki_host}:9445 +## ================================================================== +## + +## Configure CA +printf "'${pki_silent_script}': Configuring '${ca_instance_name}' . . .\n" +pkisilent ConfigureCA \ + -cs_hostname "${pki_host}" \ + -cs_port ${ca_admin_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${ca_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_password ${pki_silent_admin_password} \ + -admin_email "${pki_silent_admin_email}" \ + -agent_name ${ca_agent_name} \ + -agent_key_size ${ca_agent_key_size} \ + -agent_key_type ${ca_agent_key_type} \ + -agent_cert_subject "${ca_agent_cert_subject}" \ + -ldap_host ${pki_ldap_host} \ + -ldap_port ${pki_ldap_port} \ + -bind_dn "${pki_bind_dn}" \ + -bind_password ${pki_bind_password} \ + -base_dn "${ca_base_dn}" \ + -db_name "${ca_db_name}" \ + -key_size ${ca_key_size} \ + -key_type ${ca_key_type} \ + -key_algorithm ${ca_key_algorithm} \ + -signing_algorithm ${ca_signing_algorithm} \ + -signing_signingalgorithm ${ca_signing_signingalgorithm} \ + -ocsp_signing_signingalgorithm ${ca_ocsp_signing_signingalgorithm} \ + -save_p12 ${ca_save_p12} \ + -subsystem_name ${ca_subsystem_name} \ + -token_name ${ca_token_name} \ + -token_pwd ${ca_token_password} \ + -ca_sign_cert_subject_name "${ca_sign_cert_subject_name}" \ + -ca_subsystem_cert_subject_name "${ca_subsystem_cert_subject_name}" \ + -ca_ocsp_cert_subject_name "${ca_ocsp_cert_subject_name}" \ + -ca_server_cert_subject_name "${ca_server_cert_subject_name}" \ + -ca_audit_signing_cert_subject_name \ + "${ca_audit_signing_cert_subject_name}" \ + | tee ${pki_silent_ca_log} + +## Restart CA +/sbin/service ${ca_init_script} restart ${ca_instance_name} + + +############################################################################## +## C E R T I F I C A T E A U T H O R I T Y (Clone) ## +############################################################################## +## +## Use this to create a clone CA .. +## +## For example, upon completion, +## execute '/sbin/service ${ca_init_script} status ${ca_instance_name}': +## +## ${ca_instance_name} (pid 7843) is running ... +## +## Unsecure Port = http://${pki_host}:9180/ca/ee/ca +## Secure Agent Port = https://${pki_host}:9443/ca/agent/ca +## Secure EE Port = https://${pki_host}:9444/ca/ee/ca +## Secure Admin Port = https://${pki_host}:9445/ca/services +## PKI Console Port = pkiconsole https://${pki_host}:9445/ca +## Tomcat Port = 9701 (for shutdown) +## +## +## Security Domain URL: +## ================================================================== +## https://${pki_host}:9445 +## ================================================================== +## + +## Configure clone CA +# printf "'${pki_silent_script}': Configuring '${ca_instance_name}' . . .\n" +# pkisilent ConfigureCA \ +# -cs_hostname "${pki_host}" \ +# -cs_port ${ca_admin_port} \ +# -client_certdb_dir ${pki_silent_security_database_repository} \ +# -client_certdb_pwd ${pki_silent_security_database_password} \ +# -preop_pin ${ca_preop_pin} \ +# -domain_name "${pki_security_domain_name}" \ +# -admin_user ${pki_silent_admin_user} \ +# -admin_password ${pki_silent_admin_password} \ +# -admin_email "${pki_silent_admin_email}" \ +# -agent_name ${ca_agent_name} \ +# -agent_key_size ${ca_agent_key_size} \ +# -agent_key_type ${ca_agent_key_type} \ +# -agent_cert_subject "${ca_agent_cert_subject}" \ +# -ldap_host ${pki_ldap_host} \ +# -ldap_port ${pki_ldap_port} \ +# -bind_dn "${pki_bind_dn}" \ +# -bind_password ${pki_bind_password} \ +# -base_dn "${ca_base_dn}" \ +# -db_name "${ca_db_name}" \ +# -key_size ${ca_key_size} \ +# -key_type ${ca_key_type} \ +# -key_algorithm ${ca_key_algorithm} \ +# -save_p12 ${ca_save_p12} \ +# -subsystem_name ${ca_subsystem_name} \ +# -token_name ${ca_token_name} \ +# -token_pwd ${ca_token_password} \ +# -ca_sign_cert_subject_name "${ca_sign_cert_subject_name}" \ +# -ca_subsystem_cert_subject_name "${ca_subsystem_cert_subject_name}" \ +# -ca_ocsp_cert_subject_name "${ca_ocsp_cert_subject_name}" \ +# -ca_server_cert_subject_name "${ca_server_cert_subject_name}" \ +# -ca_audit_signing_cert_subject_name \ +# "${ca_audit_signing_cert_subject_name}" \ +# -clone ${ca_clone} \ +# -clone_p12_file ${ca_clone_p12_file} \ +# -clone_p12_password ${ca_clone_p12_password} \ +# -clone_uri ${clone_uri} \ +# -sd_hostname ${sd_hostname} \ +# -sd_admin_port ${sd_admin_port} \ +# -sd_admin_name ${sd_admin_name} \ +# -sd_admin_password ${sd_admin_password} \ +# -clone_start_tls ${clone_start_tls} \ +# | tee ${pki_silent_ca_log} + +## Restart CA +#/sbin/service ${ca_init_script} restart ${ca_instance_name} + +############################################################################## +## C E R T I F I C A T E A U T H O R I T Y (External CA - step 1) ## +############################################################################## +## +## Use this invocation for the first step in creating a CA signed by +## and external CA .. +## +## For example, upon completion, +## +## A Certificate Request has been generated and stored in /tmp/ext_ca_csr.csr +## Please submit this CSR to your external CA and obtain the CA Cert and CA Cert Chain" + +## Configure CA signed by external CA (step 1) +# printf "'${pki_silent_script}': First step in configuring '${ca_instance_name}' . . .\n" +# pkisilent ConfigureCA \ +# -cs_hostname "${pki_host}" \ +# -cs_port ${ca_admin_port} \ +# -client_certdb_dir ${pki_silent_security_database_repository} \ +# -client_certdb_pwd ${pki_silent_security_database_password} \ +# -preop_pin ${ca_preop_pin} \ +# -domain_name "${pki_security_domain_name}" \ +# -admin_user ${pki_silent_admin_user} \ +# -admin_password ${pki_silent_admin_password} \ +# -admin_email "${pki_silent_admin_email}" \ +# -agent_name ${ca_agent_name} \ +# -agent_key_size ${ca_agent_key_size} \ +# -agent_key_type ${ca_agent_key_type} \ +# -agent_cert_subject "${ca_agent_cert_subject}" \ +# -ldap_host ${pki_ldap_host} \ +# -ldap_port ${pki_ldap_port} \ +# -bind_dn "${pki_bind_dn}" \ +# -bind_password ${pki_bind_password} \ +# -base_dn "${ca_base_dn}" \ +# -db_name "${ca_db_name}" \ +# -key_size ${ca_key_size} \ +# -key_type ${ca_key_type} \ +# -key_algorithm ${ca_key_algorithm} \ +# -signing_algorithm ${ca_signing_algorithm} \ +# -signing_signingalgorithm ${ca_signing_signingalgorithm} \ +# -ocsp_signing_signingalgorithm ${ca_ocsp_signing_signingalgorithm} \ +# -save_p12 ${ca_save_p12} \ +# -subsystem_name ${ca_subsystem_name} \ +# -token_name ${ca_token_name} \ +# -token_pwd ${ca_token_password} \ +# -ca_sign_cert_subject_name "${ca_sign_cert_subject_name}" \ +# -ca_subsystem_cert_subject_name "${ca_subsystem_cert_subject_name}" \ +# -ca_ocsp_cert_subject_name "${ca_ocsp_cert_subject_name}" \ +# -ca_server_cert_subject_name "${ca_server_cert_subject_name}" \ +# -ca_audit_signing_cert_subject_name \ +# "${ca_audit_signing_cert_subject_name}" \ +# -external ${ca_external} \ +# -ext_csr_file ${ca_ext_csr_file} \ +# | tee ${pki_silent_ca_log} + +## Restart CA +#/sbin/service ${ca_init_script} restart ${ca_instance_name} + +############################################################################## +## C E R T I F I C A T E A U T H O R I T Y (External CA step 2) ## +############################################################################## +## +## Use this to create a CA signed by an external CA (step 2) +## +## For example, upon completion, +## execute '/sbin/service ${ca_init_script} status ${ca_instance_name}': +## +## ${ca_instance_name} (pid 7843) is running ... +## +## Unsecure Port = http://${pki_host}:9180/ca/ee/ca +## Secure Agent Port = https://${pki_host}:9443/ca/agent/ca +## Secure EE Port = https://${pki_host}:9444/ca/ee/ca +## Secure Admin Port = https://${pki_host}:9445/ca/services +## PKI Console Port = pkiconsole https://${pki_host}:9445/ca +## Tomcat Port = 9701 (for shutdown) +## +## +## Security Domain URL: +## ================================================================== +## https://${pki_host}:9445 +## ================================================================== +## + +## Configure an externally signed CA (step 2) +# printf "'${pki_silent_script}': Step 2 in configuring external signed '${ca_instance_name}' . . .\n" +# pkisilent ConfigureCA \ +# -cs_hostname "${pki_host}" \ +# -cs_port ${ca_admin_port} \ +# -client_certdb_dir ${pki_silent_security_database_repository} \ +# -client_certdb_pwd ${pki_silent_security_database_password} \ +# -preop_pin ${ca_preop_pin} \ +# -domain_name "${pki_security_domain_name}" \ +# -admin_user ${pki_silent_admin_user} \ +# -admin_password ${pki_silent_admin_password} \ +# -admin_email "${pki_silent_admin_email}" \ +# -agent_name ${ca_agent_name} \ +# -agent_key_size ${ca_agent_key_size} \ +# -agent_key_type ${ca_agent_key_type} \ +# -agent_cert_subject "${ca_agent_cert_subject}" \ +# -ldap_host ${pki_ldap_host} \ +# -ldap_port ${pki_ldap_port} \ +# -bind_dn "${pki_bind_dn}" \ +# -bind_password ${pki_bind_password} \ +# -base_dn "${ca_base_dn}" \ +# -db_name "${ca_db_name}" \ +# -key_size ${ca_key_size} \ +# -key_type ${ca_key_type} \ +# -key_algorithm ${ca_key_algorithm} \ +# -signing_algorithm ${ca_signing_algorithm} \ +# -signing_signingalgorithm ${ca_signing_signingalgorithm} \ +# -ocsp_signing_signingalgorithm ${ca_ocsp_signing_signingalgorithm} \ +# -save_p12 ${ca_save_p12} \ +# -subsystem_name ${ca_subsystem_name} \ +# -token_name ${ca_token_name} \ +# -token_pwd ${ca_token_password} \ +# -ca_sign_cert_subject_name "${ca_sign_cert_subject_name}" \ +# -ca_subsystem_cert_subject_name "${ca_subsystem_cert_subject_name}" \ +# -ca_ocsp_cert_subject_name "${ca_ocsp_cert_subject_name}" \ +# -ca_server_cert_subject_name "${ca_server_cert_subject_name}" \ +# -ca_audit_signing_cert_subject_name \ +# "${ca_audit_signing_cert_subject_name}" \ +# -external ${ca_external} \ +# -ext_ca_cert_file ${ca_ext_cert_file} \ +# -ext_ca_cert_chain_file ${ca_ext_cert_chain_file} \ +# | tee ${pki_silent_ca_log} + +## Restart CA +#/sbin/service ${ca_init_script} restart ${ca_instance_name} + +############################################################################## +## D A T A R E C O V E R Y M A N A G E R ## +############################################################################## +## +## For example, upon completion, +## execute '/sbin/service ${kra_init_script} status ${kra_instance_name}': +## +## ${kra_instance_name} (pid 11723) is running ... +## +## Unsecure Port = http://${pki_host}:10180/kra/ee/kra +## Secure Agent Port = https://${pki_host}:10443/kra/agent/kra +## Secure EE Port = https://${pki_host}:10444/kra/ee/kra +## Secure Admin Port = https://${pki_host}:10445/kra/services +## PKI Console Port = pkiconsole https://${pki_host}:10445/kra +## Tomcat Port = 10701 (for shutdown) +## + +## Configure DRM +printf "'${pki_silent_script}': Configuring '${kra_instance_name}' . . .\n" +pkisilent ConfigureDRM \ + -cs_hostname "${pki_host}" \ + -cs_port ${kra_admin_port} \ + -sd_hostname "${pki_security_domain_host}" \ + -sd_ssl_port ${ca_ee_port} \ + -sd_agent_port ${ca_agent_port} \ + -sd_admin_port ${ca_admin_port} \ + -sd_admin_name "${pki_security_domain_admin_name}" \ + -sd_admin_password ${pki_security_domain_admin_password} \ + -ca_hostname ${pki_security_domain_host} \ + -ca_port ${ca_nonssl_port} \ + -ca_ssl_port ${ca_ee_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${kra_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_password ${pki_silent_admin_password} \ + -admin_email "${pki_silent_admin_email}" \ + -agent_name ${kra_agent_name} \ + -ldap_host ${pki_ldap_host} \ + -ldap_port ${pki_ldap_port} \ + -bind_dn "${pki_bind_dn}" \ + -bind_password ${pki_bind_password} \ + -base_dn "${kra_base_dn}" \ + -db_name "${kra_db_name}" \ + -key_size ${kra_key_size} \ + -key_type ${kra_key_type} \ + -token_name ${kra_token_name} \ + -token_pwd ${kra_token_password} \ + -agent_key_size ${kra_agent_key_size} \ + -agent_key_type ${kra_agent_key_type} \ + -agent_cert_subject "${kra_agent_cert_subject}" \ + -subsystem_name ${kra_subsystem_name} \ + -backup_pwd ${kra_backup_password} \ + -drm_transport_cert_subject_name "${kra_transport_cert_subject_name}" \ + -drm_subsystem_cert_subject_name "${kra_subsystem_cert_subject_name}" \ + -drm_storage_cert_subject_name "${kra_storage_cert_subject_name}" \ + -drm_server_cert_subject_name "${kra_server_cert_subject_name}" \ + -drm_audit_signing_cert_subject_name \ + "${kra_audit_signing_cert_subject_name}" \ + | tee ${pki_silent_kra_log} + +## Restart drm +/sbin/service ${kra_init_script} restart ${kra_instance_name} + + +############################################################################## +## D A T A R E C O V E R Y M A N A G E R (clone) ## +############################################################################## +## +## Use this to configure a DRM clone. +## +## For example, upon completion, +## execute '/sbin/service ${kra_init_script} status ${kra_instance_name}': +## +## ${kra_instance_name} (pid 11723) is running ... +## +## Unsecure Port = http://${pki_host}:10180/kra/ee/kra +## Secure Agent Port = https://${pki_host}:10443/kra/agent/kra +## Secure EE Port = https://${pki_host}:10444/kra/ee/kra +## Secure Admin Port = https://${pki_host}:10445/kra/services +## PKI Console Port = pkiconsole https://${pki_host}:10445/kra +## Tomcat Port = 10701 (for shutdown) +## + +## Configure DRM +# printf "'${pki_silent_script}': Configuring '${kra_instance_name}' . . .\n" +# pkisilent ConfigureDRM \ +# -cs_hostname "${pki_host}" \ +# -cs_port ${kra_admin_port} \ +# -sd_hostname "${pki_security_domain_host}" \ +# -sd_ssl_port ${ca_ee_port} \ +# -sd_agent_port ${ca_agent_port} \ +# -sd_admin_port ${ca_admin_port} \ +# -sd_admin_name "${pki_security_domain_admin_name}" \ +# -sd_admin_password ${pki_security_domain_admin_password} \ +# -ca_hostname ${pki_security_domain_host} \ +# -ca_port ${ca_nonssl_port} \ +# -ca_ssl_port ${ca_ee_port} \ +# -client_certdb_dir ${pki_silent_security_database_repository} \ +# -client_certdb_pwd ${pki_silent_security_database_password} \ +# -preop_pin ${kra_preop_pin} \ +# -domain_name "${pki_security_domain_name}" \ +# -admin_user ${pki_silent_admin_user} \ +# -admin_password ${pki_silent_admin_password} \ +# -admin_email "${pki_silent_admin_email}" \ +# -agent_name ${kra_agent_name} \ +# -ldap_host ${pki_ldap_host} \ +# -ldap_port ${pki_ldap_port} \ +# -bind_dn "${pki_bind_dn}" \ +# -bind_password ${pki_bind_password} \ +# -base_dn "${kra_base_dn}" \ +# -db_name "${kra_db_name}" \ +# -key_size ${kra_key_size} \ +# -key_type ${kra_key_type} \ +# -token_name ${kra_token_name} \ +# -token_pwd ${kra_token_password} \ +# -agent_key_size ${kra_agent_key_size} \ +# -agent_key_type ${kra_agent_key_type} \ +# -agent_cert_subject "${kra_agent_cert_subject}" \ +# -subsystem_name ${kra_subsystem_name} \ +# -backup_pwd ${kra_backup_password} \ +# -drm_transport_cert_subject_name "${kra_transport_cert_subject_name}" \ +# -drm_subsystem_cert_subject_name "${kra_subsystem_cert_subject_name}" \ +# -drm_storage_cert_subject_name "${kra_storage_cert_subject_name}" \ +# -drm_server_cert_subject_name "${kra_server_cert_subject_name}" \ +# -drm_audit_signing_cert_subject_name \ +# "${kra_audit_signing_cert_subject_name}" \ +# -clone ${kra_clone} \ +# -clone_p12_file ${kra_clone_p12_file} \ +# -clone_p12_password ${kra_clone_p12_password} \ +# -clone_uri ${kra_uri} \ +# -clone_start_tls ${clone_start_tls} \ +# | tee ${pki_silent_kra_log} + +## Restart drm +#/sbin/service ${kra_init_script} restart ${kra_instance_name} + + +############################################################################## +## O N L I N E S T A T U S C E R T I F I C A T E P R O T O C O L ## +############################################################################### +## +## For example, upon completion, +## execute '/sbin/service ${ocsp_init_script} status ${ocsp_instance_name}': +## +## ${ocsp_instance_name} (pid 13058) is running ... +## +## Unsecure Port = http://${pki_host}:11180/ocsp/ee/ocsp +## Secure Agent Port = https://${pki_host}:11443/ocsp/agent/ocsp +## Secure EE Port = https://${pki_host}:11444/ocsp/ee/ocsp +## Secure Admin Port = https://${pki_host}:11445/ocsp/services +## PKI Console Port = pkiconsole https://${pki_host}:11445/ocsp +## Tomcat Port = 11701 (for shutdown) +## + +## Configure OCSP +printf "'${pki_silent_script}': Configuring '${ocsp_instance_name}' . . .\n" +pkisilent ConfigureOCSP \ + -cs_hostname "${pki_host}" \ + -cs_port ${ocsp_admin_port} \ + -sd_hostname "${pki_security_domain_host}" \ + -sd_ssl_port ${ca_ee_port} \ + -sd_agent_port ${ca_agent_port} \ + -sd_admin_port ${ca_admin_port} \ + -sd_admin_name "${pki_security_domain_admin_name}" \ + -sd_admin_password ${pki_security_domain_admin_password} \ + -ca_hostname ${pki_security_domain_host} \ + -ca_port ${ca_nonssl_port} \ + -ca_ssl_port ${ca_ee_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${ocsp_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_password ${pki_silent_admin_password} \ + -admin_email "${pki_silent_admin_email}" \ + -agent_name ${ocsp_agent_name} \ + -ldap_host ${pki_ldap_host} \ + -ldap_port ${pki_ldap_port} \ + -bind_dn "${pki_bind_dn}" \ + -bind_password ${pki_bind_password} \ + -base_dn "${ocsp_base_dn}" \ + -db_name "${ocsp_db_name}" \ + -key_size ${ocsp_key_size} \ + -key_type ${ocsp_key_type} \ + -token_name ${ocsp_token_name} \ + -token_pwd ${ocsp_token_password} \ + -agent_key_size ${ocsp_agent_key_size} \ + -agent_key_type ${ocsp_agent_key_type} \ + -agent_cert_subject "${ocsp_agent_cert_subject}" \ + -subsystem_name ${ocsp_subsystem_name} \ + -backup_pwd ${ocsp_backup_password} \ + -ocsp_sign_cert_subject_name "${ocsp_sign_cert_subject_name}" \ + -ocsp_subsystem_cert_subject_name "${ocsp_subsystem_cert_subject_name}" \ + -ocsp_server_cert_subject_name "${ocsp_server_cert_subject_name}" \ + -ocsp_audit_signing_cert_subject_name \ + "${ocsp_audit_signing_cert_subject_name}" \ + | tee ${pki_silent_ocsp_log} + +## Restart OCSP +/sbin/service ${ocsp_init_script} restart ${ocsp_instance_name} + + + +############################################################################## +## T O K E N K E Y S E R V I C E ## +############################################################################## +## +## For example, upon completion, +## execute '/sbin/service ${tks_init_script} status ${tks_instance_name}': +## +## ${tks_instance_name} (pid 14129) is running ... +## +## Unsecure Port = http://${pki_host}:13180/tks/ee/tks +## Secure Agent Port = https://${pki_host}:13443/tks/agent/tks +## Secure EE Port = https://${pki_host}:13444/tks/ee/tks +## Secure Admin Port = https://${pki_host}:13445/tks/services +## PKI Console Port = pkiconsole https://${pki_host}:13445/tks +## Tomcat Port = 13701 (for shutdown) +## + +## Configure TKS +printf "'${pki_silent_script}': Configuring '${tks_instance_name}' . . .\n" +pkisilent ConfigureTKS \ + -cs_hostname "${pki_host}" \ + -cs_port ${tks_admin_port} \ + -sd_hostname "${pki_security_domain_host}" \ + -sd_ssl_port ${ca_ee_port} \ + -sd_agent_port ${ca_agent_port} \ + -sd_admin_port ${ca_admin_port} \ + -sd_admin_name "${pki_security_domain_admin_name}" \ + -sd_admin_password ${pki_security_domain_admin_password} \ + -ca_hostname ${pki_security_domain_host} \ + -ca_port ${ca_nonssl_port} \ + -ca_ssl_port ${ca_ee_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${tks_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_password ${pki_silent_admin_password} \ + -admin_email "${pki_silent_admin_email}" \ + -agent_name ${tks_agent_name} \ + -ldap_host ${pki_ldap_host} \ + -ldap_port ${pki_ldap_port} \ + -bind_dn "${pki_bind_dn}" \ + -bind_password ${pki_bind_password} \ + -base_dn "${tks_base_dn}" \ + -db_name "${tks_db_name}" \ + -key_size ${tks_key_size} \ + -key_type ${tks_key_type} \ + -token_name ${tks_token_name} \ + -token_pwd ${tks_token_password} \ + -agent_key_size ${tks_agent_key_size} \ + -agent_key_type ${tks_agent_key_type} \ + -agent_cert_subject "${tks_agent_cert_subject}" \ + -subsystem_name ${tks_subsystem_name} \ + -backup_pwd ${tks_backup_password} \ + -tks_subsystem_cert_subject_name "${tks_subsystem_cert_subject_name}" \ + -tks_server_cert_subject_name "${tks_server_cert_subject_name}" \ + -tks_audit_signing_cert_subject_name \ + "${tks_audit_signing_cert_subject_name}" \ + | tee ${pki_silent_tks_log} + +## restart tks +/sbin/service ${tks_init_script} restart ${tks_instance_name} + + + +############################################################################## +## R E G I S T R A T I O N A U T H O R I T Y ## +############################################################################## +## +## For example, upon completion, +## execute '/sbin/service ${ra_init_script} status ${ra_instance_name}': +## +## ${ra_instance_name} (pid 15769) is running ... +## +## Unsecure Port = http://${pki_host}:12888 +## Secure Clientauth Port = https://${pki_host}:12889 +## Secure Non-Clientauth Port = https://${pki_host}:12890 +## + +## Configure RA +printf "'${pki_silent_script}': Configuring '${ra_instance_name}' . . .\n" +pkisilent ConfigureRA \ + -cs_hostname "${pki_host}" \ + -cs_port ${ra_nonclientauth_port} \ + -cs_clientauth_port ${ra_clientauth_port} \ + -sd_hostname "${pki_security_domain_host}" \ + -sd_ssl_port ${ca_ee_port} \ + -sd_agent_port ${ca_agent_port} \ + -sd_admin_port ${ca_admin_port} \ + -sd_admin_name "${pki_security_domain_admin_name}" \ + -sd_admin_password ${pki_security_domain_admin_password} \ + -ca_hostname ${ra_chosen_ca_hostname} \ + -ca_port ${ra_chosen_ca_nonssl_port} \ + -ca_ssl_port ${ra_chosen_ca_ssl_port} \ + -ca_admin_port ${ra_chosen_ca_admin_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${ra_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_password ${pki_silent_admin_password} \ + -admin_email "${pki_silent_admin_email}" \ + -agent_name ${ra_agent_name} \ + -key_size ${ra_key_size} \ + -key_type ${ra_key_type} \ + -token_name ${ra_token_name} \ + -token_pwd ${ra_token_password} \ + -agent_key_size ${ra_agent_key_size} \ + -agent_key_type ${ra_agent_key_type} \ + -agent_cert_subject "${ra_agent_cert_subject}" \ + -subsystem_name ${ra_subsystem_name} \ + -ra_server_cert_nickname "${ra_server_cert_nickname}" \ + -ra_server_cert_subject_name "${ra_server_cert_subject_name}" \ + -ra_subsystem_cert_nickname "${ra_subsystem_cert_nickname}" \ + -ra_subsystem_cert_subject_name "${ra_subsystem_cert_subject_name}" \ + | tee ${pki_silent_ra_log} + +## Restart RA +/sbin/service ${ra_init_script} restart ${ra_instance_name} + + +############################################################################## +## T O K E N P R O C E S S I N G S Y S T E M ## +############################################################################## +## +## For example, upon completion, +## execute '/sbin/service ${tps_init_script} status ${tps_instance_name}': +## +## +## ${tps_instance_name} (pid 16241) is running ... +## +## Unsecure Port = http://${pki_host}:7888/cgi-bin/so/enroll.cgi +## (ESC Security Officer Enrollment) +## Unsecure Port = http://${pki_host}:7888/cgi-bin/home/index.cgi +## (ESC Phone Home) +## Secure Clientauth Port = https://${pki_host}:7889/cgi-bin/sow/welcome.cgi +## (ESC Security Officer Workstation) +## Secure Clientauth Port = https://${pki_host}:7889/tus +## (TPS Roles - Operator/Administrator/Agent) +## Secure Non-Clientauth Port = https://${pki_host}:7890/cgi-bin/so/enroll.cgi +## (ESC Security Officer Enrollment) +## Secure Non-Clientauth Port = https://${pki_host}:7890/cgi-bin/home/index.cgi +## (ESC Phone Home) +## + +## Configure TPS +printf "'${pki_silent_script}': Configuring '${tps_instance_name}' . . .\n" +pkisilent ConfigureTPS \ + -cs_hostname "${pki_host}" \ + -cs_port ${tps_nonclientauth_port} \ + -cs_clientauth_port ${tps_clientauth_port} \ + -sd_hostname "${pki_security_domain_host}" \ + -sd_ssl_port ${ca_ee_port} \ + -sd_agent_port ${ca_agent_port} \ + -sd_admin_port ${ca_admin_port} \ + -sd_admin_name "${pki_security_domain_admin_name}" \ + -sd_admin_password ${pki_security_domain_admin_password} \ + -ca_hostname ${tps_chosen_ca_hostname} \ + -ca_port ${tps_chosen_ca_nonssl_port} \ + -ca_ssl_port ${tps_chosen_ca_ssl_port} \ + -ca_admin_port ${tps_chosen_ca_admin_port} \ + -drm_hostname ${tps_chosen_drm_hostname} \ + -drm_ssl_port ${tps_chosen_drm_ssl_port} \ + -ss_keygen ${tps_ss_keygen} \ + -tks_hostname ${tps_chosen_tks_hostname} \ + -tks_ssl_port ${tps_chosen_tks_ssl_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${tps_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_password ${pki_silent_admin_password} \ + -admin_email "${pki_silent_admin_email}" \ + -agent_name ${tps_agent_name} \ + -ldap_host ${pki_ldap_host} \ + -ldap_port ${pki_ldap_port} \ + -bind_dn "${pki_bind_dn}" \ + -bind_password ${pki_bind_password} \ + -base_dn "${tps_base_dn}" \ + -db_name "${tps_db_name}" \ + -key_size ${tps_key_size} \ + -key_type ${tps_key_type} \ + -token_name ${tps_token_name} \ + -token_pwd ${tps_token_password} \ + -agent_key_size ${tps_agent_key_size} \ + -agent_key_type ${tps_agent_key_type} \ + -agent_cert_subject "${tps_agent_cert_subject}" \ + -subsystem_name ${tps_subsystem_name} \ + -ldap_auth_host ${tps_ldap_auth_host} \ + -ldap_auth_port ${tps_ldap_auth_port} \ + -ldap_auth_base_dn ${tps_ldap_auth_base_dn} \ + -tps_server_cert_subject_name "${tps_server_cert_subject_name}" \ + -tps_server_cert_nickname "${tps_server_cert_nickname}" \ + -tps_subsystem_cert_subject_name "${tps_subsystem_cert_subject_name}" \ + -tps_subsystem_cert_nickname "${tps_subsystem_cert_nickname}" \ + -tps_audit_signing_cert_subject_name \ + "${tps_audit_signing_cert_subject_name}" \ + -tps_audit_signing_cert_nickname \ + "${tps_audit_signing_cert_nickname}" \ + | tee ${pki_silent_tps_log} + +## Restart TPS +/sbin/service ${tps_init_script} restart ${tps_instance_name} + +exit 0 + diff --git a/base/silent/templates/subca_silent.template b/base/silent/templates/subca_silent.template new file mode 100755 index 000000000..1475996d1 --- /dev/null +++ b/base/silent/templates/subca_silent.template @@ -0,0 +1,513 @@ +#!/bin/bash +## BEGIN COPYRIGHT BLOCK +## (C) 2009 Red Hat, Inc. +## All rights reserved. +## END COPYRIGHT BLOCK + + +## Always switch into this base directory +## prior to script execution so that all +## of its output is written to this directory + +cd `dirname $0` + + +## Disallow script to be run as the name of this template +subca_silent_script=`basename $0` +if [ "${subca_silent_script}" = "subca_silent.template" ] ; then + printf "\n" + printf "Usage: (1) Install AND configure a directory server instance.\n\n" + printf " (2) Install AND configure a Root CA subsystem instance\n" + printf " that is its own security domain.\n\n" + printf " (3) Use 'pkicreate' to install a second CA subsystem\n" + printf " instance (this will become a Subordinate CA).\n" + printf " [Do NOT configure this CA subsystem instance!]\n\n" + printf " (4) Install the 'pki-silent' package.\n\n" + printf " (5) Copy '$0' to a new script name\n" + printf " without the '.template' extension.\n" + printf " (e .g. - 'configure_subca_instance')\n\n" + printf " (6) Fill in all MANDATORY user-defined variables\n" + printf " in the new script.\n\n" + printf " (7) Change any OPTIONAL user-defined variables\n" + printf " in the new script as desired.\n\n" + printf " (8) Become the 'root' user, and execute the new script to\n" + printf " configure a Subordinate CA subsystem instance.\n\n" + exit 255 +fi + + +## +## This script MUST be run as root! +## + +ROOTUID=0 + +OS=`uname` +if [ "${OS}" = "Linux" ] ; then + MY_EUID=`/usr/bin/id -u` + MY_UID=`/usr/bin/id -ur` + USERNAME=`/usr/bin/id -un` +else + printf "ERROR: Unsupported operating system '${OS}'!\n" + exit 255 +fi + +if [ "${MY_UID}" != "${ROOTUID}" ] && + [ "${MY_EUID}" != "${ROOTUID}" ] ; then + printf "ERROR: The '$0' script must be run as root!\n" + exit 255 +fi + + + +############################################################################## +############################################################################## +## ## +## P K I S I L E N T - V A R I A B L E D E C L A R A T I O N ## +## ## +############################################################################## +############################################################################## + +############################################################################## +## U S E R - D E F I N E D V A R I A B L E S ( M A N D A T O R Y ) ## +############################################################################## + +## +## IMPORTANT: 'Escape' ALL spaces in EACH variable specified below! +## +## For Example: +## +## pki_security_domain_name="My\ Security\ Domain" +## + +## PKI Silent Security Database Variables +## (e. g. - PKI Silent "browser" database) +pki_silent_security_database_repository="/tmp" +pki_silent_security_database_password= + +## PKI Security Domain Variables +## (e. g. - Security Domain Login Panel) +pki_security_domain_name= +pki_security_domain_host=`hostname` +pki_security_domain_admin_name=admin +pki_security_domain_admin_password= + +## PKI Internal LDAP Database Variables +## (e. g. - Database Panel) +pki_ldap_host=localhost +pki_ldap_port=389 +pki_bind_dn="cn=Directory\ Manager" +pki_bind_password= + +## PKI Instance-Specific Token Variables +## (e. g. - Module Panel) +subca_token_name=internal +subca_token_password= + +## PKI Instance-Specific Backup Variables +## (e. g. - Backup Key and Certificates Panel) +subca_backup_password= + +## PKI Email Variables +## +## For example, to specify 'pkitest@example.com': +## +## pki_email_name=pkitest +## pki_email_company=example +## pki_email_domain=com +## +pki_email_name= +pki_email_company= +pki_email_domain= + +## PKI Silent Admin Variables +## (e. g. - Import Admin Certificate into PKI Silent "browser" database) +pki_silent_admin_user=admin +pki_silent_admin_password= +pki_silent_admin_email="${pki_email_name}\@${pki_email_company}\.${pki_email_domain}" + + + +############################################################################## +## P R E - D E F I N E D " D E F A U L T " V A R I A B L E S ## +############################################################################## + +## PKI Subsystem Host (computed by default) +pki_host=`hostname` + +## PKI Subsystem Names +ca_subsystem_name="Certificate\ Authority" + +## PKI Subsystem Instance Names +subca_instance_name="pki-subca" + +## PKI Subsystem Init Script Names +subca_init_script="pki-cad" + +## +## NOTE: Default PKI Instance Ports +## +## CA: +## +## *180 - non-secure port (not role specific) +## *701 - non-secure Tomcat port +## *443 - secure EE port +## *444 - secure Agent port +## *445 - secure Admin port +## +## +## For Example: +## +## semanage port -l | grep pki +## +## pki_ca_port_t tcp 9180, 9701, 9443, 9444, 9445 +## pki_subca_port_t tcp 9580, 9801, 9543, 9544, 9545 +## + +## CA ports +ca_nonssl_port=9180 +ca_agent_port=9443 +ca_ee_port=9444 +ca_admin_port=9445 + +## Subordinate CA ports +subca_nonssl_port=9580 +subca_agent_port=9543 +subca_ee_port=9544 +subca_admin_port=9545 + + + +############################################################################## +## U S E R - D E F I N E D V A R I A B L E S ( O P T I O N A L ) ## +############################################################################## + +## PKI Silent Log Files +pki_silent_subca_log=/tmp/subca.log + + +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## Firefox browser's security libraries would be something similar +## to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## Certificate Authority 2 - ${pki_security_domain_name} ,, +## CA Administrator of Instance ${subca_instance_name}'s +## ${pki_security_domain_name} ID u,u,u +## ${pki_host} P,, +## Certificate Authority - ${pki_security_domain_name} CT,C,C +## +## where: +## +## Nickname: "Certificate Authority 2 - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority 2," +## + "o=${pki_security_domain_name}" +## +## Nickname: "CA Administrator of Instance " +## + "${subca_instance_name}'s " +## + "${pki_security_domain_name} ID" +## Subject Name: "cn=CA Administrator of Instance " +## + "${subca_instance_name}," +## + "uid=admin," +## + "e=${pki_silent_admin_email}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "${pki_host}" +## Subject Name: "cn=${pki_host}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Certificate Authority - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## + + +## Miscellaneous CA Variables +## +## REMINDER: 'Escape' ALL spaces in EACH variable specified below! +## +## NOTE: For comparison's sake, if the default instances were manually +## configured using a Firefox browser, the content of the corresponding +## "/var/lib/${subca_instance_name}/alias/" security libraries would be +## something similar to this: +## +## Certificate Nickname Trust Attributes +## SSL,S/MIME,JAR/XPI +## +## caSigningCert cert-${subca_instance_name} CTu,Cu,Cu +## Server-Cert cert-${subca_instance_name} u,u,u +## Certificate Authority - ${pki_security_domain_name} CT,c, +## ocspSigningCert cert-${subca_instance_name} u,u,u +## auditSigningCert cert-${subca_instance_name} u,u,u +## subsystemCert cert-${subca_instance_name} u,u,u +## +## where: +## +## Nickname: "caSigningCert cert-${subca_instance_name}" +## Subject Name: "cn=Certificate Authority 2," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Server-Cert cert-${subca_instance_name}" +## Subject Name: "cn=${pki_host}," +## + "o=${pki_security_domain_name}" +## +## Nickname: "Certificate Authority - " +## + "${pki_security_domain_name}" +## Subject Name: "cn=Certificate Authority," +## + "o=${pki_security_domain_name}" +## +## Nickname: "ocspSigningCert cert-${subca_instance_name}" +## Subject Name: "cn=OCSP Signing Certificate 2," +## + "o=${pki_security_domain_name}" +## +## Nickname: "auditSigningCert cert-${subca_instance_name}" +## Subject Name: "cn=CA Audit Signing Certificate 2," +## + "o=${pki_security_domain_name}" +## +## Nickname: "subsystemCert cert-${subca_instance_name}" +## Subject Name: "cn=CA Subsystem Certificate 2," +## + "o=${pki_security_domain_name}" +## +## NOTE: The parameters for the signing algorithms have the following meaning: +## subca_signing_algorithm - signature algorithm used by the CA and OCSP signing certs to sign objects. +## subca_signing_signingalgorithm - optionally specify the algorithm used by the CA signing cert to sign objects +## subca_ocsp_signing_signingalgorithm - optionally specify the algorithm used by the CA ocsp signing cert to sign objects +## + +subca_agent_name="CA\ Administrator\ of\ Instance\ ${subca_instance_name}\'s\ ${pki_security_domain_name}\ ID" +subca_agent_key_size=2048 +subca_agent_key_type=rsa +subca_agent_cert_subject="cn=CA\ Administrator\ of\ Instance\ ${subca_instance_name},uid=admin,e=${pki_silent_admin_email},o=${pki_security_domain_name}" +subca_base_dn="dc=${pki_host}-${subca_instance_name}" +subca_db_name="${pki_host}-${subca_instance_name}" +subca_key_size=2048 +subca_key_type=rsa +subca_signing_algorithm=SHA256withRSA +subca_signing_signingalgorithm=SHA256withRSA +subca_ocsp_signing_signingalgorithm=SHA256withRSA +subca_sign_cert_subject_name="cn=Certificate\ Authority\ 2,o=${pki_security_domain_name}" +subca_subsystem_cert_subject_name="cn=CA\ Subsystem\ Certificate\ 2,o=${pki_security_domain_name}" +subca_ocsp_cert_subject_name="cn=OCSP\ Signing\ Certificate\ 2,o=${pki_security_domain_name}" +subca_server_cert_subject_name="cn=${pki_host},o=${pki_security_domain_name}" +subca_audit_signing_cert_subject_name="cn=CA\ Audit\ Signing\ Certificate\ 2,o=${pki_security_domain_name}" + + + +############################################################################## +############################################################################## +## ## +## P K I S I L E N T - S U B S Y S T E M C O N F I G U R A T I O N ## +## ## +############################################################################## +############################################################################## + +############################################################################## +## P K I S I L E N T I N I T I A L I Z A T I O N ## +############################################################################## + +## (1) Make certain that user has defined all MANDATORY user-defined variables! +usage_errors=0 +usage_error_preamble="ERROR: User MUST define a value for" + +if [ "${pki_silent_security_database_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_silent_security_database_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_security_domain_name}" = "" ] ; then + printf "${usage_error_preamble} 'pki_security_domain_name'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_security_domain_admin_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_security_domain_admin_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_bind_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_bind_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${subca_token_password}" = "" ] ; then + printf "${usage_error_preamble} 'subca_token_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${subca_backup_password}" = "" ] ; then + printf "${usage_error_preamble} 'subca_backup_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_email_name}" = "" ] ; then + printf "${usage_error_preamble} 'pki_email_name'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_email_company}" = "" ] ; then + printf "${usage_error_preamble} 'pki_email_company'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_email_domain}" = "" ] ; then + printf "${usage_error_preamble} 'pki_email_domain'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi +if [ "${pki_silent_admin_password}" = "" ] ; then + printf "${usage_error_preamble} 'pki_silent_admin_password'!\n" + usage_errors=`expr ${usage_errors} + 1` +fi + + +## (2) Make certain that a PKI instance of the specified name EXISTS, +## but has NOT been previously CONFIGURED! +existence_errors=0 +existence_error_preamble="ERROR: No PKI Instance named" +configuration_errors=0 +configuration_error_preamble="ERROR: A PKI Instance named" +configuration_error_postamble="EXISTS,\n but has PREVIOUSLY been CONFIGURED!" + +if [ ! -f "/var/lib/${subca_instance_name}/conf/CS.cfg" ] ; then + printf "${existence_error_preamble} '${subca_instance_name}' EXISTS!\n" + existence_errors=`expr ${existence_errors} + 1` +else + subca_configuration_check=`grep -c preop /var/lib/${subca_instance_name}/conf/CS.cfg` + if [ ${subca_configuration_check} -eq 0 ] ; then + printf "${configuration_error_preamble} '${subca_instance_name}' " + printf "${configuration_error_postamble}\n" + configuration_errors=`expr ${configuration_errors} + 1` + fi +fi + + +if [ ${usage_errors} -ne 0 ] || + [ ${existence_errors} -ne 0 ] || + [ ${configuration_errors} -ne 0 ] ; then + printf "\n" + printf "Please correct ALL errors listed above and re-run\n" + printf "the '$0' script!\n\n" + exit 255 +fi + + +## (3) Make certain that 'pkisilent' exists and is executable on this system. +if [ ! -x "/usr/bin/pkisilent" ] ; then + printf "\n" + printf "ERROR: Please install the 'pki-silent' package and re-run\n" + printf "the '$0' script!\n\n" + exit 255 +fi + + +## (4) Check for old PKI Silent Security Databases, but DO NOT remove them! +## Instead, inform the user and exit this script. +if [ -f "${pki_silent_security_database_repository}/cert8.db" ] || + [ -f "${pki_silent_security_database_repository}/key3.db" ] || + [ -f "${pki_silent_security_database_repository}/secmod.db" ] ; then + printf "\n" + printf "WARNING: At least one of the security databases\n" + printf " (i. e. - 'cert8.db', 'key3.db', and/or 'secmod.db')\n" + printf " required by '${subca_silent_script}' exists at the\n" + printf " specified location '${pki_silent_security_database_repository}'.\n" + printf "\n" + printf " Please MANUALLY move or erase these security database(s),\n" + printf " or specify a different location before re-running this script.\n\n" + exit 255 +fi + + +## (5) Remove ALL old PKI Silent log files +printf "Removing old PKI Silent log files:\n" +if [ -f ${pki_silent_subca_log} ] ; then + printf " Removing old '${pki_silent_subca_log}' . . . " + rm ${pki_silent_subca_log} + printf "done.\n" +fi +printf "Done.\n\n" + + + +############################################################################## +## C A L C U L A T E P K I I N S T A N C E P I N S ## +############################################################################## + +## PKI Subsystem Instance PINS +subca_preop_pin=`cat /var/lib/${subca_instance_name}/conf/CS.cfg \ + | grep preop.pin | grep -v grep | awk -F= '{print $2}'` + + + +############################################################################## +## C E R T I F I C A T E A U T H O R I T Y ## +############################################################################## +## +## For example, upon completion, +## execute '/sbin/service ${subca_init_script} status ${subca_instance_name}': +## +## ${subca_instance_name} (pid 7843) is running ... +## +## Unsecure Port = http://${pki_host}:9180/ca/ee/ca +## Secure Agent Port = https://${pki_host}:9443/ca/agent/ca +## Secure EE Port = https://${pki_host}:9444/ca/ee/ca +## Secure Admin Port = https://${pki_host}:9445/ca/services +## PKI Console Port = pkiconsole https://${pki_host}:9445/ca +## Tomcat Port = 9701 (for shutdown) +## +## +## Security Domain URL: +## ================================================================== +## https://${pki_host}:9445 +## ================================================================== +## + +## Configure Subordinate CA +printf "'${subca_silent_script}': Configuring '${subca_instance_name}' . . .\n" +pkisilent ConfigureSubCA \ + -cs_hostname "${pki_host}" \ + -cs_port ${subca_admin_port} \ + -sd_hostname "${pki_security_domain_host}" \ + -sd_ssl_port ${ca_ee_port} \ + -sd_agent_port ${ca_agent_port} \ + -sd_admin_port ${ca_admin_port} \ + -sd_admin_name "${pki_security_domain_admin_name}" \ + -sd_admin_password ${pki_security_domain_admin_password} \ + -ca_hostname ${pki_security_domain_host} \ + -ca_port ${ca_nonssl_port} \ + -ca_ssl_port ${ca_ee_port} \ + -client_certdb_dir ${pki_silent_security_database_repository} \ + -client_certdb_pwd ${pki_silent_security_database_password} \ + -preop_pin ${subca_preop_pin} \ + -domain_name "${pki_security_domain_name}" \ + -admin_user ${pki_silent_admin_user} \ + -admin_email "${pki_silent_admin_email}" \ + -admin_password ${pki_silent_admin_password} \ + -agent_name ${subca_agent_name} \ + -ldap_host ${pki_ldap_host} \ + -ldap_port ${pki_ldap_port} \ + -bind_dn "${pki_bind_dn}" \ + -bind_password ${pki_bind_password} \ + -base_dn "${subca_base_dn}" \ + -db_name "${subca_db_name}" \ + -key_size ${subca_key_size} \ + -key_type ${subca_key_type} \ + -signing_algorithm ${subca_signing_algorithm} \ + -signing_signingalgorithm ${subca_signing_signingalgorithm} \ + -ocsp_signing_signingalgorithm ${subca_ocsp_signing_signingalgorithm} \ + -token_name ${subca_token_name} \ + -token_pwd ${subca_token_password} \ + -agent_key_size ${subca_agent_key_size} \ + -agent_key_type ${subca_agent_key_type} \ + -agent_cert_subject "${subca_agent_cert_subject}" \ + -backup_pwd ${subca_backup_password} \ + -subsystem_name "${ca_subsystem_name}" \ + -subca_sign_cert_subject_name "${subca_sign_cert_subject_name}" \ + -subca_subsystem_cert_subject_name "${subca_subsystem_cert_subject_name}" \ + -subca_ocsp_cert_subject_name "${subca_ocsp_cert_subject_name}" \ + -subca_server_cert_subject_name "${subca_server_cert_subject_name}" \ + -subca_audit_signing_cert_subject_name \ + "${subca_audit_signing_cert_subject_name}" \ + | tee ${pki_silent_subca_log} + +## Restart Subordinate CA +/sbin/service ${subca_init_script} restart ${subca_instance_name} + +exit 0 + |