From e0e0d90ebff497686991a933ae2f7db24e7d8e0f Mon Sep 17 00:00:00 2001 From: Apple Date: Thu, 10 Dec 2015 21:22:37 +0000 Subject: [PATCH] Security-57336.10.29.tar.gz --- CircleJoinRequested/CircleJoinRequested.1 | 79 - CircleJoinRequested/CircleJoinRequested.m | 30 +- ...com.apple.private.alloy.keychainsync.plist | Bin 373 -> 458 bytes ...ple.security.idskeychainsyncingproxy.plist | 2 + ...idskeychainsyncingproxy.entitlements.plist | 4 + Keychain/SyncViewController.m | 12 + ...com.apple.private.alloy.keychainsync.plist | Bin 373 -> 458 bytes ...ple.security.idskeychainsyncingproxy.plist | 6 +- ...idskeychainsyncingproxy.entitlements.plist | 17 +- .../KNAppDelegate.m | 2 +- OSX/Keychain/KDSecCircle.m | 11 + .../xcshareddata/xcschemes/secdtests.xcscheme | 4 + OSX/include/security_asn1 | 1 + OSX/include/security_asn1/SecAsn1Coder.c | 225 - OSX/include/security_asn1/SecAsn1Coder.h | 153 - OSX/include/security_asn1/SecAsn1Templates.c | 373 -- OSX/include/security_asn1/SecAsn1Templates.h | 135 - OSX/include/security_asn1/SecAsn1Types.h | 244 - OSX/include/security_asn1/SecNssCoder.cpp | 207 - OSX/include/security_asn1/SecNssCoder.h | 164 - OSX/include/security_asn1/X509Templates.c | 222 - OSX/include/security_asn1/X509Templates.h | 199 - OSX/include/security_asn1/asn1Templates.h | 33 - .../security_asn1/certExtensionTemplates.c | 322 -- .../security_asn1/certExtensionTemplates.h | 274 - OSX/include/security_asn1/csrTemplates.c | 69 - OSX/include/security_asn1/csrTemplates.h | 77 - OSX/include/security_asn1/keyTemplates.c | 225 - OSX/include/security_asn1/keyTemplates.h | 276 - OSX/include/security_asn1/nameTemplates.c | 262 - OSX/include/security_asn1/nameTemplates.h | 195 - OSX/include/security_asn1/nsprPortX.c | 250 - OSX/include/security_asn1/nssUtils.c | 68 - OSX/include/security_asn1/nssUtils.h | 54 - OSX/include/security_asn1/nssilckt.h | 220 - OSX/include/security_asn1/nssilock.h | 316 -- OSX/include/security_asn1/nsslocks.h | 67 - OSX/include/security_asn1/ocspTemplates.c | 298 - OSX/include/security_asn1/ocspTemplates.h | 337 -- OSX/include/security_asn1/oidsalg.c | 501 -- OSX/include/security_asn1/oidsalg.h | 167 - OSX/include/security_asn1/oidsattr.c | 506 -- OSX/include/security_asn1/oidsattr.h | 225 - OSX/include/security_asn1/oidsbase.h | 363 -- OSX/include/security_asn1/oidsocsp.c | 43 - OSX/include/security_asn1/oidsocsp.h | 51 - OSX/include/security_asn1/osKeyTemplates.c | 163 - OSX/include/security_asn1/osKeyTemplates.h | 208 - OSX/include/security_asn1/pkcs12Templates.c | 289 - OSX/include/security_asn1/pkcs12Templates.h | 284 - OSX/include/security_asn1/pkcs7Templates.c | 162 - OSX/include/security_asn1/pkcs7Templates.h | 165 - OSX/include/security_asn1/plarena.c | 423 -- OSX/include/security_asn1/plarena.h | 222 - OSX/include/security_asn1/plarenas.h | 126 - OSX/include/security_asn1/plstr.h | 467 -- OSX/include/security_asn1/prbit.h | 108 - OSX/include/security_asn1/prcpucfg.h | 192 - OSX/include/security_asn1/prcvar.h | 123 - OSX/include/security_asn1/prenv.h | 154 - OSX/include/security_asn1/prerr.h | 275 - OSX/include/security_asn1/prerror.h | 323 -- OSX/include/security_asn1/prinit.h | 240 - OSX/include/security_asn1/prinrval.h | 172 - OSX/include/security_asn1/prlock.h | 123 - OSX/include/security_asn1/prlog.h | 262 - OSX/include/security_asn1/prlong.h | 425 -- OSX/include/security_asn1/prmem.h | 156 - OSX/include/security_asn1/prmon.h | 110 - OSX/include/security_asn1/protypes.h | 251 - OSX/include/security_asn1/prthread.h | 283 - OSX/include/security_asn1/prtime.h | 295 - OSX/include/security_asn1/prtypes.h | 570 -- OSX/include/security_asn1/prvrsion.h | 134 - OSX/include/security_asn1/secErrorStr.c | 208 - OSX/include/security_asn1/secasn1.h | 219 - OSX/include/security_asn1/secasn1d.c | 3167 ----------- OSX/include/security_asn1/secasn1e.c | 1646 ------ OSX/include/security_asn1/secasn1t.h | 143 - OSX/include/security_asn1/secasn1u.c | 115 - OSX/include/security_asn1/seccomon.h | 125 - OSX/include/security_asn1/secerr.h | 206 - OSX/include/security_asn1/secport.c | 669 --- OSX/include/security_asn1/secport.h | 290 - OSX/include/security_asn1/security_asn1.exp | 166 - OSX/include/security_cdsa_client | 1 + OSX/include/security_cdsa_client/DLDBList.cpp | 53 - OSX/include/security_cdsa_client/DLDBList.h | 74 - .../security_cdsa_client/aclclient.cpp | 324 -- OSX/include/security_cdsa_client/aclclient.h | 199 - OSX/include/security_cdsa_client/clclient.cpp | 54 - OSX/include/security_cdsa_client/clclient.h | 75 - .../security_cdsa_client/cryptoclient.cpp | 143 - .../security_cdsa_client/cryptoclient.h | 116 - .../security_cdsa_client/cspclient.cpp | 264 - OSX/include/security_cdsa_client/cspclient.h | 269 - .../security_cdsa_client/cssmclient.cpp | 528 -- OSX/include/security_cdsa_client/cssmclient.h | 378 -- .../security_cdsa_client/dl_standard.cpp | 195 - .../security_cdsa_client/dl_standard.h | 167 - OSX/include/security_cdsa_client/dlclient.cpp | 905 --- OSX/include/security_cdsa_client/dlclient.h | 560 -- .../security_cdsa_client/dlclientpriv.cpp | 35 - .../security_cdsa_client/dliterators.cpp | 127 - .../security_cdsa_client/dliterators.h | 272 - OSX/include/security_cdsa_client/dlquery.cpp | 128 - OSX/include/security_cdsa_client/dlquery.h | 131 - OSX/include/security_cdsa_client/genkey.cpp | 94 - OSX/include/security_cdsa_client/genkey.h | 79 - .../security_cdsa_client/keychainacl.cpp | 133 - .../security_cdsa_client/keychainacl.h | 89 - .../security_cdsa_client/keyclient.cpp | 120 - OSX/include/security_cdsa_client/keyclient.h | 113 - .../security_cdsa_client/macclient.cpp | 102 - OSX/include/security_cdsa_client/macclient.h | 90 - .../security_cdsa_client/mds_standard.cpp | 228 - .../security_cdsa_client/mds_standard.h | 205 - .../security_cdsa_client/mdsclient.cpp | 158 - OSX/include/security_cdsa_client/mdsclient.h | 102 - .../security_cdsa_client/multidldb.cpp | 235 - OSX/include/security_cdsa_client/multidldb.h | 101 - .../security_cdsa_client/securestorage.cpp | 650 --- .../security_cdsa_client/securestorage.h | 343 -- .../security_cdsa_client/signclient.cpp | 97 - OSX/include/security_cdsa_client/signclient.h | 93 - OSX/include/security_cdsa_client/tpclient.cpp | 136 - OSX/include/security_cdsa_client/tpclient.h | 108 - OSX/include/security_cdsa_client/wrapkey.cpp | 193 - OSX/include/security_cdsa_client/wrapkey.h | 127 - OSX/include/security_cdsa_plugin | 1 + OSX/include/security_cdsa_plugin/ACsession.h | 52 - OSX/include/security_cdsa_plugin/CLsession.h | 51 - .../security_cdsa_plugin/CSPsession.cpp | 1156 ---- OSX/include/security_cdsa_plugin/CSPsession.h | 545 -- .../security_cdsa_plugin/DLsession.cpp | 57 - OSX/include/security_cdsa_plugin/DLsession.h | 57 - OSX/include/security_cdsa_plugin/Database.cpp | 232 - OSX/include/security_cdsa_plugin/Database.h | 248 - .../security_cdsa_plugin/DatabaseSession.cpp | 692 --- .../security_cdsa_plugin/DatabaseSession.h | 140 - .../security_cdsa_plugin/DbContext.cpp | 44 - OSX/include/security_cdsa_plugin/DbContext.h | 76 - OSX/include/security_cdsa_plugin/TPsession.h | 56 - OSX/include/security_cdsa_plugin/c++plugin.h | 42 - .../security_cdsa_plugin/csputilities.cpp | 152 - .../security_cdsa_plugin/cssmplugin.cpp | 184 - OSX/include/security_cdsa_plugin/cssmplugin.h | 130 - .../security_cdsa_plugin/generator.cfg | 59 - OSX/include/security_cdsa_plugin/generator.mk | 29 - OSX/include/security_cdsa_plugin/generator.pl | 247 - .../security_cdsa_plugin/pluginsession.cpp | 91 - .../security_cdsa_plugin/pluginsession.h | 92 - OSX/include/security_cdsa_plugin/pluginspi.h | 123 - OSX/include/security_cdsa_utilities | 1 + .../AuthorizationData.cpp | 362 -- .../AuthorizationData.h | 201 - .../AuthorizationWalkers.h | 82 - .../security_cdsa_utilities/KeySchema.h | 70 - .../security_cdsa_utilities/KeySchema.m4 | 129 - OSX/include/security_cdsa_utilities/Schema.h | 129 - OSX/include/security_cdsa_utilities/Schema.m4 | 471 -- .../security_cdsa_utilities/acl_any.cpp | 63 - OSX/include/security_cdsa_utilities/acl_any.h | 60 - .../acl_codesigning.cpp | 198 - .../security_cdsa_utilities/acl_codesigning.h | 95 - .../security_cdsa_utilities/acl_comment.cpp | 156 - .../security_cdsa_utilities/acl_comment.h | 71 - .../security_cdsa_utilities/acl_password.cpp | 114 - .../security_cdsa_utilities/acl_password.h | 75 - .../security_cdsa_utilities/acl_preauth.cpp | 238 - .../security_cdsa_utilities/acl_preauth.h | 132 - .../security_cdsa_utilities/acl_process.cpp | 157 - .../security_cdsa_utilities/acl_process.h | 93 - .../security_cdsa_utilities/acl_prompted.cpp | 130 - .../security_cdsa_utilities/acl_prompted.h | 85 - .../acl_protectedpw.cpp | 121 - .../security_cdsa_utilities/acl_protectedpw.h | 75 - .../security_cdsa_utilities/acl_secret.cpp | 127 - .../security_cdsa_utilities/acl_secret.h | 99 - .../security_cdsa_utilities/acl_threshold.cpp | 180 - .../security_cdsa_utilities/acl_threshold.h | 86 - .../security_cdsa_utilities/aclsubject.cpp | 160 - .../security_cdsa_utilities/aclsubject.h | 224 - .../security_cdsa_utilities/callback.cpp | 122 - .../security_cdsa_utilities/callback.h | 113 - .../security_cdsa_utilities/constdata.cpp | 44 - .../security_cdsa_utilities/constdata.h | 89 - .../security_cdsa_utilities/context.cpp | 189 - OSX/include/security_cdsa_utilities/context.h | 404 -- .../security_cdsa_utilities/cssmacl.cpp | 28 - OSX/include/security_cdsa_utilities/cssmacl.h | 63 - .../security_cdsa_utilities/cssmaclpod.cpp | 223 - .../security_cdsa_utilities/cssmaclpod.h | 356 -- .../security_cdsa_utilities/cssmalloc.cpp | 87 - .../security_cdsa_utilities/cssmalloc.h | 155 - .../security_cdsa_utilities/cssmbridge.h | 62 - .../security_cdsa_utilities/cssmcert.cpp | 88 - .../security_cdsa_utilities/cssmcert.h | 125 - .../security_cdsa_utilities/cssmcred.cpp | 112 - .../security_cdsa_utilities/cssmcred.h | 191 - .../security_cdsa_utilities/cssmdata.cpp | 248 - .../security_cdsa_utilities/cssmdata.h | 560 -- .../security_cdsa_utilities/cssmdates.cpp | 195 - .../security_cdsa_utilities/cssmdates.h | 127 - .../security_cdsa_utilities/cssmdb.cpp | 590 -- OSX/include/security_cdsa_utilities/cssmdb.h | 873 --- .../security_cdsa_utilities/cssmdbname.cpp | 149 - .../security_cdsa_utilities/cssmdbname.h | 131 - .../security_cdsa_utilities/cssmendian.cpp | 53 - .../security_cdsa_utilities/cssmendian.h | 50 - .../security_cdsa_utilities/cssmerrors.cpp | 129 - .../security_cdsa_utilities/cssmerrors.h | 68 - .../security_cdsa_utilities/cssmkey.cpp | 56 - OSX/include/security_cdsa_utilities/cssmkey.h | 151 - .../security_cdsa_utilities/cssmlist.cpp | 313 -- .../security_cdsa_utilities/cssmlist.h | 269 - .../security_cdsa_utilities/cssmpods.cpp | 179 - .../security_cdsa_utilities/cssmpods.h | 221 - .../security_cdsa_utilities/cssmtrust.cpp | 48 - .../security_cdsa_utilities/cssmtrust.h | 178 - .../security_cdsa_utilities/cssmwalkers.cpp | 28 - .../security_cdsa_utilities/cssmwalkers.h | 233 - OSX/include/security_cdsa_utilities/db++.cpp | 144 - OSX/include/security_cdsa_utilities/db++.h | 91 - .../security_cdsa_utilities/digestobject.h | 133 - .../security_cdsa_utilities/generator.mk | 26 - .../security_cdsa_utilities/generator.pl | 89 - .../security_cdsa_utilities/handleobject.cpp | 31 - .../security_cdsa_utilities/handleobject.h | 47 - .../handletemplates.cpp | 39 - .../security_cdsa_utilities/handletemplates.h | 290 - .../handletemplates_defs.h | 204 - .../security_cdsa_utilities/objectacl.cpp | 662 --- .../security_cdsa_utilities/objectacl.h | 250 - .../security_cdsa_utilities/osxverifier.cpp | 177 - .../security_cdsa_utilities/osxverifier.h | 93 - .../u32handleobject.cpp | 27 - .../security_cdsa_utilities/u32handleobject.h | 43 - .../security_cdsa_utilities/uniformrandom.cpp | 37 - .../security_cdsa_utilities/uniformrandom.h | 56 - .../security_cdsa_utilities/walkers.cpp | 47 - OSX/include/security_cdsa_utilities/walkers.h | 393 -- OSX/include/security_cdsa_utils | 1 + .../security_cdsa_utils/cuCdsaUtils.cpp | 778 --- OSX/include/security_cdsa_utils/cuCdsaUtils.h | 161 - OSX/include/security_cdsa_utils/cuDbUtils.cpp | 574 -- OSX/include/security_cdsa_utils/cuDbUtils.h | 71 - OSX/include/security_cdsa_utils/cuEnc64.c | 392 -- OSX/include/security_cdsa_utils/cuEnc64.h | 67 - OSX/include/security_cdsa_utils/cuFileIo.c | 113 - OSX/include/security_cdsa_utils/cuFileIo.h | 41 - .../security_cdsa_utils/cuOidParser.cpp | 315 -- OSX/include/security_cdsa_utils/cuOidParser.h | 62 - OSX/include/security_cdsa_utils/cuPem.cpp | 198 - OSX/include/security_cdsa_utils/cuPem.h | 50 - .../security_cdsa_utils/cuPrintCert.cpp | 1504 ----- OSX/include/security_cdsa_utils/cuPrintCert.h | 64 - OSX/include/security_cdsa_utils/cuTimeStr.cpp | 293 - OSX/include/security_cdsa_utils/cuTimeStr.h | 75 - OSX/include/security_codesigning | 1 + OSX/include/security_codesigning/CSCommon.h | 318 -- .../security_codesigning/CSCommonPriv.h | 131 - OSX/include/security_codesigning/Code.cpp | 285 - OSX/include/security_codesigning/Code.h | 89 - .../security_codesigning/CodeSigner.cpp | 308 - OSX/include/security_codesigning/CodeSigner.h | 106 - .../security_codesigning/CodeSigning.h | 37 - .../RequirementKeywords.h | 25 - .../security_codesigning/RequirementLexer.cpp | 1269 ----- .../security_codesigning/RequirementLexer.hpp | 77 - .../RequirementParser.cpp | 1331 ----- .../RequirementParser.hpp | 158 - .../RequirementParserTokenTypes.hpp | 76 - .../RequirementParserTokenTypes.txt | 56 - .../security_codesigning/Requirements.cpp | 92 - .../security_codesigning/Requirements.h | 64 - .../security_codesigning/SecAssessment.cpp | 544 -- .../security_codesigning/SecAssessment.h | 316 -- OSX/include/security_codesigning/SecCode.cpp | 316 -- OSX/include/security_codesigning/SecCode.h | 447 -- .../security_codesigning/SecCodeHost.cpp | 117 - .../security_codesigning/SecCodeHost.h | 244 - .../security_codesigning/SecCodeHostLib.c | 124 - .../security_codesigning/SecCodeHostLib.h | 110 - .../security_codesigning/SecCodePriv.h | 185 - .../security_codesigning/SecCodeSigner.cpp | 124 - .../security_codesigning/SecCodeSigner.h | 231 - .../security_codesigning/SecIntegrity.cpp | 26 - .../security_codesigning/SecIntegrity.h | 49 - .../security_codesigning/SecIntegrityLib.c | 23 - .../security_codesigning/SecIntegrityLib.h | 55 - .../security_codesigning/SecRequirement.cpp | 309 - .../security_codesigning/SecRequirement.h | 142 - .../security_codesigning/SecRequirementPriv.h | 197 - .../security_codesigning/SecStaticCode.cpp | 324 -- .../security_codesigning/SecStaticCode.h | 168 - .../security_codesigning/SecStaticCodePriv.h | 92 - OSX/include/security_codesigning/SecTask.c | 316 -- OSX/include/security_codesigning/SecTask.h | 113 - .../security_codesigning/SecTaskPriv.h | 56 - .../security_codesigning/StaticCode.cpp | 1798 ------ OSX/include/security_codesigning/StaticCode.h | 278 - .../security_codesigning/antlrplugin.cpp | 130 - .../security_codesigning/antlrplugin.h | 74 - .../security_codesigning/bundlediskrep.cpp | 691 --- .../security_codesigning/bundlediskrep.h | 138 - .../security_codesigning/cdbuilder.cpp | 259 - OSX/include/security_codesigning/cdbuilder.h | 100 - .../security_codesigning/codedirectory.cpp | 324 -- .../security_codesigning/codedirectory.h | 289 - OSX/include/security_codesigning/cs.cpp | 63 - OSX/include/security_codesigning/cs.h | 180 - OSX/include/security_codesigning/cscdefs.c | 4 - OSX/include/security_codesigning/cscdefs.h | 89 - .../security_codesigning/csdatabase.cpp | 180 - OSX/include/security_codesigning/csdatabase.h | 74 - OSX/include/security_codesigning/cserror.cpp | 88 - OSX/include/security_codesigning/cserror.h | 67 - .../security_codesigning/csgeneric.cpp | 218 - OSX/include/security_codesigning/csgeneric.h | 82 - OSX/include/security_codesigning/cskernel.cpp | 219 - OSX/include/security_codesigning/cskernel.h | 86 - .../security_codesigning/csprocess.cpp | 87 - OSX/include/security_codesigning/csprocess.h | 84 - .../security_codesigning/csutilities.cpp | 260 - .../security_codesigning/csutilities.h | 202 - .../security_codesigning/detachedrep.cpp | 103 - .../security_codesigning/detachedrep.h | 71 - .../security_codesigning/dirscanner.cpp | 200 - OSX/include/security_codesigning/dirscanner.h | 119 - OSX/include/security_codesigning/diskrep.cpp | 306 - OSX/include/security_codesigning/diskrep.h | 234 - OSX/include/security_codesigning/drmaker.cpp | 195 - OSX/include/security_codesigning/drmaker.h | 69 - .../evaluationmanager.cpp | 366 -- .../security_codesigning/evaluationmanager.h | 63 - .../security_codesigning/filediskrep.cpp | 191 - .../security_codesigning/filediskrep.h | 93 - .../security_codesigning/kerneldiskrep.cpp | 91 - .../security_codesigning/kerneldiskrep.h | 64 - OSX/include/security_codesigning/machorep.cpp | 409 -- OSX/include/security_codesigning/machorep.h | 104 - .../security_codesigning/opaquewhitelist.cpp | 269 - .../security_codesigning/opaquewhitelist.h | 60 - .../security_codesigning/piddiskrep.cpp | 170 - OSX/include/security_codesigning/piddiskrep.h | 70 - OSX/include/security_codesigning/policydb.cpp | 475 -- OSX/include/security_codesigning/policydb.h | 145 - .../security_codesigning/policyengine.cpp | 1106 ---- .../security_codesigning/policyengine.h | 101 - .../security_codesigning/quarantine++.cpp | 107 - .../security_codesigning/quarantine++.h | 77 - .../security_codesigning/reqdumper.cpp | 367 -- OSX/include/security_codesigning/reqdumper.h | 100 - .../security_codesigning/reqinterp.cpp | 583 -- OSX/include/security_codesigning/reqinterp.h | 92 - OSX/include/security_codesigning/reqmaker.cpp | 180 - OSX/include/security_codesigning/reqmaker.h | 135 - .../security_codesigning/reqparser.cpp | 125 - OSX/include/security_codesigning/reqparser.h | 66 - .../security_codesigning/reqreader.cpp | 91 - OSX/include/security_codesigning/reqreader.h | 86 - .../security_codesigning/requirement.cpp | 159 - .../security_codesigning/requirement.h | 215 - .../security_codesigning/resources.cpp | 363 -- OSX/include/security_codesigning/resources.h | 140 - .../security_codesigning.d | 98 - .../security_codesigning.exp | 176 - OSX/include/security_codesigning/sigblob.cpp | 67 - OSX/include/security_codesigning/sigblob.h | 81 - OSX/include/security_codesigning/signer.cpp | 670 --- OSX/include/security_codesigning/signer.h | 103 - .../security_codesigning/signerutils.cpp | 361 -- .../security_codesigning/signerutils.h | 201 - .../security_codesigning/singlediskrep.cpp | 139 - .../security_codesigning/singlediskrep.h | 91 - OSX/include/security_codesigning/slcrep.cpp | 171 - OSX/include/security_codesigning/slcrep.h | 94 - .../security_codesigning/syspolicy.sql | 204 - OSX/include/security_codesigning/xar++.cpp | 96 - OSX/include/security_codesigning/xar++.h | 66 - .../security_codesigning/xpcengine.cpp | 231 - OSX/include/security_codesigning/xpcengine.h | 45 - OSX/include/security_comcryption | 1 + OSX/include/security_comcryption/comDebug.h | 212 - .../security_comcryption/comcryptPriv.c | 540 -- .../security_comcryption/comcryptPriv.h | 492 -- .../security_comcryption/comcryption.c | 1438 ----- .../security_comcryption/comcryption.h | 175 - OSX/include/security_cryptkit | 1 + OSX/include/security_cryptkit/ByteRep.txt | 293 - OSX/include/security_cryptkit/CipherFileDES.c | 586 -- OSX/include/security_cryptkit/CipherFileDES.h | 67 - .../security_cryptkit/CipherFileFEED.c | 460 -- .../security_cryptkit/CipherFileFEED.h | 69 - .../security_cryptkit/CipherFileTypes.h | 83 - OSX/include/security_cryptkit/Crypt.h | 60 - OSX/include/security_cryptkit/CryptKit.def | 113 - OSX/include/security_cryptkit/CryptKit.h | 28 - .../security_cryptkit/CryptKitAsn1.cpp | 82 - OSX/include/security_cryptkit/CryptKitAsn1.h | 138 - OSX/include/security_cryptkit/CryptKitDER.cpp | 1244 ---- OSX/include/security_cryptkit/CryptKitDER.h | 198 - OSX/include/security_cryptkit/CryptKitSA.h | 23 - .../CurveParamDocs/FEEDaffine.nb | 253 - .../CurveParamDocs/FEEDsansY.nb | 324 -- .../security_cryptkit/CurveParamDocs/README | 62 - .../CurveParamDocs/curvegen.c | 105 - .../CurveParamDocs/curverecords.nb | 898 --- .../security_cryptkit/CurveParamDocs/disc.h | 312 - .../CurveParamDocs/ellproj.c | 448 -- .../CurveParamDocs/ellproj.h | 59 - .../security_cryptkit/CurveParamDocs/factor.c | 844 --- .../CurveParamDocs/fmodule.c | 410 -- .../CurveParamDocs/fmodule.h | 36 - .../security_cryptkit/CurveParamDocs/giants.c | 3517 ------------ .../security_cryptkit/CurveParamDocs/giants.h | 314 -- .../security_cryptkit/CurveParamDocs/schoof.c | 1100 ---- .../CurveParamDocs/schoofs.c | 1044 ---- .../security_cryptkit/CurveParamDocs/tools.c | 445 -- .../security_cryptkit/CurveParamDocs/tools.h | 65 - OSX/include/security_cryptkit/ECDSA_Profile.h | 90 - .../security_cryptkit/ECDSA_Verify_Prefix.h | 6 - .../security_cryptkit/HmacSha1Legacy.c | 165 - .../security_cryptkit/HmacSha1Legacy.h | 69 - OSX/include/security_cryptkit/Mathematica.FEE | 57 - OSX/include/security_cryptkit/NSCipherFile.h | 111 - OSX/include/security_cryptkit/NSCipherFile.m | 360 -- OSX/include/security_cryptkit/NSCryptors.h | 83 - OSX/include/security_cryptkit/NSDESCryptor.h | 39 - OSX/include/security_cryptkit/NSDESCryptor.m | 130 - .../security_cryptkit/NSFEEPublicKey.h | 74 - .../security_cryptkit/NSFEEPublicKey.m | 496 -- .../security_cryptkit/NSFEEPublicKeyPrivate.h | 36 - OSX/include/security_cryptkit/NSMD5Hash.h | 34 - OSX/include/security_cryptkit/NSMD5Hash.m | 79 - .../NSRandomNumberGenerator.h | 36 - .../NSRandomNumberGenerator.m | 83 - OSX/include/security_cryptkit/README | 221 - OSX/include/security_cryptkit/TOP_README | 30 - OSX/include/security_cryptkit/buildSrcTree | 34 - OSX/include/security_cryptkit/byteRep.c | 476 -- OSX/include/security_cryptkit/byteRep.h | 80 - OSX/include/security_cryptkit/changes | 222 - OSX/include/security_cryptkit/ckDES.c | 545 -- OSX/include/security_cryptkit/ckDES.h | 70 - OSX/include/security_cryptkit/ckMD5.c | 365 -- OSX/include/security_cryptkit/ckMD5.h | 90 - OSX/include/security_cryptkit/ckSHA1.c | 227 - OSX/include/security_cryptkit/ckSHA1.h | 75 - OSX/include/security_cryptkit/ckSHA1_priv.c | 321 -- OSX/include/security_cryptkit/ckSHA1_priv.h | 60 - OSX/include/security_cryptkit/ckconfig.h | 105 - OSX/include/security_cryptkit/ckutilities.c | 416 -- OSX/include/security_cryptkit/ckutilities.h | 47 - .../security_cryptkit/curveParamData.h | 540 -- .../security_cryptkit/curveParamDataOld.h | 350 -- OSX/include/security_cryptkit/curveParams.c | 1399 ----- OSX/include/security_cryptkit/curveParams.h | 230 - OSX/include/security_cryptkit/elliptic.c | 1437 ----- OSX/include/security_cryptkit/elliptic.h | 165 - .../security_cryptkit/ellipticMeasure.h | 85 - OSX/include/security_cryptkit/ellipticProj.c | 565 -- OSX/include/security_cryptkit/ellipticProj.h | 76 - OSX/include/security_cryptkit/enc64.c | 417 -- OSX/include/security_cryptkit/enc64.h | 65 - OSX/include/security_cryptkit/engineNSA127.c | 542 -- OSX/include/security_cryptkit/falloc.c | 109 - OSX/include/security_cryptkit/falloc.h | 47 - OSX/include/security_cryptkit/feeCipherFile.c | 280 - OSX/include/security_cryptkit/feeCipherFile.h | 164 - .../security_cryptkit/feeCipherFileAtom.c | 400 -- OSX/include/security_cryptkit/feeDES.c | 529 -- OSX/include/security_cryptkit/feeDES.h | 141 - OSX/include/security_cryptkit/feeDebug.h | 194 - .../security_cryptkit/feeDigitalSignature.c | 674 --- .../security_cryptkit/feeDigitalSignature.h | 111 - OSX/include/security_cryptkit/feeECDSA.c | 697 --- OSX/include/security_cryptkit/feeECDSA.h | 84 - OSX/include/security_cryptkit/feeFEED.c | 1233 ---- OSX/include/security_cryptkit/feeFEED.h | 140 - OSX/include/security_cryptkit/feeFEEDExp.c | 735 --- OSX/include/security_cryptkit/feeFEEDExp.h | 126 - OSX/include/security_cryptkit/feeFunctions.h | 69 - OSX/include/security_cryptkit/feeHash.c | 110 - OSX/include/security_cryptkit/feeHash.h | 81 - OSX/include/security_cryptkit/feePublicKey.c | 1612 ------ OSX/include/security_cryptkit/feePublicKey.h | 341 -- .../security_cryptkit/feePublicKeyPrivate.h | 43 - OSX/include/security_cryptkit/feeRandom.c | 206 - OSX/include/security_cryptkit/feeRandom.h | 49 - OSX/include/security_cryptkit/feeTypes.h | 174 - OSX/include/security_cryptkit/giantFFT.c | 519 -- OSX/include/security_cryptkit/giantIntegers.c | 1744 ------ OSX/include/security_cryptkit/giantIntegers.h | 162 - .../security_cryptkit/giantPortCommon.h | 46 - .../security_cryptkit/giantPort_Generic.h | 165 - OSX/include/security_cryptkit/giantPort_PPC.c | 236 - OSX/include/security_cryptkit/giantPort_PPC.h | 119 - .../security_cryptkit/giantPort_PPC_Gnu.h | 83 - .../security_cryptkit/giantPort_PPC_Gnu.s | 300 - .../security_cryptkit/giantPort_i486.h | 126 - .../security_cryptkit/giantPort_i486.s | 149 - OSX/include/security_cryptkit/mutils.h | 36 - OSX/include/security_cryptkit/mutils.m | 44 - OSX/include/security_cryptkit/platform.c | 197 - OSX/include/security_cryptkit/platform.h | 73 - OSX/include/security_cryptkit/unixMakefile | 102 - OSX/include/security_filedb | 1 + OSX/include/security_filedb/AppleDatabase.cpp | 2564 --------- OSX/include/security_filedb/AppleDatabase.h | 666 --- OSX/include/security_filedb/AtomicFile.cpp | 1262 ----- OSX/include/security_filedb/AtomicFile.h | 257 - OSX/include/security_filedb/DbIndex.cpp | 476 -- OSX/include/security_filedb/DbIndex.h | 198 - OSX/include/security_filedb/DbQuery.cpp | 30 - OSX/include/security_filedb/DbQuery.h | 45 - OSX/include/security_filedb/DbValue.cpp | 555 -- OSX/include/security_filedb/DbValue.h | 213 - OSX/include/security_filedb/MetaAttribute.cpp | 158 - OSX/include/security_filedb/MetaAttribute.h | 162 - OSX/include/security_filedb/MetaRecord.cpp | 580 -- OSX/include/security_filedb/MetaRecord.h | 176 - .../security_filedb/OverUnderflowCheck.h | 85 - .../security_filedb/ReadWriteSection.cpp | 57 - .../security_filedb/ReadWriteSection.h | 209 - .../security_filedb/SelectionPredicate.cpp | 51 - .../security_filedb/SelectionPredicate.h | 52 - OSX/include/security_keychain | 1 + OSX/include/security_keychain/ACL.cpp | 434 -- OSX/include/security_keychain/ACL.h | 157 - OSX/include/security_keychain/Access.cpp | 380 -- OSX/include/security_keychain/Access.h | 139 - .../AppleBaselineEscrowCertificates.h | 178 - OSX/include/security_keychain/CCallbackMgr.cp | 239 - OSX/include/security_keychain/CCallbackMgr.h | 102 - OSX/include/security_keychain/Certificate.cpp | 1471 ----- OSX/include/security_keychain/Certificate.h | 151 - .../security_keychain/CertificateRequest.cpp | 858 --- .../security_keychain/CertificateRequest.h | 154 - .../security_keychain/CertificateValues.cpp | 610 -- .../security_keychain/CertificateValues.h | 74 - .../security_keychain/DLDBListCFPref.cpp | 1079 ---- .../security_keychain/DLDBListCFPref.h | 222 - .../security_keychain/DynamicDLDBList.cpp | 235 - .../security_keychain/DynamicDLDBList.h | 74 - .../security_keychain/ExtendedAttribute.cpp | 192 - .../security_keychain/ExtendedAttribute.h | 90 - OSX/include/security_keychain/Globals.cpp | 73 - OSX/include/security_keychain/Globals.h | 75 - OSX/include/security_keychain/Identity.cpp | 135 - OSX/include/security_keychain/Identity.h | 68 - .../security_keychain/IdentityCursor.cpp | 351 -- .../security_keychain/IdentityCursor.h | 89 - OSX/include/security_keychain/Item.cpp | 1548 ----- OSX/include/security_keychain/Item.h | 213 - OSX/include/security_keychain/KCCursor.cpp | 308 - OSX/include/security_keychain/KCCursor.h | 86 - .../security_keychain/KCEventNotifier.cpp | 79 - .../security_keychain/KCEventNotifier.h | 60 - OSX/include/security_keychain/KCExceptions.h | 96 - OSX/include/security_keychain/KCUtilities.cpp | 30 - OSX/include/security_keychain/KCUtilities.h | 45 - OSX/include/security_keychain/KeyItem.cpp | 1420 ----- OSX/include/security_keychain/KeyItem.h | 141 - OSX/include/security_keychain/Keychains.cpp | 1332 ----- OSX/include/security_keychain/Keychains.h | 267 - .../security_keychain/MacOSErrorStrings.h | 61 - OSX/include/security_keychain/Password.cpp | 147 - OSX/include/security_keychain/Password.h | 81 - OSX/include/security_keychain/Policies.cpp | 361 -- OSX/include/security_keychain/Policies.h | 85 - .../security_keychain/PolicyCursor.cpp | 118 - OSX/include/security_keychain/PolicyCursor.h | 93 - OSX/include/security_keychain/PrimaryKey.cpp | 134 - OSX/include/security_keychain/PrimaryKey.h | 75 - OSX/include/security_keychain/SecACL.cpp | 294 - OSX/include/security_keychain/SecACL.h | 228 - OSX/include/security_keychain/SecAccess.cpp | 715 --- OSX/include/security_keychain/SecAccess.h | 221 - OSX/include/security_keychain/SecAccessPriv.h | 76 - OSX/include/security_keychain/SecAsn1TypesP.h | 241 - OSX/include/security_keychain/SecBase.cpp | 1120 ---- OSX/include/security_keychain/SecBase.h | 655 --- OSX/include/security_keychain/SecBase64P.c | 489 -- OSX/include/security_keychain/SecBase64P.h | 247 - OSX/include/security_keychain/SecBaseP.h | 91 - OSX/include/security_keychain/SecBasePriv.h | 92 - OSX/include/security_keychain/SecBridge.h | 90 - OSX/include/security_keychain/SecCFTypes.cpp | 70 - OSX/include/security_keychain/SecCFTypes.h | 107 - .../security_keychain/SecCertificate.cpp | 1538 ----- .../security_keychain/SecCertificate.h | 480 -- .../SecCertificateBundle.cpp | 82 - .../security_keychain/SecCertificateBundle.h | 77 - .../SecCertificateInternalP.h | 312 - .../security_keychain/SecCertificateOIDs.h | 172 - .../security_keychain/SecCertificateP.c | 4743 ---------------- .../security_keychain/SecCertificateP.h | 114 - .../security_keychain/SecCertificatePriv.h | 308 - .../security_keychain/SecCertificatePrivP.h | 176 - .../SecCertificateRequest.cpp | 190 - .../security_keychain/SecCertificateRequest.h | 191 - OSX/include/security_keychain/SecExport.cpp | 340 -- .../security_keychain/SecExternalRep.cpp | 541 -- .../security_keychain/SecExternalRep.h | 181 - .../SecFDERecoveryAsymmetricCrypto.cpp | 188 - .../SecFDERecoveryAsymmetricCrypto.h | 63 - OSX/include/security_keychain/SecFrameworkP.c | 274 - OSX/include/security_keychain/SecFrameworkP.h | 64 - OSX/include/security_keychain/SecIdentity.cpp | 1152 ---- OSX/include/security_keychain/SecIdentity.h | 204 - .../security_keychain/SecIdentityPriv.h | 152 - .../security_keychain/SecIdentitySearch.cpp | 118 - .../security_keychain/SecIdentitySearch.h | 91 - .../security_keychain/SecIdentitySearchPriv.h | 87 - OSX/include/security_keychain/SecImport.cpp | 412 -- .../security_keychain/SecImportExport.c | 335 -- .../security_keychain/SecImportExport.h | 683 --- .../security_keychain/SecImportExportAgg.cpp | 897 --- .../security_keychain/SecImportExportAgg.h | 82 - .../SecImportExportCrypto.cpp | 744 --- .../security_keychain/SecImportExportCrypto.h | 123 - .../SecImportExportOpenSSH.cpp | 633 --- .../SecImportExportOpenSSH.h | 80 - .../security_keychain/SecImportExportPem.cpp | 504 -- .../security_keychain/SecImportExportPem.h | 71 - .../SecImportExportPkcs8.cpp | 978 ---- .../security_keychain/SecImportExportPkcs8.h | 63 - .../SecImportExportUtils.cpp | 972 ---- .../security_keychain/SecImportExportUtils.h | 219 - OSX/include/security_keychain/SecInternal.h | 67 - OSX/include/security_keychain/SecInternalP.h | 67 - OSX/include/security_keychain/SecItem.cpp | 4998 ----------------- OSX/include/security_keychain/SecItem.h | 1163 ---- .../security_keychain/SecItemConstants.c | 236 - OSX/include/security_keychain/SecItemPriv.h | 395 -- OSX/include/security_keychain/SecKey.cpp | 2288 -------- OSX/include/security_keychain/SecKey.h | 612 -- OSX/include/security_keychain/SecKeyPriv.h | 397 -- OSX/include/security_keychain/SecKeychain.cpp | 1283 ----- OSX/include/security_keychain/SecKeychain.h | 626 --- .../SecKeychainAddIToolsPassword.cpp | 105 - .../security_keychain/SecKeychainItem.cpp | 912 --- .../security_keychain/SecKeychainItem.h | 332 -- .../SecKeychainItemExtendedAttributes.cpp | 367 -- .../SecKeychainItemExtendedAttributes.h | 126 - .../security_keychain/SecKeychainItemPriv.h | 164 - .../security_keychain/SecKeychainPriv.h | 128 - .../security_keychain/SecKeychainSearch.cpp | 129 - .../security_keychain/SecKeychainSearch.h | 80 - .../security_keychain/SecKeychainSearchPriv.h | 57 - .../SecNetscapeTemplates.cpp | 69 - .../security_keychain/SecNetscapeTemplates.h | 93 - OSX/include/security_keychain/SecPassword.cpp | 264 - OSX/include/security_keychain/SecPassword.h | 95 - .../security_keychain/SecPkcs8Templates.cpp | 94 - .../security_keychain/SecPkcs8Templates.h | 110 - OSX/include/security_keychain/SecPolicy.cpp | 963 ---- OSX/include/security_keychain/SecPolicy.h | 424 -- OSX/include/security_keychain/SecPolicyPriv.h | 229 - .../security_keychain/SecPolicySearch.cpp | 111 - .../security_keychain/SecPolicySearch.h | 87 - OSX/include/security_keychain/SecRSAKeyP.h | 60 - OSX/include/security_keychain/SecRandom.c | 63 - OSX/include/security_keychain/SecRandom.h | 71 - OSX/include/security_keychain/SecRandomP.h | 58 - .../security_keychain/SecRecoveryPassword.c | 478 -- .../security_keychain/SecRecoveryPassword.h | 106 - OSX/include/security_keychain/SecTrust.cpp | 1297 ----- OSX/include/security_keychain/SecTrust.h | 700 --- OSX/include/security_keychain/SecTrustPriv.h | 181 - .../security_keychain/SecTrustSettings.cpp | 1030 ---- .../security_keychain/SecTrustSettings.h | 322 -- .../SecTrustSettingsCertificates.h | 285 - .../security_keychain/SecTrustSettingsPriv.h | 143 - .../SecTrustedApplication.cpp | 213 - .../security_keychain/SecTrustedApplication.h | 85 - .../SecTrustedApplicationPriv.h | 175 - .../security_keychain/SecWrappedKeys.cpp | 494 -- OSX/include/security_keychain/Security.h | 106 - .../security_keychain/StorageManager.cpp | 1975 ------- .../security_keychain/StorageManager.h | 183 - OSX/include/security_keychain/Trust.cpp | 943 ---- OSX/include/security_keychain/Trust.h | 191 - .../security_keychain/TrustAdditions.cpp | 1250 ----- .../security_keychain/TrustAdditions.h | 52 - OSX/include/security_keychain/TrustItem.cpp | 192 - OSX/include/security_keychain/TrustItem.h | 81 - .../security_keychain/TrustKeychains.h | 55 - .../security_keychain/TrustRevocation.cpp | 732 --- .../security_keychain/TrustSettings.cpp | 1585 ------ OSX/include/security_keychain/TrustSettings.h | 256 - .../security_keychain/TrustSettingsSchema.h | 150 - .../security_keychain/TrustSettingsUtils.cpp | 98 - .../security_keychain/TrustSettingsUtils.h | 57 - OSX/include/security_keychain/TrustStore.cpp | 261 - OSX/include/security_keychain/TrustStore.h | 79 - .../security_keychain/TrustedApplication.cpp | 174 - .../security_keychain/TrustedApplication.h | 79 - .../security_keychain/UnlockReferralItem.cpp | 127 - .../security_keychain/UnlockReferralItem.h | 66 - .../security_keychain/certextensionsP.h | 546 -- .../security_keychain/cssmdatetime.cpp | 465 -- OSX/include/security_keychain/cssmdatetime.h | 67 - .../security_keychain/defaultcreds.cpp | 195 - OSX/include/security_keychain/defaultcreds.h | 78 - .../security_keychain/generateErrStrings.pl | 98 - .../security_keychain/security_keychain.exp | 761 --- .../security_keychain/tsaDERUtilities.c | 121 - .../security_keychain/tsaDERUtilities.h | 45 - OSX/include/security_ocspd | 1 + OSX/include/security_ocspd/ocspExtensions.cpp | 200 - OSX/include/security_ocspd/ocspExtensions.h | 179 - OSX/include/security_ocspd/ocspResponse.cpp | 562 -- OSX/include/security_ocspd/ocspResponse.h | 229 - OSX/include/security_ocspd/ocspdClient.h | 152 - OSX/include/security_ocspd/ocspdDbSchema.cpp | 54 - OSX/include/security_ocspd/ocspdDbSchema.h | 106 - OSX/include/security_ocspd/ocspdDebug.h | 66 - OSX/include/security_ocspd/ocspdTypes.h | 42 - OSX/include/security_ocspd/ocspdUtils.cpp | 417 -- OSX/include/security_ocspd/ocspdUtils.h | 111 - OSX/include/security_pkcs12 | 1 + OSX/include/security_pkcs12/SecPkcs12.cpp | 914 --- OSX/include/security_pkcs12/SecPkcs12.h | 571 -- .../security_pkcs12/pkcs12BagAttrs.cpp | 164 - OSX/include/security_pkcs12/pkcs12BagAttrs.h | 123 - OSX/include/security_pkcs12/pkcs12Coder.cpp | 414 -- OSX/include/security_pkcs12/pkcs12Coder.h | 419 -- OSX/include/security_pkcs12/pkcs12Crypto.cpp | 647 --- OSX/include/security_pkcs12/pkcs12Crypto.h | 172 - OSX/include/security_pkcs12/pkcs12Debug.h | 48 - OSX/include/security_pkcs12/pkcs12Decode.cpp | 532 -- OSX/include/security_pkcs12/pkcs12Encode.cpp | 497 -- .../security_pkcs12/pkcs12Keychain.cpp | 458 -- OSX/include/security_pkcs12/pkcs12SafeBag.cpp | 528 -- OSX/include/security_pkcs12/pkcs12SafeBag.h | 297 - .../security_pkcs12/pkcs12Templates.cpp | 293 - OSX/include/security_pkcs12/pkcs12Templates.h | 286 - OSX/include/security_pkcs12/pkcs12Utils.cpp | 832 --- OSX/include/security_pkcs12/pkcs12Utils.h | 186 - .../security_pkcs12/pkcs7Templates.cpp | 162 - OSX/include/security_pkcs12/pkcs7Templates.h | 167 - OSX/include/security_pkcs12/pkcsoids.cpp | 35 - OSX/include/security_pkcs12/pkcsoids.h | 45 - OSX/include/security_smime | 1 + OSX/include/security_smime/SecCMS.c | 140 - OSX/include/security_smime/SecCMS.h | 43 - OSX/include/security_smime/SecCmsBase.h | 511 -- .../security_smime/SecCmsContentInfo.h | 212 - OSX/include/security_smime/SecCmsDecoder.h | 143 - .../security_smime/SecCmsDigestContext.h | 78 - .../security_smime/SecCmsDigestedData.h | 77 - OSX/include/security_smime/SecCmsEncoder.h | 129 - .../security_smime/SecCmsEncryptedData.h | 76 - .../security_smime/SecCmsEnvelopedData.h | 80 - OSX/include/security_smime/SecCmsMessage.h | 163 - .../security_smime/SecCmsRecipientInfo.h | 81 - OSX/include/security_smime/SecCmsSignedData.h | 197 - OSX/include/security_smime/SecCmsSignerInfo.h | 263 - OSX/include/security_smime/SecSMIME.h | 56 - OSX/include/security_smime/SecSMIMEPriv.h | 170 - OSX/include/security_smime/cert.c | 854 --- OSX/include/security_smime/cert.h | 132 - OSX/include/security_smime/cmsarray.c | 227 - OSX/include/security_smime/cmsasn1.c | 599 -- OSX/include/security_smime/cmsattr.c | 451 -- OSX/include/security_smime/cmscinfo.c | 420 -- OSX/include/security_smime/cmscipher.c | 1199 ---- OSX/include/security_smime/cmsdecode.c | 735 --- OSX/include/security_smime/cmsdigdata.c | 229 - OSX/include/security_smime/cmsdigest.c | 290 - OSX/include/security_smime/cmsencdata.c | 294 - OSX/include/security_smime/cmsencode.c | 785 --- OSX/include/security_smime/cmsenvdata.c | 440 -- OSX/include/security_smime/cmslocal.h | 346 -- OSX/include/security_smime/cmsmessage.c | 362 -- OSX/include/security_smime/cmspriv.h | 510 -- OSX/include/security_smime/cmspubkey.c | 1449 ----- OSX/include/security_smime/cmsrecinfo.c | 716 --- OSX/include/security_smime/cmsreclist.c | 237 - OSX/include/security_smime/cmsreclist.h | 57 - OSX/include/security_smime/cmssigdata.c | 1203 ---- OSX/include/security_smime/cmssiginfo.c | 1439 ----- OSX/include/security_smime/cmstpriv.h | 502 -- OSX/include/security_smime/cmsutil.c | 416 -- OSX/include/security_smime/cryptohi.c | 552 -- OSX/include/security_smime/cryptohi.h | 143 - OSX/include/security_smime/plhash.c | 538 -- OSX/include/security_smime/plhash.h | 164 - OSX/include/security_smime/secalgid.c | 172 - OSX/include/security_smime/secitem.c | 304 - OSX/include/security_smime/secitem.h | 117 - OSX/include/security_smime/secoid.c | 1490 ----- OSX/include/security_smime/secoid.h | 118 - OSX/include/security_smime/secoidt.h | 61 - OSX/include/security_smime/security_smime.exp | 133 - OSX/include/security_smime/siginfoUtils.cpp | 62 - OSX/include/security_smime/smimeutil.c | 802 --- OSX/include/security_smime/testcms | 43 - OSX/include/security_smime/tsaSupport.c | 1412 ----- OSX/include/security_smime/tsaSupport.h | 54 - OSX/include/security_smime/tsaSupportPriv.h | 60 - OSX/include/security_smime/tsaTemplates.c | 255 - OSX/include/security_smime/tsaTemplates.h | 129 - OSX/include/security_utilities | 1 + OSX/include/security_utilities/adornments.cpp | 93 - OSX/include/security_utilities/adornments.h | 202 - OSX/include/security_utilities/alloc.cpp | 159 - OSX/include/security_utilities/alloc.h | 240 - OSX/include/security_utilities/blob.cpp | 134 - OSX/include/security_utilities/blob.h | 208 - OSX/include/security_utilities/bufferfifo.cpp | 94 - OSX/include/security_utilities/bufferfifo.h | 76 - OSX/include/security_utilities/buffers.cpp | 106 - OSX/include/security_utilities/buffers.h | 162 - OSX/include/security_utilities/ccaudit.cpp | 152 - OSX/include/security_utilities/ccaudit.h | 189 - OSX/include/security_utilities/cfclass.cpp | 258 - OSX/include/security_utilities/cfclass.h | 55 - OSX/include/security_utilities/cfmach++.cpp | 129 - OSX/include/security_utilities/cfmach++.h | 71 - OSX/include/security_utilities/cfmunge.cpp | 596 -- OSX/include/security_utilities/cfmunge.h | 136 - .../security_utilities/cfutilities.cpp | 318 -- OSX/include/security_utilities/cfutilities.h | 636 --- .../security_utilities/coderepository.cpp | 90 - .../security_utilities/coderepository.h | 110 - OSX/include/security_utilities/crc.c | 61 - OSX/include/security_utilities/crc.h | 18 - OSX/include/security_utilities/daemon.cpp | 112 - OSX/include/security_utilities/daemon.h | 43 - OSX/include/security_utilities/debugging.cpp | 518 -- OSX/include/security_utilities/debugging.h | 129 - .../security_utilities/debugging_internal.cpp | 47 - .../security_utilities/debugging_internal.h | 61 - OSX/include/security_utilities/debugsupport.h | 210 - OSX/include/security_utilities/devrandom.cpp | 82 - OSX/include/security_utilities/devrandom.h | 67 - OSX/include/security_utilities/dispatch.cpp | 159 - OSX/include/security_utilities/dispatch.h | 126 - OSX/include/security_utilities/dtrace.mk | 2 - .../security_utilities/dyld_cache_format.h | 69 - OSX/include/security_utilities/dyldcache.cpp | 146 - OSX/include/security_utilities/dyldcache.h | 160 - OSX/include/security_utilities/endian.cpp | 33 - OSX/include/security_utilities/endian.h | 141 - OSX/include/security_utilities/errors.cpp | 178 - OSX/include/security_utilities/errors.h | 139 - OSX/include/security_utilities/exports | 1 - OSX/include/security_utilities/fdmover.cpp | 104 - OSX/include/security_utilities/fdmover.h | 93 - OSX/include/security_utilities/fdsel.cpp | 96 - OSX/include/security_utilities/fdsel.h | 80 - OSX/include/security_utilities/globalizer.cpp | 95 - OSX/include/security_utilities/globalizer.h | 208 - OSX/include/security_utilities/hashing.cpp | 66 - OSX/include/security_utilities/hashing.h | 186 - OSX/include/security_utilities/headermap.cpp | 150 - OSX/include/security_utilities/headermap.h | 93 - OSX/include/security_utilities/hosts.cpp | 151 - OSX/include/security_utilities/hosts.h | 82 - OSX/include/security_utilities/inetreply.cpp | 91 - OSX/include/security_utilities/inetreply.h | 100 - OSX/include/security_utilities/iodevices.cpp | 272 - OSX/include/security_utilities/iodevices.h | 166 - OSX/include/security_utilities/ip++.cpp | 381 -- OSX/include/security_utilities/ip++.h | 278 - OSX/include/security_utilities/kq++.cpp | 69 - OSX/include/security_utilities/kq++.h | 95 - OSX/include/security_utilities/ktracecodes.h | 144 - OSX/include/security_utilities/logging.cpp | 112 - OSX/include/security_utilities/logging.h | 73 - OSX/include/security_utilities/mach++.cpp | 456 -- OSX/include/security_utilities/mach++.h | 325 -- OSX/include/security_utilities/mach_notify.c | 552 -- OSX/include/security_utilities/mach_notify.h | 136 - OSX/include/security_utilities/macho++.cpp | 795 --- OSX/include/security_utilities/macho++.h | 241 - .../security_utilities/machrunloopserver.cpp | 111 - .../security_utilities/machrunloopserver.h | 80 - OSX/include/security_utilities/machserver.cpp | 606 -- OSX/include/security_utilities/machserver.h | 250 - OSX/include/security_utilities/memstreams.h | 168 - OSX/include/security_utilities/memutils.h | 124 - OSX/include/security_utilities/muscle++.cpp | 256 - OSX/include/security_utilities/muscle++.h | 198 - OSX/include/security_utilities/osxcode.cpp | 260 - OSX/include/security_utilities/osxcode.h | 136 - OSX/include/security_utilities/pcsc++.cpp | 414 -- OSX/include/security_utilities/pcsc++.h | 199 - OSX/include/security_utilities/powerwatch.cpp | 256 - OSX/include/security_utilities/powerwatch.h | 114 - OSX/include/security_utilities/refcount.h | 179 - .../security_utilities/seccfobject.cpp | 270 - OSX/include/security_utilities/seccfobject.h | 176 - .../security_utilities/security_utilities.d | 84 - .../security_utilities/security_utilities.h | 67 - OSX/include/security_utilities/selector.cpp | 204 - OSX/include/security_utilities/selector.h | 125 - .../security_utilities/simpleprefs.cpp | 496 -- OSX/include/security_utilities/simpleprefs.h | 206 - OSX/include/security_utilities/socks++.cpp | 162 - OSX/include/security_utilities/socks++.h | 222 - OSX/include/security_utilities/socks++4.cpp | 134 - OSX/include/security_utilities/socks++4.h | 86 - OSX/include/security_utilities/socks++5.cpp | 208 - OSX/include/security_utilities/socks++5.h | 125 - OSX/include/security_utilities/sqlite++.cpp | 442 -- OSX/include/security_utilities/sqlite++.h | 284 - OSX/include/security_utilities/streams.cpp | 144 - OSX/include/security_utilities/streams.h | 192 - OSX/include/security_utilities/superblob.cpp | 10 - OSX/include/security_utilities/superblob.h | 237 - OSX/include/security_utilities/threading.cpp | 266 - OSX/include/security_utilities/threading.h | 358 -- .../security_utilities/threading_internal.h | 125 - OSX/include/security_utilities/timeflow.cpp | 117 - OSX/include/security_utilities/timeflow.h | 162 - OSX/include/security_utilities/tqueue.cpp | 33 - OSX/include/security_utilities/tqueue.h | 141 - .../security_utilities/trackingallocator.cpp | 89 - .../security_utilities/trackingallocator.h | 65 - .../security_utilities/transactions.cpp | 54 - OSX/include/security_utilities/transactions.h | 107 - OSX/include/security_utilities/typedvalue.cpp | 38 - OSX/include/security_utilities/typedvalue.h | 86 - OSX/include/security_utilities/unix++.cpp | 536 -- OSX/include/security_utilities/unix++.h | 339 -- OSX/include/security_utilities/unixchild.cpp | 502 -- OSX/include/security_utilities/unixchild.h | 136 - OSX/include/security_utilities/url.cpp | 150 - OSX/include/security_utilities/url.h | 82 - OSX/include/security_utilities/utilities.cpp | 125 - OSX/include/security_utilities/utilities.h | 315 -- .../security_utilities/utility_config.h | 113 - OSX/include/security_utilities/vproc++.cpp | 55 - OSX/include/security_utilities/vproc++.h | 63 - OSX/include/securityd_client | 1 + .../securityd_client/SharedMemoryClient.cpp | 189 - .../securityd_client/SharedMemoryClient.h | 46 - .../securityd_client/SharedMemoryCommon.h | 43 - OSX/include/securityd_client/dictionary.cpp | 365 -- OSX/include/securityd_client/dictionary.h | 99 - .../securityd_client/eventlistener.cpp | 310 - OSX/include/securityd_client/eventlistener.h | 62 - OSX/include/securityd_client/handletypes.h | 86 - OSX/include/securityd_client/sec_xdr.c | 293 - OSX/include/securityd_client/sec_xdr.h | 70 - OSX/include/securityd_client/sec_xdr_array.c | 170 - .../securityd_client/sec_xdr_reference.c | 158 - OSX/include/securityd_client/sec_xdr_sizeof.c | 217 - OSX/include/securityd_client/sec_xdrmem.c | 287 - OSX/include/securityd_client/ss_types.h | 105 - OSX/include/securityd_client/ssblob.cpp | 80 - OSX/include/securityd_client/ssblob.h | 224 - OSX/include/securityd_client/ssclient.cpp | 223 - OSX/include/securityd_client/ssclient.h | 450 -- OSX/include/securityd_client/sscommon.h | 104 - OSX/include/securityd_client/ssnotify.h | 118 - OSX/include/securityd_client/sstransit.cpp | 172 - OSX/include/securityd_client/sstransit.h | 139 - OSX/include/securityd_client/transition.cpp | 1045 ---- OSX/include/securityd_client/ucsp_types.h | 43 - OSX/include/securityd_client/xdr_auth.c | 83 - OSX/include/securityd_client/xdr_auth.h | 41 - OSX/include/securityd_client/xdr_cssm.c | 846 --- OSX/include/securityd_client/xdr_cssm.h | 222 - OSX/include/securityd_client/xdr_dldb.cpp | 56 - OSX/include/securityd_client/xdr_dldb.h | 74 - OSX/lib/AppWorkaround.plist | 60 + OSX/lib/security.exp-in | 2 + .../lib/tpCertGroup.cpp | 4 + .../lib/tpPolicies.cpp | 105 +- .../lib/tpPolicies.h | 3 +- OSX/libsecurity_asn1/Security | 1 + OSX/libsecurity_asn1/Security/SecAsn1Coder.c | 225 - OSX/libsecurity_asn1/Security/SecAsn1Coder.h | 153 - .../Security/SecAsn1Templates.c | 373 -- .../Security/SecAsn1Templates.h | 135 - OSX/libsecurity_asn1/Security/SecAsn1Types.h | 244 - OSX/libsecurity_asn1/Security/SecNssCoder.cpp | 207 - OSX/libsecurity_asn1/Security/SecNssCoder.h | 164 - OSX/libsecurity_asn1/Security/X509Templates.c | 222 - OSX/libsecurity_asn1/Security/X509Templates.h | 199 - OSX/libsecurity_asn1/Security/asn1Templates.h | 33 - .../Security/certExtensionTemplates.c | 322 -- .../Security/certExtensionTemplates.h | 274 - OSX/libsecurity_asn1/Security/csrTemplates.c | 69 - OSX/libsecurity_asn1/Security/csrTemplates.h | 77 - OSX/libsecurity_asn1/Security/keyTemplates.c | 225 - OSX/libsecurity_asn1/Security/keyTemplates.h | 276 - OSX/libsecurity_asn1/Security/nameTemplates.c | 262 - OSX/libsecurity_asn1/Security/nameTemplates.h | 195 - OSX/libsecurity_asn1/Security/nsprPortX.c | 250 - OSX/libsecurity_asn1/Security/nssUtils.c | 68 - OSX/libsecurity_asn1/Security/nssUtils.h | 54 - OSX/libsecurity_asn1/Security/nssilckt.h | 220 - OSX/libsecurity_asn1/Security/nssilock.h | 316 -- OSX/libsecurity_asn1/Security/nsslocks.h | 67 - OSX/libsecurity_asn1/Security/ocspTemplates.c | 298 - OSX/libsecurity_asn1/Security/ocspTemplates.h | 337 -- OSX/libsecurity_asn1/Security/oidsalg.c | 501 -- OSX/libsecurity_asn1/Security/oidsalg.h | 167 - OSX/libsecurity_asn1/Security/oidsattr.c | 506 -- OSX/libsecurity_asn1/Security/oidsattr.h | 225 - OSX/libsecurity_asn1/Security/oidsbase.h | 363 -- OSX/libsecurity_asn1/Security/oidsocsp.c | 43 - OSX/libsecurity_asn1/Security/oidsocsp.h | 51 - .../Security/osKeyTemplates.c | 163 - .../Security/osKeyTemplates.h | 208 - .../Security/pkcs12Templates.c | 289 - .../Security/pkcs12Templates.h | 284 - .../Security/pkcs7Templates.c | 162 - .../Security/pkcs7Templates.h | 165 - OSX/libsecurity_asn1/Security/plarena.c | 423 -- OSX/libsecurity_asn1/Security/plarena.h | 222 - OSX/libsecurity_asn1/Security/plarenas.h | 126 - OSX/libsecurity_asn1/Security/plstr.h | 467 -- OSX/libsecurity_asn1/Security/prbit.h | 108 - OSX/libsecurity_asn1/Security/prcpucfg.h | 192 - OSX/libsecurity_asn1/Security/prcvar.h | 123 - OSX/libsecurity_asn1/Security/prenv.h | 154 - OSX/libsecurity_asn1/Security/prerr.h | 275 - OSX/libsecurity_asn1/Security/prerror.h | 323 -- OSX/libsecurity_asn1/Security/prinit.h | 240 - OSX/libsecurity_asn1/Security/prinrval.h | 172 - OSX/libsecurity_asn1/Security/prlock.h | 123 - OSX/libsecurity_asn1/Security/prlog.h | 262 - OSX/libsecurity_asn1/Security/prlong.h | 425 -- OSX/libsecurity_asn1/Security/prmem.h | 156 - OSX/libsecurity_asn1/Security/prmon.h | 110 - OSX/libsecurity_asn1/Security/protypes.h | 251 - OSX/libsecurity_asn1/Security/prthread.h | 283 - OSX/libsecurity_asn1/Security/prtime.h | 295 - OSX/libsecurity_asn1/Security/prtypes.h | 570 -- OSX/libsecurity_asn1/Security/prvrsion.h | 134 - OSX/libsecurity_asn1/Security/secErrorStr.c | 208 - OSX/libsecurity_asn1/Security/secasn1.h | 219 - OSX/libsecurity_asn1/Security/secasn1d.c | 3167 ----------- OSX/libsecurity_asn1/Security/secasn1e.c | 1646 ------ OSX/libsecurity_asn1/Security/secasn1t.h | 143 - OSX/libsecurity_asn1/Security/secasn1u.c | 115 - OSX/libsecurity_asn1/Security/seccomon.h | 125 - OSX/libsecurity_asn1/Security/secerr.h | 206 - OSX/libsecurity_asn1/Security/secport.c | 669 --- OSX/libsecurity_asn1/Security/secport.h | 290 - .../Security/security_asn1.exp | 166 - OSX/libsecurity_asn1/lib/oidsalg.c | 13 +- OSX/libsecurity_asn1/lib/oidsalg.h | 9 +- OSX/libsecurity_asn1/lib/plarena.c | 24 +- OSX/libsecurity_asn1/lib/plarena.h | 18 +- OSX/libsecurity_asn1/lib/secasn1d.c | 118 +- OSX/libsecurity_asn1/security_asn1 | 1 + .../security_asn1/SecAsn1Coder.c | 225 - .../security_asn1/SecAsn1Coder.h | 153 - .../security_asn1/SecAsn1Templates.c | 373 -- .../security_asn1/SecAsn1Templates.h | 135 - .../security_asn1/SecAsn1Types.h | 244 - .../security_asn1/SecNssCoder.cpp | 207 - .../security_asn1/SecNssCoder.h | 164 - .../security_asn1/X509Templates.c | 222 - .../security_asn1/X509Templates.h | 199 - .../security_asn1/asn1Templates.h | 33 - .../security_asn1/certExtensionTemplates.c | 322 -- .../security_asn1/certExtensionTemplates.h | 274 - .../security_asn1/csrTemplates.c | 69 - .../security_asn1/csrTemplates.h | 77 - .../security_asn1/keyTemplates.c | 225 - .../security_asn1/keyTemplates.h | 276 - .../security_asn1/nameTemplates.c | 262 - .../security_asn1/nameTemplates.h | 195 - .../security_asn1/nsprPortX.c | 250 - OSX/libsecurity_asn1/security_asn1/nssUtils.c | 68 - OSX/libsecurity_asn1/security_asn1/nssUtils.h | 54 - OSX/libsecurity_asn1/security_asn1/nssilckt.h | 220 - OSX/libsecurity_asn1/security_asn1/nssilock.h | 316 -- OSX/libsecurity_asn1/security_asn1/nsslocks.h | 67 - .../security_asn1/ocspTemplates.c | 298 - .../security_asn1/ocspTemplates.h | 337 -- OSX/libsecurity_asn1/security_asn1/oidsalg.c | 501 -- OSX/libsecurity_asn1/security_asn1/oidsalg.h | 167 - OSX/libsecurity_asn1/security_asn1/oidsattr.c | 506 -- OSX/libsecurity_asn1/security_asn1/oidsattr.h | 225 - OSX/libsecurity_asn1/security_asn1/oidsbase.h | 363 -- OSX/libsecurity_asn1/security_asn1/oidsocsp.c | 43 - OSX/libsecurity_asn1/security_asn1/oidsocsp.h | 51 - .../security_asn1/osKeyTemplates.c | 163 - .../security_asn1/osKeyTemplates.h | 208 - .../security_asn1/pkcs12Templates.c | 289 - .../security_asn1/pkcs12Templates.h | 284 - .../security_asn1/pkcs7Templates.c | 162 - .../security_asn1/pkcs7Templates.h | 165 - OSX/libsecurity_asn1/security_asn1/plarena.c | 423 -- OSX/libsecurity_asn1/security_asn1/plarena.h | 222 - OSX/libsecurity_asn1/security_asn1/plarenas.h | 126 - OSX/libsecurity_asn1/security_asn1/plstr.h | 467 -- OSX/libsecurity_asn1/security_asn1/prbit.h | 108 - OSX/libsecurity_asn1/security_asn1/prcpucfg.h | 192 - OSX/libsecurity_asn1/security_asn1/prcvar.h | 123 - OSX/libsecurity_asn1/security_asn1/prenv.h | 154 - OSX/libsecurity_asn1/security_asn1/prerr.h | 275 - OSX/libsecurity_asn1/security_asn1/prerror.h | 323 -- OSX/libsecurity_asn1/security_asn1/prinit.h | 240 - OSX/libsecurity_asn1/security_asn1/prinrval.h | 172 - OSX/libsecurity_asn1/security_asn1/prlock.h | 123 - OSX/libsecurity_asn1/security_asn1/prlog.h | 262 - OSX/libsecurity_asn1/security_asn1/prlong.h | 425 -- OSX/libsecurity_asn1/security_asn1/prmem.h | 156 - OSX/libsecurity_asn1/security_asn1/prmon.h | 110 - OSX/libsecurity_asn1/security_asn1/protypes.h | 251 - OSX/libsecurity_asn1/security_asn1/prthread.h | 283 - OSX/libsecurity_asn1/security_asn1/prtime.h | 295 - OSX/libsecurity_asn1/security_asn1/prtypes.h | 570 -- OSX/libsecurity_asn1/security_asn1/prvrsion.h | 134 - .../security_asn1/secErrorStr.c | 208 - OSX/libsecurity_asn1/security_asn1/secasn1.h | 219 - OSX/libsecurity_asn1/security_asn1/secasn1d.c | 3167 ----------- OSX/libsecurity_asn1/security_asn1/secasn1e.c | 1646 ------ OSX/libsecurity_asn1/security_asn1/secasn1t.h | 143 - OSX/libsecurity_asn1/security_asn1/secasn1u.c | 115 - OSX/libsecurity_asn1/security_asn1/seccomon.h | 125 - OSX/libsecurity_asn1/security_asn1/secerr.h | 206 - OSX/libsecurity_asn1/security_asn1/secport.c | 669 --- OSX/libsecurity_asn1/security_asn1/secport.h | 290 - .../security_asn1/security_asn1.exp | 166 - OSX/libsecurity_cms/lib/CMSDecoder.cpp | 2 +- OSX/libsecurity_cryptkit/lib/feeECDSA.c | 8 + OSX/libsecurity_cssm/lib/oidsbase.h | 7 + OSX/libsecurity_cssm/lib/oidscert.cpp | 15 +- OSX/libsecurity_cssm/lib/oidscert.h | 3 +- OSX/libsecurity_filedb/lib/AtomicFile.cpp | 16 +- OSX/libsecurity_keychain/Security | 1 + OSX/libsecurity_keychain/Security/ACL.cpp | 434 -- OSX/libsecurity_keychain/Security/ACL.h | 157 - OSX/libsecurity_keychain/Security/Access.cpp | 380 -- OSX/libsecurity_keychain/Security/Access.h | 139 - .../AppleBaselineEscrowCertificates.h | 178 - .../Security/CCallbackMgr.cp | 239 - .../Security/CCallbackMgr.h | 102 - .../Security/Certificate.cpp | 1471 ----- .../Security/Certificate.h | 151 - .../Security/CertificateRequest.cpp | 858 --- .../Security/CertificateRequest.h | 154 - .../Security/CertificateValues.cpp | 610 -- .../Security/CertificateValues.h | 74 - .../Security/DLDBListCFPref.cpp | 1079 ---- .../Security/DLDBListCFPref.h | 222 - .../Security/DynamicDLDBList.cpp | 235 - .../Security/DynamicDLDBList.h | 74 - .../Security/ExtendedAttribute.cpp | 192 - .../Security/ExtendedAttribute.h | 90 - OSX/libsecurity_keychain/Security/Globals.cpp | 73 - OSX/libsecurity_keychain/Security/Globals.h | 75 - .../Security/Identity.cpp | 135 - OSX/libsecurity_keychain/Security/Identity.h | 68 - .../Security/IdentityCursor.cpp | 351 -- .../Security/IdentityCursor.h | 89 - OSX/libsecurity_keychain/Security/Item.cpp | 1548 ----- OSX/libsecurity_keychain/Security/Item.h | 213 - .../Security/KCCursor.cpp | 308 - OSX/libsecurity_keychain/Security/KCCursor.h | 86 - .../Security/KCEventNotifier.cpp | 79 - .../Security/KCEventNotifier.h | 60 - .../Security/KCExceptions.h | 96 - .../Security/KCUtilities.cpp | 30 - .../Security/KCUtilities.h | 45 - OSX/libsecurity_keychain/Security/KeyItem.cpp | 1420 ----- OSX/libsecurity_keychain/Security/KeyItem.h | 141 - .../Security/Keychains.cpp | 1332 ----- OSX/libsecurity_keychain/Security/Keychains.h | 267 - .../Security/MacOSErrorStrings.h | 61 - .../Security/Password.cpp | 147 - OSX/libsecurity_keychain/Security/Password.h | 81 - .../Security/Policies.cpp | 361 -- OSX/libsecurity_keychain/Security/Policies.h | 85 - .../Security/PolicyCursor.cpp | 118 - .../Security/PolicyCursor.h | 93 - .../Security/PrimaryKey.cpp | 134 - .../Security/PrimaryKey.h | 75 - OSX/libsecurity_keychain/Security/SecACL.cpp | 294 - OSX/libsecurity_keychain/Security/SecACL.h | 228 - .../Security/SecAccess.cpp | 715 --- OSX/libsecurity_keychain/Security/SecAccess.h | 221 - .../Security/SecAccessPriv.h | 76 - .../Security/SecAsn1TypesP.h | 241 - OSX/libsecurity_keychain/Security/SecBase.cpp | 1120 ---- OSX/libsecurity_keychain/Security/SecBase.h | 655 --- .../Security/SecBase64P.c | 489 -- .../Security/SecBase64P.h | 247 - OSX/libsecurity_keychain/Security/SecBaseP.h | 91 - .../Security/SecBasePriv.h | 92 - OSX/libsecurity_keychain/Security/SecBridge.h | 90 - .../Security/SecCFTypes.cpp | 70 - .../Security/SecCFTypes.h | 107 - .../Security/SecCertificate.cpp | 1538 ----- .../Security/SecCertificate.h | 480 -- .../Security/SecCertificateBundle.cpp | 82 - .../Security/SecCertificateBundle.h | 77 - .../Security/SecCertificateInternalP.h | 312 - .../Security/SecCertificateOIDs.h | 172 - .../Security/SecCertificateP.c | 4743 ---------------- .../Security/SecCertificateP.h | 114 - .../Security/SecCertificatePriv.h | 308 - .../Security/SecCertificatePrivP.h | 176 - .../Security/SecCertificateRequest.cpp | 190 - .../Security/SecCertificateRequest.h | 191 - .../Security/SecExport.cpp | 340 -- .../Security/SecExternalRep.cpp | 541 -- .../Security/SecExternalRep.h | 181 - .../SecFDERecoveryAsymmetricCrypto.cpp | 188 - .../Security/SecFDERecoveryAsymmetricCrypto.h | 63 - .../Security/SecFrameworkP.c | 274 - .../Security/SecFrameworkP.h | 64 - .../Security/SecIdentity.cpp | 1152 ---- .../Security/SecIdentity.h | 204 - .../Security/SecIdentityPriv.h | 152 - .../Security/SecIdentitySearch.cpp | 118 - .../Security/SecIdentitySearch.h | 91 - .../Security/SecIdentitySearchPriv.h | 87 - .../Security/SecImport.cpp | 412 -- .../Security/SecImportExport.c | 335 -- .../Security/SecImportExport.h | 683 --- .../Security/SecImportExportAgg.cpp | 897 --- .../Security/SecImportExportAgg.h | 82 - .../Security/SecImportExportCrypto.cpp | 744 --- .../Security/SecImportExportCrypto.h | 123 - .../Security/SecImportExportOpenSSH.cpp | 633 --- .../Security/SecImportExportOpenSSH.h | 80 - .../Security/SecImportExportPem.cpp | 504 -- .../Security/SecImportExportPem.h | 71 - .../Security/SecImportExportPkcs8.cpp | 978 ---- .../Security/SecImportExportPkcs8.h | 63 - .../Security/SecImportExportUtils.cpp | 972 ---- .../Security/SecImportExportUtils.h | 219 - .../Security/SecInternal.h | 67 - .../Security/SecInternalP.h | 67 - OSX/libsecurity_keychain/Security/SecItem.cpp | 4998 ----------------- OSX/libsecurity_keychain/Security/SecItem.h | 1163 ---- .../Security/SecItemConstants.c | 236 - .../Security/SecItemPriv.h | 395 -- OSX/libsecurity_keychain/Security/SecKey.cpp | 2288 -------- OSX/libsecurity_keychain/Security/SecKey.h | 612 -- .../Security/SecKeyPriv.h | 397 -- .../Security/SecKeychain.cpp | 1283 ----- .../Security/SecKeychain.h | 626 --- .../Security/SecKeychainAddIToolsPassword.cpp | 105 - .../Security/SecKeychainItem.cpp | 912 --- .../Security/SecKeychainItem.h | 332 -- .../SecKeychainItemExtendedAttributes.cpp | 367 -- .../SecKeychainItemExtendedAttributes.h | 126 - .../Security/SecKeychainItemPriv.h | 164 - .../Security/SecKeychainPriv.h | 128 - .../Security/SecKeychainSearch.cpp | 129 - .../Security/SecKeychainSearch.h | 80 - .../Security/SecKeychainSearchPriv.h | 57 - .../Security/SecNetscapeTemplates.cpp | 69 - .../Security/SecNetscapeTemplates.h | 93 - .../Security/SecPassword.cpp | 264 - .../Security/SecPassword.h | 95 - .../Security/SecPkcs8Templates.cpp | 94 - .../Security/SecPkcs8Templates.h | 110 - .../Security/SecPolicy.cpp | 963 ---- OSX/libsecurity_keychain/Security/SecPolicy.h | 424 -- .../Security/SecPolicyPriv.h | 229 - .../Security/SecPolicySearch.cpp | 111 - .../Security/SecPolicySearch.h | 87 - .../Security/SecRSAKeyP.h | 60 - OSX/libsecurity_keychain/Security/SecRandom.c | 63 - OSX/libsecurity_keychain/Security/SecRandom.h | 71 - .../Security/SecRandomP.h | 58 - .../Security/SecRecoveryPassword.c | 478 -- .../Security/SecRecoveryPassword.h | 106 - .../Security/SecTrust.cpp | 1297 ----- OSX/libsecurity_keychain/Security/SecTrust.h | 700 --- .../Security/SecTrustPriv.h | 181 - .../Security/SecTrustSettings.cpp | 1030 ---- .../Security/SecTrustSettings.h | 322 -- .../Security/SecTrustSettingsCertificates.h | 285 - .../Security/SecTrustSettingsPriv.h | 143 - .../Security/SecTrustedApplication.cpp | 213 - .../Security/SecTrustedApplication.h | 85 - .../Security/SecTrustedApplicationPriv.h | 175 - .../Security/SecWrappedKeys.cpp | 494 -- OSX/libsecurity_keychain/Security/Security.h | 106 - .../Security/StorageManager.cpp | 1975 ------- .../Security/StorageManager.h | 183 - OSX/libsecurity_keychain/Security/Trust.cpp | 943 ---- OSX/libsecurity_keychain/Security/Trust.h | 191 - .../Security/TrustAdditions.cpp | 1250 ----- .../Security/TrustAdditions.h | 52 - .../Security/TrustItem.cpp | 192 - OSX/libsecurity_keychain/Security/TrustItem.h | 81 - .../Security/TrustKeychains.h | 55 - .../Security/TrustRevocation.cpp | 732 --- .../Security/TrustSettings.cpp | 1585 ------ .../Security/TrustSettings.h | 256 - .../Security/TrustSettingsSchema.h | 150 - .../Security/TrustSettingsUtils.cpp | 98 - .../Security/TrustSettingsUtils.h | 57 - .../Security/TrustStore.cpp | 261 - .../Security/TrustStore.h | 79 - .../Security/TrustedApplication.cpp | 174 - .../Security/TrustedApplication.h | 79 - .../Security/UnlockReferralItem.cpp | 127 - .../Security/UnlockReferralItem.h | 66 - .../Security/certextensionsP.h | 546 -- .../Security/cssmdatetime.cpp | 465 -- .../Security/cssmdatetime.h | 67 - .../Security/defaultcreds.cpp | 195 - .../Security/defaultcreds.h | 78 - .../Security/generateErrStrings.pl | 98 - .../Security/security_keychain.exp | 761 --- .../Security/tsaDERUtilities.c | 121 - .../Security/tsaDERUtilities.h | 45 - .../lib/AppleBaselineEscrowCertificates.h | 70 +- OSX/libsecurity_keychain/lib/SecPolicy.cpp | 49 +- OSX/libsecurity_keychain/lib/SecPolicyPriv.h | 18 +- .../lib/SecTrustSettings.cpp | 3 + .../lib/SecTrustSettingsCertificates.h | 328 +- .../lib/security_keychain.exp | 2 + OSX/libsecurity_keychain/libDER/libDER/oids.c | 7 + OSX/libsecurity_keychain/libDER/libDER/oids.h | 4 +- .../libDER/libDER/oidsPriv.h | 1 + .../project.pbxproj | 6 + .../regressions/kc-41-sececkey.c | 24 +- .../regressions/keychain_regressions.h | 1 + .../regressions/si-20-sectrust-provisioning.c | 263 + .../regressions/si-20-sectrust-provisioning.h | 692 +++ OSX/libsecurity_ocspd/common/ocspdClient.h | 153 +- OSX/libsecurity_ssl/Security | 1 + OSX/libsecurity_ssl/Security/CipherSuite.h | 261 - .../Security/SSLRecordInternal.c | 392 -- .../Security/SSLRecordInternal.h | 45 - .../Security/SecureTransport.h | 1360 ----- .../Security/SecureTransportPriv.h | 842 --- OSX/libsecurity_ssl/Security/appleSession.c | 470 -- OSX/libsecurity_ssl/Security/appleSession.h | 55 - OSX/libsecurity_ssl/Security/cipherSpecs.h | 108 - OSX/libsecurity_ssl/Security/security_ssl.exp | 94 - OSX/libsecurity_ssl/Security/ssl.h | 36 - OSX/libsecurity_ssl/Security/sslBuildFlags.h | 101 - OSX/libsecurity_ssl/Security/sslCipherSpecs.c | 496 -- OSX/libsecurity_ssl/Security/sslCipherSpecs.h | 58 - OSX/libsecurity_ssl/Security/sslContext.c | 2644 --------- OSX/libsecurity_ssl/Security/sslContext.h | 288 - OSX/libsecurity_ssl/Security/sslCrypto.c | 625 --- OSX/libsecurity_ssl/Security/sslCrypto.h | 87 - OSX/libsecurity_ssl/Security/sslDebug.h | 131 - OSX/libsecurity_ssl/Security/sslKeychain.c | 251 - OSX/libsecurity_ssl/Security/sslKeychain.h | 53 - OSX/libsecurity_ssl/Security/sslMemory.c | 248 - OSX/libsecurity_ssl/Security/sslMemory.h | 74 - OSX/libsecurity_ssl/Security/sslPriv.h | 53 - OSX/libsecurity_ssl/Security/sslRecord.c | 124 - OSX/libsecurity_ssl/Security/sslRecord.h | 62 - OSX/libsecurity_ssl/Security/sslTransport.c | 538 -- OSX/libsecurity_ssl/Security/sslTypes.h | 167 - OSX/libsecurity_ssl/Security/sslUtils.c | 140 - OSX/libsecurity_ssl/Security/sslUtils.h | 82 - OSX/libsecurity_ssl/Security/tlsCallbacks.c | 254 - OSX/libsecurity_ssl/Security/tlsCallbacks.h | 32 - .../Security/tls_record_internal.h | 79 - OSX/libsecurity_ssl/security_ssl | 1 + .../security_ssl/CipherSuite.h | 261 - .../security_ssl/SSLRecordInternal.c | 392 -- .../security_ssl/SSLRecordInternal.h | 45 - .../security_ssl/SecureTransport.h | 1360 ----- .../security_ssl/SecureTransportPriv.h | 842 --- .../security_ssl/appleSession.c | 470 -- .../security_ssl/appleSession.h | 55 - .../security_ssl/cipherSpecs.h | 108 - .../security_ssl/security_ssl.exp | 94 - OSX/libsecurity_ssl/security_ssl/ssl.h | 36 - .../security_ssl/sslBuildFlags.h | 101 - .../security_ssl/sslCipherSpecs.c | 496 -- .../security_ssl/sslCipherSpecs.h | 58 - OSX/libsecurity_ssl/security_ssl/sslContext.c | 2644 --------- OSX/libsecurity_ssl/security_ssl/sslContext.h | 288 - OSX/libsecurity_ssl/security_ssl/sslCrypto.c | 625 --- OSX/libsecurity_ssl/security_ssl/sslCrypto.h | 87 - OSX/libsecurity_ssl/security_ssl/sslDebug.h | 131 - .../security_ssl/sslKeychain.c | 251 - .../security_ssl/sslKeychain.h | 53 - OSX/libsecurity_ssl/security_ssl/sslMemory.c | 248 - OSX/libsecurity_ssl/security_ssl/sslMemory.h | 74 - OSX/libsecurity_ssl/security_ssl/sslPriv.h | 53 - OSX/libsecurity_ssl/security_ssl/sslRecord.c | 124 - OSX/libsecurity_ssl/security_ssl/sslRecord.h | 62 - .../security_ssl/sslTransport.c | 538 -- OSX/libsecurity_ssl/security_ssl/sslTypes.h | 167 - OSX/libsecurity_ssl/security_ssl/sslUtils.c | 140 - OSX/libsecurity_ssl/security_ssl/sslUtils.h | 82 - .../security_ssl/tlsCallbacks.c | 254 - .../security_ssl/tlsCallbacks.h | 32 - .../security_ssl/tls_record_internal.h | 79 - OSX/sec/ProjectHeaders/SOSCircle/Tool | 1 + .../SOSCircle/Tool/SOSCommands.h | 81 - .../SOSCircle/Tool/keychain_sync.c | 1264 ----- OSX/sec/ProjectHeaders/Security/CKBridge | 1 + .../Security/CKBridge/CKClient.c | 493 -- .../Security/CKBridge/CKClient.h | 62 - .../CKBridge/SOSCloudKeychainClient.c | 771 --- .../CKBridge/SOSCloudKeychainClient.h | 124 - .../CKBridge/SOSCloudKeychainConstants.c | 109 - .../CKBridge/SOSCloudKeychainConstants.h | 92 - .../Security/CKBridge/SOSCloudTransport.c | 558 -- .../Security/CKBridge/SOSCloudTransport.h | 69 - .../ProjectHeaders/Security/SecureObjectSync | 1 + .../Security/SecureObjectSync/SOSARCDefines.h | 65 - .../Security/SecureObjectSync/SOSAccount.c | 1746 ------ .../Security/SecureObjectSync/SOSAccount.h | 263 - .../SecureObjectSync/SOSAccountBackup.c | 559 -- .../SecureObjectSync/SOSAccountCircles.c | 181 - .../SOSAccountCloudParameters.c | 85 - .../SecureObjectSync/SOSAccountCredentials.c | 322 -- .../Security/SecureObjectSync/SOSAccountDer.c | 183 - .../SecureObjectSync/SOSAccountFullPeerInfo.c | 199 - .../SecureObjectSync/SOSAccountHSAJoin.c | 99 - .../SecureObjectSync/SOSAccountHSAJoin.h | 19 - .../SecureObjectSync/SOSAccountPeers.c | 167 - .../SecureObjectSync/SOSAccountPersistence.c | 411 -- .../SecureObjectSync/SOSAccountPriv.h | 319 -- .../SecureObjectSync/SOSAccountRingUpdate.c | 370 -- .../SecureObjectSync/SOSAccountRings.c | 225 - .../SecureObjectSync/SOSAccountUpdate.c | 718 --- .../SecureObjectSync/SOSBackupEvent.c | 161 - .../SecureObjectSync/SOSBackupEvent.h | 41 - .../SecureObjectSync/SOSBackupSliceKeyBag.c | 431 -- .../SecureObjectSync/SOSBackupSliceKeyBag.h | 83 - .../SecureObjectSync/SOSChangeTracker.c | 249 - .../SecureObjectSync/SOSChangeTracker.h | 110 - .../Security/SecureObjectSync/SOSCircle.c | 1266 ----- .../Security/SecureObjectSync/SOSCircle.h | 158 - .../Security/SecureObjectSync/SOSCircleDer.c | 170 - .../Security/SecureObjectSync/SOSCircleDer.h | 14 - .../Security/SecureObjectSync/SOSCirclePriv.h | 49 - .../SecureObjectSync/SOSCircleRings.h | 30 - .../Security/SecureObjectSync/SOSCircleV2.c | 13 - .../Security/SecureObjectSync/SOSCircleV2.h | 26 - .../SecureObjectSync/SOSCloudCircle.c | 1140 ---- .../SecureObjectSync/SOSCloudCircle.h | 607 -- .../SecureObjectSync/SOSCloudCircleInternal.h | 121 - .../Security/SecureObjectSync/SOSCoder.c | 563 -- .../Security/SecureObjectSync/SOSCoder.h | 73 - .../SecureObjectSync/SOSConcordanceTrust.h | 30 - .../Security/SecureObjectSync/SOSDataSource.h | 255 - .../SecureObjectSync/SOSDigestVector.c | 428 -- .../SecureObjectSync/SOSDigestVector.h | 96 - .../SecureObjectSync/SOSECWrapUnwrap.c | 111 - .../Security/SecureObjectSync/SOSEngine.c | 2308 -------- .../Security/SecureObjectSync/SOSEngine.h | 143 - .../SecureObjectSync/SOSExports.exp-in | 308 - .../SecureObjectSync/SOSForerunnerSession.c | 1462 ----- .../SecureObjectSync/SOSForerunnerSession.h | 380 -- .../SecureObjectSync/SOSFullPeerInfo.c | 587 -- .../SecureObjectSync/SOSFullPeerInfo.h | 102 - .../Security/SecureObjectSync/SOSGenCount.c | 86 - .../Security/SecureObjectSync/SOSGenCount.h | 25 - .../Security/SecureObjectSync/SOSInternal.c | 280 - .../Security/SecureObjectSync/SOSInternal.h | 132 - .../Security/SecureObjectSync/SOSKVSKeys.c | 339 -- .../Security/SecureObjectSync/SOSKVSKeys.h | 75 - .../Security/SecureObjectSync/SOSManifest.c | 254 - .../Security/SecureObjectSync/SOSManifest.h | 101 - .../Security/SecureObjectSync/SOSMessage.c | 1184 ---- .../Security/SecureObjectSync/SOSMessage.h | 138 - .../Security/SecureObjectSync/SOSPeer.c | 1090 ---- .../Security/SecureObjectSync/SOSPeer.h | 140 - .../Security/SecureObjectSync/SOSPeerCoder.c | 124 - .../Security/SecureObjectSync/SOSPeerCoder.h | 23 - .../Security/SecureObjectSync/SOSPeerInfo.c | 921 --- .../Security/SecureObjectSync/SOSPeerInfo.h | 212 - .../SecureObjectSync/SOSPeerInfoCollections.c | 254 - .../SecureObjectSync/SOSPeerInfoCollections.h | 68 - .../SecureObjectSync/SOSPeerInfoDER.c | 152 - .../SecureObjectSync/SOSPeerInfoDER.h | 32 - .../SecureObjectSync/SOSPeerInfoInternal.h | 36 - .../SecureObjectSync/SOSPeerInfoPriv.h | 38 - .../SecureObjectSync/SOSPeerInfoRingState.c | 13 - .../SecureObjectSync/SOSPeerInfoRingState.h | 30 - .../SOSPeerInfoSecurityProperties.c | 146 - .../SOSPeerInfoSecurityProperties.h | 35 - .../Security/SecureObjectSync/SOSPeerInfoV2.c | 337 -- .../Security/SecureObjectSync/SOSPeerInfoV2.h | 53 - .../Security/SecureObjectSync/SOSPlatform.h | 25 - .../Security/SecureObjectSync/SOSRing.h | 91 - .../Security/SecureObjectSync/SOSRingBackup.c | 251 - .../Security/SecureObjectSync/SOSRingBackup.h | 17 - .../Security/SecureObjectSync/SOSRingBasic.c | 155 - .../Security/SecureObjectSync/SOSRingBasic.h | 16 - .../SOSRingConcordanceTrust.c | 185 - .../SOSRingConcordanceTrust.h | 14 - .../Security/SecureObjectSync/SOSRingDER.c | 115 - .../Security/SecureObjectSync/SOSRingDER.h | 14 - .../SecureObjectSync/SOSRingPeerInfoUtils.c | 41 - .../SecureObjectSync/SOSRingPeerInfoUtils.h | 14 - .../Security/SecureObjectSync/SOSRingTypes.c | 572 -- .../Security/SecureObjectSync/SOSRingTypes.h | 58 - .../Security/SecureObjectSync/SOSRingUtils.c | 931 --- .../Security/SecureObjectSync/SOSRingUtils.h | 146 - .../Security/SecureObjectSync/SOSRingV0.c | 151 - .../Security/SecureObjectSync/SOSRingV0.h | 14 - .../Security/SecureObjectSync/SOSTransport.c | 571 -- .../Security/SecureObjectSync/SOSTransport.h | 33 - .../SecureObjectSync/SOSTransportBackupPeer.c | 41 - .../SecureObjectSync/SOSTransportBackupPeer.h | 21 - .../SecureObjectSync/SOSTransportCircle.c | 112 - .../SecureObjectSync/SOSTransportCircle.h | 68 - .../SecureObjectSync/SOSTransportCircleKVS.c | 456 -- .../SecureObjectSync/SOSTransportCircleKVS.h | 27 - .../SecureObjectSync/SOSTransportCoder.c | 229 - .../SecureObjectSync/SOSTransportCoder.h | 21 - .../SOSTransportKeyParameter.c | 67 - .../SOSTransportKeyParameter.h | 37 - .../SOSTransportKeyParameterKVS.c | 138 - .../SOSTransportKeyParameterKVS.h | 16 - .../SecureObjectSync/SOSTransportMessage.c | 151 - .../SecureObjectSync/SOSTransportMessage.h | 60 - .../SecureObjectSync/SOSTransportMessageIDS.c | 331 -- .../SecureObjectSync/SOSTransportMessageIDS.h | 34 - .../SecureObjectSync/SOSTransportMessageKVS.c | 282 - .../SecureObjectSync/SOSTransportMessageKVS.h | 24 - .../Security/SecureObjectSync/SOSTypes.h | 100 - .../Security/SecureObjectSync/SOSUserKeygen.c | 350 -- .../Security/SecureObjectSync/SOSUserKeygen.h | 36 - .../SecureObjectSync/SOSViewManager.c | 190 - .../SecureObjectSync/SOSViewManager.h | 54 - .../SecureObjectSync/SOSViewQueries.c | 93 - .../SecureObjectSync/SOSViewQueries.h | 70 - .../Security/SecureObjectSync/SOSViews.c | 502 -- .../Security/SecureObjectSync/SOSViews.h | 85 - OSX/sec/ProjectHeaders/Security/Tool | 1 + .../Security/Tool/SecurityCommands.h | 146 - .../Security/Tool/add_internet_password.c | 186 - .../ProjectHeaders/Security/Tool/codesign.c | 427 -- .../Security/Tool/keychain_add.c | 133 - .../Security/Tool/keychain_backup.c | 173 - .../Security/Tool/keychain_find.c | 560 -- .../Security/Tool/keychain_util.c | 373 -- .../Security/Tool/keychain_util.h | 33 - .../Security/Tool/log_control.c | 192 - .../Security/Tool/pkcs12_util.c | 379 -- OSX/sec/ProjectHeaders/Security/Tool/scep.c | 608 -- .../Security/Tool/show_certificates.c | 293 - OSX/sec/ProjectHeaders/Security/Tool/spc.c | 727 --- OSX/sec/ProjectHeaders/SecurityTool | 1 + .../SecurityTool/SecurityTool.c | 405 -- .../SecurityTool/SecurityTool.h | 66 - .../SecurityTool/builtin_commands.h | 37 - .../ProjectHeaders/SecurityTool/digest_calc.c | 102 - .../SecurityTool/entitlements.plist | 17 - OSX/sec/ProjectHeaders/SecurityTool/leaks.c | 109 - OSX/sec/ProjectHeaders/SecurityTool/leaks.h | 37 - .../ProjectHeaders/SecurityTool/print_cert.c | 195 - .../ProjectHeaders/SecurityTool/print_cert.h | 42 - .../ProjectHeaders/SecurityTool/security.1 | 595 -- .../ProjectHeaders/SecurityTool/tool_errors.h | 76 - .../CKBridge/SOSCloudKeychainClient.c | 5 +- .../CKBridge/SOSCloudKeychainClient.h | 6 +- .../CloudKeychainProxy/CKDKVSProxy.m | 99 +- .../IDSKeychainSyncingProxy/IDSProxy.h | 11 +- .../IDSKeychainSyncingProxy/IDSProxy.m | 301 +- ...idskeychainsyncingproxy.entitlements.plist | 4 + .../idskeychainsyncingproxy.m | 2 +- OSX/sec/SOSCircle/Regressions/sc-40-circle.c | 69 +- .../Regressions/sc-42-circlegencount.c | 18 +- .../SOSCircle/SecureObjectSync/SOSAccount.c | 343 +- .../SOSCircle/SecureObjectSync/SOSAccount.h | 7 +- .../SecureObjectSync/SOSAccountBackup.c | 71 +- .../SecureObjectSync/SOSAccountCircles.c | 22 +- .../SecureObjectSync/SOSAccountCredentials.c | 167 +- .../SecureObjectSync/SOSAccountFullPeerInfo.c | 8 + .../SecureObjectSync/SOSAccountPeers.c | 10 + .../SecureObjectSync/SOSAccountPersistence.c | 4 + .../SecureObjectSync/SOSAccountPriv.h | 10 +- .../SecureObjectSync/SOSAccountRingUpdate.c | 32 +- .../SecureObjectSync/SOSAccountRings.c | 23 +- .../SecureObjectSync/SOSAccountUpdate.c | 33 +- .../SecureObjectSync/SOSBackupSliceKeyBag.c | 8 +- .../SOSCircle/SecureObjectSync/SOSCircle.c | 144 +- .../SOSCircle/SecureObjectSync/SOSCircle.h | 7 +- .../SecureObjectSync/SOSCirclePriv.h | 3 +- .../SecureObjectSync/SOSCloudCircle.c | 116 +- .../SecureObjectSync/SOSCloudCircle.h | 59 +- .../SOSCircle/SecureObjectSync/SOSEngine.c | 75 +- .../SecureObjectSync/SOSExports.exp-in | 12 +- .../SecureObjectSync/SOSForerunnerSession.c | 4 +- .../SecureObjectSync/SOSFullPeerInfo.c | 14 + .../SecureObjectSync/SOSFullPeerInfo.h | 4 + .../SOSCircle/SecureObjectSync/SOSGenCount.c | 15 + .../SOSCircle/SecureObjectSync/SOSGenCount.h | 2 + .../SOSCircle/SecureObjectSync/SOSManifest.c | 6 +- OSX/sec/SOSCircle/SecureObjectSync/SOSPeer.c | 12 +- .../SOSCircle/SecureObjectSync/SOSPeerInfo.c | 49 +- .../SOSCircle/SecureObjectSync/SOSPeerInfo.h | 8 + .../SecureObjectSync/SOSPeerInfoCollections.c | 14 + .../SecureObjectSync/SOSPeerInfoCollections.h | 1 + .../SecureObjectSync/SOSPeerInfoV2.c | 9 + .../SecureObjectSync/SOSPeerInfoV2.h | 4 + .../SecureObjectSync/SOSRingBackup.c | 9 +- .../SOSCircle/SecureObjectSync/SOSRingUtils.c | 18 +- .../SOSCircle/SecureObjectSync/SOSRingUtils.h | 5 +- .../SOSCircle/SecureObjectSync/SOSTransport.c | 33 +- .../SOSCircle/SecureObjectSync/SOSTransport.h | 3 +- .../SOSTransportKeyParameterKVS.c | 5 +- .../SecureObjectSync/SOSTransportMessageIDS.c | 97 +- .../SecureObjectSync/SOSTransportMessageIDS.h | 8 +- OSX/sec/SOSCircle/SecureObjectSync/SOSViews.c | 13 +- OSX/sec/SOSCircle/Tool/SOSCommands.h | 7 +- OSX/sec/SOSCircle/Tool/keychain_sync.c | 106 +- .../AppleBaselineEscrowCertificates.h | 70 +- .../Regressions/Security_regressions.h | 3 + .../Regressions/secitem/si-20-sectrust-att.c | 550 ++ .../secitem/si-81-sectrust-server-auth.c | 38 +- .../secitem/si-85-sectrust-ssl-policy.c | 248 + .../secitem/si-86-sectrust-eap-tls.c | 69 + .../secitem/si-86-sectrust-eap-tls.h | 158 + OSX/sec/Security/SecBasePriv.h | 1 + OSX/sec/Security/SecExports.exp-in | 5 + OSX/sec/Security/SecItem.c | 2 + OSX/sec/Security/SecPolicy.c | 128 +- OSX/sec/Security/SecPolicyPriv.h | 15 +- OSX/sec/Security/SecuritydXPC.c | 12 + OSX/sec/SharedWebCredential/swcagent_client.h | 3 +- OSX/sec/ipc/com.apple.securityd.plist | 11 + OSX/sec/ipc/securityd_client.h | 20 +- OSX/sec/ipc/server.c | 303 +- OSX/sec/sec.xcodeproj/project.pbxproj | 28 +- .../securityd/Regressions/SOSAccountTesting.h | 10 +- .../Regressions/SOSTransportTestTransports.c | 3 +- .../secd-52-offering-gencount-reset.c | 4 +- .../Regressions/secd-55-account-circle.c | 53 +- .../Regressions/secd-57-account-leave.c | 6 +- .../Regressions/secd-59-account-cleanup.c | 4 +- .../secd-60-account-cloud-identity.c | 4 +- ...d-61-account-leave-not-in-kansas-anymore.c | 6 +- .../Regressions/secd-62-account-backup.c | 12 +- .../secd-63-account-resurrection.c | 4 +- .../secd-65-account-retirement-reset.c | 191 + .../Regressions/secd-74-engine-beer-servers.c | 2 +- .../Regressions/secd-95-escrow-persistence.c | 175 + .../securityd/Regressions/secd_regressions.h | 2 + OSX/sec/securityd/SOSCloudCircleServer.c | 269 +- OSX/sec/securityd/SOSCloudCircleServer.h | 14 +- OSX/sec/securityd/SecItemDataSource.c | 24 +- OSX/sec/securityd/SecItemServer.c | 67 + OSX/sec/securityd/SecItemServer.h | 12 + OSX/sec/securityd/SecPolicyServer.c | 56 +- OSX/sec/securityd/iCloudTrace.c | 36 +- OSX/sec/securityd/iCloudTrace.h | 7 +- OSX/sec/securityd/nameconstraints.c | 109 +- OSX/sec/securityd/nameconstraints.h | 2 +- OSX/sec/securityd/spi.c | 8 +- OSX/utilities/Regressions/su-08-secbuffer.c | 10 +- OSX/utilities/src/debugging.h | 1 + OSX/utilities/src/iCloudKeychainTrace.c | 4 + OSX/utilities/utilities | 1 + OSX/utilities/utilities/SecAKSWrappers.c | 133 - OSX/utilities/utilities/SecAKSWrappers.h | 133 - OSX/utilities/utilities/SecAppleAnchor.c | 587 -- OSX/utilities/utilities/SecAppleAnchorPriv.h | 34 - OSX/utilities/utilities/SecBuffer.c | 37 - OSX/utilities/utilities/SecBuffer.h | 40 - OSX/utilities/utilities/SecCFCCWrappers.c | 43 - OSX/utilities/utilities/SecCFCCWrappers.h | 43 - OSX/utilities/utilities/SecCFError.c | 217 - OSX/utilities/utilities/SecCFError.h | 164 - OSX/utilities/utilities/SecCFRelease.h | 66 - OSX/utilities/utilities/SecCFWrappers.c | 240 - OSX/utilities/utilities/SecCFWrappers.h | 918 --- OSX/utilities/utilities/SecCertificateTrace.c | 549 -- OSX/utilities/utilities/SecCertificateTrace.h | 53 - OSX/utilities/utilities/SecCoreCrypto.c | 68 - OSX/utilities/utilities/SecCoreCrypto.h | 44 - OSX/utilities/utilities/SecDb.c | 1387 ----- OSX/utilities/utilities/SecDb.h | 167 - OSX/utilities/utilities/SecDispatchRelease.h | 74 - OSX/utilities/utilities/SecFileLocations.c | 263 - OSX/utilities/utilities/SecFileLocations.h | 48 - OSX/utilities/utilities/SecIOFormat.h | 103 - OSX/utilities/utilities/SecInternalRelease.c | 46 - .../utilities/SecInternalReleasePriv.h | 21 - OSX/utilities/utilities/SecMeta.h | 203 - OSX/utilities/utilities/SecSCTUtils.c | 65 - OSX/utilities/utilities/SecSCTUtils.h | 33 - OSX/utilities/utilities/SecXPCError.c | 104 - OSX/utilities/utilities/SecXPCError.h | 49 - OSX/utilities/utilities/array_size.h | 30 - .../utilities/cloud_keychain_diagnose.c | 1252 ----- OSX/utilities/utilities/comparison.c | 35 - OSX/utilities/utilities/comparison.h | 38 - OSX/utilities/utilities/debugging.c | 618 -- OSX/utilities/utilities/debugging.h | 157 - OSX/utilities/utilities/debugging_test.h | 32 - OSX/utilities/utilities/der_array.c | 91 - OSX/utilities/utilities/der_boolean.c | 70 - OSX/utilities/utilities/der_data.c | 103 - OSX/utilities/utilities/der_date.c | 409 -- OSX/utilities/utilities/der_date.h | 43 - OSX/utilities/utilities/der_dictionary.c | 244 - OSX/utilities/utilities/der_null.c | 66 - OSX/utilities/utilities/der_number.c | 138 - OSX/utilities/utilities/der_plist.c | 185 - OSX/utilities/utilities/der_plist.h | 62 - OSX/utilities/utilities/der_plist_internal.c | 34 - OSX/utilities/utilities/der_plist_internal.h | 137 - OSX/utilities/utilities/der_set.c | 186 - OSX/utilities/utilities/der_set.h | 27 - OSX/utilities/utilities/der_string.c | 94 - OSX/utilities/utilities/fileIo.c | 100 - OSX/utilities/utilities/fileIo.h | 26 - OSX/utilities/utilities/iCloudKeychainTrace.c | 455 -- OSX/utilities/utilities/iCloudKeychainTrace.h | 54 - OSX/utilities/utilities/iOSforOSX-SecAttr.c | 55 - OSX/utilities/utilities/iOSforOSX-SecRandom.c | 29 - OSX/utilities/utilities/iOSforOSX.c | 83 - OSX/utilities/utilities/iOSforOSX.h | 50 - OSX/utilities/utilities/simulate_crash.c | 64 - OSX/utilities/utilities/sqlutils.h | 53 - Security.xcodeproj/project.pbxproj | 158 +- .../xcshareddata/xcschemes/Debug.xcscheme | 16 +- .../xcshareddata/xcschemes/Release.xcscheme | 20 +- .../xcshareddata/xcschemes/secdtests.xcscheme | 8 + .../ssl-policy-certs/InvalidEKUTest16.cer | Bin 0 -> 992 bytes .../ssl-policy-certs/InvalidHostnameTest1.cer | Bin 0 -> 999 bytes .../ssl-policy-certs/InvalidHostnameTest2.cer | Bin 0 -> 1000 bytes .../InvalidHostnameTest22.cer | Bin 0 -> 992 bytes .../InvalidHostnameTest23.cer | Bin 0 -> 993 bytes .../InvalidHostnameTest24.cer | Bin 0 -> 993 bytes .../InvalidWildcardTest10.cer | Bin 0 -> 983 bytes .../InvalidWildcardTest11.cer | Bin 0 -> 985 bytes .../InvalidWildcardTest12.cer | Bin 0 -> 991 bytes .../InvalidWildcardTest13Test14.cer | Bin 0 -> 996 bytes .../InvalidWildcardTest15.cer | Bin 0 -> 991 bytes .../InvalidWildcardTest25Test26.cer | Bin 0 -> 1000 bytes .../InvalidWildcardTest5Test6.cer | Bin 0 -> 1000 bytes .../SSL Trust Policy Test CA certificates.pem | 23 + ...L Trust Policy Test CA.certAuthorityConfig | 112 + .../ssl-policy-certs/SSLTrustPolicyTest.plist | 246 + .../ssl-policy-certs/SSLTrustPolicyTestCA.p12 | Bin 0 -> 1498 bytes .../SSLTrustPolicyTestRootCertificate.cer | Bin 0 -> 987 bytes .../ssl-policy-certs/TestDescriptions.txt | 264 + .../ssl-policy-certs/ValidEKUTest17.cer | Bin 0 -> 968 bytes .../ValidHostnameTest18Test19Test20.cer | Bin 0 -> 1007 bytes .../ssl-policy-certs/ValidHostnameTest21.cer | Bin 0 -> 997 bytes .../ssl-policy-certs/ValidHostnameTest3.cer | Bin 0 -> 974 bytes .../ssl-policy-certs/ValidHostnameTest4.cer | Bin 0 -> 1000 bytes .../ValidWildcardTest7Test8Test9.cer | Bin 0 -> 1006 bytes ckcdiagnose/ckcdiagnose.sh | 7 +- libsecurity_smime/Security | 1 + libsecurity_smime/Security/SecAsn1Item.c | 306 - libsecurity_smime/Security/SecAsn1Item.h | 117 - libsecurity_smime/Security/SecCmsBase.h | 469 -- .../Security/SecCmsContentInfo.h | 209 - libsecurity_smime/Security/SecCmsDecoder.h | 140 - .../Security/SecCmsDigestContext.h | 79 - .../Security/SecCmsDigestedData.h | 77 - libsecurity_smime/Security/SecCmsEncoder.h | 134 - .../Security/SecCmsEncryptedData.h | 76 - .../Security/SecCmsEnvelopedData.h | 71 - libsecurity_smime/Security/SecCmsMessage.h | 154 - .../Security/SecCmsRecipientInfo.h | 75 - libsecurity_smime/Security/SecCmsSignedData.h | 192 - libsecurity_smime/Security/SecCmsSignerInfo.h | 197 - libsecurity_smime/Security/SecSMIME.h | 56 - libsecurity_smime/Security/SecSMIMEPriv.h | 173 - libsecurity_smime/Security/cert.c | 723 --- libsecurity_smime/Security/cert.h | 125 - libsecurity_smime/Security/cmsarray.c | 227 - libsecurity_smime/Security/cmsasn1.c | 593 -- libsecurity_smime/Security/cmsattr.c | 454 -- libsecurity_smime/Security/cmscinfo.c | 394 -- libsecurity_smime/Security/cmscipher.c | 1292 ----- libsecurity_smime/Security/cmsdecode.c | 728 --- libsecurity_smime/Security/cmsdigdata.c | 237 - libsecurity_smime/Security/cmsdigest.c | 400 -- libsecurity_smime/Security/cmsencdata.c | 299 - libsecurity_smime/Security/cmsencode.c | 768 --- libsecurity_smime/Security/cmsenvdata.c | 456 -- libsecurity_smime/Security/cmslocal.h | 338 -- libsecurity_smime/Security/cmsmessage.c | 295 - libsecurity_smime/Security/cmspriv.h | 541 -- libsecurity_smime/Security/cmspubkey.c | 575 -- libsecurity_smime/Security/cmsrecinfo.c | 665 --- libsecurity_smime/Security/cmsreclist.c | 242 - libsecurity_smime/Security/cmsreclist.h | 57 - libsecurity_smime/Security/cmssigdata.c | 1015 ---- libsecurity_smime/Security/cmssiginfo.c | 1252 ----- libsecurity_smime/Security/cmstpriv.h | 483 -- libsecurity_smime/Security/cmsutil.c | 429 -- libsecurity_smime/Security/crypto-embedded.c | 387 -- libsecurity_smime/Security/cryptohi.c | 548 -- libsecurity_smime/Security/cryptohi.h | 144 - libsecurity_smime/Security/plhash.c | 538 -- libsecurity_smime/Security/plhash.h | 162 - libsecurity_smime/Security/secalgid.c | 170 - libsecurity_smime/Security/secoid.c | 1553 ----- libsecurity_smime/Security/secoid.h | 120 - libsecurity_smime/Security/secoidt.h | 61 - libsecurity_smime/Security/security_smime.exp | 114 - libsecurity_smime/Security/smimeutil.c | 815 --- libsecurity_smime/Security/testcms | 43 - libsecurity_smime/security_smime | 1 + .../security_smime/SecAsn1Item.c | 306 - .../security_smime/SecAsn1Item.h | 117 - libsecurity_smime/security_smime/SecCmsBase.h | 469 -- .../security_smime/SecCmsContentInfo.h | 209 - .../security_smime/SecCmsDecoder.h | 140 - .../security_smime/SecCmsDigestContext.h | 79 - .../security_smime/SecCmsDigestedData.h | 77 - .../security_smime/SecCmsEncoder.h | 134 - .../security_smime/SecCmsEncryptedData.h | 76 - .../security_smime/SecCmsEnvelopedData.h | 71 - .../security_smime/SecCmsMessage.h | 154 - .../security_smime/SecCmsRecipientInfo.h | 75 - .../security_smime/SecCmsSignedData.h | 192 - .../security_smime/SecCmsSignerInfo.h | 197 - libsecurity_smime/security_smime/SecSMIME.h | 56 - .../security_smime/SecSMIMEPriv.h | 173 - libsecurity_smime/security_smime/cert.c | 723 --- libsecurity_smime/security_smime/cert.h | 125 - libsecurity_smime/security_smime/cmsarray.c | 227 - libsecurity_smime/security_smime/cmsasn1.c | 593 -- libsecurity_smime/security_smime/cmsattr.c | 454 -- libsecurity_smime/security_smime/cmscinfo.c | 394 -- libsecurity_smime/security_smime/cmscipher.c | 1292 ----- libsecurity_smime/security_smime/cmsdecode.c | 728 --- libsecurity_smime/security_smime/cmsdigdata.c | 237 - libsecurity_smime/security_smime/cmsdigest.c | 400 -- libsecurity_smime/security_smime/cmsencdata.c | 299 - libsecurity_smime/security_smime/cmsencode.c | 768 --- libsecurity_smime/security_smime/cmsenvdata.c | 456 -- libsecurity_smime/security_smime/cmslocal.h | 338 -- libsecurity_smime/security_smime/cmsmessage.c | 295 - libsecurity_smime/security_smime/cmspriv.h | 541 -- libsecurity_smime/security_smime/cmspubkey.c | 575 -- libsecurity_smime/security_smime/cmsrecinfo.c | 665 --- libsecurity_smime/security_smime/cmsreclist.c | 242 - libsecurity_smime/security_smime/cmsreclist.h | 57 - libsecurity_smime/security_smime/cmssigdata.c | 1015 ---- libsecurity_smime/security_smime/cmssiginfo.c | 1252 ----- libsecurity_smime/security_smime/cmstpriv.h | 483 -- libsecurity_smime/security_smime/cmsutil.c | 429 -- .../security_smime/crypto-embedded.c | 387 -- libsecurity_smime/security_smime/cryptohi.c | 548 -- libsecurity_smime/security_smime/cryptohi.h | 144 - libsecurity_smime/security_smime/plhash.c | 538 -- libsecurity_smime/security_smime/plhash.h | 162 - libsecurity_smime/security_smime/secalgid.c | 170 - libsecurity_smime/security_smime/secoid.c | 1553 ----- libsecurity_smime/security_smime/secoid.h | 120 - libsecurity_smime/security_smime/secoidt.h | 61 - .../security_smime/security_smime.exp | 114 - libsecurity_smime/security_smime/smimeutil.c | 815 --- libsecurity_smime/security_smime/testcms | 43 - ntlm/ntlmBlobPriv.c | 5 +- sectask/SecTask.c | 26 +- securityd/security_agent_client | 1 + securityd/security_agent_server | 1 + 1861 files changed, 6517 insertions(+), 487620 deletions(-) delete mode 100644 CircleJoinRequested/CircleJoinRequested.1 create mode 120000 OSX/include/security_asn1 delete mode 100644 OSX/include/security_asn1/SecAsn1Coder.c delete mode 100644 OSX/include/security_asn1/SecAsn1Coder.h delete mode 100644 OSX/include/security_asn1/SecAsn1Templates.c delete mode 100644 OSX/include/security_asn1/SecAsn1Templates.h delete mode 100644 OSX/include/security_asn1/SecAsn1Types.h delete mode 100644 OSX/include/security_asn1/SecNssCoder.cpp delete mode 100644 OSX/include/security_asn1/SecNssCoder.h delete mode 100644 OSX/include/security_asn1/X509Templates.c delete mode 100644 OSX/include/security_asn1/X509Templates.h delete mode 100644 OSX/include/security_asn1/asn1Templates.h delete mode 100644 OSX/include/security_asn1/certExtensionTemplates.c delete mode 100644 OSX/include/security_asn1/certExtensionTemplates.h delete mode 100644 OSX/include/security_asn1/csrTemplates.c delete mode 100644 OSX/include/security_asn1/csrTemplates.h delete mode 100644 OSX/include/security_asn1/keyTemplates.c delete mode 100644 OSX/include/security_asn1/keyTemplates.h delete mode 100644 OSX/include/security_asn1/nameTemplates.c delete mode 100644 OSX/include/security_asn1/nameTemplates.h delete mode 100644 OSX/include/security_asn1/nsprPortX.c delete mode 100644 OSX/include/security_asn1/nssUtils.c delete mode 100644 OSX/include/security_asn1/nssUtils.h delete mode 100644 OSX/include/security_asn1/nssilckt.h delete mode 100644 OSX/include/security_asn1/nssilock.h delete mode 100644 OSX/include/security_asn1/nsslocks.h delete mode 100644 OSX/include/security_asn1/ocspTemplates.c delete mode 100644 OSX/include/security_asn1/ocspTemplates.h delete mode 100644 OSX/include/security_asn1/oidsalg.c delete mode 100644 OSX/include/security_asn1/oidsalg.h delete mode 100644 OSX/include/security_asn1/oidsattr.c delete mode 100644 OSX/include/security_asn1/oidsattr.h delete mode 100644 OSX/include/security_asn1/oidsbase.h delete mode 100644 OSX/include/security_asn1/oidsocsp.c delete mode 100644 OSX/include/security_asn1/oidsocsp.h delete mode 100644 OSX/include/security_asn1/osKeyTemplates.c delete mode 100644 OSX/include/security_asn1/osKeyTemplates.h delete mode 100644 OSX/include/security_asn1/pkcs12Templates.c delete mode 100644 OSX/include/security_asn1/pkcs12Templates.h delete mode 100644 OSX/include/security_asn1/pkcs7Templates.c delete mode 100644 OSX/include/security_asn1/pkcs7Templates.h delete mode 100644 OSX/include/security_asn1/plarena.c delete mode 100644 OSX/include/security_asn1/plarena.h delete mode 100644 OSX/include/security_asn1/plarenas.h delete mode 100644 OSX/include/security_asn1/plstr.h delete mode 100644 OSX/include/security_asn1/prbit.h delete mode 100644 OSX/include/security_asn1/prcpucfg.h delete mode 100644 OSX/include/security_asn1/prcvar.h delete mode 100644 OSX/include/security_asn1/prenv.h delete mode 100644 OSX/include/security_asn1/prerr.h delete mode 100644 OSX/include/security_asn1/prerror.h delete mode 100644 OSX/include/security_asn1/prinit.h delete mode 100644 OSX/include/security_asn1/prinrval.h delete mode 100644 OSX/include/security_asn1/prlock.h delete mode 100644 OSX/include/security_asn1/prlog.h delete mode 100644 OSX/include/security_asn1/prlong.h delete mode 100644 OSX/include/security_asn1/prmem.h delete mode 100644 OSX/include/security_asn1/prmon.h delete mode 100644 OSX/include/security_asn1/protypes.h delete mode 100644 OSX/include/security_asn1/prthread.h delete mode 100644 OSX/include/security_asn1/prtime.h delete mode 100644 OSX/include/security_asn1/prtypes.h delete mode 100644 OSX/include/security_asn1/prvrsion.h delete mode 100644 OSX/include/security_asn1/secErrorStr.c delete mode 100644 OSX/include/security_asn1/secasn1.h delete mode 100644 OSX/include/security_asn1/secasn1d.c delete mode 100644 OSX/include/security_asn1/secasn1e.c delete mode 100644 OSX/include/security_asn1/secasn1t.h delete mode 100644 OSX/include/security_asn1/secasn1u.c delete mode 100644 OSX/include/security_asn1/seccomon.h delete mode 100644 OSX/include/security_asn1/secerr.h delete mode 100644 OSX/include/security_asn1/secport.c delete mode 100644 OSX/include/security_asn1/secport.h delete mode 100644 OSX/include/security_asn1/security_asn1.exp create mode 120000 OSX/include/security_cdsa_client delete mode 100644 OSX/include/security_cdsa_client/DLDBList.cpp delete mode 100644 OSX/include/security_cdsa_client/DLDBList.h delete mode 100644 OSX/include/security_cdsa_client/aclclient.cpp delete mode 100644 OSX/include/security_cdsa_client/aclclient.h delete mode 100644 OSX/include/security_cdsa_client/clclient.cpp delete mode 100644 OSX/include/security_cdsa_client/clclient.h delete mode 100644 OSX/include/security_cdsa_client/cryptoclient.cpp delete mode 100644 OSX/include/security_cdsa_client/cryptoclient.h delete mode 100644 OSX/include/security_cdsa_client/cspclient.cpp delete mode 100644 OSX/include/security_cdsa_client/cspclient.h delete mode 100644 OSX/include/security_cdsa_client/cssmclient.cpp delete mode 100644 OSX/include/security_cdsa_client/cssmclient.h delete mode 100644 OSX/include/security_cdsa_client/dl_standard.cpp delete mode 100644 OSX/include/security_cdsa_client/dl_standard.h delete mode 100644 OSX/include/security_cdsa_client/dlclient.cpp delete mode 100644 OSX/include/security_cdsa_client/dlclient.h delete mode 100644 OSX/include/security_cdsa_client/dlclientpriv.cpp delete mode 100644 OSX/include/security_cdsa_client/dliterators.cpp delete mode 100644 OSX/include/security_cdsa_client/dliterators.h delete mode 100644 OSX/include/security_cdsa_client/dlquery.cpp delete mode 100644 OSX/include/security_cdsa_client/dlquery.h delete mode 100644 OSX/include/security_cdsa_client/genkey.cpp delete mode 100644 OSX/include/security_cdsa_client/genkey.h delete mode 100644 OSX/include/security_cdsa_client/keychainacl.cpp delete mode 100644 OSX/include/security_cdsa_client/keychainacl.h delete mode 100644 OSX/include/security_cdsa_client/keyclient.cpp delete mode 100644 OSX/include/security_cdsa_client/keyclient.h delete mode 100644 OSX/include/security_cdsa_client/macclient.cpp delete mode 100644 OSX/include/security_cdsa_client/macclient.h delete mode 100644 OSX/include/security_cdsa_client/mds_standard.cpp delete mode 100644 OSX/include/security_cdsa_client/mds_standard.h delete mode 100644 OSX/include/security_cdsa_client/mdsclient.cpp delete mode 100644 OSX/include/security_cdsa_client/mdsclient.h delete mode 100644 OSX/include/security_cdsa_client/multidldb.cpp delete mode 100644 OSX/include/security_cdsa_client/multidldb.h delete mode 100644 OSX/include/security_cdsa_client/securestorage.cpp delete mode 100644 OSX/include/security_cdsa_client/securestorage.h delete mode 100644 OSX/include/security_cdsa_client/signclient.cpp delete mode 100644 OSX/include/security_cdsa_client/signclient.h delete mode 100644 OSX/include/security_cdsa_client/tpclient.cpp delete mode 100644 OSX/include/security_cdsa_client/tpclient.h delete mode 100644 OSX/include/security_cdsa_client/wrapkey.cpp delete mode 100644 OSX/include/security_cdsa_client/wrapkey.h create mode 120000 OSX/include/security_cdsa_plugin delete mode 100644 OSX/include/security_cdsa_plugin/ACsession.h delete mode 100644 OSX/include/security_cdsa_plugin/CLsession.h delete mode 100644 OSX/include/security_cdsa_plugin/CSPsession.cpp delete mode 100644 OSX/include/security_cdsa_plugin/CSPsession.h delete mode 100644 OSX/include/security_cdsa_plugin/DLsession.cpp delete mode 100644 OSX/include/security_cdsa_plugin/DLsession.h delete mode 100644 OSX/include/security_cdsa_plugin/Database.cpp delete mode 100644 OSX/include/security_cdsa_plugin/Database.h delete mode 100644 OSX/include/security_cdsa_plugin/DatabaseSession.cpp delete mode 100644 OSX/include/security_cdsa_plugin/DatabaseSession.h delete mode 100644 OSX/include/security_cdsa_plugin/DbContext.cpp delete mode 100644 OSX/include/security_cdsa_plugin/DbContext.h delete mode 100644 OSX/include/security_cdsa_plugin/TPsession.h delete mode 100644 OSX/include/security_cdsa_plugin/c++plugin.h delete mode 100644 OSX/include/security_cdsa_plugin/csputilities.cpp delete mode 100644 OSX/include/security_cdsa_plugin/cssmplugin.cpp delete mode 100644 OSX/include/security_cdsa_plugin/cssmplugin.h delete mode 100644 OSX/include/security_cdsa_plugin/generator.cfg delete mode 100644 OSX/include/security_cdsa_plugin/generator.mk delete mode 100644 OSX/include/security_cdsa_plugin/generator.pl delete mode 100644 OSX/include/security_cdsa_plugin/pluginsession.cpp delete mode 100644 OSX/include/security_cdsa_plugin/pluginsession.h delete mode 100644 OSX/include/security_cdsa_plugin/pluginspi.h create mode 120000 OSX/include/security_cdsa_utilities delete mode 100644 OSX/include/security_cdsa_utilities/AuthorizationData.cpp delete mode 100644 OSX/include/security_cdsa_utilities/AuthorizationData.h delete mode 100644 OSX/include/security_cdsa_utilities/AuthorizationWalkers.h delete mode 100644 OSX/include/security_cdsa_utilities/KeySchema.h delete mode 100644 OSX/include/security_cdsa_utilities/KeySchema.m4 delete mode 100644 OSX/include/security_cdsa_utilities/Schema.h delete mode 100644 OSX/include/security_cdsa_utilities/Schema.m4 delete mode 100644 OSX/include/security_cdsa_utilities/acl_any.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_any.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_codesigning.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_codesigning.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_comment.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_comment.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_password.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_password.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_preauth.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_preauth.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_process.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_process.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_prompted.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_prompted.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_protectedpw.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_protectedpw.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_secret.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_secret.h delete mode 100644 OSX/include/security_cdsa_utilities/acl_threshold.cpp delete mode 100644 OSX/include/security_cdsa_utilities/acl_threshold.h delete mode 100644 OSX/include/security_cdsa_utilities/aclsubject.cpp delete mode 100644 OSX/include/security_cdsa_utilities/aclsubject.h delete mode 100644 OSX/include/security_cdsa_utilities/callback.cpp delete mode 100644 OSX/include/security_cdsa_utilities/callback.h delete mode 100644 OSX/include/security_cdsa_utilities/constdata.cpp delete mode 100644 OSX/include/security_cdsa_utilities/constdata.h delete mode 100644 OSX/include/security_cdsa_utilities/context.cpp delete mode 100644 OSX/include/security_cdsa_utilities/context.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmacl.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmacl.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmaclpod.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmaclpod.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmalloc.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmalloc.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmbridge.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmcert.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmcert.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmcred.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmcred.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmdata.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmdata.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmdates.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmdates.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmdb.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmdb.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmdbname.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmdbname.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmendian.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmendian.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmerrors.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmerrors.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmkey.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmkey.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmlist.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmlist.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmpods.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmpods.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmtrust.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmtrust.h delete mode 100644 OSX/include/security_cdsa_utilities/cssmwalkers.cpp delete mode 100644 OSX/include/security_cdsa_utilities/cssmwalkers.h delete mode 100644 OSX/include/security_cdsa_utilities/db++.cpp delete mode 100644 OSX/include/security_cdsa_utilities/db++.h delete mode 100644 OSX/include/security_cdsa_utilities/digestobject.h delete mode 100644 OSX/include/security_cdsa_utilities/generator.mk delete mode 100644 OSX/include/security_cdsa_utilities/generator.pl delete mode 100644 OSX/include/security_cdsa_utilities/handleobject.cpp delete mode 100644 OSX/include/security_cdsa_utilities/handleobject.h delete mode 100644 OSX/include/security_cdsa_utilities/handletemplates.cpp delete mode 100644 OSX/include/security_cdsa_utilities/handletemplates.h delete mode 100644 OSX/include/security_cdsa_utilities/handletemplates_defs.h delete mode 100644 OSX/include/security_cdsa_utilities/objectacl.cpp delete mode 100644 OSX/include/security_cdsa_utilities/objectacl.h delete mode 100644 OSX/include/security_cdsa_utilities/osxverifier.cpp delete mode 100644 OSX/include/security_cdsa_utilities/osxverifier.h delete mode 100644 OSX/include/security_cdsa_utilities/u32handleobject.cpp delete mode 100644 OSX/include/security_cdsa_utilities/u32handleobject.h delete mode 100644 OSX/include/security_cdsa_utilities/uniformrandom.cpp delete mode 100644 OSX/include/security_cdsa_utilities/uniformrandom.h delete mode 100644 OSX/include/security_cdsa_utilities/walkers.cpp delete mode 100644 OSX/include/security_cdsa_utilities/walkers.h create mode 120000 OSX/include/security_cdsa_utils delete mode 100644 OSX/include/security_cdsa_utils/cuCdsaUtils.cpp delete mode 100644 OSX/include/security_cdsa_utils/cuCdsaUtils.h delete mode 100644 OSX/include/security_cdsa_utils/cuDbUtils.cpp delete mode 100644 OSX/include/security_cdsa_utils/cuDbUtils.h delete mode 100644 OSX/include/security_cdsa_utils/cuEnc64.c delete mode 100644 OSX/include/security_cdsa_utils/cuEnc64.h delete mode 100644 OSX/include/security_cdsa_utils/cuFileIo.c delete mode 100644 OSX/include/security_cdsa_utils/cuFileIo.h delete mode 100644 OSX/include/security_cdsa_utils/cuOidParser.cpp delete mode 100644 OSX/include/security_cdsa_utils/cuOidParser.h delete mode 100644 OSX/include/security_cdsa_utils/cuPem.cpp delete mode 100644 OSX/include/security_cdsa_utils/cuPem.h delete mode 100644 OSX/include/security_cdsa_utils/cuPrintCert.cpp delete mode 100644 OSX/include/security_cdsa_utils/cuPrintCert.h delete mode 100644 OSX/include/security_cdsa_utils/cuTimeStr.cpp delete mode 100644 OSX/include/security_cdsa_utils/cuTimeStr.h create mode 120000 OSX/include/security_codesigning delete mode 100644 OSX/include/security_codesigning/CSCommon.h delete mode 100644 OSX/include/security_codesigning/CSCommonPriv.h delete mode 100644 OSX/include/security_codesigning/Code.cpp delete mode 100644 OSX/include/security_codesigning/Code.h delete mode 100644 OSX/include/security_codesigning/CodeSigner.cpp delete mode 100644 OSX/include/security_codesigning/CodeSigner.h delete mode 100644 OSX/include/security_codesigning/CodeSigning.h delete mode 100644 OSX/include/security_codesigning/RequirementKeywords.h delete mode 100644 OSX/include/security_codesigning/RequirementLexer.cpp delete mode 100644 OSX/include/security_codesigning/RequirementLexer.hpp delete mode 100644 OSX/include/security_codesigning/RequirementParser.cpp delete mode 100644 OSX/include/security_codesigning/RequirementParser.hpp delete mode 100644 OSX/include/security_codesigning/RequirementParserTokenTypes.hpp delete mode 100644 OSX/include/security_codesigning/RequirementParserTokenTypes.txt delete mode 100644 OSX/include/security_codesigning/Requirements.cpp delete mode 100644 OSX/include/security_codesigning/Requirements.h delete mode 100644 OSX/include/security_codesigning/SecAssessment.cpp delete mode 100644 OSX/include/security_codesigning/SecAssessment.h delete mode 100644 OSX/include/security_codesigning/SecCode.cpp delete mode 100644 OSX/include/security_codesigning/SecCode.h delete mode 100644 OSX/include/security_codesigning/SecCodeHost.cpp delete mode 100644 OSX/include/security_codesigning/SecCodeHost.h delete mode 100644 OSX/include/security_codesigning/SecCodeHostLib.c delete mode 100644 OSX/include/security_codesigning/SecCodeHostLib.h delete mode 100644 OSX/include/security_codesigning/SecCodePriv.h delete mode 100644 OSX/include/security_codesigning/SecCodeSigner.cpp delete mode 100644 OSX/include/security_codesigning/SecCodeSigner.h delete mode 100644 OSX/include/security_codesigning/SecIntegrity.cpp delete mode 100644 OSX/include/security_codesigning/SecIntegrity.h delete mode 100644 OSX/include/security_codesigning/SecIntegrityLib.c delete mode 100644 OSX/include/security_codesigning/SecIntegrityLib.h delete mode 100644 OSX/include/security_codesigning/SecRequirement.cpp delete mode 100644 OSX/include/security_codesigning/SecRequirement.h delete mode 100644 OSX/include/security_codesigning/SecRequirementPriv.h delete mode 100644 OSX/include/security_codesigning/SecStaticCode.cpp delete mode 100644 OSX/include/security_codesigning/SecStaticCode.h delete mode 100644 OSX/include/security_codesigning/SecStaticCodePriv.h delete mode 100644 OSX/include/security_codesigning/SecTask.c delete mode 100644 OSX/include/security_codesigning/SecTask.h delete mode 100644 OSX/include/security_codesigning/SecTaskPriv.h delete mode 100644 OSX/include/security_codesigning/StaticCode.cpp delete mode 100644 OSX/include/security_codesigning/StaticCode.h delete mode 100644 OSX/include/security_codesigning/antlrplugin.cpp delete mode 100644 OSX/include/security_codesigning/antlrplugin.h delete mode 100644 OSX/include/security_codesigning/bundlediskrep.cpp delete mode 100644 OSX/include/security_codesigning/bundlediskrep.h delete mode 100644 OSX/include/security_codesigning/cdbuilder.cpp delete mode 100644 OSX/include/security_codesigning/cdbuilder.h delete mode 100644 OSX/include/security_codesigning/codedirectory.cpp delete mode 100644 OSX/include/security_codesigning/codedirectory.h delete mode 100644 OSX/include/security_codesigning/cs.cpp delete mode 100644 OSX/include/security_codesigning/cs.h delete mode 100644 OSX/include/security_codesigning/cscdefs.c delete mode 100644 OSX/include/security_codesigning/cscdefs.h delete mode 100644 OSX/include/security_codesigning/csdatabase.cpp delete mode 100644 OSX/include/security_codesigning/csdatabase.h delete mode 100644 OSX/include/security_codesigning/cserror.cpp delete mode 100644 OSX/include/security_codesigning/cserror.h delete mode 100644 OSX/include/security_codesigning/csgeneric.cpp delete mode 100644 OSX/include/security_codesigning/csgeneric.h delete mode 100644 OSX/include/security_codesigning/cskernel.cpp delete mode 100644 OSX/include/security_codesigning/cskernel.h delete mode 100644 OSX/include/security_codesigning/csprocess.cpp delete mode 100644 OSX/include/security_codesigning/csprocess.h delete mode 100644 OSX/include/security_codesigning/csutilities.cpp delete mode 100644 OSX/include/security_codesigning/csutilities.h delete mode 100644 OSX/include/security_codesigning/detachedrep.cpp delete mode 100644 OSX/include/security_codesigning/detachedrep.h delete mode 100644 OSX/include/security_codesigning/dirscanner.cpp delete mode 100644 OSX/include/security_codesigning/dirscanner.h delete mode 100644 OSX/include/security_codesigning/diskrep.cpp delete mode 100644 OSX/include/security_codesigning/diskrep.h delete mode 100644 OSX/include/security_codesigning/drmaker.cpp delete mode 100644 OSX/include/security_codesigning/drmaker.h delete mode 100644 OSX/include/security_codesigning/evaluationmanager.cpp delete mode 100644 OSX/include/security_codesigning/evaluationmanager.h delete mode 100644 OSX/include/security_codesigning/filediskrep.cpp delete mode 100644 OSX/include/security_codesigning/filediskrep.h delete mode 100644 OSX/include/security_codesigning/kerneldiskrep.cpp delete mode 100644 OSX/include/security_codesigning/kerneldiskrep.h delete mode 100644 OSX/include/security_codesigning/machorep.cpp delete mode 100644 OSX/include/security_codesigning/machorep.h delete mode 100644 OSX/include/security_codesigning/opaquewhitelist.cpp delete mode 100644 OSX/include/security_codesigning/opaquewhitelist.h delete mode 100644 OSX/include/security_codesigning/piddiskrep.cpp delete mode 100644 OSX/include/security_codesigning/piddiskrep.h delete mode 100644 OSX/include/security_codesigning/policydb.cpp delete mode 100644 OSX/include/security_codesigning/policydb.h delete mode 100644 OSX/include/security_codesigning/policyengine.cpp delete mode 100644 OSX/include/security_codesigning/policyengine.h delete mode 100644 OSX/include/security_codesigning/quarantine++.cpp delete mode 100644 OSX/include/security_codesigning/quarantine++.h delete mode 100644 OSX/include/security_codesigning/reqdumper.cpp delete mode 100644 OSX/include/security_codesigning/reqdumper.h delete mode 100644 OSX/include/security_codesigning/reqinterp.cpp delete mode 100644 OSX/include/security_codesigning/reqinterp.h delete mode 100644 OSX/include/security_codesigning/reqmaker.cpp delete mode 100644 OSX/include/security_codesigning/reqmaker.h delete mode 100644 OSX/include/security_codesigning/reqparser.cpp delete mode 100644 OSX/include/security_codesigning/reqparser.h delete mode 100644 OSX/include/security_codesigning/reqreader.cpp delete mode 100644 OSX/include/security_codesigning/reqreader.h delete mode 100644 OSX/include/security_codesigning/requirement.cpp delete mode 100644 OSX/include/security_codesigning/requirement.h delete mode 100644 OSX/include/security_codesigning/resources.cpp delete mode 100644 OSX/include/security_codesigning/resources.h delete mode 100644 OSX/include/security_codesigning/security_codesigning.d delete mode 100644 OSX/include/security_codesigning/security_codesigning.exp delete mode 100644 OSX/include/security_codesigning/sigblob.cpp delete mode 100644 OSX/include/security_codesigning/sigblob.h delete mode 100644 OSX/include/security_codesigning/signer.cpp delete mode 100644 OSX/include/security_codesigning/signer.h delete mode 100644 OSX/include/security_codesigning/signerutils.cpp delete mode 100644 OSX/include/security_codesigning/signerutils.h delete mode 100644 OSX/include/security_codesigning/singlediskrep.cpp delete mode 100644 OSX/include/security_codesigning/singlediskrep.h delete mode 100644 OSX/include/security_codesigning/slcrep.cpp delete mode 100644 OSX/include/security_codesigning/slcrep.h delete mode 100644 OSX/include/security_codesigning/syspolicy.sql delete mode 100644 OSX/include/security_codesigning/xar++.cpp delete mode 100644 OSX/include/security_codesigning/xar++.h delete mode 100644 OSX/include/security_codesigning/xpcengine.cpp delete mode 100644 OSX/include/security_codesigning/xpcengine.h create mode 120000 OSX/include/security_comcryption delete mode 100644 OSX/include/security_comcryption/comDebug.h delete mode 100644 OSX/include/security_comcryption/comcryptPriv.c delete mode 100644 OSX/include/security_comcryption/comcryptPriv.h delete mode 100644 OSX/include/security_comcryption/comcryption.c delete mode 100644 OSX/include/security_comcryption/comcryption.h create mode 120000 OSX/include/security_cryptkit delete mode 100644 OSX/include/security_cryptkit/ByteRep.txt delete mode 100644 OSX/include/security_cryptkit/CipherFileDES.c delete mode 100644 OSX/include/security_cryptkit/CipherFileDES.h delete mode 100644 OSX/include/security_cryptkit/CipherFileFEED.c delete mode 100644 OSX/include/security_cryptkit/CipherFileFEED.h delete mode 100644 OSX/include/security_cryptkit/CipherFileTypes.h delete mode 100644 OSX/include/security_cryptkit/Crypt.h delete mode 100644 OSX/include/security_cryptkit/CryptKit.def delete mode 100644 OSX/include/security_cryptkit/CryptKit.h delete mode 100644 OSX/include/security_cryptkit/CryptKitAsn1.cpp delete mode 100644 OSX/include/security_cryptkit/CryptKitAsn1.h delete mode 100644 OSX/include/security_cryptkit/CryptKitDER.cpp delete mode 100644 OSX/include/security_cryptkit/CryptKitDER.h delete mode 100644 OSX/include/security_cryptkit/CryptKitSA.h delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/FEEDaffine.nb delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/FEEDsansY.nb delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/README delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/curvegen.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/curverecords.nb delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/disc.h delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/ellproj.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/ellproj.h delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/factor.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/fmodule.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/fmodule.h delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/giants.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/giants.h delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/schoof.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/schoofs.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/tools.c delete mode 100644 OSX/include/security_cryptkit/CurveParamDocs/tools.h delete mode 100644 OSX/include/security_cryptkit/ECDSA_Profile.h delete mode 100644 OSX/include/security_cryptkit/ECDSA_Verify_Prefix.h delete mode 100644 OSX/include/security_cryptkit/HmacSha1Legacy.c delete mode 100644 OSX/include/security_cryptkit/HmacSha1Legacy.h delete mode 100644 OSX/include/security_cryptkit/Mathematica.FEE delete mode 100644 OSX/include/security_cryptkit/NSCipherFile.h delete mode 100644 OSX/include/security_cryptkit/NSCipherFile.m delete mode 100644 OSX/include/security_cryptkit/NSCryptors.h delete mode 100644 OSX/include/security_cryptkit/NSDESCryptor.h delete mode 100644 OSX/include/security_cryptkit/NSDESCryptor.m delete mode 100644 OSX/include/security_cryptkit/NSFEEPublicKey.h delete mode 100644 OSX/include/security_cryptkit/NSFEEPublicKey.m delete mode 100644 OSX/include/security_cryptkit/NSFEEPublicKeyPrivate.h delete mode 100644 OSX/include/security_cryptkit/NSMD5Hash.h delete mode 100644 OSX/include/security_cryptkit/NSMD5Hash.m delete mode 100644 OSX/include/security_cryptkit/NSRandomNumberGenerator.h delete mode 100644 OSX/include/security_cryptkit/NSRandomNumberGenerator.m delete mode 100644 OSX/include/security_cryptkit/README delete mode 100644 OSX/include/security_cryptkit/TOP_README delete mode 100644 OSX/include/security_cryptkit/buildSrcTree delete mode 100644 OSX/include/security_cryptkit/byteRep.c delete mode 100644 OSX/include/security_cryptkit/byteRep.h delete mode 100644 OSX/include/security_cryptkit/changes delete mode 100644 OSX/include/security_cryptkit/ckDES.c delete mode 100644 OSX/include/security_cryptkit/ckDES.h delete mode 100644 OSX/include/security_cryptkit/ckMD5.c delete mode 100644 OSX/include/security_cryptkit/ckMD5.h delete mode 100644 OSX/include/security_cryptkit/ckSHA1.c delete mode 100644 OSX/include/security_cryptkit/ckSHA1.h delete mode 100644 OSX/include/security_cryptkit/ckSHA1_priv.c delete mode 100644 OSX/include/security_cryptkit/ckSHA1_priv.h delete mode 100644 OSX/include/security_cryptkit/ckconfig.h delete mode 100644 OSX/include/security_cryptkit/ckutilities.c delete mode 100644 OSX/include/security_cryptkit/ckutilities.h delete mode 100644 OSX/include/security_cryptkit/curveParamData.h delete mode 100644 OSX/include/security_cryptkit/curveParamDataOld.h delete mode 100644 OSX/include/security_cryptkit/curveParams.c delete mode 100644 OSX/include/security_cryptkit/curveParams.h delete mode 100644 OSX/include/security_cryptkit/elliptic.c delete mode 100644 OSX/include/security_cryptkit/elliptic.h delete mode 100644 OSX/include/security_cryptkit/ellipticMeasure.h delete mode 100644 OSX/include/security_cryptkit/ellipticProj.c delete mode 100644 OSX/include/security_cryptkit/ellipticProj.h delete mode 100644 OSX/include/security_cryptkit/enc64.c delete mode 100644 OSX/include/security_cryptkit/enc64.h delete mode 100644 OSX/include/security_cryptkit/engineNSA127.c delete mode 100644 OSX/include/security_cryptkit/falloc.c delete mode 100644 OSX/include/security_cryptkit/falloc.h delete mode 100644 OSX/include/security_cryptkit/feeCipherFile.c delete mode 100644 OSX/include/security_cryptkit/feeCipherFile.h delete mode 100644 OSX/include/security_cryptkit/feeCipherFileAtom.c delete mode 100644 OSX/include/security_cryptkit/feeDES.c delete mode 100644 OSX/include/security_cryptkit/feeDES.h delete mode 100644 OSX/include/security_cryptkit/feeDebug.h delete mode 100644 OSX/include/security_cryptkit/feeDigitalSignature.c delete mode 100644 OSX/include/security_cryptkit/feeDigitalSignature.h delete mode 100644 OSX/include/security_cryptkit/feeECDSA.c delete mode 100644 OSX/include/security_cryptkit/feeECDSA.h delete mode 100644 OSX/include/security_cryptkit/feeFEED.c delete mode 100644 OSX/include/security_cryptkit/feeFEED.h delete mode 100644 OSX/include/security_cryptkit/feeFEEDExp.c delete mode 100644 OSX/include/security_cryptkit/feeFEEDExp.h delete mode 100644 OSX/include/security_cryptkit/feeFunctions.h delete mode 100644 OSX/include/security_cryptkit/feeHash.c delete mode 100644 OSX/include/security_cryptkit/feeHash.h delete mode 100644 OSX/include/security_cryptkit/feePublicKey.c delete mode 100644 OSX/include/security_cryptkit/feePublicKey.h delete mode 100644 OSX/include/security_cryptkit/feePublicKeyPrivate.h delete mode 100644 OSX/include/security_cryptkit/feeRandom.c delete mode 100644 OSX/include/security_cryptkit/feeRandom.h delete mode 100644 OSX/include/security_cryptkit/feeTypes.h delete mode 100644 OSX/include/security_cryptkit/giantFFT.c delete mode 100644 OSX/include/security_cryptkit/giantIntegers.c delete mode 100644 OSX/include/security_cryptkit/giantIntegers.h delete mode 100644 OSX/include/security_cryptkit/giantPortCommon.h delete mode 100644 OSX/include/security_cryptkit/giantPort_Generic.h delete mode 100644 OSX/include/security_cryptkit/giantPort_PPC.c delete mode 100644 OSX/include/security_cryptkit/giantPort_PPC.h delete mode 100644 OSX/include/security_cryptkit/giantPort_PPC_Gnu.h delete mode 100644 OSX/include/security_cryptkit/giantPort_PPC_Gnu.s delete mode 100644 OSX/include/security_cryptkit/giantPort_i486.h delete mode 100644 OSX/include/security_cryptkit/giantPort_i486.s delete mode 100644 OSX/include/security_cryptkit/mutils.h delete mode 100644 OSX/include/security_cryptkit/mutils.m delete mode 100644 OSX/include/security_cryptkit/platform.c delete mode 100644 OSX/include/security_cryptkit/platform.h delete mode 100644 OSX/include/security_cryptkit/unixMakefile create mode 120000 OSX/include/security_filedb delete mode 100644 OSX/include/security_filedb/AppleDatabase.cpp delete mode 100644 OSX/include/security_filedb/AppleDatabase.h delete mode 100644 OSX/include/security_filedb/AtomicFile.cpp delete mode 100644 OSX/include/security_filedb/AtomicFile.h delete mode 100644 OSX/include/security_filedb/DbIndex.cpp delete mode 100644 OSX/include/security_filedb/DbIndex.h delete mode 100644 OSX/include/security_filedb/DbQuery.cpp delete mode 100644 OSX/include/security_filedb/DbQuery.h delete mode 100644 OSX/include/security_filedb/DbValue.cpp delete mode 100644 OSX/include/security_filedb/DbValue.h delete mode 100644 OSX/include/security_filedb/MetaAttribute.cpp delete mode 100644 OSX/include/security_filedb/MetaAttribute.h delete mode 100644 OSX/include/security_filedb/MetaRecord.cpp delete mode 100644 OSX/include/security_filedb/MetaRecord.h delete mode 100644 OSX/include/security_filedb/OverUnderflowCheck.h delete mode 100644 OSX/include/security_filedb/ReadWriteSection.cpp delete mode 100644 OSX/include/security_filedb/ReadWriteSection.h delete mode 100644 OSX/include/security_filedb/SelectionPredicate.cpp delete mode 100644 OSX/include/security_filedb/SelectionPredicate.h create mode 120000 OSX/include/security_keychain delete mode 100644 OSX/include/security_keychain/ACL.cpp delete mode 100644 OSX/include/security_keychain/ACL.h delete mode 100644 OSX/include/security_keychain/Access.cpp delete mode 100644 OSX/include/security_keychain/Access.h delete mode 100644 OSX/include/security_keychain/AppleBaselineEscrowCertificates.h delete mode 100644 OSX/include/security_keychain/CCallbackMgr.cp delete mode 100644 OSX/include/security_keychain/CCallbackMgr.h delete mode 100644 OSX/include/security_keychain/Certificate.cpp delete mode 100644 OSX/include/security_keychain/Certificate.h delete mode 100644 OSX/include/security_keychain/CertificateRequest.cpp delete mode 100644 OSX/include/security_keychain/CertificateRequest.h delete mode 100644 OSX/include/security_keychain/CertificateValues.cpp delete mode 100644 OSX/include/security_keychain/CertificateValues.h delete mode 100644 OSX/include/security_keychain/DLDBListCFPref.cpp delete mode 100644 OSX/include/security_keychain/DLDBListCFPref.h delete mode 100644 OSX/include/security_keychain/DynamicDLDBList.cpp delete mode 100644 OSX/include/security_keychain/DynamicDLDBList.h delete mode 100644 OSX/include/security_keychain/ExtendedAttribute.cpp delete mode 100644 OSX/include/security_keychain/ExtendedAttribute.h delete mode 100644 OSX/include/security_keychain/Globals.cpp delete mode 100644 OSX/include/security_keychain/Globals.h delete mode 100644 OSX/include/security_keychain/Identity.cpp delete mode 100644 OSX/include/security_keychain/Identity.h delete mode 100644 OSX/include/security_keychain/IdentityCursor.cpp delete mode 100644 OSX/include/security_keychain/IdentityCursor.h delete mode 100644 OSX/include/security_keychain/Item.cpp delete mode 100644 OSX/include/security_keychain/Item.h delete mode 100644 OSX/include/security_keychain/KCCursor.cpp delete mode 100644 OSX/include/security_keychain/KCCursor.h delete mode 100644 OSX/include/security_keychain/KCEventNotifier.cpp delete mode 100644 OSX/include/security_keychain/KCEventNotifier.h delete mode 100644 OSX/include/security_keychain/KCExceptions.h delete mode 100644 OSX/include/security_keychain/KCUtilities.cpp delete mode 100644 OSX/include/security_keychain/KCUtilities.h delete mode 100644 OSX/include/security_keychain/KeyItem.cpp delete mode 100644 OSX/include/security_keychain/KeyItem.h delete mode 100644 OSX/include/security_keychain/Keychains.cpp delete mode 100644 OSX/include/security_keychain/Keychains.h delete mode 100644 OSX/include/security_keychain/MacOSErrorStrings.h delete mode 100644 OSX/include/security_keychain/Password.cpp delete mode 100644 OSX/include/security_keychain/Password.h delete mode 100644 OSX/include/security_keychain/Policies.cpp delete mode 100644 OSX/include/security_keychain/Policies.h delete mode 100644 OSX/include/security_keychain/PolicyCursor.cpp delete mode 100644 OSX/include/security_keychain/PolicyCursor.h delete mode 100644 OSX/include/security_keychain/PrimaryKey.cpp delete mode 100644 OSX/include/security_keychain/PrimaryKey.h delete mode 100644 OSX/include/security_keychain/SecACL.cpp delete mode 100644 OSX/include/security_keychain/SecACL.h delete mode 100644 OSX/include/security_keychain/SecAccess.cpp delete mode 100644 OSX/include/security_keychain/SecAccess.h delete mode 100644 OSX/include/security_keychain/SecAccessPriv.h delete mode 100644 OSX/include/security_keychain/SecAsn1TypesP.h delete mode 100644 OSX/include/security_keychain/SecBase.cpp delete mode 100644 OSX/include/security_keychain/SecBase.h delete mode 100644 OSX/include/security_keychain/SecBase64P.c delete mode 100644 OSX/include/security_keychain/SecBase64P.h delete mode 100644 OSX/include/security_keychain/SecBaseP.h delete mode 100644 OSX/include/security_keychain/SecBasePriv.h delete mode 100644 OSX/include/security_keychain/SecBridge.h delete mode 100644 OSX/include/security_keychain/SecCFTypes.cpp delete mode 100644 OSX/include/security_keychain/SecCFTypes.h delete mode 100644 OSX/include/security_keychain/SecCertificate.cpp delete mode 100644 OSX/include/security_keychain/SecCertificate.h delete mode 100644 OSX/include/security_keychain/SecCertificateBundle.cpp delete mode 100644 OSX/include/security_keychain/SecCertificateBundle.h delete mode 100644 OSX/include/security_keychain/SecCertificateInternalP.h delete mode 100644 OSX/include/security_keychain/SecCertificateOIDs.h delete mode 100644 OSX/include/security_keychain/SecCertificateP.c delete mode 100644 OSX/include/security_keychain/SecCertificateP.h delete mode 100644 OSX/include/security_keychain/SecCertificatePriv.h delete mode 100644 OSX/include/security_keychain/SecCertificatePrivP.h delete mode 100644 OSX/include/security_keychain/SecCertificateRequest.cpp delete mode 100644 OSX/include/security_keychain/SecCertificateRequest.h delete mode 100644 OSX/include/security_keychain/SecExport.cpp delete mode 100644 OSX/include/security_keychain/SecExternalRep.cpp delete mode 100644 OSX/include/security_keychain/SecExternalRep.h delete mode 100644 OSX/include/security_keychain/SecFDERecoveryAsymmetricCrypto.cpp delete mode 100644 OSX/include/security_keychain/SecFDERecoveryAsymmetricCrypto.h delete mode 100644 OSX/include/security_keychain/SecFrameworkP.c delete mode 100644 OSX/include/security_keychain/SecFrameworkP.h delete mode 100644 OSX/include/security_keychain/SecIdentity.cpp delete mode 100644 OSX/include/security_keychain/SecIdentity.h delete mode 100644 OSX/include/security_keychain/SecIdentityPriv.h delete mode 100644 OSX/include/security_keychain/SecIdentitySearch.cpp delete mode 100644 OSX/include/security_keychain/SecIdentitySearch.h delete mode 100644 OSX/include/security_keychain/SecIdentitySearchPriv.h delete mode 100644 OSX/include/security_keychain/SecImport.cpp delete mode 100644 OSX/include/security_keychain/SecImportExport.c delete mode 100644 OSX/include/security_keychain/SecImportExport.h delete mode 100644 OSX/include/security_keychain/SecImportExportAgg.cpp delete mode 100644 OSX/include/security_keychain/SecImportExportAgg.h delete mode 100644 OSX/include/security_keychain/SecImportExportCrypto.cpp delete mode 100644 OSX/include/security_keychain/SecImportExportCrypto.h delete mode 100644 OSX/include/security_keychain/SecImportExportOpenSSH.cpp delete mode 100644 OSX/include/security_keychain/SecImportExportOpenSSH.h delete mode 100644 OSX/include/security_keychain/SecImportExportPem.cpp delete mode 100644 OSX/include/security_keychain/SecImportExportPem.h delete mode 100644 OSX/include/security_keychain/SecImportExportPkcs8.cpp delete mode 100644 OSX/include/security_keychain/SecImportExportPkcs8.h delete mode 100644 OSX/include/security_keychain/SecImportExportUtils.cpp delete mode 100644 OSX/include/security_keychain/SecImportExportUtils.h delete mode 100644 OSX/include/security_keychain/SecInternal.h delete mode 100644 OSX/include/security_keychain/SecInternalP.h delete mode 100644 OSX/include/security_keychain/SecItem.cpp delete mode 100644 OSX/include/security_keychain/SecItem.h delete mode 100644 OSX/include/security_keychain/SecItemConstants.c delete mode 100644 OSX/include/security_keychain/SecItemPriv.h delete mode 100644 OSX/include/security_keychain/SecKey.cpp delete mode 100644 OSX/include/security_keychain/SecKey.h delete mode 100644 OSX/include/security_keychain/SecKeyPriv.h delete mode 100644 OSX/include/security_keychain/SecKeychain.cpp delete mode 100644 OSX/include/security_keychain/SecKeychain.h delete mode 100644 OSX/include/security_keychain/SecKeychainAddIToolsPassword.cpp delete mode 100644 OSX/include/security_keychain/SecKeychainItem.cpp delete mode 100644 OSX/include/security_keychain/SecKeychainItem.h delete mode 100644 OSX/include/security_keychain/SecKeychainItemExtendedAttributes.cpp delete mode 100644 OSX/include/security_keychain/SecKeychainItemExtendedAttributes.h delete mode 100644 OSX/include/security_keychain/SecKeychainItemPriv.h delete mode 100644 OSX/include/security_keychain/SecKeychainPriv.h delete mode 100644 OSX/include/security_keychain/SecKeychainSearch.cpp delete mode 100644 OSX/include/security_keychain/SecKeychainSearch.h delete mode 100644 OSX/include/security_keychain/SecKeychainSearchPriv.h delete mode 100644 OSX/include/security_keychain/SecNetscapeTemplates.cpp delete mode 100644 OSX/include/security_keychain/SecNetscapeTemplates.h delete mode 100644 OSX/include/security_keychain/SecPassword.cpp delete mode 100644 OSX/include/security_keychain/SecPassword.h delete mode 100644 OSX/include/security_keychain/SecPkcs8Templates.cpp delete mode 100644 OSX/include/security_keychain/SecPkcs8Templates.h delete mode 100644 OSX/include/security_keychain/SecPolicy.cpp delete mode 100644 OSX/include/security_keychain/SecPolicy.h delete mode 100644 OSX/include/security_keychain/SecPolicyPriv.h delete mode 100644 OSX/include/security_keychain/SecPolicySearch.cpp delete mode 100644 OSX/include/security_keychain/SecPolicySearch.h delete mode 100644 OSX/include/security_keychain/SecRSAKeyP.h delete mode 100644 OSX/include/security_keychain/SecRandom.c delete mode 100644 OSX/include/security_keychain/SecRandom.h delete mode 100644 OSX/include/security_keychain/SecRandomP.h delete mode 100644 OSX/include/security_keychain/SecRecoveryPassword.c delete mode 100644 OSX/include/security_keychain/SecRecoveryPassword.h delete mode 100644 OSX/include/security_keychain/SecTrust.cpp delete mode 100644 OSX/include/security_keychain/SecTrust.h delete mode 100644 OSX/include/security_keychain/SecTrustPriv.h delete mode 100644 OSX/include/security_keychain/SecTrustSettings.cpp delete mode 100644 OSX/include/security_keychain/SecTrustSettings.h delete mode 100644 OSX/include/security_keychain/SecTrustSettingsCertificates.h delete mode 100644 OSX/include/security_keychain/SecTrustSettingsPriv.h delete mode 100644 OSX/include/security_keychain/SecTrustedApplication.cpp delete mode 100644 OSX/include/security_keychain/SecTrustedApplication.h delete mode 100644 OSX/include/security_keychain/SecTrustedApplicationPriv.h delete mode 100644 OSX/include/security_keychain/SecWrappedKeys.cpp delete mode 100644 OSX/include/security_keychain/Security.h delete mode 100644 OSX/include/security_keychain/StorageManager.cpp delete mode 100644 OSX/include/security_keychain/StorageManager.h delete mode 100644 OSX/include/security_keychain/Trust.cpp delete mode 100644 OSX/include/security_keychain/Trust.h delete mode 100644 OSX/include/security_keychain/TrustAdditions.cpp delete mode 100644 OSX/include/security_keychain/TrustAdditions.h delete mode 100644 OSX/include/security_keychain/TrustItem.cpp delete mode 100644 OSX/include/security_keychain/TrustItem.h delete mode 100644 OSX/include/security_keychain/TrustKeychains.h delete mode 100644 OSX/include/security_keychain/TrustRevocation.cpp delete mode 100644 OSX/include/security_keychain/TrustSettings.cpp delete mode 100644 OSX/include/security_keychain/TrustSettings.h delete mode 100644 OSX/include/security_keychain/TrustSettingsSchema.h delete mode 100644 OSX/include/security_keychain/TrustSettingsUtils.cpp delete mode 100644 OSX/include/security_keychain/TrustSettingsUtils.h delete mode 100644 OSX/include/security_keychain/TrustStore.cpp delete mode 100644 OSX/include/security_keychain/TrustStore.h delete mode 100644 OSX/include/security_keychain/TrustedApplication.cpp delete mode 100644 OSX/include/security_keychain/TrustedApplication.h delete mode 100644 OSX/include/security_keychain/UnlockReferralItem.cpp delete mode 100644 OSX/include/security_keychain/UnlockReferralItem.h delete mode 100644 OSX/include/security_keychain/certextensionsP.h delete mode 100644 OSX/include/security_keychain/cssmdatetime.cpp delete mode 100644 OSX/include/security_keychain/cssmdatetime.h delete mode 100644 OSX/include/security_keychain/defaultcreds.cpp delete mode 100644 OSX/include/security_keychain/defaultcreds.h delete mode 100644 OSX/include/security_keychain/generateErrStrings.pl delete mode 100644 OSX/include/security_keychain/security_keychain.exp delete mode 100644 OSX/include/security_keychain/tsaDERUtilities.c delete mode 100644 OSX/include/security_keychain/tsaDERUtilities.h create mode 120000 OSX/include/security_ocspd delete mode 100644 OSX/include/security_ocspd/ocspExtensions.cpp delete mode 100644 OSX/include/security_ocspd/ocspExtensions.h delete mode 100644 OSX/include/security_ocspd/ocspResponse.cpp delete mode 100644 OSX/include/security_ocspd/ocspResponse.h delete mode 100644 OSX/include/security_ocspd/ocspdClient.h delete mode 100644 OSX/include/security_ocspd/ocspdDbSchema.cpp delete mode 100644 OSX/include/security_ocspd/ocspdDbSchema.h delete mode 100644 OSX/include/security_ocspd/ocspdDebug.h delete mode 100644 OSX/include/security_ocspd/ocspdTypes.h delete mode 100644 OSX/include/security_ocspd/ocspdUtils.cpp delete mode 100644 OSX/include/security_ocspd/ocspdUtils.h create mode 120000 OSX/include/security_pkcs12 delete mode 100644 OSX/include/security_pkcs12/SecPkcs12.cpp delete mode 100644 OSX/include/security_pkcs12/SecPkcs12.h delete mode 100644 OSX/include/security_pkcs12/pkcs12BagAttrs.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12BagAttrs.h delete mode 100644 OSX/include/security_pkcs12/pkcs12Coder.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12Coder.h delete mode 100644 OSX/include/security_pkcs12/pkcs12Crypto.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12Crypto.h delete mode 100644 OSX/include/security_pkcs12/pkcs12Debug.h delete mode 100644 OSX/include/security_pkcs12/pkcs12Decode.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12Encode.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12Keychain.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12SafeBag.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12SafeBag.h delete mode 100644 OSX/include/security_pkcs12/pkcs12Templates.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12Templates.h delete mode 100644 OSX/include/security_pkcs12/pkcs12Utils.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs12Utils.h delete mode 100644 OSX/include/security_pkcs12/pkcs7Templates.cpp delete mode 100644 OSX/include/security_pkcs12/pkcs7Templates.h delete mode 100644 OSX/include/security_pkcs12/pkcsoids.cpp delete mode 100644 OSX/include/security_pkcs12/pkcsoids.h create mode 120000 OSX/include/security_smime delete mode 100644 OSX/include/security_smime/SecCMS.c delete mode 100644 OSX/include/security_smime/SecCMS.h delete mode 100644 OSX/include/security_smime/SecCmsBase.h delete mode 100644 OSX/include/security_smime/SecCmsContentInfo.h delete mode 100644 OSX/include/security_smime/SecCmsDecoder.h delete mode 100644 OSX/include/security_smime/SecCmsDigestContext.h delete mode 100644 OSX/include/security_smime/SecCmsDigestedData.h delete mode 100644 OSX/include/security_smime/SecCmsEncoder.h delete mode 100644 OSX/include/security_smime/SecCmsEncryptedData.h delete mode 100644 OSX/include/security_smime/SecCmsEnvelopedData.h delete mode 100644 OSX/include/security_smime/SecCmsMessage.h delete mode 100644 OSX/include/security_smime/SecCmsRecipientInfo.h delete mode 100644 OSX/include/security_smime/SecCmsSignedData.h delete mode 100644 OSX/include/security_smime/SecCmsSignerInfo.h delete mode 100644 OSX/include/security_smime/SecSMIME.h delete mode 100644 OSX/include/security_smime/SecSMIMEPriv.h delete mode 100644 OSX/include/security_smime/cert.c delete mode 100644 OSX/include/security_smime/cert.h delete mode 100644 OSX/include/security_smime/cmsarray.c delete mode 100644 OSX/include/security_smime/cmsasn1.c delete mode 100644 OSX/include/security_smime/cmsattr.c delete mode 100644 OSX/include/security_smime/cmscinfo.c delete mode 100644 OSX/include/security_smime/cmscipher.c delete mode 100644 OSX/include/security_smime/cmsdecode.c delete mode 100644 OSX/include/security_smime/cmsdigdata.c delete mode 100644 OSX/include/security_smime/cmsdigest.c delete mode 100644 OSX/include/security_smime/cmsencdata.c delete mode 100644 OSX/include/security_smime/cmsencode.c delete mode 100644 OSX/include/security_smime/cmsenvdata.c delete mode 100644 OSX/include/security_smime/cmslocal.h delete mode 100644 OSX/include/security_smime/cmsmessage.c delete mode 100644 OSX/include/security_smime/cmspriv.h delete mode 100644 OSX/include/security_smime/cmspubkey.c delete mode 100644 OSX/include/security_smime/cmsrecinfo.c delete mode 100644 OSX/include/security_smime/cmsreclist.c delete mode 100644 OSX/include/security_smime/cmsreclist.h delete mode 100644 OSX/include/security_smime/cmssigdata.c delete mode 100644 OSX/include/security_smime/cmssiginfo.c delete mode 100644 OSX/include/security_smime/cmstpriv.h delete mode 100644 OSX/include/security_smime/cmsutil.c delete mode 100644 OSX/include/security_smime/cryptohi.c delete mode 100644 OSX/include/security_smime/cryptohi.h delete mode 100644 OSX/include/security_smime/plhash.c delete mode 100644 OSX/include/security_smime/plhash.h delete mode 100644 OSX/include/security_smime/secalgid.c delete mode 100644 OSX/include/security_smime/secitem.c delete mode 100644 OSX/include/security_smime/secitem.h delete mode 100644 OSX/include/security_smime/secoid.c delete mode 100644 OSX/include/security_smime/secoid.h delete mode 100644 OSX/include/security_smime/secoidt.h delete mode 100644 OSX/include/security_smime/security_smime.exp delete mode 100644 OSX/include/security_smime/siginfoUtils.cpp delete mode 100644 OSX/include/security_smime/smimeutil.c delete mode 100755 OSX/include/security_smime/testcms delete mode 100644 OSX/include/security_smime/tsaSupport.c delete mode 100644 OSX/include/security_smime/tsaSupport.h delete mode 100644 OSX/include/security_smime/tsaSupportPriv.h delete mode 100644 OSX/include/security_smime/tsaTemplates.c delete mode 100644 OSX/include/security_smime/tsaTemplates.h create mode 120000 OSX/include/security_utilities delete mode 100644 OSX/include/security_utilities/adornments.cpp delete mode 100644 OSX/include/security_utilities/adornments.h delete mode 100644 OSX/include/security_utilities/alloc.cpp delete mode 100644 OSX/include/security_utilities/alloc.h delete mode 100644 OSX/include/security_utilities/blob.cpp delete mode 100644 OSX/include/security_utilities/blob.h delete mode 100644 OSX/include/security_utilities/bufferfifo.cpp delete mode 100644 OSX/include/security_utilities/bufferfifo.h delete mode 100644 OSX/include/security_utilities/buffers.cpp delete mode 100644 OSX/include/security_utilities/buffers.h delete mode 100644 OSX/include/security_utilities/ccaudit.cpp delete mode 100644 OSX/include/security_utilities/ccaudit.h delete mode 100644 OSX/include/security_utilities/cfclass.cpp delete mode 100644 OSX/include/security_utilities/cfclass.h delete mode 100644 OSX/include/security_utilities/cfmach++.cpp delete mode 100644 OSX/include/security_utilities/cfmach++.h delete mode 100644 OSX/include/security_utilities/cfmunge.cpp delete mode 100644 OSX/include/security_utilities/cfmunge.h delete mode 100644 OSX/include/security_utilities/cfutilities.cpp delete mode 100644 OSX/include/security_utilities/cfutilities.h delete mode 100644 OSX/include/security_utilities/coderepository.cpp delete mode 100644 OSX/include/security_utilities/coderepository.h delete mode 100644 OSX/include/security_utilities/crc.c delete mode 100644 OSX/include/security_utilities/crc.h delete mode 100644 OSX/include/security_utilities/daemon.cpp delete mode 100644 OSX/include/security_utilities/daemon.h delete mode 100644 OSX/include/security_utilities/debugging.cpp delete mode 100644 OSX/include/security_utilities/debugging.h delete mode 100644 OSX/include/security_utilities/debugging_internal.cpp delete mode 100644 OSX/include/security_utilities/debugging_internal.h delete mode 100644 OSX/include/security_utilities/debugsupport.h delete mode 100644 OSX/include/security_utilities/devrandom.cpp delete mode 100644 OSX/include/security_utilities/devrandom.h delete mode 100644 OSX/include/security_utilities/dispatch.cpp delete mode 100644 OSX/include/security_utilities/dispatch.h delete mode 100644 OSX/include/security_utilities/dtrace.mk delete mode 100644 OSX/include/security_utilities/dyld_cache_format.h delete mode 100644 OSX/include/security_utilities/dyldcache.cpp delete mode 100644 OSX/include/security_utilities/dyldcache.h delete mode 100644 OSX/include/security_utilities/endian.cpp delete mode 100644 OSX/include/security_utilities/endian.h delete mode 100644 OSX/include/security_utilities/errors.cpp delete mode 100644 OSX/include/security_utilities/errors.h delete mode 100644 OSX/include/security_utilities/exports delete mode 100644 OSX/include/security_utilities/fdmover.cpp delete mode 100644 OSX/include/security_utilities/fdmover.h delete mode 100644 OSX/include/security_utilities/fdsel.cpp delete mode 100644 OSX/include/security_utilities/fdsel.h delete mode 100644 OSX/include/security_utilities/globalizer.cpp delete mode 100644 OSX/include/security_utilities/globalizer.h delete mode 100644 OSX/include/security_utilities/hashing.cpp delete mode 100644 OSX/include/security_utilities/hashing.h delete mode 100644 OSX/include/security_utilities/headermap.cpp delete mode 100644 OSX/include/security_utilities/headermap.h delete mode 100644 OSX/include/security_utilities/hosts.cpp delete mode 100644 OSX/include/security_utilities/hosts.h delete mode 100644 OSX/include/security_utilities/inetreply.cpp delete mode 100644 OSX/include/security_utilities/inetreply.h delete mode 100644 OSX/include/security_utilities/iodevices.cpp delete mode 100644 OSX/include/security_utilities/iodevices.h delete mode 100644 OSX/include/security_utilities/ip++.cpp delete mode 100644 OSX/include/security_utilities/ip++.h delete mode 100644 OSX/include/security_utilities/kq++.cpp delete mode 100644 OSX/include/security_utilities/kq++.h delete mode 100644 OSX/include/security_utilities/ktracecodes.h delete mode 100644 OSX/include/security_utilities/logging.cpp delete mode 100644 OSX/include/security_utilities/logging.h delete mode 100644 OSX/include/security_utilities/mach++.cpp delete mode 100644 OSX/include/security_utilities/mach++.h delete mode 100644 OSX/include/security_utilities/mach_notify.c delete mode 100644 OSX/include/security_utilities/mach_notify.h delete mode 100644 OSX/include/security_utilities/macho++.cpp delete mode 100644 OSX/include/security_utilities/macho++.h delete mode 100644 OSX/include/security_utilities/machrunloopserver.cpp delete mode 100644 OSX/include/security_utilities/machrunloopserver.h delete mode 100644 OSX/include/security_utilities/machserver.cpp delete mode 100644 OSX/include/security_utilities/machserver.h delete mode 100644 OSX/include/security_utilities/memstreams.h delete mode 100644 OSX/include/security_utilities/memutils.h delete mode 100644 OSX/include/security_utilities/muscle++.cpp delete mode 100644 OSX/include/security_utilities/muscle++.h delete mode 100644 OSX/include/security_utilities/osxcode.cpp delete mode 100644 OSX/include/security_utilities/osxcode.h delete mode 100644 OSX/include/security_utilities/pcsc++.cpp delete mode 100644 OSX/include/security_utilities/pcsc++.h delete mode 100644 OSX/include/security_utilities/powerwatch.cpp delete mode 100644 OSX/include/security_utilities/powerwatch.h delete mode 100644 OSX/include/security_utilities/refcount.h delete mode 100644 OSX/include/security_utilities/seccfobject.cpp delete mode 100644 OSX/include/security_utilities/seccfobject.h delete mode 100644 OSX/include/security_utilities/security_utilities.d delete mode 100644 OSX/include/security_utilities/security_utilities.h delete mode 100644 OSX/include/security_utilities/selector.cpp delete mode 100644 OSX/include/security_utilities/selector.h delete mode 100644 OSX/include/security_utilities/simpleprefs.cpp delete mode 100644 OSX/include/security_utilities/simpleprefs.h delete mode 100644 OSX/include/security_utilities/socks++.cpp delete mode 100644 OSX/include/security_utilities/socks++.h delete mode 100644 OSX/include/security_utilities/socks++4.cpp delete mode 100644 OSX/include/security_utilities/socks++4.h delete mode 100644 OSX/include/security_utilities/socks++5.cpp delete mode 100644 OSX/include/security_utilities/socks++5.h delete mode 100644 OSX/include/security_utilities/sqlite++.cpp delete mode 100644 OSX/include/security_utilities/sqlite++.h delete mode 100644 OSX/include/security_utilities/streams.cpp delete mode 100644 OSX/include/security_utilities/streams.h delete mode 100644 OSX/include/security_utilities/superblob.cpp delete mode 100644 OSX/include/security_utilities/superblob.h delete mode 100644 OSX/include/security_utilities/threading.cpp delete mode 100644 OSX/include/security_utilities/threading.h delete mode 100644 OSX/include/security_utilities/threading_internal.h delete mode 100644 OSX/include/security_utilities/timeflow.cpp delete mode 100644 OSX/include/security_utilities/timeflow.h delete mode 100644 OSX/include/security_utilities/tqueue.cpp delete mode 100644 OSX/include/security_utilities/tqueue.h delete mode 100644 OSX/include/security_utilities/trackingallocator.cpp delete mode 100644 OSX/include/security_utilities/trackingallocator.h delete mode 100644 OSX/include/security_utilities/transactions.cpp delete mode 100644 OSX/include/security_utilities/transactions.h delete mode 100644 OSX/include/security_utilities/typedvalue.cpp delete mode 100644 OSX/include/security_utilities/typedvalue.h delete mode 100644 OSX/include/security_utilities/unix++.cpp delete mode 100644 OSX/include/security_utilities/unix++.h delete mode 100644 OSX/include/security_utilities/unixchild.cpp delete mode 100644 OSX/include/security_utilities/unixchild.h delete mode 100644 OSX/include/security_utilities/url.cpp delete mode 100644 OSX/include/security_utilities/url.h delete mode 100644 OSX/include/security_utilities/utilities.cpp delete mode 100644 OSX/include/security_utilities/utilities.h delete mode 100644 OSX/include/security_utilities/utility_config.h delete mode 100644 OSX/include/security_utilities/vproc++.cpp delete mode 100644 OSX/include/security_utilities/vproc++.h create mode 120000 OSX/include/securityd_client delete mode 100644 OSX/include/securityd_client/SharedMemoryClient.cpp delete mode 100644 OSX/include/securityd_client/SharedMemoryClient.h delete mode 100644 OSX/include/securityd_client/SharedMemoryCommon.h delete mode 100644 OSX/include/securityd_client/dictionary.cpp delete mode 100644 OSX/include/securityd_client/dictionary.h delete mode 100644 OSX/include/securityd_client/eventlistener.cpp delete mode 100644 OSX/include/securityd_client/eventlistener.h delete mode 100644 OSX/include/securityd_client/handletypes.h delete mode 100644 OSX/include/securityd_client/sec_xdr.c delete mode 100644 OSX/include/securityd_client/sec_xdr.h delete mode 100644 OSX/include/securityd_client/sec_xdr_array.c delete mode 100644 OSX/include/securityd_client/sec_xdr_reference.c delete mode 100644 OSX/include/securityd_client/sec_xdr_sizeof.c delete mode 100644 OSX/include/securityd_client/sec_xdrmem.c delete mode 100644 OSX/include/securityd_client/ss_types.h delete mode 100644 OSX/include/securityd_client/ssblob.cpp delete mode 100644 OSX/include/securityd_client/ssblob.h delete mode 100644 OSX/include/securityd_client/ssclient.cpp delete mode 100644 OSX/include/securityd_client/ssclient.h delete mode 100644 OSX/include/securityd_client/sscommon.h delete mode 100644 OSX/include/securityd_client/ssnotify.h delete mode 100644 OSX/include/securityd_client/sstransit.cpp delete mode 100644 OSX/include/securityd_client/sstransit.h delete mode 100644 OSX/include/securityd_client/transition.cpp delete mode 100644 OSX/include/securityd_client/ucsp_types.h delete mode 100644 OSX/include/securityd_client/xdr_auth.c delete mode 100644 OSX/include/securityd_client/xdr_auth.h delete mode 100644 OSX/include/securityd_client/xdr_cssm.c delete mode 100644 OSX/include/securityd_client/xdr_cssm.h delete mode 100644 OSX/include/securityd_client/xdr_dldb.cpp delete mode 100644 OSX/include/securityd_client/xdr_dldb.h create mode 120000 OSX/libsecurity_asn1/Security delete mode 100644 OSX/libsecurity_asn1/Security/SecAsn1Coder.c delete mode 100644 OSX/libsecurity_asn1/Security/SecAsn1Coder.h delete mode 100644 OSX/libsecurity_asn1/Security/SecAsn1Templates.c delete mode 100644 OSX/libsecurity_asn1/Security/SecAsn1Templates.h delete mode 100644 OSX/libsecurity_asn1/Security/SecAsn1Types.h delete mode 100644 OSX/libsecurity_asn1/Security/SecNssCoder.cpp delete mode 100644 OSX/libsecurity_asn1/Security/SecNssCoder.h delete mode 100644 OSX/libsecurity_asn1/Security/X509Templates.c delete mode 100644 OSX/libsecurity_asn1/Security/X509Templates.h delete mode 100644 OSX/libsecurity_asn1/Security/asn1Templates.h delete mode 100644 OSX/libsecurity_asn1/Security/certExtensionTemplates.c delete mode 100644 OSX/libsecurity_asn1/Security/certExtensionTemplates.h delete mode 100644 OSX/libsecurity_asn1/Security/csrTemplates.c delete mode 100644 OSX/libsecurity_asn1/Security/csrTemplates.h delete mode 100644 OSX/libsecurity_asn1/Security/keyTemplates.c delete mode 100644 OSX/libsecurity_asn1/Security/keyTemplates.h delete mode 100644 OSX/libsecurity_asn1/Security/nameTemplates.c delete mode 100644 OSX/libsecurity_asn1/Security/nameTemplates.h delete mode 100644 OSX/libsecurity_asn1/Security/nsprPortX.c delete mode 100644 OSX/libsecurity_asn1/Security/nssUtils.c delete mode 100644 OSX/libsecurity_asn1/Security/nssUtils.h delete mode 100644 OSX/libsecurity_asn1/Security/nssilckt.h delete mode 100644 OSX/libsecurity_asn1/Security/nssilock.h delete mode 100644 OSX/libsecurity_asn1/Security/nsslocks.h delete mode 100644 OSX/libsecurity_asn1/Security/ocspTemplates.c delete mode 100644 OSX/libsecurity_asn1/Security/ocspTemplates.h delete mode 100644 OSX/libsecurity_asn1/Security/oidsalg.c delete mode 100644 OSX/libsecurity_asn1/Security/oidsalg.h delete mode 100644 OSX/libsecurity_asn1/Security/oidsattr.c delete mode 100644 OSX/libsecurity_asn1/Security/oidsattr.h delete mode 100644 OSX/libsecurity_asn1/Security/oidsbase.h delete mode 100644 OSX/libsecurity_asn1/Security/oidsocsp.c delete mode 100644 OSX/libsecurity_asn1/Security/oidsocsp.h delete mode 100644 OSX/libsecurity_asn1/Security/osKeyTemplates.c delete mode 100644 OSX/libsecurity_asn1/Security/osKeyTemplates.h delete mode 100644 OSX/libsecurity_asn1/Security/pkcs12Templates.c delete mode 100644 OSX/libsecurity_asn1/Security/pkcs12Templates.h delete mode 100644 OSX/libsecurity_asn1/Security/pkcs7Templates.c delete mode 100644 OSX/libsecurity_asn1/Security/pkcs7Templates.h delete mode 100644 OSX/libsecurity_asn1/Security/plarena.c delete mode 100644 OSX/libsecurity_asn1/Security/plarena.h delete mode 100644 OSX/libsecurity_asn1/Security/plarenas.h delete mode 100644 OSX/libsecurity_asn1/Security/plstr.h delete mode 100644 OSX/libsecurity_asn1/Security/prbit.h delete mode 100644 OSX/libsecurity_asn1/Security/prcpucfg.h delete mode 100644 OSX/libsecurity_asn1/Security/prcvar.h delete mode 100644 OSX/libsecurity_asn1/Security/prenv.h delete mode 100644 OSX/libsecurity_asn1/Security/prerr.h delete mode 100644 OSX/libsecurity_asn1/Security/prerror.h delete mode 100644 OSX/libsecurity_asn1/Security/prinit.h delete mode 100644 OSX/libsecurity_asn1/Security/prinrval.h delete mode 100644 OSX/libsecurity_asn1/Security/prlock.h delete mode 100644 OSX/libsecurity_asn1/Security/prlog.h delete mode 100644 OSX/libsecurity_asn1/Security/prlong.h delete mode 100644 OSX/libsecurity_asn1/Security/prmem.h delete mode 100644 OSX/libsecurity_asn1/Security/prmon.h delete mode 100644 OSX/libsecurity_asn1/Security/protypes.h delete mode 100644 OSX/libsecurity_asn1/Security/prthread.h delete mode 100644 OSX/libsecurity_asn1/Security/prtime.h delete mode 100644 OSX/libsecurity_asn1/Security/prtypes.h delete mode 100644 OSX/libsecurity_asn1/Security/prvrsion.h delete mode 100644 OSX/libsecurity_asn1/Security/secErrorStr.c delete mode 100644 OSX/libsecurity_asn1/Security/secasn1.h delete mode 100644 OSX/libsecurity_asn1/Security/secasn1d.c delete mode 100644 OSX/libsecurity_asn1/Security/secasn1e.c delete mode 100644 OSX/libsecurity_asn1/Security/secasn1t.h delete mode 100644 OSX/libsecurity_asn1/Security/secasn1u.c delete mode 100644 OSX/libsecurity_asn1/Security/seccomon.h delete mode 100644 OSX/libsecurity_asn1/Security/secerr.h delete mode 100644 OSX/libsecurity_asn1/Security/secport.c delete mode 100644 OSX/libsecurity_asn1/Security/secport.h delete mode 100644 OSX/libsecurity_asn1/Security/security_asn1.exp create mode 120000 OSX/libsecurity_asn1/security_asn1 delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecAsn1Coder.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecAsn1Coder.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecAsn1Templates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecAsn1Templates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecAsn1Types.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecNssCoder.cpp delete mode 100644 OSX/libsecurity_asn1/security_asn1/SecNssCoder.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/X509Templates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/X509Templates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/asn1Templates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/certExtensionTemplates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/certExtensionTemplates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/csrTemplates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/csrTemplates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/keyTemplates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/keyTemplates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/nameTemplates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/nameTemplates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/nsprPortX.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/nssUtils.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/nssUtils.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/nssilckt.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/nssilock.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/nsslocks.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/ocspTemplates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/ocspTemplates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsalg.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsalg.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsattr.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsattr.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsbase.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsocsp.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/oidsocsp.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/osKeyTemplates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/osKeyTemplates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/pkcs12Templates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/pkcs12Templates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/pkcs7Templates.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/pkcs7Templates.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/plarena.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/plarena.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/plarenas.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/plstr.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prbit.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prcpucfg.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prcvar.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prenv.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prerr.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prerror.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prinit.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prinrval.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prlock.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prlog.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prlong.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prmem.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prmon.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/protypes.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prthread.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prtime.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prtypes.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/prvrsion.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/secErrorStr.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/secasn1.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/secasn1d.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/secasn1e.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/secasn1t.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/secasn1u.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/seccomon.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/secerr.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/secport.c delete mode 100644 OSX/libsecurity_asn1/security_asn1/secport.h delete mode 100644 OSX/libsecurity_asn1/security_asn1/security_asn1.exp create mode 120000 OSX/libsecurity_keychain/Security delete mode 100644 OSX/libsecurity_keychain/Security/ACL.cpp delete mode 100644 OSX/libsecurity_keychain/Security/ACL.h delete mode 100644 OSX/libsecurity_keychain/Security/Access.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Access.h delete mode 100644 OSX/libsecurity_keychain/Security/AppleBaselineEscrowCertificates.h delete mode 100644 OSX/libsecurity_keychain/Security/CCallbackMgr.cp delete mode 100644 OSX/libsecurity_keychain/Security/CCallbackMgr.h delete mode 100644 OSX/libsecurity_keychain/Security/Certificate.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Certificate.h delete mode 100644 OSX/libsecurity_keychain/Security/CertificateRequest.cpp delete mode 100644 OSX/libsecurity_keychain/Security/CertificateRequest.h delete mode 100644 OSX/libsecurity_keychain/Security/CertificateValues.cpp delete mode 100644 OSX/libsecurity_keychain/Security/CertificateValues.h delete mode 100644 OSX/libsecurity_keychain/Security/DLDBListCFPref.cpp delete mode 100644 OSX/libsecurity_keychain/Security/DLDBListCFPref.h delete mode 100644 OSX/libsecurity_keychain/Security/DynamicDLDBList.cpp delete mode 100644 OSX/libsecurity_keychain/Security/DynamicDLDBList.h delete mode 100644 OSX/libsecurity_keychain/Security/ExtendedAttribute.cpp delete mode 100644 OSX/libsecurity_keychain/Security/ExtendedAttribute.h delete mode 100644 OSX/libsecurity_keychain/Security/Globals.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Globals.h delete mode 100644 OSX/libsecurity_keychain/Security/Identity.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Identity.h delete mode 100644 OSX/libsecurity_keychain/Security/IdentityCursor.cpp delete mode 100644 OSX/libsecurity_keychain/Security/IdentityCursor.h delete mode 100644 OSX/libsecurity_keychain/Security/Item.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Item.h delete mode 100644 OSX/libsecurity_keychain/Security/KCCursor.cpp delete mode 100644 OSX/libsecurity_keychain/Security/KCCursor.h delete mode 100644 OSX/libsecurity_keychain/Security/KCEventNotifier.cpp delete mode 100644 OSX/libsecurity_keychain/Security/KCEventNotifier.h delete mode 100644 OSX/libsecurity_keychain/Security/KCExceptions.h delete mode 100644 OSX/libsecurity_keychain/Security/KCUtilities.cpp delete mode 100644 OSX/libsecurity_keychain/Security/KCUtilities.h delete mode 100644 OSX/libsecurity_keychain/Security/KeyItem.cpp delete mode 100644 OSX/libsecurity_keychain/Security/KeyItem.h delete mode 100644 OSX/libsecurity_keychain/Security/Keychains.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Keychains.h delete mode 100644 OSX/libsecurity_keychain/Security/MacOSErrorStrings.h delete mode 100644 OSX/libsecurity_keychain/Security/Password.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Password.h delete mode 100644 OSX/libsecurity_keychain/Security/Policies.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Policies.h delete mode 100644 OSX/libsecurity_keychain/Security/PolicyCursor.cpp delete mode 100644 OSX/libsecurity_keychain/Security/PolicyCursor.h delete mode 100644 OSX/libsecurity_keychain/Security/PrimaryKey.cpp delete mode 100644 OSX/libsecurity_keychain/Security/PrimaryKey.h delete mode 100644 OSX/libsecurity_keychain/Security/SecACL.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecACL.h delete mode 100644 OSX/libsecurity_keychain/Security/SecAccess.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecAccess.h delete mode 100644 OSX/libsecurity_keychain/Security/SecAccessPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecAsn1TypesP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecBase.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecBase.h delete mode 100644 OSX/libsecurity_keychain/Security/SecBase64P.c delete mode 100644 OSX/libsecurity_keychain/Security/SecBase64P.h delete mode 100644 OSX/libsecurity_keychain/Security/SecBaseP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecBasePriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecBridge.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCFTypes.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecCFTypes.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificate.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificate.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateBundle.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateBundle.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateInternalP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateOIDs.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateP.c delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificatePriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificatePrivP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateRequest.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecCertificateRequest.h delete mode 100644 OSX/libsecurity_keychain/Security/SecExport.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecExternalRep.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecExternalRep.h delete mode 100644 OSX/libsecurity_keychain/Security/SecFDERecoveryAsymmetricCrypto.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecFDERecoveryAsymmetricCrypto.h delete mode 100644 OSX/libsecurity_keychain/Security/SecFrameworkP.c delete mode 100644 OSX/libsecurity_keychain/Security/SecFrameworkP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecIdentity.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecIdentity.h delete mode 100644 OSX/libsecurity_keychain/Security/SecIdentityPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecIdentitySearch.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecIdentitySearch.h delete mode 100644 OSX/libsecurity_keychain/Security/SecIdentitySearchPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImport.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExport.c delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExport.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportAgg.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportAgg.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportCrypto.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportCrypto.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportOpenSSH.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportOpenSSH.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportPem.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportPem.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportPkcs8.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportPkcs8.h delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportUtils.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecImportExportUtils.h delete mode 100644 OSX/libsecurity_keychain/Security/SecInternal.h delete mode 100644 OSX/libsecurity_keychain/Security/SecInternalP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecItem.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecItem.h delete mode 100644 OSX/libsecurity_keychain/Security/SecItemConstants.c delete mode 100644 OSX/libsecurity_keychain/Security/SecItemPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKey.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecKey.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeyPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychain.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychain.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainAddIToolsPassword.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainItem.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainItem.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainItemExtendedAttributes.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainItemExtendedAttributes.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainItemPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainSearch.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainSearch.h delete mode 100644 OSX/libsecurity_keychain/Security/SecKeychainSearchPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecNetscapeTemplates.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecNetscapeTemplates.h delete mode 100644 OSX/libsecurity_keychain/Security/SecPassword.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecPassword.h delete mode 100644 OSX/libsecurity_keychain/Security/SecPkcs8Templates.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecPkcs8Templates.h delete mode 100644 OSX/libsecurity_keychain/Security/SecPolicy.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecPolicy.h delete mode 100644 OSX/libsecurity_keychain/Security/SecPolicyPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecPolicySearch.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecPolicySearch.h delete mode 100644 OSX/libsecurity_keychain/Security/SecRSAKeyP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecRandom.c delete mode 100644 OSX/libsecurity_keychain/Security/SecRandom.h delete mode 100644 OSX/libsecurity_keychain/Security/SecRandomP.h delete mode 100644 OSX/libsecurity_keychain/Security/SecRecoveryPassword.c delete mode 100644 OSX/libsecurity_keychain/Security/SecRecoveryPassword.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrust.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecTrust.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustSettings.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustSettings.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustSettingsCertificates.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustSettingsPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustedApplication.cpp delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustedApplication.h delete mode 100644 OSX/libsecurity_keychain/Security/SecTrustedApplicationPriv.h delete mode 100644 OSX/libsecurity_keychain/Security/SecWrappedKeys.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Security.h delete mode 100644 OSX/libsecurity_keychain/Security/StorageManager.cpp delete mode 100644 OSX/libsecurity_keychain/Security/StorageManager.h delete mode 100644 OSX/libsecurity_keychain/Security/Trust.cpp delete mode 100644 OSX/libsecurity_keychain/Security/Trust.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustAdditions.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustAdditions.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustItem.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustItem.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustKeychains.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustRevocation.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustSettings.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustSettings.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustSettingsSchema.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustSettingsUtils.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustSettingsUtils.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustStore.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustStore.h delete mode 100644 OSX/libsecurity_keychain/Security/TrustedApplication.cpp delete mode 100644 OSX/libsecurity_keychain/Security/TrustedApplication.h delete mode 100644 OSX/libsecurity_keychain/Security/UnlockReferralItem.cpp delete mode 100644 OSX/libsecurity_keychain/Security/UnlockReferralItem.h delete mode 100644 OSX/libsecurity_keychain/Security/certextensionsP.h delete mode 100644 OSX/libsecurity_keychain/Security/cssmdatetime.cpp delete mode 100644 OSX/libsecurity_keychain/Security/cssmdatetime.h delete mode 100644 OSX/libsecurity_keychain/Security/defaultcreds.cpp delete mode 100644 OSX/libsecurity_keychain/Security/defaultcreds.h delete mode 100644 OSX/libsecurity_keychain/Security/generateErrStrings.pl delete mode 100644 OSX/libsecurity_keychain/Security/security_keychain.exp delete mode 100644 OSX/libsecurity_keychain/Security/tsaDERUtilities.c delete mode 100644 OSX/libsecurity_keychain/Security/tsaDERUtilities.h create mode 100644 OSX/libsecurity_keychain/regressions/si-20-sectrust-provisioning.c create mode 100644 OSX/libsecurity_keychain/regressions/si-20-sectrust-provisioning.h mode change 100644 => 120000 OSX/libsecurity_ocspd/common/ocspdClient.h create mode 120000 OSX/libsecurity_ssl/Security delete mode 100644 OSX/libsecurity_ssl/Security/CipherSuite.h delete mode 100644 OSX/libsecurity_ssl/Security/SSLRecordInternal.c delete mode 100644 OSX/libsecurity_ssl/Security/SSLRecordInternal.h delete mode 100644 OSX/libsecurity_ssl/Security/SecureTransport.h delete mode 100644 OSX/libsecurity_ssl/Security/SecureTransportPriv.h delete mode 100644 OSX/libsecurity_ssl/Security/appleSession.c delete mode 100644 OSX/libsecurity_ssl/Security/appleSession.h delete mode 100644 OSX/libsecurity_ssl/Security/cipherSpecs.h delete mode 100644 OSX/libsecurity_ssl/Security/security_ssl.exp delete mode 100644 OSX/libsecurity_ssl/Security/ssl.h delete mode 100644 OSX/libsecurity_ssl/Security/sslBuildFlags.h delete mode 100644 OSX/libsecurity_ssl/Security/sslCipherSpecs.c delete mode 100644 OSX/libsecurity_ssl/Security/sslCipherSpecs.h delete mode 100644 OSX/libsecurity_ssl/Security/sslContext.c delete mode 100644 OSX/libsecurity_ssl/Security/sslContext.h delete mode 100644 OSX/libsecurity_ssl/Security/sslCrypto.c delete mode 100644 OSX/libsecurity_ssl/Security/sslCrypto.h delete mode 100644 OSX/libsecurity_ssl/Security/sslDebug.h delete mode 100644 OSX/libsecurity_ssl/Security/sslKeychain.c delete mode 100644 OSX/libsecurity_ssl/Security/sslKeychain.h delete mode 100644 OSX/libsecurity_ssl/Security/sslMemory.c delete mode 100644 OSX/libsecurity_ssl/Security/sslMemory.h delete mode 100644 OSX/libsecurity_ssl/Security/sslPriv.h delete mode 100644 OSX/libsecurity_ssl/Security/sslRecord.c delete mode 100644 OSX/libsecurity_ssl/Security/sslRecord.h delete mode 100644 OSX/libsecurity_ssl/Security/sslTransport.c delete mode 100644 OSX/libsecurity_ssl/Security/sslTypes.h delete mode 100644 OSX/libsecurity_ssl/Security/sslUtils.c delete mode 100644 OSX/libsecurity_ssl/Security/sslUtils.h delete mode 100644 OSX/libsecurity_ssl/Security/tlsCallbacks.c delete mode 100644 OSX/libsecurity_ssl/Security/tlsCallbacks.h delete mode 100644 OSX/libsecurity_ssl/Security/tls_record_internal.h create mode 120000 OSX/libsecurity_ssl/security_ssl delete mode 100644 OSX/libsecurity_ssl/security_ssl/CipherSuite.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/SSLRecordInternal.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/SSLRecordInternal.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/SecureTransport.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/SecureTransportPriv.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/appleSession.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/appleSession.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/cipherSpecs.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/security_ssl.exp delete mode 100644 OSX/libsecurity_ssl/security_ssl/ssl.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslBuildFlags.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslCipherSpecs.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslCipherSpecs.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslContext.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslContext.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslCrypto.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslCrypto.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslDebug.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslKeychain.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslKeychain.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslMemory.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslMemory.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslPriv.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslRecord.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslRecord.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslTransport.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslTypes.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslUtils.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/sslUtils.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/tlsCallbacks.c delete mode 100644 OSX/libsecurity_ssl/security_ssl/tlsCallbacks.h delete mode 100644 OSX/libsecurity_ssl/security_ssl/tls_record_internal.h create mode 120000 OSX/sec/ProjectHeaders/SOSCircle/Tool delete mode 100644 OSX/sec/ProjectHeaders/SOSCircle/Tool/SOSCommands.h delete mode 100644 OSX/sec/ProjectHeaders/SOSCircle/Tool/keychain_sync.c create mode 120000 OSX/sec/ProjectHeaders/Security/CKBridge delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/CKClient.c delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/CKClient.h delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/SOSCloudKeychainClient.c delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/SOSCloudKeychainClient.h delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/SOSCloudKeychainConstants.c delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/SOSCloudKeychainConstants.h delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/SOSCloudTransport.c delete mode 100644 OSX/sec/ProjectHeaders/Security/CKBridge/SOSCloudTransport.h create mode 120000 OSX/sec/ProjectHeaders/Security/SecureObjectSync delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSARCDefines.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccount.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccount.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountBackup.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountCircles.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountCloudParameters.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountCredentials.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountDer.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountFullPeerInfo.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountHSAJoin.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountHSAJoin.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountPeers.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountPersistence.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountPriv.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountRingUpdate.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountRings.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSAccountUpdate.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSBackupEvent.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSBackupEvent.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSBackupSliceKeyBag.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSBackupSliceKeyBag.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSChangeTracker.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSChangeTracker.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircle.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircle.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircleDer.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircleDer.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCirclePriv.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircleRings.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircleV2.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCircleV2.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCloudCircle.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCloudCircle.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCloudCircleInternal.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCoder.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSCoder.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSConcordanceTrust.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSDataSource.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSDigestVector.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSDigestVector.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSECWrapUnwrap.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSEngine.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSEngine.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSExports.exp-in delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSForerunnerSession.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSForerunnerSession.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSFullPeerInfo.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSFullPeerInfo.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSGenCount.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSGenCount.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSInternal.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSInternal.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSKVSKeys.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSKVSKeys.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSManifest.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSManifest.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSMessage.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSMessage.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeer.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeer.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerCoder.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerCoder.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfo.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfo.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoCollections.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoCollections.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoDER.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoDER.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoInternal.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoPriv.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoRingState.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoRingState.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoSecurityProperties.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoSecurityProperties.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoV2.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPeerInfoV2.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSPlatform.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRing.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingBackup.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingBackup.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingBasic.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingBasic.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingConcordanceTrust.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingConcordanceTrust.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingDER.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingDER.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingPeerInfoUtils.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingPeerInfoUtils.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingTypes.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingTypes.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingUtils.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingUtils.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingV0.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSRingV0.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransport.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransport.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportBackupPeer.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportBackupPeer.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportCircle.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportCircle.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportCircleKVS.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportCircleKVS.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportCoder.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportCoder.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportKeyParameter.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportKeyParameter.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportKeyParameterKVS.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportKeyParameterKVS.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportMessage.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportMessage.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportMessageIDS.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportMessageIDS.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportMessageKVS.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTransportMessageKVS.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSTypes.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSUserKeygen.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSUserKeygen.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSViewManager.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSViewManager.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSViewQueries.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSViewQueries.h delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSViews.c delete mode 100644 OSX/sec/ProjectHeaders/Security/SecureObjectSync/SOSViews.h create mode 120000 OSX/sec/ProjectHeaders/Security/Tool delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/SecurityCommands.h delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/add_internet_password.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/codesign.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/keychain_add.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/keychain_backup.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/keychain_find.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/keychain_util.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/keychain_util.h delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/log_control.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/pkcs12_util.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/scep.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/show_certificates.c delete mode 100644 OSX/sec/ProjectHeaders/Security/Tool/spc.c create mode 120000 OSX/sec/ProjectHeaders/SecurityTool delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/SecurityTool.c delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/SecurityTool.h delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/builtin_commands.h delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/digest_calc.c delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/entitlements.plist delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/leaks.c delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/leaks.h delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/print_cert.c delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/print_cert.h delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/security.1 delete mode 100644 OSX/sec/ProjectHeaders/SecurityTool/tool_errors.h create mode 100644 OSX/sec/Security/Regressions/secitem/si-20-sectrust-att.c create mode 100644 OSX/sec/Security/Regressions/secitem/si-85-sectrust-ssl-policy.c create mode 100644 OSX/sec/Security/Regressions/secitem/si-86-sectrust-eap-tls.c create mode 100644 OSX/sec/Security/Regressions/secitem/si-86-sectrust-eap-tls.h create mode 100644 OSX/sec/securityd/Regressions/secd-65-account-retirement-reset.c create mode 100644 OSX/sec/securityd/Regressions/secd-95-escrow-persistence.c create mode 120000 OSX/utilities/utilities delete mode 100644 OSX/utilities/utilities/SecAKSWrappers.c delete mode 100644 OSX/utilities/utilities/SecAKSWrappers.h delete mode 100644 OSX/utilities/utilities/SecAppleAnchor.c delete mode 100644 OSX/utilities/utilities/SecAppleAnchorPriv.h delete mode 100644 OSX/utilities/utilities/SecBuffer.c delete mode 100644 OSX/utilities/utilities/SecBuffer.h delete mode 100644 OSX/utilities/utilities/SecCFCCWrappers.c delete mode 100644 OSX/utilities/utilities/SecCFCCWrappers.h delete mode 100644 OSX/utilities/utilities/SecCFError.c delete mode 100644 OSX/utilities/utilities/SecCFError.h delete mode 100644 OSX/utilities/utilities/SecCFRelease.h delete mode 100644 OSX/utilities/utilities/SecCFWrappers.c delete mode 100644 OSX/utilities/utilities/SecCFWrappers.h delete mode 100644 OSX/utilities/utilities/SecCertificateTrace.c delete mode 100644 OSX/utilities/utilities/SecCertificateTrace.h delete mode 100644 OSX/utilities/utilities/SecCoreCrypto.c delete mode 100644 OSX/utilities/utilities/SecCoreCrypto.h delete mode 100644 OSX/utilities/utilities/SecDb.c delete mode 100644 OSX/utilities/utilities/SecDb.h delete mode 100644 OSX/utilities/utilities/SecDispatchRelease.h delete mode 100644 OSX/utilities/utilities/SecFileLocations.c delete mode 100644 OSX/utilities/utilities/SecFileLocations.h delete mode 100644 OSX/utilities/utilities/SecIOFormat.h delete mode 100644 OSX/utilities/utilities/SecInternalRelease.c delete mode 100644 OSX/utilities/utilities/SecInternalReleasePriv.h delete mode 100644 OSX/utilities/utilities/SecMeta.h delete mode 100644 OSX/utilities/utilities/SecSCTUtils.c delete mode 100644 OSX/utilities/utilities/SecSCTUtils.h delete mode 100644 OSX/utilities/utilities/SecXPCError.c delete mode 100644 OSX/utilities/utilities/SecXPCError.h delete mode 100644 OSX/utilities/utilities/array_size.h delete mode 100644 OSX/utilities/utilities/cloud_keychain_diagnose.c delete mode 100644 OSX/utilities/utilities/comparison.c delete mode 100644 OSX/utilities/utilities/comparison.h delete mode 100644 OSX/utilities/utilities/debugging.c delete mode 100644 OSX/utilities/utilities/debugging.h delete mode 100644 OSX/utilities/utilities/debugging_test.h delete mode 100644 OSX/utilities/utilities/der_array.c delete mode 100644 OSX/utilities/utilities/der_boolean.c delete mode 100644 OSX/utilities/utilities/der_data.c delete mode 100644 OSX/utilities/utilities/der_date.c delete mode 100644 OSX/utilities/utilities/der_date.h delete mode 100644 OSX/utilities/utilities/der_dictionary.c delete mode 100644 OSX/utilities/utilities/der_null.c delete mode 100644 OSX/utilities/utilities/der_number.c delete mode 100644 OSX/utilities/utilities/der_plist.c delete mode 100644 OSX/utilities/utilities/der_plist.h delete mode 100644 OSX/utilities/utilities/der_plist_internal.c delete mode 100644 OSX/utilities/utilities/der_plist_internal.h delete mode 100644 OSX/utilities/utilities/der_set.c delete mode 100644 OSX/utilities/utilities/der_set.h delete mode 100644 OSX/utilities/utilities/der_string.c delete mode 100644 OSX/utilities/utilities/fileIo.c delete mode 100644 OSX/utilities/utilities/fileIo.h delete mode 100644 OSX/utilities/utilities/iCloudKeychainTrace.c delete mode 100644 OSX/utilities/utilities/iCloudKeychainTrace.h delete mode 100644 OSX/utilities/utilities/iOSforOSX-SecAttr.c delete mode 100644 OSX/utilities/utilities/iOSforOSX-SecRandom.c delete mode 100644 OSX/utilities/utilities/iOSforOSX.c delete mode 100644 OSX/utilities/utilities/iOSforOSX.h delete mode 100644 OSX/utilities/utilities/simulate_crash.c delete mode 100644 OSX/utilities/utilities/sqlutils.h create mode 100644 SecurityTests/ssl-policy-certs/InvalidEKUTest16.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidHostnameTest1.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidHostnameTest2.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidHostnameTest22.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidHostnameTest23.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidHostnameTest24.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest10.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest11.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest12.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest13Test14.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest15.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest25Test26.cer create mode 100644 SecurityTests/ssl-policy-certs/InvalidWildcardTest5Test6.cer create mode 100644 SecurityTests/ssl-policy-certs/SSL Trust Policy Test CA/SSL Trust Policy Test CA certificates.pem create mode 100644 SecurityTests/ssl-policy-certs/SSL Trust Policy Test CA/SSL Trust Policy Test CA.certAuthorityConfig create mode 100644 SecurityTests/ssl-policy-certs/SSLTrustPolicyTest.plist create mode 100644 SecurityTests/ssl-policy-certs/SSLTrustPolicyTestCA.p12 create mode 100644 SecurityTests/ssl-policy-certs/SSLTrustPolicyTestRootCertificate.cer create mode 100644 SecurityTests/ssl-policy-certs/TestDescriptions.txt create mode 100644 SecurityTests/ssl-policy-certs/ValidEKUTest17.cer create mode 100644 SecurityTests/ssl-policy-certs/ValidHostnameTest18Test19Test20.cer create mode 100644 SecurityTests/ssl-policy-certs/ValidHostnameTest21.cer create mode 100644 SecurityTests/ssl-policy-certs/ValidHostnameTest3.cer create mode 100644 SecurityTests/ssl-policy-certs/ValidHostnameTest4.cer create mode 100644 SecurityTests/ssl-policy-certs/ValidWildcardTest7Test8Test9.cer create mode 120000 libsecurity_smime/Security delete mode 100644 libsecurity_smime/Security/SecAsn1Item.c delete mode 100644 libsecurity_smime/Security/SecAsn1Item.h delete mode 100644 libsecurity_smime/Security/SecCmsBase.h delete mode 100644 libsecurity_smime/Security/SecCmsContentInfo.h delete mode 100644 libsecurity_smime/Security/SecCmsDecoder.h delete mode 100644 libsecurity_smime/Security/SecCmsDigestContext.h delete mode 100644 libsecurity_smime/Security/SecCmsDigestedData.h delete mode 100644 libsecurity_smime/Security/SecCmsEncoder.h delete mode 100644 libsecurity_smime/Security/SecCmsEncryptedData.h delete mode 100644 libsecurity_smime/Security/SecCmsEnvelopedData.h delete mode 100644 libsecurity_smime/Security/SecCmsMessage.h delete mode 100644 libsecurity_smime/Security/SecCmsRecipientInfo.h delete mode 100644 libsecurity_smime/Security/SecCmsSignedData.h delete mode 100644 libsecurity_smime/Security/SecCmsSignerInfo.h delete mode 100644 libsecurity_smime/Security/SecSMIME.h delete mode 100644 libsecurity_smime/Security/SecSMIMEPriv.h delete mode 100644 libsecurity_smime/Security/cert.c delete mode 100644 libsecurity_smime/Security/cert.h delete mode 100644 libsecurity_smime/Security/cmsarray.c delete mode 100644 libsecurity_smime/Security/cmsasn1.c delete mode 100644 libsecurity_smime/Security/cmsattr.c delete mode 100644 libsecurity_smime/Security/cmscinfo.c delete mode 100644 libsecurity_smime/Security/cmscipher.c delete mode 100644 libsecurity_smime/Security/cmsdecode.c delete mode 100644 libsecurity_smime/Security/cmsdigdata.c delete mode 100644 libsecurity_smime/Security/cmsdigest.c delete mode 100644 libsecurity_smime/Security/cmsencdata.c delete mode 100644 libsecurity_smime/Security/cmsencode.c delete mode 100644 libsecurity_smime/Security/cmsenvdata.c delete mode 100644 libsecurity_smime/Security/cmslocal.h delete mode 100644 libsecurity_smime/Security/cmsmessage.c delete mode 100644 libsecurity_smime/Security/cmspriv.h delete mode 100644 libsecurity_smime/Security/cmspubkey.c delete mode 100644 libsecurity_smime/Security/cmsrecinfo.c delete mode 100644 libsecurity_smime/Security/cmsreclist.c delete mode 100644 libsecurity_smime/Security/cmsreclist.h delete mode 100644 libsecurity_smime/Security/cmssigdata.c delete mode 100644 libsecurity_smime/Security/cmssiginfo.c delete mode 100644 libsecurity_smime/Security/cmstpriv.h delete mode 100644 libsecurity_smime/Security/cmsutil.c delete mode 100644 libsecurity_smime/Security/crypto-embedded.c delete mode 100644 libsecurity_smime/Security/cryptohi.c delete mode 100644 libsecurity_smime/Security/cryptohi.h delete mode 100644 libsecurity_smime/Security/plhash.c delete mode 100644 libsecurity_smime/Security/plhash.h delete mode 100644 libsecurity_smime/Security/secalgid.c delete mode 100644 libsecurity_smime/Security/secoid.c delete mode 100644 libsecurity_smime/Security/secoid.h delete mode 100644 libsecurity_smime/Security/secoidt.h delete mode 100644 libsecurity_smime/Security/security_smime.exp delete mode 100644 libsecurity_smime/Security/smimeutil.c delete mode 100755 libsecurity_smime/Security/testcms create mode 120000 libsecurity_smime/security_smime delete mode 100644 libsecurity_smime/security_smime/SecAsn1Item.c delete mode 100644 libsecurity_smime/security_smime/SecAsn1Item.h delete mode 100644 libsecurity_smime/security_smime/SecCmsBase.h delete mode 100644 libsecurity_smime/security_smime/SecCmsContentInfo.h delete mode 100644 libsecurity_smime/security_smime/SecCmsDecoder.h delete mode 100644 libsecurity_smime/security_smime/SecCmsDigestContext.h delete mode 100644 libsecurity_smime/security_smime/SecCmsDigestedData.h delete mode 100644 libsecurity_smime/security_smime/SecCmsEncoder.h delete mode 100644 libsecurity_smime/security_smime/SecCmsEncryptedData.h delete mode 100644 libsecurity_smime/security_smime/SecCmsEnvelopedData.h delete mode 100644 libsecurity_smime/security_smime/SecCmsMessage.h delete mode 100644 libsecurity_smime/security_smime/SecCmsRecipientInfo.h delete mode 100644 libsecurity_smime/security_smime/SecCmsSignedData.h delete mode 100644 libsecurity_smime/security_smime/SecCmsSignerInfo.h delete mode 100644 libsecurity_smime/security_smime/SecSMIME.h delete mode 100644 libsecurity_smime/security_smime/SecSMIMEPriv.h delete mode 100644 libsecurity_smime/security_smime/cert.c delete mode 100644 libsecurity_smime/security_smime/cert.h delete mode 100644 libsecurity_smime/security_smime/cmsarray.c delete mode 100644 libsecurity_smime/security_smime/cmsasn1.c delete mode 100644 libsecurity_smime/security_smime/cmsattr.c delete mode 100644 libsecurity_smime/security_smime/cmscinfo.c delete mode 100644 libsecurity_smime/security_smime/cmscipher.c delete mode 100644 libsecurity_smime/security_smime/cmsdecode.c delete mode 100644 libsecurity_smime/security_smime/cmsdigdata.c delete mode 100644 libsecurity_smime/security_smime/cmsdigest.c delete mode 100644 libsecurity_smime/security_smime/cmsencdata.c delete mode 100644 libsecurity_smime/security_smime/cmsencode.c delete mode 100644 libsecurity_smime/security_smime/cmsenvdata.c delete mode 100644 libsecurity_smime/security_smime/cmslocal.h delete mode 100644 libsecurity_smime/security_smime/cmsmessage.c delete mode 100644 libsecurity_smime/security_smime/cmspriv.h delete mode 100644 libsecurity_smime/security_smime/cmspubkey.c delete mode 100644 libsecurity_smime/security_smime/cmsrecinfo.c delete mode 100644 libsecurity_smime/security_smime/cmsreclist.c delete mode 100644 libsecurity_smime/security_smime/cmsreclist.h delete mode 100644 libsecurity_smime/security_smime/cmssigdata.c delete mode 100644 libsecurity_smime/security_smime/cmssiginfo.c delete mode 100644 libsecurity_smime/security_smime/cmstpriv.h delete mode 100644 libsecurity_smime/security_smime/cmsutil.c delete mode 100644 libsecurity_smime/security_smime/crypto-embedded.c delete mode 100644 libsecurity_smime/security_smime/cryptohi.c delete mode 100644 libsecurity_smime/security_smime/cryptohi.h delete mode 100644 libsecurity_smime/security_smime/plhash.c delete mode 100644 libsecurity_smime/security_smime/plhash.h delete mode 100644 libsecurity_smime/security_smime/secalgid.c delete mode 100644 libsecurity_smime/security_smime/secoid.c delete mode 100644 libsecurity_smime/security_smime/secoid.h delete mode 100644 libsecurity_smime/security_smime/secoidt.h delete mode 100644 libsecurity_smime/security_smime/security_smime.exp delete mode 100644 libsecurity_smime/security_smime/smimeutil.c delete mode 100755 libsecurity_smime/security_smime/testcms create mode 120000 securityd/security_agent_client create mode 120000 securityd/security_agent_server diff --git a/CircleJoinRequested/CircleJoinRequested.1 b/CircleJoinRequested/CircleJoinRequested.1 deleted file mode 100644 index 40da368b..00000000 --- a/CircleJoinRequested/CircleJoinRequested.1 +++ /dev/null @@ -1,79 +0,0 @@ -.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. -.\"See Also: -.\"man mdoc.samples for a complete listing of options -.\"man mdoc for the short list of editing options -.\"/usr/share/misc/mdoc.template -.Dd 3/12/13 \" DATE -.Dt CircleJoinRequested 1 \" Program name and manual section number -.Os Darwin -.Sh NAME \" Section Header - required - don't modify -.Nm CircleJoinRequested, -.\" The following lines are read in generating the apropos(man -k) database. Use only key -.\" words here as the database is built based on the words here and in the .ND line. -.Nm Other_name_for_same_program(), -.Nm Yet another name for the same program. -.\" Use .Nm macro to designate other names for the documented program. -.Nd This line parsed for whatis database. -.Sh SYNOPSIS \" Section Header - required - don't modify -.Nm -.Op Fl abcd \" [-abcd] -.Op Fl a Ar path \" [-a path] -.Op Ar file \" [file] -.Op Ar \" [file ...] -.Ar arg0 \" Underlined argument - use .Ar anywhere to underline -arg2 ... \" Arguments -.Sh DESCRIPTION \" Section Header - required - don't modify -Use the .Nm macro to refer to your program throughout the man page like such: -.Nm -Underlining is accomplished with the .Ar macro like this: -.Ar underlined text . -.Pp \" Inserts a space -A list of items with descriptions: -.Bl -tag -width -indent \" Begins a tagged list -.It item a \" Each item preceded by .It macro -Description of item a -.It item b -Description of item b -.El \" Ends the list -.Pp -A list of flags and their descriptions: -.Bl -tag -width -indent \" Differs from above in tag removed -.It Fl a \"-a flag as a list item -Description of -a flag -.It Fl b -Description of -b flag -.El \" Ends the list -.Pp -.\" .Sh ENVIRONMENT \" May not be needed -.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 -.\" .It Ev ENV_VAR_1 -.\" Description of ENV_VAR_1 -.\" .It Ev ENV_VAR_2 -.\" Description of ENV_VAR_2 -.\" .El -.Sh FILES \" File used or created by the topic of the man page -.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact -.It Pa /usr/share/file_name -FILE_1 description -.It Pa /Users/joeuser/Library/really_long_file_name -FILE_2 description -.El \" Ends the list -.\" .Sh DIAGNOSTICS \" May not be needed -.\" .Bl -diag -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .El -.Sh SEE ALSO -.\" List links in ascending order by section, alphabetically within a section. -.\" Please do not reference files that do not exist without filing a bug report -.Xr a 1 , -.Xr b 1 , -.Xr c 1 , -.Xr a 2 , -.Xr b 2 , -.Xr a 3 , -.Xr b 3 -.\" .Sh BUGS \" Document known, unremedied bugs -.\" .Sh HISTORY \" Document history if command behaves in a unique manner \ No newline at end of file diff --git a/CircleJoinRequested/CircleJoinRequested.m b/CircleJoinRequested/CircleJoinRequested.m index bcae9ddd..0da63c65 100644 --- a/CircleJoinRequested/CircleJoinRequested.m +++ b/CircleJoinRequested/CircleJoinRequested.m @@ -114,14 +114,19 @@ static BOOL processRequests(CFErrorRef *error) { NSMutableArray *toReject = [[applicantsInState(ApplicantRejected) mapWithBlock:^id(id obj) {return (id)[obj rawPeerInfo];}] mutableCopy]; bool ok = true; - NSLog(@"Process accept: %@", toAccept); - NSLog(@"Process reject: %@", toReject); - - if ([toAccept count]) + if ([toAccept count]) { + NSLog(@"Process accept: %@", toAccept); ok = ok && SOSCCAcceptApplicants((__bridge CFArrayRef) toAccept, error); + if (ok) { + NSLog(@"kSOSCCHoldLockForInitialSync"); + notify_post(kSOSCCHoldLockForInitialSync); + } + } - if ([toReject count]) + if ([toReject count]) { + NSLog(@"Process reject: %@", toReject); ok = ok && SOSCCRejectApplicants((__bridge CFArrayRef) toReject, error); + } return ok; } @@ -183,7 +188,7 @@ static void applicantChoice(CFUserNotificationRef userNotification, CFOptionFlag CFReleaseNull(error); } - NSString *password = (__bridge NSString *)(CFUserNotificationGetResponseValue(userNotification, kCFUserNotificationTextFieldValuesKey, 0)); + NSString *password = (__bridge NSString *) CFUserNotificationGetResponseValue(userNotification, kCFUserNotificationTextFieldValuesKey, 0); if (!password) { NSLog(@"No password given, retry"); askAboutAll(true); @@ -196,13 +201,13 @@ static void applicantChoice(CFUserNotificationRef userNotification, CFOptionFlag // (which results in a process error -- I think this is 13355140), as a workaround we retry // failure a few times before we give up. for (int try = 0; try < 5 && !processed; try++) { - if (!SOSCCTryUserCredentials(CFSTR(""), (__bridge CFDataRef)(passwordBytes), &error)) { + if (!SOSCCTryUserCredentials(CFSTR(""), (__bridge CFDataRef) passwordBytes, &error)) { NSLog(@"Try user credentials failed %@", error); if ((error == NULL) || (CFEqual(kSOSErrorDomain, CFErrorGetDomain(error)) && kSOSErrorWrongPassword == CFErrorGetCode(error))) { NSLog(@"Calling askAboutAll again..."); [onScreen enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - Applicant* applicant = (Applicant*) obj; + Applicant *applicant = (Applicant*) obj; applicant.applicantUIState = ApplicantWaiting; }]; askAboutAll(true); @@ -241,7 +246,7 @@ static void passwordFailurePrompt() }; CFOptionFlags flags = kCFUserNotificationPlainAlertLevel; SInt32 err; - CFUserNotificationRef note = CFUserNotificationCreate(NULL, 0.0, flags, &err, (__bridge CFDictionaryRef)noteAttributes); + CFUserNotificationRef note = CFUserNotificationCreate(NULL, 0.0, flags, &err, (__bridge CFDictionaryRef) noteAttributes); if (note) { CFUserNotificationReceiveResponse(note, 0.0, &flags); @@ -324,14 +329,14 @@ static void askAboutAll(bool passwordFailure) CFOptionFlags flags = flagsForAsk(applicantToAskAbout); if (currentAlert) { - SInt32 err = CFUserNotificationUpdate(currentAlert, 0, flags, (__bridge CFDictionaryRef)noteAttributes); + SInt32 err = CFUserNotificationUpdate(currentAlert, 0, flags, (__bridge CFDictionaryRef) noteAttributes); if (err) { NSLog(@"CFUserNotificationUpdate err=%d", (int)err); EXIT_LOGGED_FAILURE(EX_SOFTWARE); } } else { SInt32 err = 0; - currentAlert = CFUserNotificationCreate(NULL, 0.0, flags, &err, (__bridge CFDictionaryRef)(noteAttributes)); + currentAlert = CFUserNotificationCreate(NULL, 0.0, flags, &err, (__bridge CFDictionaryRef) noteAttributes); if (err) { NSLog(@"Can't make notification for %@ err=%x", applicantToAskAbout, (int)err); EXIT_LOGGED_FAILURE(EX_SOFTWARE); @@ -413,7 +418,8 @@ static void postApplicationReminderAlert(NSDate *nowish, PersistentState *state, NSString *body = getLocalizedApplicationReminder(); bool has_iCSC = iCloudResetAvailable(); - if (state.defaultPendingApplicationReminderAlertInterval != state.pendingApplicationReminderAlertInterval) { + if (CPIsInternalDevice() && + state.defaultPendingApplicationReminderAlertInterval != state.pendingApplicationReminderAlertInterval) { body = [body stringByAppendingFormat: @"〖debug interval %u; wait time %@〗", state.pendingApplicationReminderAlertInterval, [nowish copyDescriptionOfIntervalSince:state.applicationDate]]; diff --git a/IDSKeychainSyncingProxy/com.apple.private.alloy.keychainsync.plist b/IDSKeychainSyncingProxy/com.apple.private.alloy.keychainsync.plist index f18a40e0a374d1366696389fbaf5c05a61449bc1..f08f2617b1ce77c9f0708dda9741267278cb8c15 100644 GIT binary patch delta 230 zcmey$bc#7EsURn_xWvHVCLP+TmRN>amOero;%ubCL5C`(bCqB}0W8h$rX3%6X xVQ^sZV#s1BXXs*B$*`4S8^c|OSB!#;4vbNZF^sVcV8Fx(p&5jsG?Zd&0RSMNJyrk! delta 169 zcmX@b{FTWzsURn_xWvHV1|t(Q3o9Et2PYRd4=*RbKy0RSPJU@haB5LmW^!t@OJ;FF zPGY5BVs2_=KxuJCNPa3-%_ciBI!%sc)Uuak wP-ie^ux0RKh-Ii@XlIzrFoj_u!wH5*3{M!IGV(Bh0TUyHW)OtZP>RtQ0M8OC=l}o! diff --git a/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist b/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist index 967a5daa..e571be54 100644 --- a/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist +++ b/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist @@ -24,6 +24,8 @@ MachServices + com.apple.private.alloy.keychainsync-idswake + com.apple.security.idskeychainsyncingproxy diff --git a/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist b/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist index e7b0d95f..93d2bd92 100644 --- a/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist +++ b/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist @@ -2,6 +2,10 @@ + com.apple.wifi.manager-access + + com.apple.private.ids.remoteurlconnection + com.apple.private.ids.messaging.high-priority com.apple.private.alloy.keychainsync diff --git a/Keychain/SyncViewController.m b/Keychain/SyncViewController.m index dcd9f24e..20c5e490 100644 --- a/Keychain/SyncViewController.m +++ b/Keychain/SyncViewController.m @@ -129,6 +129,18 @@ __unused static const uint64_t maxTimeToWaitInSeconds = 30ull * NSEC_PER_SEC; break; case kSOSCCNotInCircle: bx = SOSCCRequestToJoinCircle(&error); + if (bx) { + CFMutableSetRef viewsToEnable = CFSetCreateMutable(NULL, 0, NULL); + CFMutableSetRef viewsToDisable = CFSetCreateMutable(NULL, 0, NULL); + CFSetAddValue(viewsToEnable, (void*)kSOSViewWiFi); + CFSetAddValue(viewsToEnable, (void*)kSOSViewAutofillPasswords); + CFSetAddValue(viewsToEnable, (void*)kSOSViewSafariCreditCards); + CFSetAddValue(viewsToEnable, (void*)kSOSViewOtherSyncable); + + bx = SOSCCViewSet(viewsToEnable, viewsToDisable); + CFRelease(viewsToEnable); + CFRelease(viewsToDisable); + } break; default: NSLog(@"Request to join circle with bad status: %@ (%d)", SOSCCGetStatusDescription(ccstatus), ccstatus); diff --git a/OSX/IDSKeychainSyncingProxy/com.apple.private.alloy.keychainsync.plist b/OSX/IDSKeychainSyncingProxy/com.apple.private.alloy.keychainsync.plist index f18a40e0a374d1366696389fbaf5c05a61449bc1..f08f2617b1ce77c9f0708dda9741267278cb8c15 100644 GIT binary patch delta 230 zcmey$bc#7EsURn_xWvHVCLP+TmRN>amOero;%ubCL5C`(bCqB}0W8h$rX3%6X xVQ^sZV#s1BXXs*B$*`4S8^c|OSB!#;4vbNZF^sVcV8Fx(p&5jsG?Zd&0RSMNJyrk! delta 169 zcmX@b{FTWzsURn_xWvHV1|t(Q3o9Et2PYRd4=*RbKy0RSPJU@haB5LmW^!t@OJ;FF zPGY5BVs2_=KxuJCNPa3-%_ciBI!%sc)Uuak wP-ie^ux0RKh-Ii@XlIzrFoj_u!wH5*3{M!IGV(Bh0TUyHW)OtZP>RtQ0M8OC=l}o! diff --git a/OSX/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist b/OSX/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist index b8b1e6db..6732c264 100644 --- a/OSX/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist +++ b/OSX/IDSKeychainSyncingProxy/com.apple.security.idskeychainsyncingproxy.plist @@ -21,13 +21,13 @@ WAIT4DEBUGGER NO - DEBUGSCOPE - all ProcessType Adaptive MachServices + com.apple.private.alloy.keychainsync-idswake + com.apple.security.idskeychainsyncingproxy @@ -39,7 +39,7 @@ EnablePressuredExit - KeepAlive + enabletransactions diff --git a/OSX/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist b/OSX/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist index 06f7c014..93d2bd92 100644 --- a/OSX/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist +++ b/OSX/IDSKeychainSyncingProxy/idskeychainsyncingproxy.entitlements.plist @@ -2,18 +2,25 @@ - keychain-access-groups + com.apple.wifi.manager-access + + com.apple.private.ids.remoteurlconnection + + com.apple.private.ids.messaging.high-priority - IMCore - InternetAccounts + com.apple.private.alloy.keychainsync com.apple.private.ids.messaging com.apple.private.alloy.keychainsync - com.apple.private.ids.messaging.high-priority + keychain-access-groups - com.apple.private.alloy.keychainsync + IMCore + apple + InternetAccounts + application-identifier + com.apple.security.idskeychainsyncingproxy diff --git a/OSX/Keychain Circle Notification/KNAppDelegate.m b/OSX/Keychain Circle Notification/KNAppDelegate.m index 8640fb3d..eec4fc7e 100644 --- a/OSX/Keychain Circle Notification/KNAppDelegate.m +++ b/OSX/Keychain Circle Notification/KNAppDelegate.m @@ -425,6 +425,7 @@ bool isAppleInternal(void) } } + // Improve wording of the iCloud keychain drop/reset error messages // Contrary to HI spec (and I think it makes more sense) // 1. otherButton == top : Not Now // 2. actionButton == bottom: Continue @@ -522,7 +523,6 @@ bool isAppleInternal(void) } } - // Improve wording of the iCloud keychain drop/reset error messages // Contrary to HI spec (and I think it makes more sense) // 1. otherButton == top : Not Now // 2. actionButton == bottom: Continue diff --git a/OSX/Keychain/KDSecCircle.m b/OSX/Keychain/KDSecCircle.m index c053ee2f..31cbc174 100644 --- a/OSX/Keychain/KDSecCircle.m +++ b/OSX/Keychain/KDSecCircle.m @@ -191,6 +191,17 @@ typedef void (^applicantBlock)(id applicant); } else { SOSCCRequestToJoinCircle(&err); } + + CFMutableSetRef viewsToEnable = CFSetCreateMutable(NULL, 0, NULL); + CFMutableSetRef viewsToDisable = CFSetCreateMutable(NULL, 0, NULL); + CFSetAddValue(viewsToEnable, (void*)kSOSViewWiFi); + CFSetAddValue(viewsToEnable, (void*)kSOSViewAutofillPasswords); + CFSetAddValue(viewsToEnable, (void*)kSOSViewSafariCreditCards); + CFSetAddValue(viewsToEnable, (void*)kSOSViewOtherSyncable); + + SOSCCViewSet(viewsToEnable, viewsToDisable); + CFRelease(viewsToEnable); + CFRelease(viewsToDisable); } -(void)disableSync diff --git a/OSX/OSX.xcodeproj/xcshareddata/xcschemes/secdtests.xcscheme b/OSX/OSX.xcodeproj/xcshareddata/xcschemes/secdtests.xcscheme index fe54a353..ba3b7779 100644 --- a/OSX/OSX.xcodeproj/xcshareddata/xcschemes/secdtests.xcscheme +++ b/OSX/OSX.xcodeproj/xcshareddata/xcschemes/secdtests.xcscheme @@ -80,6 +80,10 @@ argument = "-s" isEnabled = "NO"> + + diff --git a/OSX/include/security_asn1 b/OSX/include/security_asn1 new file mode 120000 index 00000000..09ef0802 --- /dev/null +++ b/OSX/include/security_asn1 @@ -0,0 +1 @@ +./libsecurity_asn1/lib \ No newline at end of file diff --git a/OSX/include/security_asn1/SecAsn1Coder.c b/OSX/include/security_asn1/SecAsn1Coder.c deleted file mode 100644 index e72dd1a2..00000000 --- a/OSX/include/security_asn1/SecAsn1Coder.c +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * SecAsn1Coder.h: ANS1 encode/decode object, ANSI C version. - */ - -#include "SecAsn1Coder.h" -#include "plarenas.h" -#include "prerror.h" -#include "seccomon.h" -#include "secasn1.h" -#include - -/* - * Default chunk size for new arena pool. - * FIXME: analyze & measure different defaults here. I'm pretty sure - * that only performance - not correct behavior - is affected by - * an arena pool's chunk size. - */ -#define CHUNKSIZE_DEF 1024 - -/* - * Caller's SecAsn1CoderRef points to one of these. - */ -typedef struct SecAsn1Coder { - PLArenaPool *mPool; -} SecAsn1Coder_t; - -/* - * Create/destroy SecAsn1Coder object. - */ -OSStatus SecAsn1CoderCreate( - SecAsn1CoderRef *coder) -{ - if(coder == NULL) { - return errSecParam; - } - SecAsn1CoderRef _coder = (SecAsn1CoderRef)malloc(sizeof(SecAsn1Coder_t)); - _coder->mPool = PORT_NewArena(CHUNKSIZE_DEF); - if(_coder->mPool == NULL) { - free(_coder); - return errSecAllocate; - } - *coder = _coder; - return errSecSuccess; -} - -OSStatus SecAsn1CoderRelease( - SecAsn1CoderRef coder) -{ - if(coder == NULL) { - return errSecParam; - } - if(coder->mPool != NULL) { - /* - * Note: we're asking for a memory zero here, but - * PORT_FreeArena doesn't do that (yet). - */ - PORT_FreeArena(coder->mPool, PR_TRUE); - coder->mPool = NULL; - } - free(coder); - return errSecSuccess; -} - -/* - * DER decode an untyped item per the specified template array. - * The result is allocated in this SecAsn1Coder's memory pool and - * is freed when this object is released. - * - * The dest pointer is a template-specific struct allocated by the caller - * and must be zeroed by the caller. - */ -OSStatus SecAsn1Decode( - SecAsn1CoderRef coder, - const void *src, // DER-encoded source - size_t len, - const SecAsn1Template *templ, - void *dest) -{ - if((coder == NULL) || (src == NULL) || (templ == NULL) || (dest == NULL)) { - return errSecParam; - } - SECStatus prtn = SEC_ASN1Decode(coder->mPool, dest, templ, (const char *)src, len); - if(prtn) { - return errSecDecode; - } - else { - return errSecSuccess; - } -} - -/* - * Convenience routine, decode from a SecAsn1Item. - */ -OSStatus SecAsn1DecodeData( - SecAsn1CoderRef coder, - const SecAsn1Item *src, - const SecAsn1Template *templ, - void *dest) -{ - return SecAsn1Decode(coder, src->Data, src->Length, templ, dest); -} - -/* - * DER encode. The encoded data (in dest.Data) is allocated in this - * SecAsn1Coder's memory pool and is freed when this object is released. - * - * The src pointer is a template-specific struct. - */ -OSStatus SecAsn1EncodeItem( - SecAsn1CoderRef coder, - const void *src, - const SecAsn1Template *templ, - SecAsn1Item *dest) -{ - if((coder == NULL) || (src == NULL) || (templ == NULL) || (dest == NULL)) { - return errSecParam; - } - dest->Data = NULL; - dest->Length = 0; - - SecAsn1Item *rtnItem = SEC_ASN1EncodeItem(coder->mPool, dest, src, templ); - if(rtnItem == NULL) { - /* FIXME what to return here? */ - return errSecParam; - } - else { - return errSecSuccess; - } -} - -/* - * Some alloc-related methods which come in handy when using - * this object. All memory is allocated using this object's - * memory pool. Caller never has to free it. Used for - * temp allocs of memory which only needs a scope which is the - * same as this object. - * - * These return a errSecAllocate in the highly unlikely event of - * a malloc failure. - */ -void *SecAsn1Malloc( - SecAsn1CoderRef coder, - size_t len) -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnonnull" - // After introducing nullability annotations, coder is supposed to be nonnull, suppress the warning - if(coder == NULL) { - return NULL; - } -#pragma clang diagnostic pop - return PORT_ArenaAlloc(coder->mPool, len); -} - -/* malloc item.Data, set item.Length */ -OSStatus SecAsn1AllocItem( - SecAsn1CoderRef coder, - SecAsn1Item *item, - size_t len) -{ - if((coder == NULL) || (item == NULL)) { - return errSecParam; - } - item->Data = (uint8_t *)PORT_ArenaAlloc(coder->mPool, len); - if(item->Data == NULL) { - return errSecAllocate; - } - item->Length = len; - return errSecSuccess; -} - -/* malloc and copy, various forms */ -OSStatus SecAsn1AllocCopy( - SecAsn1CoderRef coder, - const void *src, - size_t len, - SecAsn1Item *dest) -{ - if(src == NULL) { - return errSecParam; - } - OSStatus ortn = SecAsn1AllocItem(coder, dest, len); - if(ortn) { - return ortn; - } - memmove(dest->Data, src, len); - return errSecSuccess; -} - -OSStatus SecAsn1AllocCopyItem( - SecAsn1CoderRef coder, - const SecAsn1Item *src, - SecAsn1Item *dest) -{ - return SecAsn1AllocCopy(coder, src->Data, src->Length, dest); -} - -bool SecAsn1OidCompare(const SecAsn1Oid *oid1, const SecAsn1Oid *oid2) { - if (!oid1 || !oid2) - return oid1 == oid2; - if (oid1->Length != oid2->Length) - return false; - return !memcmp(oid1->Data, oid2->Data, oid1->Length); -} diff --git a/OSX/include/security_asn1/SecAsn1Coder.h b/OSX/include/security_asn1/SecAsn1Coder.h deleted file mode 100644 index 00002aee..00000000 --- a/OSX/include/security_asn1/SecAsn1Coder.h +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * SecAsn1Coder.h: ANS1 encode/decode object. - * - * A SecAsn1Coder is capable of encoding and decoding both DER and BER data - * streams, based on caller-supplied templates which in turn are based - * upon ASN.1 specifications. A SecAsn1Coder allocates memory during encode - * and decode using a memory pool which is owned and managed by the SecAsn1Coder - * object, and which is freed when the SecAsn1Coder object os released. - */ - -#ifndef _SEC_ASN1_CODER_H_ -#define _SEC_ASN1_CODER_H_ - -#include -#include -#include -#include /* error codes */ - -#ifdef __cplusplus -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -/* - * Opaque reference to a SecAsn1Coder object. - */ -typedef struct SecAsn1Coder *SecAsn1CoderRef; - -/* - * Create/destroy SecAsn1Coder object. - */ -OSStatus SecAsn1CoderCreate( - SecAsn1CoderRef __nullable * __nonnull coder); - -OSStatus SecAsn1CoderRelease( - SecAsn1CoderRef coder); - -/* - * DER decode an untyped item per the specified template array. - * The result is allocated in this SecAsn1Coder's memory pool and - * is freed when this object is released. - * - * The templates argument points to a an array of SecAsn1Templates - * defining the object to be decoded; the end of the array is - * indicated by a SecAsn1Template with file kind equalling 0. - * - * The dest pointer is a template-specific struct allocated by the caller - * and must be zeroed by the caller. - * - * Returns errSecUnknownFormat on decode-specific error. - */ -OSStatus SecAsn1Decode( - SecAsn1CoderRef coder, - const void *src, // DER-encoded source - size_t len, - const SecAsn1Template *templates, - void *dest); - -/* - * Convenience routine, decode from a SecAsn1Item. - */ -OSStatus SecAsn1DecodeData( - SecAsn1CoderRef coder, - const SecAsn1Item *src, - const SecAsn1Template *templ, - void *dest); - -/* - * DER encode. The encoded data (in dest.Data) is allocated in this - * SecAsn1Coder's memory pool and is freed when this object is released. - * - * The src pointer is a template-specific struct. - * - * The templates argument points to a an array of SecAsn1Templates - * defining the object to be decoded; the end of the array is - * indicated by a SecAsn1Template with file kind equalling 0. - */ -OSStatus SecAsn1EncodeItem( - SecAsn1CoderRef coder, - const void *src, - const SecAsn1Template *templates, - SecAsn1Item *dest); - -/* - * Some alloc-related methods which come in handy when using - * this object. All memory is allocated using this object's - * memory pool. Caller never has to free it. Used for - * temp allocs of memory which only needs a scope which is the - * same as this object. - * - * All except SecAsn1Malloc return a errSecAllocate in the highly - * unlikely event of a malloc failure. - * - * SecAsn1Malloc() returns a pointer to allocated memory, like - * malloc(). - */ -void *SecAsn1Malloc( - SecAsn1CoderRef coder, - size_t len); - -/* Allocate item.Data, set item.Length */ -OSStatus SecAsn1AllocItem( - SecAsn1CoderRef coder, - SecAsn1Item *item, - size_t len); - -/* Allocate and copy, various forms */ -OSStatus SecAsn1AllocCopy( - SecAsn1CoderRef coder, - const void *src, /* memory copied from here */ - size_t len, /* length to allocate & copy */ - SecAsn1Item *dest); /* dest->Data allocated and copied to; - * dest->Length := len */ - -OSStatus SecAsn1AllocCopyItem( - SecAsn1CoderRef coder, - const SecAsn1Item *src, /* src->Length bytes allocated and copied from - * src->Data */ - SecAsn1Item *dest); /* dest->Data allocated and copied to; - * dest->Length := src->Length */ - -/* Compare two decoded OIDs. Returns true iff they are equivalent. */ -bool SecAsn1OidCompare(const SecAsn1Oid *oid1, const SecAsn1Oid *oid2); - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif /* _SEC_ASN1_CODER_H_ */ diff --git a/OSX/include/security_asn1/SecAsn1Templates.c b/OSX/include/security_asn1/SecAsn1Templates.c deleted file mode 100644 index edd945e0..00000000 --- a/OSX/include/security_asn1/SecAsn1Templates.c +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright (c) 2003-2004,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * SecAsn1Templates.c - Common ASN1 templates for use with libsecurity_asn1. - */ - -#include "secasn1t.h" -#include "seccomon.h" -#include - -/* - * Generic templates for individual/simple items and pointers to - * and sets of same. - * - * If you need to add a new one, please note the following: - * - For each new basic type you should add *four* templates: - * one plain, one PointerTo, one SequenceOf and one SetOf. - * - If the new type can be constructed (meaning, it is a - * *string* type according to BER/DER rules), then you should - * or-in SEC_ASN1_MAY_STREAM to the type in the basic template. - * See the definition of the OctetString template for an example. - * - It may not be obvious, but these are in *alphabetical* - * order based on the SEC_ASN1_XXX name; so put new ones in - * the appropriate place. - */ - -const SecAsn1Template kSecAsn1AnyTemplate[] = { - { SEC_ASN1_ANY | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToAnyTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1AnyTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfAnyTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1AnyTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfAnyTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1AnyTemplate } -}; - -const SecAsn1Template kSecAsn1BitStringTemplate[] = { - { SEC_ASN1_BIT_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToBitStringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1BitStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfBitStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1BitStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfBitStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1BitStringTemplate } -}; - -const SecAsn1Template kSecAsn1BMPStringTemplate[] = { - { SEC_ASN1_BMP_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToBMPStringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1BMPStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfBMPStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1BMPStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfBMPStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1BMPStringTemplate } -}; - -const SecAsn1Template kSecAsn1BooleanTemplate[] = { - { SEC_ASN1_BOOLEAN, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToBooleanTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1BooleanTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfBooleanTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1BooleanTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfBooleanTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1BooleanTemplate } -}; - -const SecAsn1Template kSecAsn1EnumeratedTemplate[] = { - { SEC_ASN1_ENUMERATED, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToEnumeratedTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1EnumeratedTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfEnumeratedTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1EnumeratedTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfEnumeratedTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1EnumeratedTemplate } -}; - -const SecAsn1Template kSecAsn1GeneralizedTimeTemplate[] = { - { SEC_ASN1_GENERALIZED_TIME | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item)} -}; - -const SecAsn1Template kSecAsn1PointerToGeneralizedTimeTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1GeneralizedTimeTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfGeneralizedTimeTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1GeneralizedTimeTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfGeneralizedTimeTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1GeneralizedTimeTemplate } -}; - -const SecAsn1Template kSecAsn1IA5StringTemplate[] = { - { SEC_ASN1_IA5_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToIA5StringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1IA5StringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfIA5StringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1IA5StringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfIA5StringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1IA5StringTemplate } -}; - -const SecAsn1Template kSecAsn1IntegerTemplate[] = { - { SEC_ASN1_INTEGER | SEC_ASN1_SIGNED_INT, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1UnsignedIntegerTemplate[] = { - { SEC_ASN1_INTEGER, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToIntegerTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1IntegerTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfIntegerTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1IntegerTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfIntegerTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1IntegerTemplate } -}; - -const SecAsn1Template kSecAsn1NullTemplate[] = { - { SEC_ASN1_NULL, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToNullTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1NullTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfNullTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1NullTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfNullTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1NullTemplate } -}; - -const SecAsn1Template kSecAsn1ObjectIDTemplate[] = { - { SEC_ASN1_OBJECT_ID, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToObjectIDTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1ObjectIDTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfObjectIDTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1ObjectIDTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfObjectIDTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1ObjectIDTemplate } -}; - -const SecAsn1Template kSecAsn1OctetStringTemplate[] = { - { SEC_ASN1_OCTET_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToOctetStringTemplate[] = { - { SEC_ASN1_POINTER | SEC_ASN1_MAY_STREAM, 0, kSecAsn1OctetStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfOctetStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1OctetStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfOctetStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1OctetStringTemplate } -}; - -const SecAsn1Template kSecAsn1PrintableStringTemplate[] = { - { SEC_ASN1_PRINTABLE_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item)} -}; - -const SecAsn1Template kSecAsn1PointerToPrintableStringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1PrintableStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfPrintableStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1PrintableStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfPrintableStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1PrintableStringTemplate } -}; - -#ifdef __APPLE__ -const SecAsn1Template kSecAsn1TeletexStringTemplate[] = { - { SEC_ASN1_TELETEX_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item)} -}; - -const SecAsn1Template kSecAsn1PointerToTeletexStringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1TeletexStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfTeletexStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1TeletexStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfTeletexStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1TeletexStringTemplate } -}; -#endif /* __APPLE__ */ - -const SecAsn1Template kSecAsn1T61StringTemplate[] = { - { SEC_ASN1_T61_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToT61StringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1T61StringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfT61StringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1T61StringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfT61StringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1T61StringTemplate } -}; - -const SecAsn1Template kSecAsn1UniversalStringTemplate[] = { - { SEC_ASN1_UNIVERSAL_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item)} -}; - -const SecAsn1Template kSecAsn1PointerToUniversalStringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1UniversalStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfUniversalStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1UniversalStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfUniversalStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1UniversalStringTemplate } -}; - -const SecAsn1Template kSecAsn1UTCTimeTemplate[] = { - { SEC_ASN1_UTC_TIME | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToUTCTimeTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1UTCTimeTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfUTCTimeTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1UTCTimeTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfUTCTimeTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1UTCTimeTemplate } -}; - -const SecAsn1Template kSecAsn1UTF8StringTemplate[] = { - { SEC_ASN1_UTF8_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item)} -}; - -const SecAsn1Template kSecAsn1PointerToUTF8StringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1UTF8StringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfUTF8StringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1UTF8StringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfUTF8StringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1UTF8StringTemplate } -}; - -const SecAsn1Template kSecAsn1VisibleStringTemplate[] = { - { SEC_ASN1_VISIBLE_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1PointerToVisibleStringTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1VisibleStringTemplate } -}; - -const SecAsn1Template kSecAsn1SequenceOfVisibleStringTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1VisibleStringTemplate } -}; - -const SecAsn1Template kSecAsn1SetOfVisibleStringTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1VisibleStringTemplate } -}; - - -/* - * Template for skipping a subitem. - * - * Note that it only makes sense to use this for decoding (when you want - * to decode something where you are only interested in one or two of - * the fields); you cannot encode a SKIP! - */ -const SecAsn1Template kSecAsn1SkipTemplate[] = { - { SEC_ASN1_SKIP } -}; - -#ifndef __APPLE__ - -/* These functions simply return the address of the above-declared templates. -** This is necessary for Windows DLLs. Sigh. -*/ -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_AnyTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_BMPStringTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_BooleanTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_BitStringTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_IA5StringTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_GeneralizedTimeTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_IntegerTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_NullTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_ObjectIDTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_OctetStringTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_PointerToAnyTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_PointerToOctetStringTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_SetOfAnyTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_UTCTimeTemplate) -SEC_ASN1_CHOOSER_IMPLEMENT(SEC_UTF8StringTemplate) - -#endif /* __APPLE__ */ diff --git a/OSX/include/security_asn1/SecAsn1Templates.h b/OSX/include/security_asn1/SecAsn1Templates.h deleted file mode 100644 index 800e1264..00000000 --- a/OSX/include/security_asn1/SecAsn1Templates.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * SecAsn1Templates.h - Common ASN1 primitive templates for use with SecAsn1Coder. - */ - -#ifndef _SEC_ASN1_TEMPLATES_H_ -#define _SEC_ASN1_TEMPLATES_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -/************************************************************************/ - -/* - * Generic Templates - * One for each of the simple types, plus a special one for ANY, plus: - * - a pointer to each one of those - * - a set of each one of those - * - a sequence of each one of those - */ - -extern const SecAsn1Template kSecAsn1AnyTemplate[]; -extern const SecAsn1Template kSecAsn1BitStringTemplate[]; -extern const SecAsn1Template kSecAsn1BMPStringTemplate[]; -extern const SecAsn1Template kSecAsn1BooleanTemplate[]; -extern const SecAsn1Template kSecAsn1EnumeratedTemplate[]; -extern const SecAsn1Template kSecAsn1GeneralizedTimeTemplate[]; -extern const SecAsn1Template kSecAsn1IA5StringTemplate[]; -extern const SecAsn1Template kSecAsn1IntegerTemplate[]; -extern const SecAsn1Template kSecAsn1UnsignedIntegerTemplate[]; -extern const SecAsn1Template kSecAsn1NullTemplate[]; -extern const SecAsn1Template kSecAsn1ObjectIDTemplate[]; -extern const SecAsn1Template kSecAsn1OctetStringTemplate[]; -extern const SecAsn1Template kSecAsn1PrintableStringTemplate[]; -extern const SecAsn1Template kSecAsn1T61StringTemplate[]; -extern const SecAsn1Template kSecAsn1UniversalStringTemplate[]; -extern const SecAsn1Template kSecAsn1UTCTimeTemplate[]; -extern const SecAsn1Template kSecAsn1UTF8StringTemplate[]; -extern const SecAsn1Template kSecAsn1VisibleStringTemplate[]; -extern const SecAsn1Template kSecAsn1TeletexStringTemplate[]; - -extern const SecAsn1Template kSecAsn1PointerToAnyTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToBitStringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToBMPStringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToBooleanTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToEnumeratedTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToGeneralizedTimeTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToIA5StringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToIntegerTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToNullTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToObjectIDTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToOctetStringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToPrintableStringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToT61StringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToUniversalStringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToUTCTimeTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToUTF8StringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToVisibleStringTemplate[]; -extern const SecAsn1Template kSecAsn1PointerToTeletexStringTemplate[]; - -extern const SecAsn1Template kSecAsn1SequenceOfAnyTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfBitStringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfBMPStringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfBooleanTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfEnumeratedTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfGeneralizedTimeTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfIA5StringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfIntegerTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfNullTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfObjectIDTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfOctetStringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfPrintableStringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfT61StringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfUniversalStringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfUTCTimeTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfUTF8StringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfVisibleStringTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfTeletexStringTemplate[]; - -extern const SecAsn1Template kSecAsn1SetOfAnyTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfBitStringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfBMPStringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfBooleanTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfEnumeratedTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfGeneralizedTimeTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfIA5StringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfIntegerTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfNullTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfObjectIDTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfOctetStringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfPrintableStringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfT61StringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfUniversalStringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfUTCTimeTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfUTF8StringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfVisibleStringTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfTeletexStringTemplate[]; - -/* - * Template for skipping a subitem; only used when decoding. - */ -extern const SecAsn1Template kSecAsn1SkipTemplate[]; - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif /* _SEC_ASN1_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/SecAsn1Types.h b/OSX/include/security_asn1/SecAsn1Types.h deleted file mode 100644 index df78b872..00000000 --- a/OSX/include/security_asn1/SecAsn1Types.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Types for encoding/decoding of ASN.1 using BER/DER (Basic/Distinguished - * Encoding Rules). - */ - -#ifndef _SEC_ASN1_TYPES_H_ -#define _SEC_ASN1_TYPES_H_ - -#include /* Boolean */ -#include -#include - -#include -#if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR -/* @@@ We need something that tells us which platform we are building - for that let's us distinguish if we are doing an emulator build. */ - -typedef struct { - size_t Length; - uint8_t * __nullable Data; -} SecAsn1Item, SecAsn1Oid; - -typedef struct { - SecAsn1Oid algorithm; - SecAsn1Item parameters; -} SecAsn1AlgId; - -typedef struct { - SecAsn1AlgId algorithm; - SecAsn1Item subjectPublicKey; -} SecAsn1PubKeyInfo; - -#else -#include -#include - -typedef CSSM_DATA SecAsn1Item; -typedef CSSM_OID SecAsn1Oid; -typedef CSSM_X509_ALGORITHM_IDENTIFIER SecAsn1AlgId; -typedef CSSM_X509_SUBJECT_PUBLIC_KEY_INFO SecAsn1PubKeyInfo; - -#endif - -CF_ASSUME_NONNULL_BEGIN - -/* - * An array of these structures defines a BER/DER encoding for an object. - * - * The array usually starts with a dummy entry whose kind is SEC_ASN1_SEQUENCE; - * such an array is terminated with an entry where kind == 0. (An array - * which consists of a single component does not require a second dummy - * entry -- the array is only searched as long as previous component(s) - * instruct it.) - */ -typedef struct SecAsn1Template_struct { - /* - * Kind of item being decoded/encoded, including tags and modifiers. - */ - uint32_t kind; - - /* - * This value is the offset from the base of the structure (i.e., the - * (void *) passed as 'src' to SecAsn1EncodeItem, or the 'dst' argument - * passed to SecAsn1CoderRef()) to the field that holds the value being - * decoded/encoded. - */ - uint32_t offset; - - /* - * When kind suggests it (e.g., SEC_ASN1_POINTER, SEC_ASN1_GROUP, - * SEC_ASN1_INLINE, or a component that is *not* a SEC_ASN1_UNIVERSAL), - * this points to a sub-template for nested encoding/decoding. - * OR, iff SEC_ASN1_DYNAMIC is set, then this is a pointer to a pointer - * to a function which will return the appropriate template when called - * at runtime. NOTE! that explicit level of indirection, which is - * necessary because ANSI does not allow you to store a function - * pointer directly as a "void *" so we must store it separately and - * dereference it to get at the function pointer itself. - */ - const void *sub; - - /* - * In the first element of a template array, the value is the size - * of the structure to allocate when this template is being referenced - * by another template via SEC_ASN1_POINTER or SEC_ASN1_GROUP. - * In all other cases, the value is ignored. - */ - uint32_t size; -} SecAsn1Template; - - -/* - * BER/DER values for ASN.1 identifier octets. - */ -#define SEC_ASN1_TAG_MASK 0xff - -/* - * BER/DER universal type tag numbers. - */ -#define SEC_ASN1_TAGNUM_MASK 0x1f -#define SEC_ASN1_BOOLEAN 0x01 -#define SEC_ASN1_INTEGER 0x02 -#define SEC_ASN1_BIT_STRING 0x03 -#define SEC_ASN1_OCTET_STRING 0x04 -#define SEC_ASN1_NULL 0x05 -#define SEC_ASN1_OBJECT_ID 0x06 -#define SEC_ASN1_OBJECT_DESCRIPTOR 0x07 -/* External type and instance-of type 0x08 */ -#define SEC_ASN1_REAL 0x09 -#define SEC_ASN1_ENUMERATED 0x0a -#define SEC_ASN1_EMBEDDED_PDV 0x0b -#define SEC_ASN1_UTF8_STRING 0x0c -/* not used 0x0d */ -/* not used 0x0e */ -/* not used 0x0f */ -#define SEC_ASN1_SEQUENCE 0x10 -#define SEC_ASN1_SET 0x11 -#define SEC_ASN1_NUMERIC_STRING 0x12 -#define SEC_ASN1_PRINTABLE_STRING 0x13 -#define SEC_ASN1_T61_STRING 0x14 -#define SEC_ASN1_VIDEOTEX_STRING 0x15 -#define SEC_ASN1_IA5_STRING 0x16 -#define SEC_ASN1_UTC_TIME 0x17 -#define SEC_ASN1_GENERALIZED_TIME 0x18 -#define SEC_ASN1_GRAPHIC_STRING 0x19 -#define SEC_ASN1_VISIBLE_STRING 0x1a -#define SEC_ASN1_GENERAL_STRING 0x1b -#define SEC_ASN1_UNIVERSAL_STRING 0x1c -/* not used 0x1d */ -#define SEC_ASN1_BMP_STRING 0x1e -#define SEC_ASN1_HIGH_TAG_NUMBER 0x1f -#define SEC_ASN1_TELETEX_STRING SEC_ASN1_T61_STRING - -/* - * Modifiers to type tags. These are also specified by a/the - * standard, and must not be changed. - */ -#define SEC_ASN1_METHOD_MASK 0x20 -#define SEC_ASN1_PRIMITIVE 0x00 -#define SEC_ASN1_CONSTRUCTED 0x20 - -#define SEC_ASN1_CLASS_MASK 0xc0 -#define SEC_ASN1_UNIVERSAL 0x00 -#define SEC_ASN1_APPLICATION 0x40 -#define SEC_ASN1_CONTEXT_SPECIFIC 0x80 -#define SEC_ASN1_PRIVATE 0xc0 - -/* - * Our additions, used for templates. - * These are not defined by any standard; the values are used internally only. - * Just be careful to keep them out of the low 8 bits. - */ -#define SEC_ASN1_OPTIONAL 0x00100 -#define SEC_ASN1_EXPLICIT 0x00200 -#define SEC_ASN1_ANY 0x00400 -#define SEC_ASN1_INLINE 0x00800 -#define SEC_ASN1_POINTER 0x01000 -#define SEC_ASN1_GROUP 0x02000 /* with SET or SEQUENCE means - * SET OF or SEQUENCE OF */ -#define SEC_ASN1_DYNAMIC 0x04000 /* subtemplate is found by calling - * a function at runtime */ -#define SEC_ASN1_SKIP 0x08000 /* skip a field; only for decoding */ -#define SEC_ASN1_INNER 0x10000 /* with ANY means capture the - * contents only (not the id, len, - * or eoc); only for decoding */ -#define SEC_ASN1_SAVE 0x20000 /* stash away the encoded bytes first; - * only for decoding */ -#define SEC_ASN1_SKIP_REST 0x80000 /* skip all following fields; - * only for decoding */ -#define SEC_ASN1_CHOICE 0x100000 /* pick one from a template */ - -/* - * Indicate that a type SEC_ASN1_INTEGER is actually signed. - * The default is unsigned, which causes a leading zero to be - * encoded if the MS bit of the source data is 1. - */ -#define SEC_ASN1_SIGNED_INT 0X800000 - -/* Shorthand/Aliases */ -#define SEC_ASN1_SEQUENCE_OF (SEC_ASN1_GROUP | SEC_ASN1_SEQUENCE) -#define SEC_ASN1_SET_OF (SEC_ASN1_GROUP | SEC_ASN1_SET) -#define SEC_ASN1_ANY_CONTENTS (SEC_ASN1_ANY | SEC_ASN1_INNER) - -/* - * Function used for SEC_ASN1_DYNAMIC. - * "arg" is a pointer to the top-level structure being encoded or - * decoded. - * - * "enc" when true, means that we are encoding (false means decoding) - * - * "buf" For decode only; points to the start of the decoded data for - * the current template. Callee can use the tag at this location - * to infer the returned template. Not used on encode. - * - * "Dest" points to the template-specific item being decoded to - * or encoded from. (This is as opposed to arg, which - * points to the start of the struct associated with the - * current array of templates). - */ - -typedef const SecAsn1Template * SecAsn1TemplateChooser( - void *arg, - Boolean enc, - const char *buf, - void *dest); - -typedef SecAsn1TemplateChooser * SecAsn1TemplateChooserPtr; - -CF_ASSUME_NONNULL_END - -#endif /* _SEC_ASN1_TYPES_H_ */ diff --git a/OSX/include/security_asn1/SecNssCoder.cpp b/OSX/include/security_asn1/SecNssCoder.cpp deleted file mode 100644 index 08bac8fb..00000000 --- a/OSX/include/security_asn1/SecNssCoder.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * SecNssCoder.cpp: simple C++ wrapper for PLArenaPool and the - * high-level ANS1 encode/decode routines. - */ - -#include -#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) - -#include "SecNssCoder.h" -#include -#include -#include -#include -#include - -#ifdef NDEBUG -#define THROW_ENABLE 1 -#else -/* disable link against Security framework when true */ -#define THROW_ENABLE 0 -#endif - -#if THROW_ENABLE -#define THROW_ERROR Security::CssmError::throwMe(CSSMERR_CSSM_MEMORY_ERROR) -#else -#define THROW_ERROR -#endif - -SecNssCoder::SecNssCoder(PRUint32 chunkSize /* = SNC_CHUNKSIZE_DEF */) - : mPool(NULL) -{ - mPool = PORT_NewArena(chunkSize); - if(mPool == NULL) { - THROW_ERROR; - } -} - -SecNssCoder::~SecNssCoder() -{ - if(mPool != NULL) { - /* - * Note: we're asking for a memory zero here, but - * PORT_FreeArena doesn't do that (yet). - */ - PORT_FreeArena(mPool, PR_TRUE); - mPool = NULL; - } -} - -PRErrorCode SecNssCoder::decode( - const void *src, // BER-encoded source - size_t len, - const SecAsn1Template *templ, - void *dest) -{ - SECStatus prtn; - - assert(mPool != NULL); - prtn = SEC_ASN1Decode(mPool, dest, templ, (const char *)src, len); - if(prtn) { - return PR_GetError(); - } - else { - return 0; - } -} - -PRErrorCode SecNssCoder::encodeItem( - const void *src, - const SecAsn1Template *templ, - SECItem &dest) -{ - assert(mPool != NULL); - - dest.Data = NULL; - dest.Length = 0; - - SECItem *rtnItem = SEC_ASN1EncodeItem(mPool, &dest, src, templ); - if(rtnItem == NULL) { - return PR_GetError(); - } - else { - return 0; - } -} - -void *SecNssCoder::malloc(size_t len) -{ - assert(mPool != NULL); - void *rtn = PORT_ArenaAlloc(mPool, len); - if(rtn == NULL) { - THROW_ERROR; - } - return rtn; -} - -/* allocate space for num copies of specified type */ -void *SecNssCoder::malloc_T( - size_t unit_bytesize, - size_t num_units) -{ - if (num_units>=SIZE_MAX/unit_bytesize) { - THROW_ERROR; - return NULL; - } - return malloc(unit_bytesize * num_units); -} - - -/* malloc item.Data, set item.Length */ -void SecNssCoder::allocItem( - SECItem &item, - size_t len) -{ - item.Data = (uint8 *)malloc(len); - item.Length = len; -} - -/* malloc and copy */ -void SecNssCoder::allocCopyItem( - const void *src, - size_t len, - SECItem &dest) -{ - allocItem(dest, len); - memmove(dest.Data, src, len); -} - -/* - * This is pretty much a copy of SEC_ASN1EncodeItem, with a Allocator - * malloc replacing the sec_asn1e_allocate_item to alloc the output data. - */ -PRErrorCode SecNssEncodeItem( - const void *src, - const SecAsn1Template *templ, - Security::Allocator &alloc, - SECItem &dest) -{ - unsigned long encoding_length = 0; - SECStatus rv; - - dest.Data = NULL; - dest.Length = 0; - - rv = SEC_ASN1Encode (src, templ, - sec_asn1e_encode_item_count, &encoding_length); - if (rv != SECSuccess) { - return PR_GetError(); - } - - /* replace this... - dest = sec_asn1e_allocate_item (poolp, dest, encoding_length); - if (dest == NULL) - return NULL; - ... with this: */ - dest.Data = (uint8 *)alloc.malloc(encoding_length); - dest.Length = 0; - /* end replacement */ - - rv = SEC_ASN1Encode (src, templ, sec_asn1e_encode_item_store, &dest); - if (rv != SECSuccess) { - return PR_GetError(); - } - - assert(encoding_length == dest.Length); - return 0; -} - -PRErrorCode SecNssEncodeItemOdata( - const void *src, - const SecAsn1Template *templ, - CssmOwnedData &odata) -{ - Allocator &alloc = odata.allocator; - SECItem sitem; - PRErrorCode prtn; - - prtn = SecNssEncodeItem(src, templ, alloc, sitem); - if(prtn) { - return prtn; - } - odata.set(sitem.Data, sitem.Length); - return 0; -} - -#endif /* TARGET_OS_MAC */ diff --git a/OSX/include/security_asn1/SecNssCoder.h b/OSX/include/security_asn1/SecNssCoder.h deleted file mode 100644 index 14effa89..00000000 --- a/OSX/include/security_asn1/SecNssCoder.h +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * SecNssCoder.h: simple C++ wrapper for PLArenaPool and the - * high-level ANS1 encode/decode routines. - */ -#ifndef _SEC_NSS_CODER_H_ -#define _SEC_NSS_CODER_H_ - -#include -#include -#include -#include -#include -#include - -/* - * Default chunk size for new arena pool. - * FIXME: analyze & measure different defaults here. I'm pretty sure - * that only performance - not correct behavior - is affected by - * an arena pool's chunk size. - */ -#define SNC_CHUNKSIZE_DEF 1024 - -class SecNssCoder -{ -public: - SecNssCoder( - PRUint32 chunkSize = SNC_CHUNKSIZE_DEF); - ~SecNssCoder(); - - /* - * BER decode an untyped item per the specified - * template array. The result is allocated - * by this object's PLArenaPool and is freed when - * this object is deleted. - * - * The dest pointer is a template-specific struct allocated - * by the caller and must be zeroed by the caller. - * - * This does not throw any exceptions; error status - * (obtained from PR_GetError() is returned. - */ - PRErrorCode decode( - const void *src, // BER-encoded source - size_t len, - const SecAsn1Template *templ, - void *dest); - - /* convenience routine, decode from an SECItem */ - PRErrorCode decodeItem( - const SECItem &item, // BER-encoded source - const SecAsn1Template *templ, - void *dest) - { - return decode(item.Data, item.Length, templ, dest); - } - - - /* - * BER-encode. This object's arena pool retains a copy of - * the encoded data. - * - * The src pointer is a template-specific struct. - * - * This does not throw any exceptions; error status - * (obtained from PR_GetError() is returned. - */ - PRErrorCode encodeItem( - const void *src, - const SecAsn1Template *templ, - SECItem &dest); - - /* - * Some alloc-related methods which come in handy when using - * this class. All memory is allocated using this object's - * arena pool. Caller never has to free it. Used for - * temp allocs of memory which only needs a scope which is the - * same as this object. - * - * These throw a CssmError in the highly unlikely event of - * a malloc failure. - */ - void *malloc( - size_t len); - - /* allocate space for num copies of specified type */ - template T *mallocn(unsigned num = 1) - { return reinterpret_cast(malloc_T(sizeof(T),num)); } - - /* malloc item.Data, set item.Length */ - void allocItem( - SECItem &item, - size_t len); - - /* malloc and copy, various forms */ - void allocCopyItem( - const void *src, - size_t len, - SECItem &dest); - - void allocCopyItem( - const SECItem &src, - SECItem &dest) - { allocCopyItem(src.Data, src.Length, dest); } - - void allocCopyItem( - const CssmData &src, - SECItem &dest) - { allocCopyItem(src.data(), src.length(), dest); } - - PLArenaPool *pool() const { return mPool;} - -private: - PLArenaPool *mPool; - - void *malloc_T(size_t unit_bytesize, - size_t num_units); -}; - -/* - * Stateless function to BER-encode directly into a Allocator's - * space. The only persistent allocated memory is allocated by - * the Allocator. - * - * The src pointer is a template-specific struct. - * - * This does not throw any exceptions; error status - * (obtained from PR_GetError() is returned. - */ -PRErrorCode SecNssEncodeItem( - const void *src, - const SecAsn1Template *templ, - Allocator &alloc, - SECItem &dest); - -/* - * Same thing, using a CssmOwnedData. - */ -PRErrorCode SecNssEncodeItemOdata( - const void *src, - const SecAsn1Template *templ, - CssmOwnedData &odata); - -#endif /* _SEC_NSS_CODER_H_ */ diff --git a/OSX/include/security_asn1/X509Templates.c b/OSX/include/security_asn1/X509Templates.c deleted file mode 100644 index 4677b4ee..00000000 --- a/OSX/include/security_asn1/X509Templates.c +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * X509Templates.c - Common ASN1 templates for use with libNSSDer. - */ - -#include "SecAsn1Templates.h" -#include "X509Templates.h" -#include "keyTemplates.h" -#include -#include - -/* - * Validity - */ -/* - * NSS_Time Template chooser. - */ -static const NSS_TagChoice timeChoices[] = { - { SEC_ASN1_GENERALIZED_TIME, kSecAsn1GeneralizedTimeTemplate} , - { SEC_ASN1_UTC_TIME, kSecAsn1UTCTimeTemplate }, - { 0, NULL} -}; - -static const SecAsn1Template * NSS_TimeChooser( - void *arg, - Boolean enc, - const char *buf, - void *dest) -{ - return SecAsn1TaggedTemplateChooser(arg, enc, buf, dest, timeChoices); -} - -static const SecAsn1TemplateChooserPtr NSS_TimeChooserPtr = NSS_TimeChooser; - -const SecAsn1Template kSecAsn1ValidityTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_Validity) }, - { SEC_ASN1_INLINE | SEC_ASN1_DYNAMIC, - offsetof(NSS_Validity,notBefore.item), - &NSS_TimeChooserPtr }, - { SEC_ASN1_INLINE | SEC_ASN1_DYNAMIC, - offsetof(NSS_Validity,notAfter.item), - &NSS_TimeChooserPtr }, - { 0 } -}; - -/* X509 cert extension */ -const SecAsn1Template kSecAsn1CertExtensionTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_CertExtension) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_CertExtension,extnId) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_BOOLEAN, /* XXX DER_DEFAULT */ - offsetof(NSS_CertExtension,critical) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSS_CertExtension,value) }, - { 0, } -}; - -const SecAsn1Template kSecAsn1SequenceOfCertExtensionTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1CertExtensionTemplate } -}; - -/* TBS Cert */ -const SecAsn1Template kSecAsn1TBSCertificateTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_TBSCertificate) }, - /* optional version, explicit tag 0, default 0 */ - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, /* XXX DER_DEFAULT */ - offsetof(NSS_TBSCertificate,version), - kSecAsn1IntegerTemplate }, - /* serial number is SIGNED integer */ - { SEC_ASN1_INTEGER | SEC_ASN1_SIGNED_INT, - offsetof(NSS_TBSCertificate,serialNumber) }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCertificate,signature), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_SAVE, offsetof(NSS_TBSCertificate,derIssuer) }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCertificate,issuer), - kSecAsn1NameTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCertificate,validity), - kSecAsn1ValidityTemplate }, - { SEC_ASN1_SAVE, offsetof(NSS_TBSCertificate,derSubject) }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCertificate,subject), - kSecAsn1NameTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCertificate,subjectPublicKeyInfo), - kSecAsn1SubjectPublicKeyInfoTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(NSS_TBSCertificate,issuerID), - kSecAsn1BitStringTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 2, - offsetof(NSS_TBSCertificate,subjectID), - kSecAsn1BitStringTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 3, - offsetof(NSS_TBSCertificate,extensions), - kSecAsn1SequenceOfCertExtensionTemplate }, - { 0 } -}; - -/* - * For signing and verifying only, treating the TBS portion as an - * opaque ASN_ANY blob. - */ -const SecAsn1Template kSecAsn1SignedCertOrCRLTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_SignedCertOrCRL) }, - { SEC_ASN1_ANY, - offsetof(NSS_SignedCertOrCRL,tbsBlob) }, - { SEC_ASN1_ANY, - offsetof(NSS_SignedCertOrCRL,signatureAlgorithm) }, - { SEC_ASN1_BIT_STRING, - offsetof(NSS_SignedCertOrCRL,signature) }, - { 0 } -}; - -/* Fully specified signed certificate */ -const SecAsn1Template kSecAsn1SignedCertTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_Certificate) }, - { SEC_ASN1_INLINE, - offsetof(NSS_Certificate,tbs), - kSecAsn1TBSCertificateTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSS_Certificate,signatureAlgorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, - offsetof(NSS_Certificate,signature) }, - { 0 } -}; - -/* Entry in CRL.revokedCerts */ -const SecAsn1Template kSecAsn1RevokedCertTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_RevokedCert) }, - /* serial number - signed itneger, just like in the actual cert */ - { SEC_ASN1_INTEGER | SEC_ASN1_SIGNED_INT, - offsetof(NSS_RevokedCert,userCertificate) }, - { SEC_ASN1_INLINE | SEC_ASN1_DYNAMIC, - offsetof(NSS_RevokedCert,revocationDate.item), - &NSS_TimeChooserPtr }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_RevokedCert,extensions), - kSecAsn1CertExtensionTemplate }, - { 0, } -}; - -const SecAsn1Template kSecAsn1SequenceOfRevokedCertTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, 0, kSecAsn1RevokedCertTemplate } -}; - -/* NSS_TBSCrl (unsigned CRL) */ -const SecAsn1Template kSecAsn1TBSCrlTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_TBSCrl) }, - /* optional version, default 0 */ - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof (NSS_TBSCrl, version) }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCrl,signature), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_SAVE, offsetof(NSS_TBSCrl,derIssuer) }, - { SEC_ASN1_INLINE, - offsetof(NSS_TBSCrl,issuer), - kSecAsn1NameTemplate }, - { SEC_ASN1_INLINE | SEC_ASN1_DYNAMIC, - offsetof(NSS_TBSCrl,thisUpdate.item), - &NSS_TimeChooserPtr }, - { SEC_ASN1_INLINE | SEC_ASN1_DYNAMIC | SEC_ASN1_OPTIONAL, - offsetof(NSS_TBSCrl,nextUpdate), - &NSS_TimeChooserPtr }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_TBSCrl,revokedCerts), - kSecAsn1RevokedCertTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(NSS_TBSCrl,extensions), - kSecAsn1SequenceOfCertExtensionTemplate }, - { 0, } -}; - -/* Fully specified signed CRL */ -const SecAsn1Template kSecAsn1SignedCrlTemplate[] = -{ - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_Crl) }, - { SEC_ASN1_INLINE, - offsetof(NSS_Crl,tbs), - kSecAsn1TBSCrlTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSS_Crl,signatureAlgorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, - offsetof(NSS_Crl,signature) }, - { 0 } -}; diff --git a/OSX/include/security_asn1/X509Templates.h b/OSX/include/security_asn1/X509Templates.h deleted file mode 100644 index c4532d14..00000000 --- a/OSX/include/security_asn1/X509Templates.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * X509Templates.h - X.509 Certificate and CRL ASN1 templates - */ - -#ifndef _NSS_X509_TEMPLATES_H_ -#define _NSS_X509_TEMPLATES_H_ - -#include -#include - -/* - * Arrays of SecAsn1Templates are always associated with a specific - * C struct. We attempt to use C structs which are defined in CDSA - * if at all possible; these always start with the CSSM_ prefix. - * Otherwise we define the struct here, with an NSS_ prefix. - * In either case, the name of the C struct is listed in comments - * along with the extern declaration of the SecAsn1Template array. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -// MARK: --- X509 Validity support --- - -/* - * ASN Class : Validity - * C struct : NSS_Validity - * - * The low-level Time values, which are CHOICE of generalized - * time or UTC time, still DER-encoded upon decoding of this object. - */ -/* - * The low-level time values are eitehr Generalized Time - * (SEC_ASN1_GENERALIZED_TIME) or UTC time (SEC_ASN1_UTC_TIME). - */ -typedef NSS_TaggedItem NSS_Time; - -typedef struct { - NSS_Time notBefore; - NSS_Time notAfter; -} NSS_Validity; - -extern const SecAsn1Template kSecAsn1ValidityTemplate[]; - -// MARK: --- Certificate --- - -/* - * X509 cert extension - * ASN Class : Extension - * C struct : NSS_CertExtension - * - * With a nontrivial amount of extension-specific processing, - * this maps to a CSSM_X509_EXTENSION. - */ -typedef struct { - SecAsn1Item extnId; - SecAsn1Item critical; // optional, default = false - SecAsn1Item value; // OCTET string whose decoded value is - // an id-specific DER-encoded thing -} NSS_CertExtension; - -extern const SecAsn1Template kSecAsn1CertExtensionTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfCertExtensionTemplate[]; - -/* - * X.509 certificate object (the unsigned form) - * - * ASN class : TBSCertificate - * C struct : NSS_TBSCertificate - */ -typedef struct { - SecAsn1Item version; // optional - SecAsn1Item serialNumber; - SecAsn1AlgId signature; - NSS_Name issuer; - NSS_Validity validity; - NSS_Name subject; - SecAsn1PubKeyInfo subjectPublicKeyInfo; - SecAsn1Item issuerID; // optional, BITS - SecAsn1Item subjectID; // optional, BITS - NSS_CertExtension **extensions; // optional - - /* - * Additional DER-encoded fields copied (via SEC_ASN1_SAVE) - * during decoding. - */ - SecAsn1Item derIssuer; - SecAsn1Item derSubject; -} NSS_TBSCertificate; - -extern const SecAsn1Template kSecAsn1TBSCertificateTemplate[]; - -/* - * Fully specified signed certificate. - * - * ASN class : Certificate - * C struct : NSS_Certificate - */ -typedef struct { - NSS_TBSCertificate tbs; - SecAsn1AlgId signatureAlgorithm; - SecAsn1Item signature;// BIT STRING, length in bits -} NSS_Certificate; - -extern const SecAsn1Template kSecAsn1SignedCertTemplate[]; - -// MARK: --- CRL --- - -/* - * ASN class : revokedCertificate - * C struct : NSS_RevokedCert - */ -typedef struct { - SecAsn1Item userCertificate; // serial number - NSS_Time revocationDate; - NSS_CertExtension **extensions; // optional -} NSS_RevokedCert; - -extern const SecAsn1Template kSecAsn1RevokedCertTemplate[]; -extern const SecAsn1Template kSecAsn1SequenceOfRevokedCertTemplate[]; - -/* - * X509 Cert Revocation List (the unsigned form) - * ASN class : TBSCertList - * C struct : NSS_TBSCrl - */ -typedef struct { - SecAsn1Item version; // optional - SecAsn1AlgId signature; - NSS_Name issuer; - NSS_Time thisUpdate; - NSS_Time nextUpdate; // optional - NSS_RevokedCert **revokedCerts; // optional - NSS_CertExtension **extensions; // optional - - /* - * Additional DER-encoded fields copied (via SEC_ASN1_SAVE) - * during decoding. - */ - SecAsn1Item derIssuer; - -} NSS_TBSCrl; - -extern const SecAsn1Template kSecAsn1TBSCrlTemplate[]; - -/* - * Fully specified signed CRL. - * - * ASN class : CertificateList - * C struct : NSS_CRL - */ -typedef struct { - NSS_TBSCrl tbs; - SecAsn1AlgId signatureAlgorithm; - SecAsn1Item signature;// BIT STRING, length in bits -} NSS_Crl; - -extern const SecAsn1Template kSecAsn1SignedCrlTemplate[]; - -/* - * signed data - top-level view of a signed Cert or CRL, for - * signing and verifying only. Treats the TBS and AlgId portions - * as opaque ASN_ANY blobs. - */ -typedef struct { - SecAsn1Item tbsBlob; // ANY, DER encoded cert or CRL - SecAsn1Item signatureAlgorithm; - SecAsn1Item signature;// BIT STRING, length in bits -} NSS_SignedCertOrCRL; - -extern const SecAsn1Template kSecAsn1SignedCertOrCRLTemplate[]; - -#ifdef __cplusplus -} -#endif - -#endif /* _NSS_X509_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/asn1Templates.h b/OSX/include/security_asn1/asn1Templates.h deleted file mode 100644 index ec00625f..00000000 --- a/OSX/include/security_asn1/asn1Templates.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2005-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * asn1Templates.h - Common ASN1 primitive templates for use with SecAsn1Coder. - */ - -#ifndef _ASN1_TEMPLATES_H_ -#define _ASN1_TEMPLATES_H_ - -#warning This is for backwards compatibility. Please use instead. - -#include - -#endif /* _ASN1_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/certExtensionTemplates.c b/OSX/include/security_asn1/certExtensionTemplates.c deleted file mode 100644 index 02315128..00000000 --- a/OSX/include/security_asn1/certExtensionTemplates.c +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * certExtensionTemplates.cpp - libnssasn1 structs and templates for cert and - * CRL extensions - * - */ - -#include "certExtensionTemplates.h" -#include "SecAsn1Templates.h" -#include - -/* Basic Constraints */ -const SecAsn1Template kSecAsn1BasicConstraintsTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_BasicConstraints) }, - { SEC_ASN1_BOOLEAN | SEC_ASN1_OPTIONAL, - offsetof(NSS_BasicConstraints,cA) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, - offsetof(NSS_BasicConstraints, pathLenConstraint) }, - { 0, } -}; - -/* Authority Key Identifier */ - -/* signed integer - SEC_ASN1_SIGNED_INT state gets lost - * in SEC_ASN1_CONTEXT_SPECIFIC processing */ -const SecAsn1Template kSecAsn1SignedIntegerTemplate[] = { - { SEC_ASN1_INTEGER | SEC_ASN1_SIGNED_INT, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1AuthorityKeyIdTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_AuthorityKeyId) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_POINTER | 0, - offsetof(NSS_AuthorityKeyId,keyIdentifier), - kSecAsn1OctetStringTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(NSS_AuthorityKeyId,genNames), - kSecAsn1GeneralNamesTemplate }, - /* serial number is SIGNED integer */ - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | 2, - offsetof(NSS_AuthorityKeyId,serialNumber), - kSecAsn1SignedIntegerTemplate}, - { 0 } -}; - -/* Certificate policies */ -const SecAsn1Template kSecAsn1PolicyQualifierTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_PolicyQualifierInfo) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_PolicyQualifierInfo,policyQualifierId) }, - { SEC_ASN1_ANY, offsetof(NSS_PolicyQualifierInfo, qualifier) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1PolicyInformationTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_PolicyInformation) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_PolicyInformation,certPolicyId) }, - { SEC_ASN1_SEQUENCE_OF | SEC_ASN1_OPTIONAL, - offsetof(NSS_PolicyInformation,policyQualifiers), - kSecAsn1PolicyQualifierTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1CertPoliciesTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_CertPolicies,policies), - kSecAsn1PolicyInformationTemplate }, - { 0 } -}; - -/* CRL Distribution Points */ - -/* - * NOTE WELL: RFC2459, and all the documentation I can find, claims that - * the tag for the DistributionPointName option (tag 0) of a - * DistributionPoint is IMPLICIT and context-specific. However this - * is IMPOSSIBLE - since the underlying type (DistributionPointName) - * also relies upon context-specific tags to resolve a CHOICE. - * The real world indicates that the tag for the DistributionPoint option - * is indeed EXPLICIT. Examination of many certs' cRLDistributionPoints - * extensions shows this, and the NSS reference code also specifies - * an EXPLICIT tag for this field. - */ -const SecAsn1Template kSecAsn1DistributionPointTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_DistributionPoint) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | 0, - offsetof(NSS_DistributionPoint,distPointName), - kSecAsn1PointerToAnyTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(NSS_DistributionPoint,reasons), kSecAsn1BitStringTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | 2, - offsetof(NSS_DistributionPoint, crlIssuer), - kSecAsn1GeneralNamesTemplate - }, - { 0 } -}; - -const SecAsn1Template kSecAsn1CRLDistributionPointsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_CRLDistributionPoints,distPoints), - kSecAsn1DistributionPointTemplate }, - { 0 } -}; - - -/* - * These are the context-specific targets of the DistributionPointName - * option. - */ -const SecAsn1Template kSecAsn1DistPointFullNameTemplate[] = { - {SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0, - offsetof (NSS_GeneralNames,names), kSecAsn1GeneralNamesTemplate} -}; - -const SecAsn1Template kSecAsn1DistPointRDNTemplate[] = { - {SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, - offsetof (NSS_RDN,atvs), kSecAsn1RDNTemplate} -}; - -/* - * Issuing distribution points - * - * Although the spec says that the DistributionPointName element - * is context-specific, it must be explicit because the underlying - * type - a DistributionPointName - also relies on a context-specific - * tags to resolve a CHOICE. - */ - -/* kludge: ASN decoder doesn't handle - * SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER - * very well... */ -static const SecAsn1Template kSecAsn1OptBooleanTemplate[] = { - { SEC_ASN1_BOOLEAN | SEC_ASN1_OPTIONAL, 0, NULL, sizeof(SecAsn1Item) } -}; - -static const SecAsn1Template kSecAsn1OptBitStringTemplate[] = { - { SEC_ASN1_BIT_STRING | SEC_ASN1_OPTIONAL, 0, NULL, sizeof(SecAsn1Item) } -}; - -const SecAsn1Template kSecAsn1IssuingDistributionPointTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_IssuingDistributionPoint) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | 0, - offsetof(NSS_IssuingDistributionPoint,distPointName), - kSecAsn1PointerToAnyTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 1, - offsetof(NSS_IssuingDistributionPoint,onlyUserCerts), - kSecAsn1OptBooleanTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 2, - offsetof(NSS_IssuingDistributionPoint,onlyCACerts), - kSecAsn1OptBooleanTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 3, - offsetof(NSS_IssuingDistributionPoint,onlySomeReasons), - kSecAsn1OptBitStringTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_POINTER | 4, - offsetof(NSS_IssuingDistributionPoint,indirectCRL), - kSecAsn1OptBooleanTemplate}, - { 0 } -}; - - -/* - * Authority Information Access and Subject Information Access. - */ -const SecAsn1Template kSecAsn1AccessDescriptionTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_AccessDescription) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_AccessDescription,accessMethod) }, - /* - * NSS encoder just can't handle direct inline of an NSS_GeneralName here. - */ - { SEC_ASN1_ANY, - offsetof(NSS_AccessDescription, encodedAccessLocation) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1AuthorityInfoAccessTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_AuthorityInfoAccess,accessDescriptions), - kSecAsn1AccessDescriptionTemplate, - sizeof(NSS_AuthorityInfoAccess) } -}; - -/* - * Qualified Certificate Statements templates. - * - * This is the NSS_QC_Statement.info when NSS_QC_Statement.statementId - * is CSSMOID_OID_QCS_SYNTAX_V2. - */ -const SecAsn1Template kSecAsn1SemanticsInformationTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_SemanticsInformation) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_POINTER, - offsetof(NSS_SemanticsInformation,semanticsIdentifier), - kSecAsn1ObjectIDTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_POINTER, - offsetof(NSS_SemanticsInformation, nameRegistrationAuthorities), - kSecAsn1GeneralNamesTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1QC_StatementTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_QC_Statement) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_QC_Statement,statementId) }, - { SEC_ASN1_ANY | SEC_ASN1_OPTIONAL, - offsetof(NSS_QC_Statement, info) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1QC_StatementsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_QC_Statements,qcStatements), - kSecAsn1QC_StatementTemplate, - sizeof(NSS_QC_Statements) } -}; - -/* - * NameConstraints templates - */ -const SecAsn1Template kSecAsn1GeneralSubtreeTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_GeneralSubtree) }, - { SEC_ASN1_SEQUENCE, - offsetof(NSS_GeneralSubtree,base), - kSecAsn1GeneralNamesTemplate }, - { SEC_ASN1_INTEGER, - offsetof(NSS_GeneralSubtree,minimum) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, - offsetof(NSS_GeneralSubtree,maximum) }, - { 0, } -}; - -const SecAsn1Template kSecAsn1GeneralSubtreesTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_GeneralSubtrees,subtrees), - kSecAsn1GeneralSubtreeTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1NameConstraintsTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_NameConstraints) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | 0, - offsetof(NSS_NameConstraints,permittedSubtrees), - kSecAsn1GeneralSubtreesTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | 1, - offsetof(NSS_NameConstraints,excludedSubtrees), - kSecAsn1GeneralSubtreesTemplate }, - { 0 } -}; - -/* - * PolicyMappings templates - */ -const SecAsn1Template kSecAsn1PolicyMappingTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_PolicyMapping) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_PolicyMapping,issuerDomainPolicy) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_PolicyMapping,subjectDomainPolicy) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1PolicyMappingsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_PolicyMappings,policyMappings), - kSecAsn1PolicyMappingTemplate }, - { 0 } -}; - -/* - * PolicyConstraints templates - */ -const SecAsn1Template kSecAsn1PolicyConstraintsTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_PolicyConstraints) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | 0, - offsetof(NSS_PolicyConstraints,requireExplicitPolicy) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | 1, - offsetof(NSS_PolicyConstraints,inhibitPolicyMapping) }, - { 0 } -}; - - diff --git a/OSX/include/security_asn1/certExtensionTemplates.h b/OSX/include/security_asn1/certExtensionTemplates.h deleted file mode 100644 index fd575fb1..00000000 --- a/OSX/include/security_asn1/certExtensionTemplates.h +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * certExtensionTemplates.h - libnssasn1 structs and templates for cert and - * CRL extensions - * - */ - -#ifndef _CERT_EXTENSION_TEMPLATES_H_ -#define _CERT_EXTENSION_TEMPLATES_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Basic Constraints - * NSS struct : NSS_BasicConstraints - * CDSA struct : CE_BasicConstraints - */ -typedef struct { - SecAsn1Item cA; // BOOL - SecAsn1Item pathLenConstraint; // INTEGER optional -} NSS_BasicConstraints; - -extern const SecAsn1Template kSecAsn1BasicConstraintsTemplate[]; - -/* - * Key Usage - * NSS struct : SecAsn1Item, BIT STRING - length in bits - * CDSA struct : CE_KeyUsage - */ -#define kSecAsn1KeyUsageTemplate kSecAsn1BitStringTemplate - -/* - * Extended Key Usage - * NSS struct : NSS_ExtKeyUsage - * CDSA struct : CE_ExtendedKeyUsage - */ -typedef struct { - SecAsn1Oid **purposes; -} NSS_ExtKeyUsage; -#define kSecAsn1ExtKeyUsageTemplate kSecAsn1SequenceOfObjectIDTemplate - -/* - * Subject Key Identifier - * NSS struct : SecAsn1Item - * CDSA struct : CE_SubjectKeyID, typedef'd to a SecAsn1Item - */ -#define kSecAsn1SubjectKeyIdTemplate kSecAsn1OctetStringTemplate - -/* - * Authority Key Identifier - * NSS struct : NSS_AuthorityKeyId - * CDSA struct : CE_AuthorityKeyID - * - * All fields are optional. - * NOTE: due to an anomaly in the encoding module, if the first field - * of a sequence is optional, it has to be a POINTER type. - */ -typedef struct { - SecAsn1Item *keyIdentifier; // octet string - NSS_GeneralNames genNames; - SecAsn1Item serialNumber; // integer -} NSS_AuthorityKeyId; - -extern const SecAsn1Template kSecAsn1AuthorityKeyIdTemplate[]; - -/* - * Certificate policies. - * NSS struct : NSS_CertPolicies - * CDSA struct : CE_CertPolicies - */ -typedef struct { - SecAsn1Oid policyQualifierId; // CSSMOID_QT_CPS, CSSMOID_QT_UNOTICE - SecAsn1Item qualifier; // ASN_ANY, not interpreted here -} NSS_PolicyQualifierInfo; - -extern const SecAsn1Template kSecAsn1PolicyQualifierTemplate[]; - -typedef struct { - SecAsn1Oid certPolicyId; - NSS_PolicyQualifierInfo **policyQualifiers; // SEQUENCE OF -} NSS_PolicyInformation; - -extern const SecAsn1Template kSecAsn1PolicyInformationTemplate[]; - -typedef struct { - NSS_PolicyInformation **policies; // SEQUENCE OF -} NSS_CertPolicies; - -extern const SecAsn1Template kSecAsn1CertPoliciesTemplate[]; - -/* - * netscape-cert-type - * NSS struct : SecAsn1Item, BIT STRING - length in bits - * CDSA struct : CE_NetscapeCertType (a uint16) - */ -#define kSecAsn1NetscapeCertTypeTemplate kSecAsn1BitStringTemplate - -/* - * CRL Distribution Points. - * NSS struct : NSS_DistributionPoint, NSS_DistributionPoints - * CDSA struct : CE_CRLDistributionPoint, CE_CRLDistributionPointSyntax - */ - -typedef struct { - SecAsn1Item *distPointName; // ASN_ANY, optional - SecAsn1Item reasons; // BIT_STRING, optional - NSS_GeneralNames crlIssuer; // optional -} NSS_DistributionPoint; - -typedef struct { - NSS_DistributionPoint **distPoints; // SEQUENCE OF -} NSS_CRLDistributionPoints; - -extern const SecAsn1Template kSecAsn1DistributionPointTemplate[]; -extern const SecAsn1Template kSecAsn1CRLDistributionPointsTemplate[]; - -/* - * Resolving the NSS_DistributionPoint.distributionPoint option - * involves inspecting the tag of the ASN_ANY and using one of - * these templates. One the CDSA side the corresponding struct is - * a CE_DistributionPointName. - * - * This one resolves to an NSS_GeneralNames: - */ -#define NSS_DIST_POINT_FULL_NAME_TAG 0 -extern const SecAsn1Template kSecAsn1DistPointFullNameTemplate[]; - -/* - * This one resolves to an NSS_RDN. - */ -#define NSS_DIST_POINT_RDN_TAG 1 -extern const SecAsn1Template kSecAsn1DistPointRDNTemplate[]; - -/* - * Issuing distribution point. - * - * NSS Struct : NSS_IssuingDistributionPoint - * CDSA struct : CE_IssuingDistributionPoint - * - * All fields optional; default for ASN_BOOLs is false. - */ -typedef struct { - /* manually decode to a CE_DistributionPointName */ - SecAsn1Item *distPointName; // ASN_ANY, optional - - SecAsn1Item *onlyUserCerts; // ASN_BOOL - SecAsn1Item *onlyCACerts; // ASN_BOOL - SecAsn1Item *onlySomeReasons; // BIT STRING - SecAsn1Item *indirectCRL; // ASN_BOOL -} NSS_IssuingDistributionPoint; - -extern const SecAsn1Template kSecAsn1IssuingDistributionPointTemplate[]; - -/* - * Authority Information Access, Subject Information Access. - * - * NSS Struct : NSS_AuthorityInfoAccess - * CDSA struct : CE_AuthorityInfoAccess - */ -typedef struct { - SecAsn1Item accessMethod; - - /* NSS encoder just can't handle direct inline of an NSS_GeneralName here. - * After decode and prior to encode this is an encoded GeneralName. - */ - SecAsn1Item encodedAccessLocation; -} NSS_AccessDescription; - -typedef struct { - NSS_AccessDescription **accessDescriptions; -} NSS_AuthorityInfoAccess; - -extern const SecAsn1Template kSecAsn1AccessDescriptionTemplate[]; -extern const SecAsn1Template kSecAsn1AuthorityInfoAccessTemplate[]; - -/* - * Qualified Certificate Statements support - */ -typedef struct { - SecAsn1Oid *semanticsIdentifier; /* optional */ - NSS_GeneralNames *nameRegistrationAuthorities; /* optional */ -} NSS_SemanticsInformation; - -typedef struct { - SecAsn1Oid statementId; - SecAsn1Item info; /* optional, ANY */ -} NSS_QC_Statement; - -typedef struct { - NSS_QC_Statement **qcStatements; -} NSS_QC_Statements; - -extern const SecAsn1Template kSecAsn1SemanticsInformationTemplate[]; -extern const SecAsn1Template kSecAsn1QC_StatementTemplate[]; -extern const SecAsn1Template kSecAsn1QC_StatementsTemplate[]; - -/* - * NameConstraints support - */ -typedef struct { - NSS_GeneralNames base; - SecAsn1Item minimum; // INTEGER default=0 - SecAsn1Item maximum; // INTEGER optional -} NSS_GeneralSubtree; - -typedef struct { - NSS_GeneralSubtree **subtrees; // SEQUENCE OF -} NSS_GeneralSubtrees; - -typedef struct { - NSS_GeneralSubtrees *permittedSubtrees; // optional - NSS_GeneralSubtrees *excludedSubtrees; // optional -} NSS_NameConstraints; - -extern const SecAsn1Template kSecAsn1NameConstraintsTemplate[]; - -/* - * PolicyMappings support - */ -typedef struct { - SecAsn1Oid issuerDomainPolicy; - SecAsn1Oid subjectDomainPolicy; -} NSS_PolicyMapping; - -typedef struct { - NSS_PolicyMapping **policyMappings; // SEQUENCE OF -} NSS_PolicyMappings; - -extern const SecAsn1Template kSecAsn1PolicyMappingsTemplate[]; - -/* - * PolicyConstraints support - */ -typedef struct { - SecAsn1Item requireExplicitPolicy; // INTEGER optional - SecAsn1Item inhibitPolicyMapping; // INTEGER optional -} NSS_PolicyConstraints; - -extern const SecAsn1Template kSecAsn1PolicyConstraintsTemplate[]; - -/* - * InhibitAnyPolicy support - */ -#define kSecAsn1InhibitAnyPolicyTemplate kSecAsn1IntegerTemplate; - -#ifdef __cplusplus -} -#endif - -#endif /* _CERT_EXTENSION_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/csrTemplates.c b/OSX/include/security_asn1/csrTemplates.c deleted file mode 100644 index d4ea114b..00000000 --- a/OSX/include/security_asn1/csrTemplates.c +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * csrTemplates.cpp - ASN1 templates Cert Signing Requests (per PKCS10). - */ - -#include "SecAsn1Templates.h" -#include -#include "csrTemplates.h" -#include "keyTemplates.h" - -const SecAsn1Template kSecAsn1CertRequestInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSCertRequestInfo) }, - { SEC_ASN1_INTEGER, offsetof(NSSCertRequestInfo,version) }, - { SEC_ASN1_INLINE, - offsetof(NSSCertRequestInfo,subject), - kSecAsn1NameTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSSCertRequestInfo,subjectPublicKeyInfo), - kSecAsn1SubjectPublicKeyInfoTemplate }, - { SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSSCertRequestInfo,attributes), - kSecAsn1SetOfAttributeTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1CertRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSCertRequest) }, - { SEC_ASN1_INLINE, - offsetof(NSSCertRequest,reqInfo), - kSecAsn1CertRequestInfoTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSSCertRequest,signatureAlgorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, offsetof(NSSCertRequest,signature) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1SignedCertRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_SignedCertRequest) }, - { SEC_ASN1_ANY, - offsetof(NSS_SignedCertRequest,certRequestBlob), - kSecAsn1CertRequestInfoTemplate }, - { SEC_ASN1_INLINE, - offsetof(NSS_SignedCertRequest,signatureAlgorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, offsetof(NSS_SignedCertRequest,signature) }, - { 0 } -}; - diff --git a/OSX/include/security_asn1/csrTemplates.h b/OSX/include/security_asn1/csrTemplates.h deleted file mode 100644 index bedc7e67..00000000 --- a/OSX/include/security_asn1/csrTemplates.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * csrTemplates.h - ASN1 templates Cert Signing Requests (per PKCS10). - */ - -#ifndef _NSS_CSR_TEMPLATES_H_ -#define _NSS_CSR_TEMPLATES_H_ - -#include -#include /* for NSS_Attribute */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * ASN class : CertificationRequestInfo - * C struct : NSSCertRequestInfo - */ -typedef struct { - SecAsn1Item version; - NSS_Name subject; - SecAsn1PubKeyInfo subjectPublicKeyInfo; - NSS_Attribute **attributes; -} NSSCertRequestInfo; - -extern const SecAsn1Template kSecAsn1CertRequestInfoTemplate[]; - -/* - * ASN class : CertificationRequest - * C struct : NSSCertRequest - */ -typedef struct { - NSSCertRequestInfo reqInfo; - SecAsn1AlgId signatureAlgorithm; - SecAsn1Item signature;// BIT STRING, length in bits -} NSSCertRequest; - -extern const SecAsn1Template kSecAsn1CertRequestTemplate[]; - -/* - * This is what we use use to avoid unnecessary setup and teardown of - * a full NSSCertRequest when signing and verifying. - */ -typedef struct { - SecAsn1Item certRequestBlob; // encoded, ASN_ANY - SecAsn1AlgId signatureAlgorithm; - SecAsn1Item signature;// BIT STRING, length in bits -} NSS_SignedCertRequest; - -extern const SecAsn1Template kSecAsn1SignedCertRequestTemplate[]; - -#ifdef __cplusplus -} -#endif - -#endif /* _NSS_CSR_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/keyTemplates.c b/OSX/include/security_asn1/keyTemplates.c deleted file mode 100644 index d3c28816..00000000 --- a/OSX/include/security_asn1/keyTemplates.c +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * keyTemplate.cpp - ASN1 templates for asymmetric keys and related - * structs. - */ - -#include "SecAsn1Templates.h" -#include -#include "keyTemplates.h" - -/* AlgorithmIdentifier : SecAsn1AlgId */ -const SecAsn1Template kSecAsn1AlgorithmIDTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1AlgId) }, - { SEC_ASN1_OBJECT_ID, - offsetof(SecAsn1AlgId,algorithm), }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY, - offsetof(SecAsn1AlgId,parameters), }, - { 0, } -}; - -/* SubjectPublicKeyInfo : SecAsn1PubKeyInfo */ -const SecAsn1Template kSecAsn1SubjectPublicKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1PubKeyInfo) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1PubKeyInfo,algorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, - offsetof(SecAsn1PubKeyInfo,subjectPublicKey), }, - { 0, } -}; - -/* Attribute : NSS_Attribute */ -const SecAsn1Template kSecAsn1AttributeTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_Attribute) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSS_Attribute, attrType) }, - { SEC_ASN1_SET_OF, offsetof(NSS_Attribute, attrValue), - kSecAsn1AnyTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1SetOfAttributeTemplate[] = { - { SEC_ASN1_SET_OF, 0, kSecAsn1AttributeTemplate }, -}; - -/* PKCS8 PrivateKeyInfo : NSS_PrivateKeyInfo */ -const SecAsn1Template kSecAsn1PrivateKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_PrivateKeyInfo) }, - { SEC_ASN1_INTEGER, offsetof(NSS_PrivateKeyInfo,version) }, - { SEC_ASN1_INLINE, offsetof(NSS_PrivateKeyInfo,algorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, offsetof(NSS_PrivateKeyInfo,privateKey) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSS_PrivateKeyInfo,attributes), - kSecAsn1SetOfAttributeTemplate }, - { 0 } -}; - -/* NSS_EncryptedPrivateKeyInfo */ -const SecAsn1Template kSecAsn1EncryptedPrivateKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_EncryptedPrivateKeyInfo) }, - { SEC_ASN1_INLINE, - offsetof(NSS_EncryptedPrivateKeyInfo,algorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSS_EncryptedPrivateKeyInfo,encryptedData) }, - { 0 } -}; - -/* DigestInfo: NSS_DigestInfo */ -const SecAsn1Template kSecAsn1DigestInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DigestInfo) }, - { SEC_ASN1_INLINE, offsetof(NSS_DigestInfo,digestAlgorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, offsetof(NSS_DigestInfo,digest) }, - { 0 } -}; - -// MARK: - -// MARK: *** RSA *** - -/*** RSA public key, PKCS1 format : NSS_RSAPublicKeyPKCS1 ***/ -const SecAsn1Template kSecAsn1RSAPublicKeyPKCS1Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_RSAPublicKeyPKCS1) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPublicKeyPKCS1,modulus) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPublicKeyPKCS1,publicExponent) }, - { 0, } -}; - -/*** RSA private key key, PKCS1 format : NSS_RSAPrivateKeyPKCS1 ***/ -const SecAsn1Template kSecAsn1RSAPrivateKeyPKCS1Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_RSAPrivateKeyPKCS1) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,version) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,modulus) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,publicExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,privateExponent) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,prime1) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,prime2) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,exponent1) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,exponent2) }, - { SEC_ASN1_INTEGER, offsetof(NSS_RSAPrivateKeyPKCS1,coefficient) }, - { 0, } -}; - -// MARK: - -// MARK: *** Diffie-Hellman *** - -/**** - **** Diffie-Hellman, from PKCS3. - ****/ -const SecAsn1Template kSecAsn1DHParameterTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHParameter) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHParameter,prime) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHParameter,base) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, offsetof(NSS_DHParameter,privateValueLength) }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DHParameterBlockTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHParameterBlock) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSS_DHParameterBlock, oid) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DHParameterBlock, params), - kSecAsn1DHParameterTemplate }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DHPrivateKeyTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHPrivateKey) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSS_DHPrivateKey, dhOid) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DHPrivateKey, params), - kSecAsn1DHParameterTemplate }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHPrivateKey,secretPart) }, - { 0, } -}; - -/* - * Diffie-Hellman, X9.42 style. - */ -const SecAsn1Template kSecAsn1DHValidationParamsTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHValidationParams) }, - { SEC_ASN1_BIT_STRING, offsetof(NSS_DHValidationParams, seed) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHValidationParams, pGenCounter) }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DHDomainParamsX942Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHDomainParamsX942) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHDomainParamsX942, p) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHDomainParamsX942, g) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHDomainParamsX942, q) }, - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, - offsetof(NSS_DHDomainParamsX942, j) }, - { SEC_ASN1_POINTER | SEC_ASN1_OPTIONAL, - offsetof(NSS_DHDomainParamsX942, valParams), - kSecAsn1DHValidationParamsTemplate }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DHAlgorithmIdentifierX942Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHAlgorithmIdentifierX942) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSS_DHAlgorithmIdentifierX942, oid) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DHAlgorithmIdentifierX942, params), - kSecAsn1DHDomainParamsX942Template }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DHPrivateKeyPKCS8Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHPrivateKeyPKCS8) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DHPrivateKeyPKCS8,version) }, - { SEC_ASN1_INLINE, offsetof(NSS_DHPrivateKeyPKCS8,algorithm), - kSecAsn1DHAlgorithmIdentifierX942Template }, - { SEC_ASN1_OCTET_STRING, offsetof(NSS_DHPrivateKeyPKCS8,privateKey) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSS_DHPrivateKeyPKCS8,attributes), - kSecAsn1SetOfAttributeTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1DHPublicKeyX509Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DHPublicKeyX509) }, - { SEC_ASN1_INLINE, offsetof(NSS_DHPublicKeyX509,algorithm), - kSecAsn1DHAlgorithmIdentifierX942Template }, - { SEC_ASN1_BIT_STRING, offsetof(NSS_DHPublicKeyX509, publicKey) }, - { 0 } -}; - -/* ECDSA Private key */ -const SecAsn1Template kSecAsn1ECDSAPrivateKeyInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_ECDSA_PrivateKey) }, - { SEC_ASN1_INTEGER, offsetof(NSS_ECDSA_PrivateKey,version) }, - { SEC_ASN1_OCTET_STRING, offsetof(NSS_ECDSA_PrivateKey,privateKey) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSS_ECDSA_PrivateKey,params), kSecAsn1AnyTemplate}, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(NSS_ECDSA_PrivateKey,pubKey), kSecAsn1BitStringTemplate }, - { 0, } -}; - diff --git a/OSX/include/security_asn1/keyTemplates.h b/OSX/include/security_asn1/keyTemplates.h deleted file mode 100644 index ce726ff3..00000000 --- a/OSX/include/security_asn1/keyTemplates.h +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * keyTemplate.h - ASN1 templates for asymmetric keys and related - * structs. - */ - -#ifndef _NSS_KEY_TEMPLATES_H_ -#define _NSS_KEY_TEMPLATES_H_ - -#include - -/* - * Arrays of SecAsn1Templates are always associated with a specific - * C struct. We attempt to use C structs which are defined in CDSA - * if at all possible; these always start with the CSSM_ prefix. - * Otherwise we define the struct here, with an NSS_ prefix. - * In either case, the name of the C struct is listed in comments - * along with the extern declaration of the SecAsn1Template array. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * ASN class : AlgorithmIdentifier - * C struct : SecAsn1AlgId - */ -extern const SecAsn1Template kSecAsn1AlgorithmIDTemplate[]; - -/* - * ASN class : SubjectPublicKeyInfo - * C struct : SecAsn1PubKeyInfo - */ -extern const SecAsn1Template kSecAsn1SubjectPublicKeyInfoTemplate[]; - -/* - * ASN class : Attribute - * C struct : NSS_Attribute - */ -typedef struct { - SecAsn1Oid attrType; - SecAsn1Item **attrValue; -} NSS_Attribute; - -extern const SecAsn1Template kSecAsn1AttributeTemplate[]; -extern const SecAsn1Template kSecAsn1SetOfAttributeTemplate[]; - -/* - * PKCS8 private key info - * ASN class : PrivateKeyInfo - * C struct : NSS_PrivateKeyInfo - */ -typedef struct { - SecAsn1Item version; - SecAsn1AlgId algorithm; - SecAsn1Item privateKey; - NSS_Attribute **attributes; -} NSS_PrivateKeyInfo; - -extern const SecAsn1Template kSecAsn1PrivateKeyInfoTemplate[]; - -/* - * PKCS8 Encrypted Private Key Info - * ASN class : EncryptedPrivateKeyInfo - * C struct : NSS_EncryptedPrivateKeyInfo - * - * The decrypted encryptedData field is a DER-encoded - * NSS_PrivateKeyInfo. - */ -typedef struct { - SecAsn1AlgId algorithm; - SecAsn1Item encryptedData; -} NSS_EncryptedPrivateKeyInfo; - -extern const SecAsn1Template kSecAsn1EncryptedPrivateKeyInfoTemplate[]; - -/* - * ASN class : DigestInfo - * C struct : NSS_DigestInfo - */ -typedef struct { - SecAsn1AlgId digestAlgorithm; - SecAsn1Item digest; -} NSS_DigestInfo; - -extern const SecAsn1Template kSecAsn1DigestInfoTemplate[]; - -/* - * Key structs and templates, placed here due to their ubiquitous use. - */ - -// MARK: *** RSA *** - -/* - * RSA public key, PKCS1 format - * - * ASN class : RSAPublicKey - * C struct : NSS_RSAPublicKeyPKCS1 - */ -typedef struct { - SecAsn1Item modulus; - SecAsn1Item publicExponent; -} NSS_RSAPublicKeyPKCS1; - -extern const SecAsn1Template kSecAsn1RSAPublicKeyPKCS1Template[]; - -/* - * RSA public key, X509 format: NSS_SubjectPublicKeyInfoTemplate - */ - -/* - * RSA private key, PKCS1 format, used by openssl - * - * ASN class : RSAPrivateKey - * C struct : NSS_RSAPrivateKeyPKCS1 - */ -typedef struct { - SecAsn1Item version; - SecAsn1Item modulus; - SecAsn1Item publicExponent; - SecAsn1Item privateExponent; - SecAsn1Item prime1; - SecAsn1Item prime2; - SecAsn1Item exponent1; - SecAsn1Item exponent2; - SecAsn1Item coefficient; -} NSS_RSAPrivateKeyPKCS1; - -extern const SecAsn1Template kSecAsn1RSAPrivateKeyPKCS1Template[]; - -/* - * RSA private key, PKCS8 format: NSS_PrivateKeyInfo; the privateKey - * value is a DER-encoded NSS_RSAPrivateKeyPKCS1. - */ - -// MARK: *** Diffie-Hellman *** - -/*** from PKCS3 ***/ - -/* - * ASN class : DHParameter - * C struct : NSS_DHParameter - */ -typedef struct { - SecAsn1Item prime; - SecAsn1Item base; - SecAsn1Item privateValueLength; // optional -} NSS_DHParameter; - -extern const SecAsn1Template kSecAsn1DHParameterTemplate[]; - -/* - * ASN class : DHParameterBlock - * C struct : NSS_DHParameterBlock - */ -typedef struct { - SecAsn1Oid oid; // CSSMOID_PKCS3 - NSS_DHParameter params; -} NSS_DHParameterBlock; - -extern const SecAsn1Template kSecAsn1DHParameterBlockTemplate[]; - -/* - * ASN class : DHPrivateKey - * C struct : NSS_DHPrivateKey - */ -typedef struct { - SecAsn1Oid dhOid; // CSSMOID_DH - NSS_DHParameter params; - SecAsn1Item secretPart; -} NSS_DHPrivateKey; - -extern const SecAsn1Template kSecAsn1DHPrivateKeyTemplate[]; - -/* - * ANSI X9.42 style Diffie-Hellman keys. - * - * DomainParameters ::= SEQUENCE { -- Galois field group parameters - * p INTEGER, -- odd prime, p = jq + 1 - * g INTEGER, -- generator, g ^ q = 1 mod p - * q INTEGER, -- prime factor of p-1 - * j INTEGER OPTIONAL, -- cofactor, j >= 2 - * -- required for cofactor method - * valParms ValidationParms OPTIONAL - * } - * - * ValidationParms ::= SEQUENCE { - * seed BIT STRING, -- seed for prime number generation - * pGenCounter INTEGER -- parameter verification - * } - */ -typedef struct { - SecAsn1Item seed; // BIT STRING, length in bits - SecAsn1Item pGenCounter; -} NSS_DHValidationParams; - -typedef struct { - SecAsn1Item p; - SecAsn1Item g; - SecAsn1Item q; - SecAsn1Item j; // OPTIONAL - NSS_DHValidationParams *valParams; // OPTIONAL -} NSS_DHDomainParamsX942; - -/* Custom X9.42 D-H AlgorithmIdentifier */ -typedef struct { - SecAsn1Oid oid; // CSSMOID_ANSI_DH_PUB_NUMBER - NSS_DHDomainParamsX942 params; -} NSS_DHAlgorithmIdentifierX942; - -extern const SecAsn1Template kSecAsn1DHValidationParamsTemplate[]; -extern const SecAsn1Template kSecAsn1DHDomainParamsX942Template[]; -extern const SecAsn1Template kSecAsn1DHAlgorithmIdentifierX942Template[]; - -/* PKCS8 form of D-H private key using X9.42 domain parameters */ -typedef struct { - SecAsn1Item version; - NSS_DHAlgorithmIdentifierX942 algorithm; - /* octet string containing DER-encoded integer */ - SecAsn1Item privateKey; - NSS_Attribute **attributes; // OPTIONAL -} NSS_DHPrivateKeyPKCS8; - -/* X509 form of D-H public key using X9.42 domain parameters */ -typedef struct { - NSS_DHAlgorithmIdentifierX942 algorithm; - /* bit string containing DER-encoded integer representing - * raw public key */ - SecAsn1Item publicKey; // length in BITS -} NSS_DHPublicKeyX509; - -extern const SecAsn1Template kSecAsn1DHPrivateKeyPKCS8Template[]; -extern const SecAsn1Template kSecAsn1DHPublicKeyX509Template[]; - -// MARK: *** ECDSA *** - -/* - * ECDSA Private key as defined in section C.4 of Certicom SEC1. - * The DER encoding of this is placed in the privateKey field - * of a NSS_PrivateKeyInfo. - */ -typedef struct { - SecAsn1Item version; - SecAsn1Item privateKey; - SecAsn1Item params; /* optional, ANY */ - SecAsn1Item pubKey; /* BITSTRING, optional */ -} NSS_ECDSA_PrivateKey; - -extern const SecAsn1Template kSecAsn1ECDSAPrivateKeyInfoTemplate[]; - -#ifdef __cplusplus -} -#endif - -#endif /* _NSS_RSA_KEY_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/nameTemplates.c b/OSX/include/security_asn1/nameTemplates.c deleted file mode 100644 index 0403ab4e..00000000 --- a/OSX/include/security_asn1/nameTemplates.c +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * nameTemplates.c - ASN1 templates for X509 Name, GeneralName, etc. - */ - -#include "SecAsn1Templates.h" -#include "nameTemplates.h" -#include "X509Templates.h" -#include "keyTemplates.h" -#include -#include - -typedef struct { - SecAsn1Oid typeId; - SecAsn1Item value; // unparsed, BER-encoded -} CE_OtherName; - -// MARK: ----- Generalized NSS_TaggedItem template chooser support ----- - -/* - * Generalized Template chooser. - */ -const SecAsn1Template * SecAsn1TaggedTemplateChooser( - /* Four args passed to specific SecAsn1TemplateChooser */ - void *arg, // currently not used - Boolean enc, - const char *buf, - void *dest, - /* array of tag/template pairs */ - const NSS_TagChoice *chooser) -{ - unsigned char tag = 0; - const SecAsn1Template *templ = NULL; - NSS_TaggedItem *item = (NSS_TaggedItem *)dest; - - assert(item != NULL); - assert((chooser != NULL) && (chooser->templ != NULL)); - - if(enc) { - /* encoding: tag from an NSS_TaggedItem at *dest */ - tag = item->tag; - } - else { - /* decoding: tag from raw bytes being decoded */ - tag = buf[0] & SEC_ASN1_TAGNUM_MASK; - /* and tell caller what's coming */ - item->tag = tag; - } - - /* infer template from tag */ - const NSS_TagChoice *thisChoice; - for(thisChoice=chooser; thisChoice->templ != NULL; thisChoice++) { - if(tag == thisChoice->tag) { - templ = thisChoice->templ; - break; - } - } - if(templ == NULL) { - /* - * Tag not found. On decoding, this is the caller's fault - * and they'll have to deal with it. - * On decode, pick a template guaranteed to cause a decoding - * failure - the template from the first array of - * NSS_TagChoices should do the trick since its tag didn't match. - */ - templ = chooser[0].templ; - } - return templ; -} - -// MARK: ----- X509 Name, RDN ------ - -/* AttributeTypeAndValue */ - -/* - * NSS_ATV Template chooser. - */ -static const NSS_TagChoice atvChoices[] = { - { SEC_ASN1_PRINTABLE_STRING, kSecAsn1PrintableStringTemplate} , - { SEC_ASN1_TELETEX_STRING, kSecAsn1TeletexStringTemplate }, - { SEC_ASN1_UNIVERSAL_STRING, kSecAsn1UniversalStringTemplate }, - { SEC_ASN1_UTF8_STRING, kSecAsn1UTF8StringTemplate }, - { SEC_ASN1_BMP_STRING, kSecAsn1BMPStringTemplate }, - { SEC_ASN1_IA5_STRING, kSecAsn1IA5StringTemplate }, - { 0, NULL} -}; - -static const SecAsn1Template * NSS_ATVChooser( - void *arg, - Boolean enc, - const char *buf, - void *dest) -{ - return SecAsn1TaggedTemplateChooser(arg, enc, buf, dest, atvChoices); -} - -static const SecAsn1TemplateChooserPtr NSS_ATVChooserPtr = NSS_ATVChooser; - -const SecAsn1Template kSecAsn1ATVTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_ATV) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_ATV,type), }, - { SEC_ASN1_INLINE | SEC_ASN1_DYNAMIC, - offsetof(NSS_ATV,value), - &NSS_ATVChooserPtr }, - { 0, } -}; - -/* RelativeDistinguishedName */ -const SecAsn1Template kSecAsn1RDNTemplate[] = { - { SEC_ASN1_SET_OF, - offsetof(NSS_RDN,atvs), kSecAsn1ATVTemplate, sizeof(NSS_RDN) } -}; - -/* X509 Name */ -const SecAsn1Template kSecAsn1NameTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_Name,rdns), kSecAsn1RDNTemplate, sizeof(NSS_Name) } -}; - -// MARK: ----- OtherName, GeneralizedName ----- - -/* - * CE_OtherName.value expressed as ASN_ANY, not en/decoded. - */ -const SecAsn1Template NSS_OtherNameTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(CE_OtherName) }, - { SEC_ASN1_OBJECT_ID, - offsetof(CE_OtherName,typeId), }, - { SEC_ASN1_ANY, - offsetof(CE_OtherName,value), }, - { 0, } -}; - -/* - * For decoding an OtherName when it's a context-specific CHOICE - * of a GeneralName. - */ -const SecAsn1Template kSecAsn1GenNameOtherNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | NGT_OtherName, - 0, NSS_OtherNameTemplate, sizeof(CE_OtherName) } -}; - -/* - * NSS_GeneralName template chooser. - * First, a crufty set of templates specific to this context. - * All offsets are zero (the fundamental type is a NSS_TaggedItem). - * - * NOTE WELL: RFC2459 says that all of the choices within a - * GeneralName (which these templates implement) have implicit - * context-specific tags. - * HOWEVER: RFC2538 and the real world indicate that the directoryName - * choice is EXPLICITLY tagged. This causes an extra layer of DER - - * the "thing" is wrapped in a header consisting of the tag byte - * (SEC_ASN1_CONTEXT_SPECIFIC plus context tag plus SEC_ASN1_CONSTRUCTED) - * and the length field. - * - * To actually implement this in the current pile-of-cruft context, - * the directoryName and otherName choices are processed here with - * NSS_InnerAnyTemplate which strips off the explicit tag layer, leaving - * further processing to the app. - * - * I sure hope we don't find certs that actually conform to RFC2459 on - * this. We might have to handle both. Be forewarned. - */ - -/* inner contents of an ASN_ANY */ - -#define NSS_GEN_NAME_OFFSET (offsetof(NSS_GeneralName,item)) -#define NSS_GEN_NAME_SIZE (sizeof(NSS_GeneralName)) - -const SecAsn1Template kSecAsn1OtherNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | NGT_OtherName, - NSS_GEN_NAME_OFFSET, kSecAsn1AnyTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1RFC822NameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | NGT_RFC822Name, - NSS_GEN_NAME_OFFSET, kSecAsn1IA5StringTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1DNSNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | NGT_DNSName, - NSS_GEN_NAME_OFFSET, kSecAsn1IA5StringTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1X400AddressTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | NGT_X400Address, - NSS_GEN_NAME_OFFSET, kSecAsn1AnyTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1DirectoryNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | NGT_DirectoryName, - NSS_GEN_NAME_OFFSET, kSecAsn1AnyTemplate, NSS_GEN_NAME_SIZE } - }; -const SecAsn1Template kSecAsn1EdiPartyNameTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | NGT_EdiPartyName, - NSS_GEN_NAME_OFFSET, kSecAsn1AnyTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1URITemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | NGT_URI, - NSS_GEN_NAME_OFFSET, kSecAsn1IA5StringTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1IPAddressTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | NGT_IPAddress, - NSS_GEN_NAME_OFFSET, kSecAsn1OctetStringTemplate, NSS_GEN_NAME_SIZE } -}; -const SecAsn1Template kSecAsn1RegisteredIDTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | NGT_RegisteredID, - NSS_GEN_NAME_OFFSET, kSecAsn1ObjectIDTemplate, NSS_GEN_NAME_SIZE } -}; - -static const NSS_TagChoice genNameChoices[] = { - { NGT_OtherName, kSecAsn1OtherNameTemplate} , - { NGT_RFC822Name, kSecAsn1RFC822NameTemplate }, - { NGT_DNSName, kSecAsn1DNSNameTemplate }, - { NGT_X400Address, kSecAsn1X400AddressTemplate }, - { NGT_DirectoryName, kSecAsn1DirectoryNameTemplate }, - { NGT_EdiPartyName, kSecAsn1EdiPartyNameTemplate }, - { NGT_URI, kSecAsn1URITemplate }, - { NGT_IPAddress, kSecAsn1IPAddressTemplate }, - { NGT_RegisteredID, kSecAsn1RegisteredIDTemplate }, - { 0, NULL} -}; - -static const SecAsn1Template * NSS_genNameChooser( - void *arg, - Boolean enc, - const char *buf, - void *dest) -{ - return SecAsn1TaggedTemplateChooser(arg, enc, buf, dest, genNameChoices); -} - -static const SecAsn1TemplateChooserPtr NSS_genNameChooserPtr = - NSS_genNameChooser; - -const SecAsn1Template kSecAsn1GeneralNameTemplate[] = { - { SEC_ASN1_DYNAMIC | SEC_ASN1_CONTEXT_SPECIFIC, - offsetof(NSS_GeneralName,item), // Needed? - &NSS_genNameChooserPtr }, - { 0, } // Needed? -}; diff --git a/OSX/include/security_asn1/nameTemplates.h b/OSX/include/security_asn1/nameTemplates.h deleted file mode 100644 index 638bd09a..00000000 --- a/OSX/include/security_asn1/nameTemplates.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * nameTemplates.h - ASN1 templates for X509 Name, GeneralName, etc. - */ - -#ifndef _NSS_NAME_TEMPLATES_H_ -#define _NSS_NAME_TEMPLATES_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// MARK: ----- Generalized NSS_TaggedItem template chooser support ----- - -/* - * A tagged item for use with simple CHOICE types implemented - * via SEC_ASN1_DYNAMIC. - */ -typedef struct { - SecAsn1Item item; - unsigned char tag; -} NSS_TaggedItem; - -/* - * Type/template-specific SecAsn1TemplateChooser passes - * an array of these, terminated by a NSS_TagChoice with - * a NULL templ field, to SecAsn1TaggedTemplateChooser(). - */ -typedef struct { - unsigned char tag; - const SecAsn1Template *templ; -} NSS_TagChoice; - -/* - * Generalized Template chooser. - */ -const SecAsn1Template * SecAsn1TaggedTemplateChooser( - /* Four args passed to specific SecAsn1TemplateChooser */ - void *arg, // currently not used - Boolean enc, - const char *buf, - void *dest, - /* array of tag/template pairs */ - const NSS_TagChoice *chooser); - -// MARK: ----- X509 Name, RDN ------ - -/* - * ASN class : AttributeTypeAndValue - * C struct : NSS_ATV - * Roughly corresponds to a CSSM_X509_TYPE_VALUE_PAIR and used - * in DirectoryString elements. - */ - -/* - * This type and template process, via SEC_ASN1_DYNAMIC. the following - * tagged types: - * - * SEC_ASN1_PRINTABLE_STRING - * SEC_ASN1_TELETEX_STRING - * SEC_ASN1_UNIVERSAL_STRING - * SEC_ASN1_UTF8_STRING - * SEC_ASN1_BMP_STRING - * SEC_ASN1_IA5_STRING - * - * Note that SEC_ASN1_IA5_STRING is not a legal part of a - * DirectoryString, but some certs (e.g. the Thawte serverbasic cert) - * use this type. - */ -typedef struct { - SecAsn1Oid type; - NSS_TaggedItem value; -} NSS_ATV; - -/* - * ASN class : RelativeDistinguishedName - * C struct : NSS_RDN - * - * Corresponds to CSSM_X509_RDN. - */ -typedef struct { - NSS_ATV **atvs; -} NSS_RDN; - -/* - * ASN class : Name - * C struct : NSS_Name - * - * Corresponds to CSSM_X509_NAME. - */ -typedef struct { - NSS_RDN **rdns; -} NSS_Name; - -extern const SecAsn1Template kSecAsn1ATVTemplate[]; -extern const SecAsn1Template kSecAsn1RDNTemplate[]; -extern const SecAsn1Template kSecAsn1NameTemplate[]; - -// MARK: ----- OtherName, GeneralizedName ----- - -/* - * ASN Class : OtherName - * C struct : CE_OtherName - * - * CE_OtherName.value expressed as ASN_ANY, not en/decoded. - */ -extern const SecAsn1Template kSecAsn1OtherNameTemplate[]; - -/* - * For decoding an OtherName when it's a context-specific CHOICE - * of a GeneralName. - */ -extern const SecAsn1Template kSecAsn1GenNameOtherNameTemplate[]; - -/* - * ASN Class : GeneralName - * C struct : NSS_GeneralName, typedefd to an NSS_TaggedItem - * - * This roughly maps to a CE_GeneralName (from certextensions.h). - * The NSS_TaggedItem mechanism is used to resolve choices down - * to the SecAsn1Item level - i.e., at this level (prior to encoding - * or after decoding), NSS_GeneralName.item either contains a simple - * atomic type (IA5String, Octet string) or is raw, un{de,en}coded - * ASN_ANY. - */ -typedef NSS_TaggedItem NSS_GeneralName; - -/* - * These context-specific tag definitions, for use in - * NSS_GeneralName.tag, are from the ASN definition and map to - * CE_GeneralNameType values from certextensions.h. The values - * happen to be equivalent but apps should not count on that - - * these NSS_GeneralNameTag values are explicitly assigned per - * the ASN spec of a GeneralName. - * - * Shown with each tag is the simple type the tag maps to. - */ -typedef enum { - NGT_OtherName = 0, // ASN_ANY - NGT_RFC822Name = 1, // IA5String - NGT_DNSName = 2, // IA5String - NGT_X400Address = 3, // ASY_ANY - NGT_DirectoryName = 4, // ASN_ANY - NGT_EdiPartyName = 5, // ASN_ANY - NGT_URI = 6, // IA5String - NGT_IPAddress = 7, // OCTET_STRING - NGT_RegisteredID = 8 // OID -} NSS_GeneralNameTag; - -extern const SecAsn1Template kSecAsn1GeneralNameTemplate[]; - -/* - * ASN Class : GeneralNames - * C struct : NSS_GeneralNames - * - * Since the SEC_ANY_DYNAMIC mechanism doesn't work with POINTERs - * or GROUPs (e.g., a sequence of NSS_GeneralName elements), decoding - * an NSS_GeneralNames first requires a decode to an array of - * ANY_ANY blobs as shown here. Use SEC_SequenceOfAnyTemplate for - * that step. Each of the resulting elements is individually - * decoded into an NSS_GeneralName. - */ -typedef struct { - SecAsn1Item **names; /* sequence */ -} NSS_GeneralNames; - -#define kSecAsn1GeneralNamesTemplate kSecAsn1SequenceOfAnyTemplate - -#ifdef __cplusplus -} -#endif - -#endif /* _NSS_NAME_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/nsprPortX.c b/OSX/include/security_asn1/nsprPortX.c deleted file mode 100644 index 16d5b79c..00000000 --- a/OSX/include/security_asn1/nsprPortX.c +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * nsprPortX.c - minimal platform dependent NSPR functions to enable - * use of DER libraries - */ - -#ifndef _NSPR_PORT_X_H_ -#define _NSPR_PORT_X_H_ - -#include "prmem.h" -#include "prlock.h" -#include "prerror.h" -#include "prinit.h" -#include "prbit.h" - -#include -#include -#include - -// MARK: *** Memory *** - -NSPR_API(void *) PR_Malloc(PRSize size) -{ - return malloc(size ? size : 1); -} -NSPR_API(void *) PR_Calloc(PRSize nelem, PRSize elsize) -{ - return calloc(nelem, elsize); -} -NSPR_API(void *) PR_Realloc(void *ptr, PRSize size) -{ - return realloc(ptr, size); -} -NSPR_API(void) PR_Free(void *ptr) -{ - return free(ptr); -} - -// MARK: *** locks *** - -NSPR_API(PRLock*) PR_NewLock(void) -{ - pthread_mutex_t *pm = PR_Malloc(sizeof(pthread_mutex_t)); - if(pm == NULL) { - return NULL; - } - if(pthread_mutex_init(pm, NULL)) { - PR_Free(pm); - return NULL; - } - return (PRLock*)pm; -} - -NSPR_API(void) PR_DestroyLock(PRLock *lock) -{ - if(lock == NULL) { - return; - } - pthread_mutex_destroy((pthread_mutex_t *)lock); - PR_Free(lock); -} - -NSPR_API(void) PR_Lock(PRLock *lock) -{ - if(lock == NULL) { - return; - } - pthread_mutex_lock((pthread_mutex_t *)lock); -} - -NSPR_API(PRStatus) PR_Unlock(PRLock *lock) -{ - if(lock == NULL) { - return PR_FAILURE; - } - pthread_mutex_unlock((pthread_mutex_t *)lock); - return PR_SUCCESS; -} - -// MARK: *** get/set error *** - -/* - * key for pthread_{set,get}specific and a lock to ensure it gets - * created once - */ -static pthread_key_t PR_threadKey; -static int PR_threadKeyInitFlag; // we have a PR_threadKey -static int PR_threadKeyErrorFlag; // unable to create PR_threadKey -static pthread_mutex_t PR_threadKeyLock = PTHREAD_MUTEX_INITIALIZER; - -/* - * The thing that gets stored on a per-thread basis. A pointer to - * this is associated with key PR_threadKey. Mallocd in - * PR_getThreadErrInfo(); freed directly by free() as - * PR_threadKey's destructor. - */ -typedef struct { - PRInt32 osError; - PRErrorCode prError; -} PR_threadErrInfo; - -/* - * One-time init of PR_threadKey, returns nonzero on error. - * Does not attempt to init PR_threadKey if doCreate is false and - * a previous call to this routine resulted in error (i.e., this - * is the GetXError() following a failed SetError()). - */ -static PRInt32 PR_initThreadKey( - int doCreate) -{ - PRInt32 prtn = 0; - if(PR_threadKeyInitFlag) { - /* thread safe since we never clear this flag; we're ready to go */ - return 0; - } - pthread_mutex_lock(&PR_threadKeyLock); - if(PR_threadKeyErrorFlag && !doCreate) { - /* no error to get because the last SetXError failed */ - prtn = PR_IO_ERROR; - } - else if(!PR_threadKeyInitFlag) { - prtn = pthread_key_create(&PR_threadKey, free); - if(prtn) { - /* out of pthread_key_t's */ - PR_threadKeyErrorFlag = 1; - } - else { - PR_threadKeyErrorFlag = 0; // in case of retry */ - PR_threadKeyInitFlag = 1; // success - } - } - pthread_mutex_unlock(&PR_threadKeyLock); - return prtn; -} - -/* - * Get current thread's PR_threadErrInfo. Create one if doCreate is - * true and one does not exist. - * - * -- A nonzero *threadKeyError on return indicates that we can - * not create a pthread_key_t; in this case we return NULL. - * -- Note that NULL return with zero threadKeyError and zero - * doCreate indicates "no per-thread error set yet", which is - * not an error. - */ -static PR_threadErrInfo *PR_getThreadErrInfo( - int doCreate, - PRInt32 *threadKeyError) // RETURNED, an OSStatus -{ - *threadKeyError = PR_initThreadKey(doCreate); - if(*threadKeyError) { - return NULL; - } - PR_threadErrInfo *errInfo = pthread_getspecific(PR_threadKey); - if((errInfo == NULL) && doCreate) { - errInfo = (PR_threadErrInfo *)malloc(sizeof(*errInfo)); - if(errInfo == NULL) { - /* - * malloc failure, retriable failure of this routine (not - * a PR_threadKeyErrorFlag style error). - * Note that this is *not* detected in a subsequent - * GetXError() call, but it will allow for somewhat - * graceful recovery in case some memory gets freed - * up. - */ - *threadKeyError = PR_OUT_OF_MEMORY_ERROR; - } - else { - memset(errInfo, 0, sizeof(*errInfo)); - pthread_setspecific(PR_threadKey, errInfo); - } - } - return errInfo; -} - -PR_IMPLEMENT(PRErrorCode) PR_GetError(void) -{ - PRInt32 prtn; - PR_threadErrInfo *errInfo = PR_getThreadErrInfo(0, &prtn); - if(errInfo == NULL) { - /* no error set or per-thread logic uninitialized */ - if(prtn) { - return PR_INSUFFICIENT_RESOURCES_ERROR; - } - else { - return 0; - } - } - else { - return errInfo->prError; - } -} - -PR_IMPLEMENT(PRInt32) PR_GetOSError(void) -{ - PRInt32 prtn; - PR_threadErrInfo *errInfo = PR_getThreadErrInfo(0, &prtn); - if(errInfo == NULL) { - /* no error set or per-thread logic uninitialized */ - return prtn; - } - else { - return errInfo->osError; - } -} - -PR_IMPLEMENT(void) PR_SetError(PRErrorCode code, PRInt32 osErr) -{ - PRInt32 prtn; - PR_threadErrInfo *errInfo = PR_getThreadErrInfo(1, &prtn); - if(errInfo != NULL) { - errInfo->osError = osErr; - errInfo->prError = code; - } - /* else per-thread logic uninitialized */ -} - -// MARK: *** misc. *** - -/* -** Compute the log of the least power of 2 greater than or equal to n -*/ -NSPR_API(PRIntn) PR_CeilingLog2(PRUint32 i) -{ - PRIntn r; - PR_CEILING_LOG2(r,i); - return r; -} - -#endif /* _NSPR_PORT_X_H_ */ diff --git a/OSX/include/security_asn1/nssUtils.c b/OSX/include/security_asn1/nssUtils.c deleted file mode 100644 index 80cb1fc3..00000000 --- a/OSX/include/security_asn1/nssUtils.c +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * nssUtils.cpp - */ - -#include "nssUtils.h" -#include - -/* - * Compare two SecAsn1Items (or two SecAsn1Oids), return true if identical. - */ -int nssCompareSecAsn1Items( - const SecAsn1Item *data1, - const SecAsn1Item *data2) -{ - if((data1 == NULL) || (data1->Data == NULL) || - (data2 == NULL) || (data2->Data == NULL) || - (data1->Length != data2->Length)) { - return 0; - } - if(data1->Length != data2->Length) { - return 0; - } - return memcmp(data1->Data, data2->Data, data1->Length) == 0; -} - -int nssCompareCssmData( - const SecAsn1Item *data1, - const SecAsn1Item *data2) -{ - return nssCompareSecAsn1Items(data1,data2); -} - -/* - * How many items in a NULL-terminated array of pointers? - */ -unsigned nssArraySize( - const void **array) -{ - unsigned count = 0; - if (array) { - while (*array++) { - count++; - } - } - return count; -} - diff --git a/OSX/include/security_asn1/nssUtils.h b/OSX/include/security_asn1/nssUtils.h deleted file mode 100644 index bd42ac29..00000000 --- a/OSX/include/security_asn1/nssUtils.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * nssUtils.h - */ - -#ifndef _NSS_UTILS_H_ -#define _NSS_UTILS_H_ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* return true if two SecAsn1Items (or two SecAsn1Oids) compare equal */ -int nssCompareSecAsn1Items( - const SecAsn1Item *data1, - const SecAsn1Item *data2); - -int nssCompareCssmData( - const SecAsn1Item *data1, - const SecAsn1Item *data2); - -/* How many items in a NULL-terminated array of pointers? */ -unsigned nssArraySize( - const void **array); - -#ifdef __cplusplus -} -#endif - -#endif /* _NSS_UTILS_H_ */ - diff --git a/OSX/include/security_asn1/nssilckt.h b/OSX/include/security_asn1/nssilckt.h deleted file mode 100644 index e0b49902..00000000 --- a/OSX/include/security_asn1/nssilckt.h +++ /dev/null @@ -1,220 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** nssilock.h - Instrumented locking functions for NSS -** -** Description: -** nssilock provides instrumentation for locks and monitors in -** the NSS libraries. The instrumentation, when enabled, causes -** each call to the instrumented function to record data about -** the call to an external file. The external file -** subsequently used to extract performance data and other -** statistical information about the operation of locks used in -** the nss library. -** -** To enable compilation with instrumentation, build NSS with -** the compile time switch NEED_NSS_ILOCK defined. -** -** say: "gmake OS_CFLAGS+=-DNEED_NSS_ILOCK" at make time. -** -** At runtime, to enable recording from nssilock, one or more -** environment variables must be set. For each nssILockType to -** be recorded, an environment variable of the form NSS_ILOCK_x -** must be set to 1. For example: -** -** set NSS_ILOCK_Cert=1 -** -** nssilock uses PRLOG is used to record to trace data. The -** PRLogModule name associated with nssilock data is: "nssilock". -** To enable recording of nssilock data you will need to set the -** environment variable NSPR_LOG_MODULES to enable -** recording for the nssilock log module. Similarly, you will -** need to set the environment variable NSPR_LOG_FILE to specify -** the filename to receive the recorded data. See prlog.h for usage. -** Example: -** -** export NSPR_LOG_MODULES=nssilock:6 -** export NSPR_LOG_FILE=xxxLogfile -** -** Operation: -** nssilock wraps calls to NSPR's PZLock and PZMonitor functions -** with similarly named functions: PZ_NewLock(), etc. When NSS is -** built with lock instrumentation enabled, the PZ* functions are -** compiled into NSS; when lock instrumentation is disabled, -** calls to PZ* functions are directly mapped to PR* functions -** and the instrumentation arguments to the PZ* functions are -** compiled away. -** -** -** File Format: -** The format of the external file is implementation -** dependent. Where NSPR's PR_LOG() function is used, the file -** contains data defined for PR_LOG() plus the data written by -** the wrapped function. On some platforms and under some -** circumstances, platform dependent logging or -** instrumentation probes may be used. In any case, the -** relevant data provided by the lock instrumentation is: -** -** lockType, func, address, duration, line, file [heldTime] -** -** where: -** -** lockType: a character representation of nssILockType for the -** call. e.g. ... "cert" -** -** func: the function doing the tracing. e.g. "NewLock" -** -** address: address of the instrumented lock or monitor -** -** duration: is how long was spent in the instrumented function, -** in PRIntervalTime "ticks". -** -** line: the line number within the calling function -** -** file: the file from which the call was made -** -** heldTime: how long the lock/monitor was held. field -** present only for PZ_Unlock() and PZ_ExitMonitor(). -** -** Design Notes: -** The design for lock instrumentation was influenced by the -** need to gather performance data on NSS 3.x. It is intended -** that the effort to modify NSS to use lock instrumentation -** be minimized. Existing calls to locking functions need only -** have their names changed to the instrumentation function -** names. -** -** Private NSS Interface: -** nssilock.h defines a private interface for use by NSS. -** nssilock.h is experimental in nature and is subject to -** change or revocation without notice. ... Don't mess with -** it. -** -*/ - -/* - * $Id: - */ - -#ifndef _NSSILCKT_H_ -#define _NSSILCKT_H_ - -#include "prtypes.h" -#include "prmon.h" -#include "prlock.h" -#include "prcvar.h" - -typedef enum { - nssILockArena = 0, - nssILockSession = 1, - nssILockObject = 2, - nssILockRefLock = 3, - nssILockCert = 4, - nssILockCertDB = 5, - nssILockDBM = 6, - nssILockCache = 7, - nssILockSSL = 8, - nssILockList = 9, - nssILockSlot = 10, - nssILockFreelist = 11, - nssILockOID = 12, - nssILockAttribute = 13, - nssILockPK11cxt = 14, /* pk11context */ - nssILockRWLock = 15, - nssILockOther = 16, - nssILockSelfServ = 17, - nssILockLast /* don't use this one! */ -} nssILockType; - -/* -** Declare operation type enumerator -** enumerations identify the function being performed -*/ -typedef enum { - FlushTT = 0, - NewLock = 1, - Lock = 2, - Unlock = 3, - DestroyLock = 4, - NewCondVar = 5, - WaitCondVar = 6, - NotifyCondVar = 7, - NotifyAllCondVar = 8, - DestroyCondVar = 9, - NewMonitor = 10, - EnterMonitor = 11, - ExitMonitor = 12, - Notify = 13, - NotifyAll = 14, - Wait = 15, - DestroyMonitor = 16 -} nssILockOp; - -/* -** Declare the trace record -*/ -struct pzTrace_s { - PRUint32 threadID; /* PR_GetThreadID() */ - nssILockOp op; /* operation being performed */ - nssILockType ltype; /* lock type identifier */ - PRIntervalTime callTime; /* time spent in function */ - PRIntervalTime heldTime; /* lock held time, or -1 */ - void *lock; /* address of lock structure */ - PRIntn line; /* line number */ - char file[24]; /* filename */ -}; - -PR_BEGIN_EXTERN_C -/* -** conditionally compile in nssilock features -*/ -#if defined(NEED_NSS_ILOCK) - -/* -** declare opaque types. See: nssilock.c -*/ -typedef struct pzlock_s PZLock; -typedef struct pzcondvar_s PZCondVar; -typedef struct pzmonitor_s PZMonitor; - -#else /* NEED_NSS_ILOCK */ - -#define PZLock PRLock -#define PZCondVar PRCondVar -#define PZMonitor PRMonitor - -#endif /* NEED_NSS_ILOCK */ - -PR_END_EXTERN_C -#endif /* _NSSILCKT_H_ */ diff --git a/OSX/include/security_asn1/nssilock.h b/OSX/include/security_asn1/nssilock.h deleted file mode 100644 index 38b45738..00000000 --- a/OSX/include/security_asn1/nssilock.h +++ /dev/null @@ -1,316 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** nssilock.h - Instrumented locking functions for NSS -** -** Description: -** nssilock provides instrumentation for locks and monitors in -** the NSS libraries. The instrumentation, when enabled, causes -** each call to the instrumented function to record data about -** the call to an external file. The external file -** subsequently used to extract performance data and other -** statistical information about the operation of locks used in -** the nss library. -** -** To enable compilation with instrumentation, build NSS with -** the compile time switch NEED_NSS_ILOCK defined. -** -** say: "gmake OS_CFLAGS+=-DNEED_NSS_ILOCK" at make time. -** -** At runtime, to enable recording from nssilock, one or more -** environment variables must be set. For each nssILockType to -** be recorded, an environment variable of the form NSS_ILOCK_x -** must be set to 1. For example: -** -** set NSS_ILOCK_Cert=1 -** -** nssilock uses PRLOG is used to record to trace data. The -** PRLogModule name associated with nssilock data is: "nssilock". -** To enable recording of nssilock data you will need to set the -** environment variable NSPR_LOG_MODULES to enable -** recording for the nssilock log module. Similarly, you will -** need to set the environment variable NSPR_LOG_FILE to specify -** the filename to receive the recorded data. See prlog.h for usage. -** Example: -** -** export NSPR_LOG_MODULES=nssilock:6 -** export NSPR_LOG_FILE=xxxLogfile -** -** Operation: -** nssilock wraps calls to NSPR's PZLock and PZMonitor functions -** with similarly named functions: PZ_NewLock(), etc. When NSS is -** built with lock instrumentation enabled, the PZ* functions are -** compiled into NSS; when lock instrumentation is disabled, -** calls to PZ* functions are directly mapped to PR* functions -** and the instrumentation arguments to the PZ* functions are -** compiled away. -** -** -** File Format: -** The format of the external file is implementation -** dependent. Where NSPR's PR_LOG() function is used, the file -** contains data defined for PR_LOG() plus the data written by -** the wrapped function. On some platforms and under some -** circumstances, platform dependent logging or -** instrumentation probes may be used. In any case, the -** relevant data provided by the lock instrumentation is: -** -** lockType, func, address, duration, line, file [heldTime] -** -** where: -** -** lockType: a character representation of nssILockType for the -** call. e.g. ... "cert" -** -** func: the function doing the tracing. e.g. "NewLock" -** -** address: address of the instrumented lock or monitor -** -** duration: is how long was spent in the instrumented function, -** in PRIntervalTime "ticks". -** -** line: the line number within the calling function -** -** file: the file from which the call was made -** -** heldTime: how long the lock/monitor was held. field -** present only for PZ_Unlock() and PZ_ExitMonitor(). -** -** Design Notes: -** The design for lock instrumentation was influenced by the -** need to gather performance data on NSS 3.x. It is intended -** that the effort to modify NSS to use lock instrumentation -** be minimized. Existing calls to locking functions need only -** have their names changed to the instrumentation function -** names. -** -** Private NSS Interface: -** nssilock.h defines a private interface for use by NSS. -** nssilock.h is experimental in nature and is subject to -** change or revocation without notice. ... Don't mess with -** it. -** -*/ - -/* - * $Id: - */ - -#ifndef _NSSILOCK_H_ -#define _NSSILOCK_H_ - -#include "prtypes.h" -#include "prmon.h" -#include "prlock.h" -#include "prcvar.h" - -#include "nssilckt.h" - -PR_BEGIN_EXTERN_C - -#if defined(NEED_NSS_ILOCK) - -#define PZ_NewLock(t) pz_NewLock((t),__FILE__,__LINE__) -extern PZLock * - pz_NewLock( - nssILockType ltype, - char *file, - PRIntn line - ); - -#define PZ_Lock(k) pz_Lock((k),__FILE__,__LINE__) -extern void - pz_Lock( - PZLock *lock, - char *file, - PRIntn line - ); - -#define PZ_Unlock(k) pz_Unlock((k),__FILE__,__LINE__) -extern PRStatus - pz_Unlock( - PZLock *lock, - char *file, - PRIntn line - ); - -#define PZ_DestroyLock(k) pz_DestroyLock((k),__FILE__,__LINE__) -extern void - pz_DestroyLock( - PZLock *lock, - char *file, - PRIntn line - ); - - -#define PZ_NewCondVar(l) pz_NewCondVar((l),__FILE__,__LINE__) -extern PZCondVar * - pz_NewCondVar( - PZLock *lock, - char *file, - PRIntn line - ); - -#define PZ_DestroyCondVar(v) pz_DestroyCondVar((v),__FILE__,__LINE__) -extern void - pz_DestroyCondVar( - PZCondVar *cvar, - char *file, - PRIntn line - ); - -#define PZ_WaitCondVar(v,t) pz_WaitCondVar((v),(t),__FILE__,__LINE__) -extern PRStatus - pz_WaitCondVar( - PZCondVar *cvar, - PRIntervalTime timeout, - char *file, - PRIntn line - ); - -#define PZ_NotifyCondVar(v) pz_NotifyCondVar((v),__FILE__,__LINE__) -extern PRStatus - pz_NotifyCondVar( - PZCondVar *cvar, - char *file, - PRIntn line - ); - -#define PZ_NotifyAllCondVar(v) pz_NotifyAllCondVar((v),__FILE__,__LINE__) -extern PRStatus - pz_NotifyAllCondVar( - PZCondVar *cvar, - char *file, - PRIntn line - ); - - -#define PZ_NewMonitor(t) pz_NewMonitor((t),__FILE__,__LINE__) -extern PZMonitor * - pz_NewMonitor( - nssILockType ltype, - char *file, - PRIntn line - ); - -#define PZ_DestroyMonitor(m) pz_DestroyMonitor((m),__FILE__,__LINE__) -extern void - pz_DestroyMonitor( - PZMonitor *mon, - char *file, - PRIntn line - ); - -#define PZ_EnterMonitor(m) pz_EnterMonitor((m),__FILE__,__LINE__) -extern void - pz_EnterMonitor( - PZMonitor *mon, - char *file, - PRIntn line - ); - - -#define PZ_ExitMonitor(m) pz_ExitMonitor((m),__FILE__,__LINE__) -extern PRStatus - pz_ExitMonitor( - PZMonitor *mon, - char *file, - PRIntn line - ); - -#define PZ_InMonitor(m) (PZ_GetMonitorEntryCount(m) > 0 ) -#define PZ_GetMonitorEntryCount(m) pz_GetMonitorEntryCount((m),__FILE__,__LINE__) -extern PRIntn - pz_GetMonitorEntryCount( - PZMonitor *mon, - char *file, - PRIntn line - ); - -#define PZ_Wait(m,i) pz_Wait((m),((i)),__FILE__,__LINE__) -extern PRStatus - pz_Wait( - PZMonitor *mon, - PRIntervalTime ticks, - char *file, - PRIntn line - ); - -#define PZ_Notify(m) pz_Notify((m),__FILE__,__LINE__) -extern PRStatus - pz_Notify( - PZMonitor *mon, - char *file, - PRIntn line - ); - -#define PZ_NotifyAll(m) pz_NotifyAll((m),__FILE__,__LINE__) -extern PRStatus - pz_NotifyAll( - PZMonitor *mon, - char *file, - PRIntn line - ); - -#define PZ_TraceFlush() pz_TraceFlush() -extern void pz_TraceFlush( void ); - -#else /* NEED_NSS_ILOCK */ - -#define PZ_NewLock(t) PR_NewLock() -#define PZ_DestroyLock(k) PR_DestroyLock((k)) -#define PZ_Lock(k) PR_Lock((k)) -#define PZ_Unlock(k) PR_Unlock((k)) - -#define PZ_NewCondVar(l) PR_NewCondVar((l)) -#define PZ_DestroyCondVar(v) PR_DestroyCondVar((v)) -#define PZ_WaitCondVar(v,t) PR_WaitCondVar((v),(t)) -#define PZ_NotifyCondVar(v) PR_NotifyCondVar((v)) -#define PZ_NotifyAllCondVar(v) PR_NotifyAllCondVar((v)) - -#define PZ_NewMonitor(t) PR_NewMonitor() -#define PZ_DestroyMonitor(m) PR_DestroyMonitor((m)) -#define PZ_EnterMonitor(m) PR_EnterMonitor((m)) -#define PZ_ExitMonitor(m) PR_ExitMonitor((m)) -#define PZ_InMonitor(m) PR_InMonitor((m)) -#define PZ_Wait(m,t) PR_Wait(((m)),((t))) -#define PZ_Notify(m) PR_Notify((m)) -#define PZ_NotifyAll(m) PR_Notify((m)) -#define PZ_TraceFlush() /* nothing */ - - -#endif /* NEED_NSS_ILOCK */ - -PR_END_EXTERN_C -#endif /* _NSSILOCK_H_ */ diff --git a/OSX/include/security_asn1/nsslocks.h b/OSX/include/security_asn1/nsslocks.h deleted file mode 100644 index eb24c805..00000000 --- a/OSX/include/security_asn1/nsslocks.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * nsslocks.h - threadsafe functions to initialize lock pointers. - * - * NOTE - These are not public interfaces - * - * $Id: nsslocks.h,v 1.1 2003/01/30 22:42:07 dmitch Exp $ - */ - -#ifndef _NSSLOCKS_H_ -#define _NSSLOCKS_H_ - -#include "seccomon.h" -#include "nssilock.h" -#include "prmon.h" - -SEC_BEGIN_PROTOS - -/* Given the address of a (global) pointer to a PZLock, - * atomicly create the lock and initialize the (global) pointer, - * if it is not already created/initialized. - */ - -extern SECStatus nss_InitLock( PZLock **ppLock, nssILockType ltype ); - -/* Given the address of a (global) pointer to a PZMonitor, - * atomicly create the monitor and initialize the (global) pointer, - * if it is not already created/initialized. - */ - -extern SECStatus nss_InitMonitor(PZMonitor **ppMonitor, nssILockType ltype ); - -SEC_END_PROTOS - -#endif diff --git a/OSX/include/security_asn1/ocspTemplates.c b/OSX/include/security_asn1/ocspTemplates.c deleted file mode 100644 index 0dcbf947..00000000 --- a/OSX/include/security_asn1/ocspTemplates.c +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * ocspTemplates.cpp - ASN1 templates OCSP requests and responses. - */ - -#include "ocspTemplates.h" -#include "keyTemplates.h" /* for kSecAsn1AlgorithmIDTemplate */ -#include "SecAsn1Templates.h" -#include -#include - -// MARK: ----- OCSP Request ----- - -const SecAsn1Template kSecAsn1OCSPCertIDTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPCertID) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1OCSPCertID, algId), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, offsetof(SecAsn1OCSPCertID, issuerNameHash) }, - { SEC_ASN1_OCTET_STRING, offsetof(SecAsn1OCSPCertID, issuerPubKeyHash) }, - /* serial number is SIGNED integer */ - { SEC_ASN1_INTEGER | SEC_ASN1_SIGNED_INT, - offsetof(SecAsn1OCSPCertID, serialNumber) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPRequest) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1OCSPRequest, reqCert), - kSecAsn1OCSPCertIDTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPRequest, extensions), - kSecAsn1SequenceOfCertExtensionTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPSignatureTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPSignature) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1OCSPSignature, algId), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, offsetof(SecAsn1OCSPSignature, sig) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPSignature, certs), - kSecAsn1SequenceOfAnyTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPTbsRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPTbsRequest) }, - /* optional version, explicit tag 0, default 0 */ - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(SecAsn1OCSPTbsRequest, version), - kSecAsn1PointerToIntegerTemplate }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(SecAsn1OCSPTbsRequest, requestorName), - kSecAsn1GeneralNameTemplate }, - { SEC_ASN1_SEQUENCE_OF, - offsetof(SecAsn1OCSPTbsRequest, requestList), - kSecAsn1OCSPRequestTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 2, - offsetof(SecAsn1OCSPTbsRequest, requestExtensions), - kSecAsn1SequenceOfCertExtensionTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPSignedRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPSignedRequest) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1OCSPSignedRequest, tbsRequest), - kSecAsn1OCSPTbsRequestTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_POINTER | SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPSignedRequest, signature), - kSecAsn1OCSPSignatureTemplate }, - { 0 } -}; - -// MARK: ----- OCSP Response ----- - -const SecAsn1Template kSecAsn1OCSPRevokedInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPRevokedInfo) }, - { SEC_ASN1_GENERALIZED_TIME, offsetof(SecAsn1OCSPRevokedInfo, revocationTime) }, - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(SecAsn1OCSPRevokedInfo, revocationReason) , - kSecAsn1PointerToEnumeratedTemplate }, - { 0 } -}; - -/* three context-specific templates, app picks one of these */ - -/* - * Encode/decode CertStatus separately using one of these †hree templates. - * The result goes into SecAsn1OCSPSingleResponse.certStatus on encode. - */ -const SecAsn1Template kSecAsn1OCSPCertStatusGoodTemplate[] = { - { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(SecAsn1OCSPCertStatus, nullData), - kSecAsn1NullTemplate } -}; - -const SecAsn1Template kSecAsn1OCSPCertStatusRevokedTemplate[] = { - { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, - offsetof(SecAsn1OCSPCertStatus, revokedInfo) , - kSecAsn1OCSPRevokedInfoTemplate } -}; - -const SecAsn1Template kSecAsn1OCSPCertStatusUnknownTemplate[] = { - { SEC_ASN1_CONTEXT_SPECIFIC | 2, - offsetof(SecAsn1OCSPCertStatus, nullData), - kSecAsn1NullTemplate } -}; - -const SecAsn1Template kSecAsn1OCSPSingleResponseTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPSingleResponse) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1OCSPSingleResponse, certID), - kSecAsn1OCSPCertIDTemplate }, - { SEC_ASN1_ANY, - offsetof(SecAsn1OCSPSingleResponse, certStatus), - kSecAsn1AnyTemplate }, - { SEC_ASN1_GENERALIZED_TIME, offsetof(SecAsn1OCSPSingleResponse, thisUpdate) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPSingleResponse, nextUpdate), - kSecAsn1PointerToGeneralizedTimeTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 1, - offsetof(SecAsn1OCSPSingleResponse, singleExtensions), - kSecAsn1SequenceOfCertExtensionTemplate }, - { 0 } -}; - -/* - * support for ResponderID CHOICE - */ -const SecAsn1Template kSecAsn1OCSPResponderIDAsNameTemplate[] = { - { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1, - offsetof(SecAsn1OCSPResponderID, byName), - kSecAsn1AnyTemplate } -}; - -const SecAsn1Template kSecAsn1OCSPResponderIDAsKeyTemplate[] = { - { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 2, - offsetof(SecAsn1OCSPResponderID, byKey), - kSecAsn1OctetStringTemplate } -}; - -const SecAsn1Template kSecAsn1OCSPResponseDataTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPResponseData) }, - /* optional version, explicit tag 0, default 0 */ - { SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(SecAsn1OCSPResponseData, version), - kSecAsn1PointerToIntegerTemplate }, - { SEC_ASN1_ANY, - offsetof(SecAsn1OCSPResponseData, responderID), - kSecAsn1AnyTemplate }, - { SEC_ASN1_GENERALIZED_TIME, offsetof(SecAsn1OCSPResponseData, producedAt) }, - { SEC_ASN1_SEQUENCE_OF, - offsetof(SecAsn1OCSPResponseData, responses), - kSecAsn1OCSPSingleResponseTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 1, - offsetof(SecAsn1OCSPResponseData, responseExtensions), - kSecAsn1SequenceOfCertExtensionTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPBasicResponseTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPBasicResponse) }, - { SEC_ASN1_ANY, offsetof(SecAsn1OCSPBasicResponse, tbsResponseData) }, - { SEC_ASN1_INLINE, - offsetof(SecAsn1OCSPBasicResponse, algId), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_BIT_STRING, offsetof(SecAsn1OCSPBasicResponse, sig) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPBasicResponse, certs), - kSecAsn1SequenceOfAnyTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPResponseBytesTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPResponseBytes) }, - { SEC_ASN1_OBJECT_ID, offsetof(SecAsn1OCSPResponseBytes, responseType) }, - { SEC_ASN1_OCTET_STRING, offsetof(SecAsn1OCSPResponseBytes, response) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPPtrToResponseBytesTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1OCSPResponseBytesTemplate } -}; - -const SecAsn1Template kSecAsn1OCSPResponseTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPResponse) }, - { SEC_ASN1_ENUMERATED, offsetof(SecAsn1OCSPResponse, responseStatus) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPResponse, responseBytes), - kSecAsn1OCSPPtrToResponseBytesTemplate }, - { 0 } -}; - -// MARK: ---- OCSPD RPC ---- - -const SecAsn1Template kSecAsn1OCSPDRequestTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPDRequest) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 0, - offsetof(SecAsn1OCSPDRequest, cacheWriteDisable), - kSecAsn1PointerToBooleanTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 1, - offsetof(SecAsn1OCSPDRequest, cacheReadDisable), - kSecAsn1PointerToBooleanTemplate }, - { SEC_ASN1_OCTET_STRING, offsetof(SecAsn1OCSPDRequest, certID) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 2, - offsetof(SecAsn1OCSPDRequest, ocspReq), - kSecAsn1PointerToOctetStringTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 3, - offsetof(SecAsn1OCSPDRequest, localRespURI), - kSecAsn1PointerToIA5StringTemplate }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | 4, - offsetof(SecAsn1OCSPDRequest, urls), - kSecAsn1SequenceOfIA5StringTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPDRequestsTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPDRequests) }, - { SEC_ASN1_INTEGER, offsetof(SecAsn1OCSPDRequests, version) }, - { SEC_ASN1_SEQUENCE_OF, - offsetof(SecAsn1OCSPDRequests, requests), - kSecAsn1OCSPDRequestTemplate }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPDReplyTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPDReply) }, - { SEC_ASN1_ANY, offsetof(SecAsn1OCSPDReply, certID) }, - { SEC_ASN1_ANY, offsetof(SecAsn1OCSPDReply, ocspResp) }, - { 0 } -}; - -const SecAsn1Template kSecAsn1OCSPDRepliesTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(SecAsn1OCSPReplies) }, - { SEC_ASN1_INTEGER, offsetof(SecAsn1OCSPReplies, version) }, - { SEC_ASN1_SEQUENCE_OF, - offsetof(SecAsn1OCSPReplies, replies), - kSecAsn1OCSPDReplyTemplate }, - { 0 } -}; diff --git a/OSX/include/security_asn1/ocspTemplates.h b/OSX/include/security_asn1/ocspTemplates.h deleted file mode 100644 index 2af1efc3..00000000 --- a/OSX/include/security_asn1/ocspTemplates.h +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * ocspTemplates.h - ASN1 templates OCSP requests and responses. - */ - -#ifndef _OCSP_TEMPLATES_H_ -#define _OCSP_TEMPLATES_H_ - -#include /* NSS_CertExtension */ -#include /* NSS_GeneralName and support */ - -#ifdef __cplusplus -extern "C" { -#endif - -// MARK: ----- OCSP Request ----- - -/* - * CertID ::= SEQUENCE { - * hashAlgorithm AlgorithmIdentifier, - * issuerNameHash OCTET STRING, -- Hash of Issuer's DN - * issuerKeyHash OCTET STRING, -- Hash of Issuers public key - * serialNumber CertificateSerialNumber } -- i.e., INTEGER - */ -typedef struct { - SecAsn1AlgId algId; - SecAsn1Item issuerNameHash; - SecAsn1Item issuerPubKeyHash; - SecAsn1Item serialNumber; -} SecAsn1OCSPCertID; - -extern const SecAsn1Template kSecAsn1OCSPCertIDTemplate[]; - -/* - * Request ::= SEQUENCE { - * reqCert CertID, - * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } - */ -typedef struct { - SecAsn1OCSPCertID reqCert; - NSS_CertExtension **extensions; // optional -} SecAsn1OCSPRequest; - -extern const SecAsn1Template kSecAsn1OCSPRequestTemplate[]; - -/* - * Signature ::= SEQUENCE { - * signatureAlgorithm AlgorithmIdentifier, - * signature BIT STRING, - * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL} - * - * Since we wish to avoid knowing anything about the details of the certs, - * we declare them here as ASN_ANY, get/set as raw data, and leave it to - * the CL to parse them. - */ -typedef struct { - SecAsn1AlgId algId; - SecAsn1Item sig; // length in BITS - SecAsn1Item **certs; // OPTIONAL -} SecAsn1OCSPSignature; - -extern const SecAsn1Template kSecAsn1OCSPSignatureTemplate[]; - -/* - * TBSRequest ::= SEQUENCE { - * version [0] EXPLICIT Version DEFAULT v1, - * requestorName [1] EXPLICIT GeneralName OPTIONAL, - * requestList SEQUENCE OF Request, - * requestExtensions [2] EXPLICIT Extensions OPTIONAL } - */ -typedef struct { - SecAsn1Item *version; // OPTIONAL - NSS_GeneralName *requestorName; // OPTIONAL - SecAsn1OCSPRequest **requestList; - NSS_CertExtension **requestExtensions; // OPTIONAL -} SecAsn1OCSPTbsRequest; - -extern const SecAsn1Template kSecAsn1OCSPTbsRequestTemplate[]; - -/* - * OCSPRequest ::= SEQUENCE { - * tbsRequest TBSRequest, - * optionalSignature [0] EXPLICIT Signature OPTIONAL } - */ -typedef struct { - SecAsn1OCSPTbsRequest tbsRequest; - SecAsn1OCSPSignature *signature; // OPTIONAL -} SecAsn1OCSPSignedRequest; - -extern const SecAsn1Template kSecAsn1OCSPSignedRequestTemplate[]; - -// MARK: ----- OCSP Response ----- - -/* - * CertStatus ::= CHOICE { - * good [0] IMPLICIT NULL, - * revoked [1] IMPLICIT RevokedInfo, - * unknown [2] IMPLICIT UnknownInfo } - * - * RevokedInfo ::= SEQUENCE { - * revocationTime GeneralizedTime, - * revocationReason [0] EXPLICIT CRLReason OPTIONAL } - * - * UnknownInfo ::= NULL -- this can be replaced with an enumeration - * - * See for enum values of CE_CrlReason. - */ -typedef struct { - SecAsn1Item revocationTime; - SecAsn1Item *revocationReason; // OPTIONAL, CE_CrlReason -} SecAsn1OCSPRevokedInfo; - -typedef union { - SecAsn1OCSPRevokedInfo *revokedInfo; - SecAsn1Item *nullData; -} SecAsn1OCSPCertStatus; - -typedef enum { - CS_Good = 0, - CS_Revoked = 1, - CS_Unknown = 2, - CS_NotParsed = 0xff /* Not in protocol: means value not parsed or seen */ -} SecAsn1OCSPCertStatusTag; - -extern const SecAsn1Template kSecAsn1OCSPRevokedInfoTemplate[]; - -/* - * Encode/decode CertStatus separately using one of these  hree templates. - * The result goes into SecAsn1OCSPSingleResponse.certStatus on encode. - */ -extern const SecAsn1Template kSecAsn1OCSPCertStatusGoodTemplate[]; -extern const SecAsn1Template kSecAsn1OCSPCertStatusRevokedTemplate[]; -extern const SecAsn1Template kSecAsn1OCSPCertStatusUnknownTemplate[]; - -/* - * SingleResponse ::= SEQUENCE { - * certID CertID, - * certStatus CertStatus, - * thisUpdate GeneralizedTime, - * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, - * singleExtensions [1] EXPLICIT Extensions OPTIONAL } - */ -typedef struct { - SecAsn1OCSPCertID certID; - SecAsn1Item certStatus; // ASN_ANY here - SecAsn1Item thisUpdate; // GeneralizedTime - SecAsn1Item *nextUpdate; // GeneralizedTime, OPTIONAL - NSS_CertExtension **singleExtensions; // OPTIONAL -} SecAsn1OCSPSingleResponse; - -extern const SecAsn1Template kSecAsn1OCSPSingleResponseTemplate[]; - -/* - * ResponderID ::= CHOICE { - * byName EXPLICIT [1] Name, - * byKey EXPLICIT [2] KeyHash } - * - * Since our ASN.1 encoder/decoder can't handle CHOICEs very well, we encode - * this separately using one of the following two templates. On encode the - * result if this step of the encode goes into SecAsn1OCSPResponseData.responderID, - * where it's treated as an ANY_ANY when encoding that struct. The reverse happens - * on decode. - */ -typedef union { - SecAsn1Item byName; - SecAsn1Item byKey; // key hash in OCTET STRING -} SecAsn1OCSPResponderID; - -typedef enum { - RIT_Name = 1, - RIT_Key = 2 -} SecAsn1OCSPResponderIDTag; - -extern const SecAsn1Template kSecAsn1OCSPResponderIDAsNameTemplate[]; -extern const SecAsn1Template kSecAsn1OCSPResponderIDAsKeyTemplate[]; - -/* - * ResponseData ::= SEQUENCE { - * version [0] EXPLICIT Version DEFAULT v1, - * responderID ResponderID, - * producedAt GeneralizedTime, - * responses SEQUENCE OF SingleResponse, - * responseExtensions [1] EXPLICIT Extensions OPTIONAL } - */ -typedef struct { - SecAsn1Item *version; // OPTIONAL - SecAsn1Item responderID; // ASN_ANY here, decode/encode separately - SecAsn1Item producedAt; // GeneralizedTime - SecAsn1OCSPSingleResponse **responses; - NSS_CertExtension **responseExtensions; // OPTIONAL -} SecAsn1OCSPResponseData; - -extern const SecAsn1Template kSecAsn1OCSPResponseDataTemplate[]; - -/* - * BasicOCSPResponse ::= SEQUENCE { - * tbsResponseData ResponseData, - * signatureAlgorithm AlgorithmIdentifier, - * signature BIT STRING, - * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } - * - * Since we ALWAYS encode the tbsResponseData in preparation for signing, - * we declare it as a raw ASN_ANY in the BasicOCSPResponse. - * - * Certs are likewise ASN_ANY since we use the CL to parse and create them. - */ -typedef struct { - SecAsn1Item tbsResponseData; - SecAsn1AlgId algId; - SecAsn1Item sig; // length in BITS - SecAsn1Item **certs; // optional -} SecAsn1OCSPBasicResponse; - -extern const SecAsn1Template kSecAsn1OCSPBasicResponseTemplate[]; - -/* - * ResponseBytes ::= SEQUENCE { - * responseType OBJECT IDENTIFIER, - * response OCTET STRING } - * - * The contents of response are actually an encoded SecAsn1OCSPBasicResponse (at - * least until another response type is defined). - */ -typedef struct { - SecAsn1Oid responseType; - SecAsn1Item response; -} SecAsn1OCSPResponseBytes; - -extern const SecAsn1Template kSecAsn1OCSPResponseBytesTemplate[]; - -/* - * OCSPResponse ::= SEQUENCE { - * responseStatus OCSPResponseStatus, -- an ENUM - * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } - */ -typedef struct { - SecAsn1Item responseStatus; // see enum below - SecAsn1OCSPResponseBytes *responseBytes; // optional -} SecAsn1OCSPResponse; - -extern const SecAsn1Template kSecAsn1OCSPResponseTemplate[]; - -typedef enum { - RS_Success = 0, - RS_MalformedRequest = 1, - RS_InternalError = 2, - RS_TryLater = 3, - RS_Unused = 4, - RS_SigRequired = 5, - RS_Unauthorized = 6 -} SecAsn1OCSPResponseStatus; - -/* - * This is not part of the OCSP protocol; it's used in the communication between - * the Apple X.509 TP module and the ocspd server. - * - * OCSPDRequest ::= SEQUENCE { - * cacheWriteDisable :: = EXPLICIT [0] BOOL OPTIONAL; -- cache write disable - * -- default FALSE - * cacheWriteDisable :: = EXPLICIT [1] BOOL OPTIONAL; -- cache read disable - * -- default FALSE - * certID ::= OCTET STRING; -- for cache lookup - * ocspReq ::= EXPLICIT [2] OCTET STRING OPTIONAL; -- for net fetch - * localResp ::= EXPLICIT [3] IA5String OPTIONAL; -- for local responder - * urls ::= EXPLICIT [4] SEQUENCE of IA5String OPTIONAL; - * -- for normal net fetch - * }; - */ - -#define OCSPD_REQUEST_VERS 0 - -typedef struct { - SecAsn1Item *cacheWriteDisable; - SecAsn1Item *cacheReadDisable; - SecAsn1Item certID; // DER encoded SecAsn1OCSPCertID - SecAsn1Item *ocspReq; // DER encoded SecAsn1OCSPSignedRequest - SecAsn1Item *localRespURI; // local responder URI - SecAsn1Item **urls; // normal URIs - -} SecAsn1OCSPDRequest; - -/* - * And this is a sequence of them, packaged up and sent to ocspd in one RPC. - */ -typedef struct { - SecAsn1Item version; // OCSPD_REQUEST_VERS - SecAsn1OCSPDRequest **requests; -} SecAsn1OCSPDRequests; - -extern const SecAsn1Template kSecAsn1OCSPDRequestTemplate[]; -extern const SecAsn1Template kSecAsn1OCSPDRequestsTemplate[]; - -/* - * Unordered set of replies from ocsdp; they map back to individual - * SecAsn1OCSPDRequests by the encoded certID (which is obtained from the - * SecAsn1OCSPDRequest, NOT from the OCSP response). - */ -typedef struct { - SecAsn1Item certID; // DER encoded SecAsn1OCSPCertID - SecAsn1Item ocspResp; // DER encoded SecAsn1OCSPResponse -} SecAsn1OCSPDReply; - -#define OCSPD_REPLY_VERS 0 - -typedef struct { - SecAsn1Item version; // OCSPD_REPLY_VERS - SecAsn1OCSPDReply **replies; -} SecAsn1OCSPReplies; - -extern const SecAsn1Template kSecAsn1OCSPDReplyTemplate[]; -extern const SecAsn1Template kSecAsn1OCSPDRepliesTemplate[]; - -#ifdef __cplusplus -} -#endif - -#endif /* _OCSP_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/oidsalg.c b/OSX/include/security_asn1/oidsalg.c deleted file mode 100644 index 6aa61312..00000000 --- a/OSX/include/security_asn1/oidsalg.c +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Copyright (c) 2000-2004,2008,2010,2012-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/* - * oidsalg.c - OIDs defining crypto algorithms - */ - -#include -#include "SecAsn1Types.h" -#include "oidsbase.h" - -static const uint8_t - OID_MD2[] = { OID_RSA_HASH, 2 }, - OID_MD4[] = { OID_RSA_HASH, 4 }, - OID_MD5[] = { OID_RSA_HASH, 5 }, - OID_RSAEncryption[] = { OID_PKCS_1, 1 }, - OID_MD2WithRSA[] = { OID_PKCS_1, 2 }, - OID_MD4WithRSA[] = { OID_PKCS_1, 3 }, - OID_MD5WithRSA[] = { OID_PKCS_1, 4 }, - OID_SHA1WithRSA[] = { OID_PKCS_1, 5 }, - OID_RSAWithOAEP[] = { OID_PKCS_1, 7 }, - OID_OAEP_MGF1[] = { OID_PKCS_1, 8 }, - OID_OAEP_ID_PSPECIFIED[]= { OID_PKCS_1, 9 }, - OID_SHA224WithRSA[] = { OID_PKCS_1, 14 }, - OID_SHA256WithRSA[] = { OID_PKCS_1, 11 }, - OID_SHA384WithRSA[] = { OID_PKCS_1, 12 }, - OID_SHA512WithRSA[] = { OID_PKCS_1, 13 }, - OID_PKCS_3_ARC[] = { OID_PKCS_3 }, - OID_DHKeyAgreement[] = { OID_PKCS_3, 1 }, - /* BSAFE-specific DSA */ - OID_OIW_DSA[] = { OID_OIW_ALGORITHM, 12 }, - OID_OIW_DSAWithSHA1[] = { OID_OIW_ALGORITHM, 27 }, - /* DSA from CMS */ - OID_CMS_DSA[] = { 0x2A, 0x86, 0x48, 0xCE, 0x38, 4, 1 }, - OID_CMS_DSAWithSHA1[] = { 0x2A, 0x86, 0x48, 0xCE, 0x38, 4, 3 }, - /* DSA from JDK 1.1 */ - OID_JDK_DSA[] = { 0x2B, 0x0E, 0x03, 0x02, 0x0c }, - OID_JDK_DSAWithSHA1[] = { 0x2B, 0x0E, 0x03, 0x02, 0x0D }, - - OID_OIW_SHA1[] = { OID_OIW_ALGORITHM, 26 }, - OID_OIW_RSAWithSHA1[] = { OID_OIW_ALGORITHM, 29 }, - OID_OIW_DES_CBC[] = { OID_OIW_ALGORITHM, 7 }, - - OID_SHA224[] = { OID_NIST_HASHALG, 4}, - OID_SHA256[] = { OID_NIST_HASHALG, 1}, - OID_SHA384[] = { OID_NIST_HASHALG, 2}, - OID_SHA512[] = { OID_NIST_HASHALG, 3}, - - /* ANSI X9.42 */ - OID_ANSI_DH_PUB_NUMBER[]= { OID_ANSI_X9_42, 1 }, - OID_ANSI_DH_STATIC[] = { OID_ANSI_X9_42_SCHEME, 1 }, - OID_ANSI_DH_EPHEM[] = { OID_ANSI_X9_42_SCHEME, 2 }, - OID_ANSI_DH_ONE_FLOW[] = { OID_ANSI_X9_42_SCHEME, 3 }, - OID_ANSI_DH_HYBRID1[] = { OID_ANSI_X9_42_SCHEME, 4 }, - OID_ANSI_DH_HYBRID2[] = { OID_ANSI_X9_42_SCHEME, 5 }, - OID_ANSI_DH_HYBRID_ONEFLOW[] = { OID_ANSI_X9_42_SCHEME, 6 }, - /* sic - enumerated in reverse order in the spec */ - OID_ANSI_MQV1[] = { OID_ANSI_X9_42_SCHEME, 8 }, - OID_ANSI_MQV2[] = { OID_ANSI_X9_42_SCHEME, 7 }, - - OID_ANSI_DH_STATIC_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 1 }, - OID_ANSI_DH_EPHEM_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 2 }, - OID_ANSI_DH_ONE_FLOW_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 3 }, - OID_ANSI_DH_HYBRID1_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 4 }, - OID_ANSI_DH_HYBRID2_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 5 }, - OID_ANSI_DH_HYBRID_ONEFLOW_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 6 }, - /* sic - enumerated in reverse order in the spec */ - OID_ANSI_MQV1_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 8 }, - OID_ANSI_MQV2_SHA1[] = { OID_ANSI_X9_42_NAMED_SCHEME, 7 }; - -const SecAsn1Oid - CSSMOID_MD2 = {OID_RSA_HASH_LENGTH+1, (uint8_t *)OID_MD2}, - CSSMOID_MD4 = {OID_RSA_HASH_LENGTH+1, (uint8_t *)OID_MD4}, - CSSMOID_MD5 = {OID_RSA_HASH_LENGTH+1, (uint8_t *)OID_MD5}, - CSSMOID_RSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_RSAEncryption}, - CSSMOID_MD2WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_MD2WithRSA}, - CSSMOID_MD4WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_MD4WithRSA}, - CSSMOID_MD5WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_MD5WithRSA}, - CSSMOID_SHA1WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_SHA1WithRSA}, - CSSMOID_RSAWithOAEP = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_RSAWithOAEP}, - CSSMOID_OAEP_MGF1 = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_OAEP_MGF1}, - CSSMOID_OAEP_ID_PSPECIFIED = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_OAEP_ID_PSPECIFIED}, - CSSMOID_SHA224WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_SHA224WithRSA}, - CSSMOID_SHA256WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_SHA256WithRSA}, - CSSMOID_SHA384WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_SHA384WithRSA}, - CSSMOID_SHA512WithRSA = {OID_PKCS_1_LENGTH+1, (uint8_t *)OID_SHA512WithRSA}, - CSSMOID_PKCS3 = {OID_PKCS_3_LENGTH, (uint8_t *)OID_PKCS_3_ARC}, - CSSMOID_DH = {OID_PKCS_3_LENGTH+1, (uint8_t *)OID_DHKeyAgreement}, - CSSMOID_DSA = {OID_OIW_ALGORITHM_LENGTH+1, (uint8_t *)OID_OIW_DSA}, - CSSMOID_DSA_CMS = { 7, (uint8_t *)OID_CMS_DSA}, - CSSMOID_DSA_JDK = { 5, (uint8_t *)OID_JDK_DSA}, - CSSMOID_SHA1WithDSA = {OID_OIW_ALGORITHM_LENGTH+1, (uint8_t *)OID_OIW_DSAWithSHA1}, - CSSMOID_SHA1WithDSA_CMS = { 7, (uint8_t *)OID_CMS_DSAWithSHA1}, - CSSMOID_SHA1WithDSA_JDK = { 5, (uint8_t *)OID_JDK_DSAWithSHA1}, - CSSMOID_SHA1 = {OID_OIW_ALGORITHM_LENGTH+1, (uint8_t *)OID_OIW_SHA1}, - CSSMOID_SHA224 = {OID_NIST_HASHALG_LENGTH+1, (uint8_t *)OID_SHA224}, - CSSMOID_SHA256 = {OID_NIST_HASHALG_LENGTH+1, (uint8_t *)OID_SHA256}, - CSSMOID_SHA384 = {OID_NIST_HASHALG_LENGTH+1, (uint8_t *)OID_SHA384}, - CSSMOID_SHA512 = {OID_NIST_HASHALG_LENGTH+1, (uint8_t *)OID_SHA512}, - CSSMOID_SHA1WithRSA_OIW = {OID_OIW_ALGORITHM_LENGTH+1, (uint8_t *)OID_OIW_RSAWithSHA1}, - CSSMOID_DES_CBC = {OID_OIW_ALGORITHM_LENGTH+1, (uint8_t *)OID_OIW_DES_CBC}, - CSSMOID_ANSI_DH_PUB_NUMBER = {OID_ANSI_X9_42_LEN + 1, (uint8_t *)OID_ANSI_DH_PUB_NUMBER}, - CSSMOID_ANSI_DH_STATIC = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_DH_STATIC}, - CSSMOID_ANSI_DH_ONE_FLOW = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_DH_ONE_FLOW}, - CSSMOID_ANSI_DH_EPHEM = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_DH_EPHEM}, - CSSMOID_ANSI_DH_HYBRID1 = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_DH_HYBRID1}, - CSSMOID_ANSI_DH_HYBRID2 = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_DH_HYBRID2}, - CSSMOID_ANSI_DH_HYBRID_ONEFLOW = {OID_ANSI_X9_42_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_HYBRID_ONEFLOW}, - CSSMOID_ANSI_MQV1 = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_MQV1}, - CSSMOID_ANSI_MQV2 = {OID_ANSI_X9_42_SCHEME_LEN + 1, (uint8_t *)OID_ANSI_MQV2}, - CSSMOID_ANSI_DH_STATIC_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_STATIC_SHA1}, - CSSMOID_ANSI_DH_ONE_FLOW_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_ONE_FLOW_SHA1}, - CSSMOID_ANSI_DH_EPHEM_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_EPHEM_SHA1}, - CSSMOID_ANSI_DH_HYBRID1_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_HYBRID1_SHA1}, - CSSMOID_ANSI_DH_HYBRID2_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_HYBRID2_SHA1}, - CSSMOID_ANSI_DH_HYBRID_ONEFLOW_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_DH_HYBRID_ONEFLOW_SHA1}, - CSSMOID_ANSI_MQV1_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_MQV1_SHA1}, - CSSMOID_ANSI_MQV2_SHA1 = {OID_ANSI_X9_42_NAMED_SCHEME_LEN + 1, - (uint8_t *)OID_ANSI_MQV2_SHA1}; - - -/* iSignTP OBJECT IDENTIFIER ::= - * { appleTrustPolicy 1 } - * { 1 2 840 113635 100 1 1 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 01 01 - */ -static const uint8_t -APPLE_TP_ISIGN[] = {APPLE_TP_OID, 1}, - -/* AppleX509Basic OBJECT IDENTIFIER ::= - * { appleTrustPolicy 2 } - * { 1 2 840 113635 100 1 2 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 01 01 - */ -APPLE_TP_X509_BASIC[] = {APPLE_TP_OID, 2}, - -/* AppleSSLPolicy := {appleTrustPolicy 3 } */ -APPLE_TP_SSL[] = {APPLE_TP_OID, 3}, - -/* AppleLocalCertGenPolicy := {appleTrustPolicy 4 } */ -APPLE_TP_LOCAL_CERT_GEN[] = {APPLE_TP_OID, 4}, - -/* AppleCSRGenPolicy := {appleTrustPolicy 5 } */ -APPLE_TP_CSR_GEN[] = {APPLE_TP_OID, 5}, - -/* Apple CRL-based revocation policy := {appleTrustPolicy 6 } */ -APPLE_TP_REVOCATION_CRL[] = {APPLE_TP_OID, 6}, - -/* Apple OCSP-based revocation policy := {appleTrustPolicy 7 } */ -APPLE_TP_REVOCATION_OCSP[] = {APPLE_TP_OID, 7}, - -/* Apple S/MIME trust policy := {appleTrustPolicy 8 } */ -APPLE_TP_SMIME[] = {APPLE_TP_OID, 8}, - -/* Apple EAP trust policy := {appleTrustPolicy 9 } */ -APPLE_TP_EAP[] = {APPLE_TP_OID, 9}, - -/* - * NOTE: "Apple Code Signing Policy", CSSMOID_APPLE_TP_CODE_SIGN, was renamed - * to "Apple Software Update Signing Policy", CSSMOID_APPLE_TP_SW_UPDATE_SIGNING, - * on 8/16/06. For compatibility, we keep the TP_CODE_SIGN OID here until - * SoftwareUpdate converts to the new symbol. - * - * Apple Code Signing Policy := { appleTrustPolicy 10 } - * Apple Software Update Signing Policy := { appleTrustPolicy 10 } - */ -APPLE_SW_UPDATE_SIGNING[] = {APPLE_TP_OID, 10}, -#define APPLE_TP_CODE_SIGN APPLE_SW_UPDATE_SIGNING - -/* Apple IPSec Policy := { appleTrustPolicy 11 } */ -APPLE_TP_IP_SEC[] = {APPLE_TP_OID, 11}, - -/* Apple iChat Policy := { appleTrustPolicy 12 } */ -APPLE_TP_ICHAT[] = {APPLE_TP_OID, 12}, - -/* Apple Resource Signing Policy := { appleTrustPolicy 13 } */ -APPLE_TP_RESOURCE_SIGN[] = {APPLE_TP_OID, 13}, - -/* Apple PKINIT Client Cert Policy := { appleTrustPolicy 14 } */ -APPLE_TP_PKINIT_CLIENT[] = {APPLE_TP_OID, 14}, - -/* Apple PKINIT Server Cert Policy := { appleTrustPolicy 15 } */ -APPLE_TP_PKINIT_SERVER[] = {APPLE_TP_OID, 15}, - -/* Apple Code Signing Cert Policy := { appleTrustPolicy 16 } */ -APPLE_TP_CODE_SIGNING[] = {APPLE_TP_OID, 16}, - -/* Apple Package Signing Cert Policy := { appleTrustPolicy 17 } */ -APPLE_TP_PACKAGE_SIGNING[] = {APPLE_TP_OID, 17}, - -/* AppleID Sharing Cert Policy := { appleTrustPolicy 18 } */ -APPLE_TP_APPLEID_SHARING[] = {APPLE_TP_OID, 18}, -/* appleIDValidationPolicy */ - -/* Apple MacAppStore receipt verification policy := { appleTrustPolicy 19 } */ -APPLE_TP_MACAPPSTORE_RECEIPT[] = {APPLE_TP_OID, 19}, - -/* Apple Time Stamping Server Cert Policy := { appleTrustPolicy 20 } */ -APPLE_TP_TIMESTAMPING[] = {APPLE_TP_OID, 20}, - -/* Apple Revocation Policy := { appleTrustPolicy 21 } */ -APPLE_TP_REVOCATION[] = {APPLE_TP_OID, 21}, - -/* Apple Passbook Signing Policy := { appleTrustPolicy 22 } */ -APPLE_TP_PASSBOOK_SIGNING[] = {APPLE_TP_OID, 22}, - -/* Apple Mobile Store Policy := { appleTrustPolicy 23 } */ -APPLE_TP_MOBILE_STORE[] = {APPLE_TP_OID, 23}, - -/* Apple Escrow Service Policy := { appleTrustPolicy 24 } */ -APPLE_TP_ESCROW_SERVICE[] = {APPLE_TP_OID, 24}, - -/* Apple Configuration Profile Signing Policy := { appleTrustPolicy 25 } */ -APPLE_TP_PROFILE_SIGNING[] = {APPLE_TP_OID, 25}, - -/* Apple QA Configuration Profile Signing Policy := { appleTrustPolicy 26 } */ -APPLE_TP_QA_PROFILE_SIGNING[] = {APPLE_TP_OID, 26}, - -/* Apple Test Mobile Store Policy := { appleTrustPolicy 27 } */ -APPLE_TP_TEST_MOBILE_STORE[] = {APPLE_TP_OID, 27}, - -/* Apple PCS Escrow Service Policy := { appleTrustPolicy 34 } */ -APPLE_TP_PCS_ESCROW_SERVICE[] = {APPLE_TP_OID, 34}, - -/* - * fee OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 1 } - * { 1 2 840 113635 100 2 1 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 01 - */ -APPLE_FEE[] = {APPLE_ALG_OID, 1}, - -/* - * asc OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 2 } - * { 1 2 840 113635 100 2 2 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 02 - */ -APPLE_ASC[] = {APPLE_ALG_OID, 2}, - -/* - * fee_MD5 OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 3 } - * { 1 2 840 113635 100 2 3 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 03 - */ -APPLE_FEE_MD5[] = {APPLE_ALG_OID, 3}, - -/* - * fee_SHA1 OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 4 } - * { 1 2 840 113635 100 2 4 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 04 - */ -APPLE_FEE_SHA1[] = {APPLE_ALG_OID, 4}, - -/* - * feed OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 5 } - * { 1 2 840 113635 100 2 5 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 05 - */ -APPLE_FEED[] = {APPLE_ALG_OID, 5}, - -/* - * feedExp OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 6 } - * { 1 2 840 113635 100 2 6 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 06 - */ -APPLE_FEEDEXP[] = {APPLE_ALG_OID, 6}, - -/* - * AppleECDSA OBJECT IDENTIFIER ::= - * { appleSecurityAlgorithm 7 } - * { 1 2 840 113635 100 2 7 } - * - * BER = 06 09 2A 86 48 86 F7 63 64 02 07 - */ -APPLE_ECDSA[] = {APPLE_ALG_OID, 7}, - -/* .mac cert OIDs */ -OID_DOTMAC_CERT[] = { APPLE_DOTMAC_CERT_OID }, -OID_DOTMAC_CERT_REQ[] = { APPLE_DOTMAC_CERT_REQ_OID }, -OID_DOTMAC_CERT_REQ_IDENTITY[] = { APPLE_DOTMAC_CERT_REQ_OID, 1 }, /* deprecated */ -OID_DOTMAC_CERT_REQ_EMAIL_SIGN[] = { APPLE_DOTMAC_CERT_REQ_OID, 2 }, /* deprecated */ -OID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT[] = { APPLE_DOTMAC_CERT_REQ_OID, 3 }, /* deprecated */ -OID_DOTMAC_CERT_REQ_ARCHIVE_LIST[] = { APPLE_DOTMAC_CERT_REQ_OID, 4 }, -OID_DOTMAC_CERT_REQ_ARCHIVE_STORE[] = { APPLE_DOTMAC_CERT_REQ_OID, 5 }, -OID_DOTMAC_CERT_REQ_ARCHIVE_FETCH[] = { APPLE_DOTMAC_CERT_REQ_OID, 6 }, -OID_DOTMAC_CERT_REQ_ARCHIVE_REMOVE[] = { APPLE_DOTMAC_CERT_REQ_OID, 7 }, -OID_DOTMAC_CERT_REQ_SHARED_SERVICES[] = { APPLE_DOTMAC_CERT_REQ_OID, 8 }, /* treadstone - Shared Services */ - -/* OIDs for specifying OID/values pairs in a cert request */ -OID_DOTMAC_CERT_REQ_VALUE_USERNAME[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 1 }, -OID_DOTMAC_CERT_REQ_VALUE_PASSWORD[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 2 }, -OID_DOTMAC_CERT_REQ_VALUE_HOSTNAME[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 3 }, -OID_DOTMAC_CERT_REQ_VALUE_RENEW[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 4 }, -OID_DOTMAC_CERT_REQ_VALUE_ASYNC[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 5 }, -OID_DOTMAC_CERT_REQ_VALUE_IS_PENDING[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 6 }, -__unused OID_DOTMAC_CERT_REQ_VALUE_TYPE_ICHAT[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 7 }, -__unused OID_DOTMAC_CERT_REQ_VALUE_TYPE_SHARED_SERVICE[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 8 }, -__unused OID_DOTMAC_CERT_REQ_VALUE_TYPE_EMAIL_ENCRYPT[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 9 }, -__unused OID_DOTMAC_CERT_REQ_VALUE_TYPE_EMAIL_SIGN[] = { APPLE_DOTMAC_CERT_REQ_VALUE_OID, 10 } -; - -const SecAsn1Oid - -CSSMOID_APPLE_ISIGN = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_ISIGN}, -CSSMOID_APPLE_X509_BASIC = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_X509_BASIC}, -CSSMOID_APPLE_TP_SSL = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_SSL}, -CSSMOID_APPLE_TP_LOCAL_CERT_GEN = - {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_LOCAL_CERT_GEN}, -CSSMOID_APPLE_TP_CSR_GEN = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_CSR_GEN}, -CSSMOID_APPLE_TP_REVOCATION_CRL = - {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_REVOCATION_CRL}, -CSSMOID_APPLE_TP_REVOCATION_OCSP = - {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_REVOCATION_OCSP}, -CSSMOID_APPLE_TP_SMIME = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_SMIME}, -CSSMOID_APPLE_TP_EAP = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_EAP}, -/* CSSMOID_APPLE_TP_CODE_SIGN here for temporary compatibility */ -CSSMOID_APPLE_TP_CODE_SIGN = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_CODE_SIGN}, -CSSMOID_APPLE_TP_SW_UPDATE_SIGNING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_SW_UPDATE_SIGNING}, -CSSMOID_APPLE_TP_IP_SEC = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_IP_SEC}, -CSSMOID_APPLE_TP_ICHAT = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_ICHAT}, -CSSMOID_APPLE_TP_RESOURCE_SIGN = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_RESOURCE_SIGN}, -CSSMOID_APPLE_TP_PKINIT_CLIENT = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_PKINIT_CLIENT}, -CSSMOID_APPLE_TP_PKINIT_SERVER = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_PKINIT_SERVER}, -CSSMOID_APPLE_TP_CODE_SIGNING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_CODE_SIGNING}, -CSSMOID_APPLE_TP_PACKAGE_SIGNING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_PACKAGE_SIGNING}, -CSSMOID_APPLE_TP_MACAPPSTORE_RECEIPT = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_MACAPPSTORE_RECEIPT}, -CSSMOID_APPLE_TP_APPLEID_SHARING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_APPLEID_SHARING}, -CSSMOID_APPLE_TP_TIMESTAMPING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_TIMESTAMPING}, -CSSMOID_APPLE_TP_REVOCATION = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_REVOCATION}, -CSSMOID_APPLE_TP_PASSBOOK_SIGNING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_PASSBOOK_SIGNING}, -CSSMOID_APPLE_TP_MOBILE_STORE = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_MOBILE_STORE}, -CSSMOID_APPLE_TP_ESCROW_SERVICE = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_ESCROW_SERVICE}, -CSSMOID_APPLE_TP_PROFILE_SIGNING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_PROFILE_SIGNING}, -CSSMOID_APPLE_TP_QA_PROFILE_SIGNING = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_QA_PROFILE_SIGNING}, -CSSMOID_APPLE_TP_TEST_MOBILE_STORE = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_TEST_MOBILE_STORE}, -CSSMOID_APPLE_TP_PCS_ESCROW_SERVICE = {APPLE_TP_OID_LENGTH+1, (uint8_t *)APPLE_TP_PCS_ESCROW_SERVICE}, -CSSMOID_APPLE_FEE = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_FEE}, -CSSMOID_APPLE_ASC = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_ASC}, -CSSMOID_APPLE_FEE_MD5 = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_FEE_MD5}, -CSSMOID_APPLE_FEE_SHA1 = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_FEE_SHA1}, -CSSMOID_APPLE_FEED = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_FEED}, -CSSMOID_APPLE_FEEDEXP = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_FEEDEXP}, -CSSMOID_APPLE_ECDSA = {APPLE_ALG_OID_LENGTH+1, (uint8_t *)APPLE_ECDSA}, -/* .mac cert OIDs */ -CSSMOID_DOTMAC_CERT = { APPLE_DOTMAC_CERT_OID_LENGTH, - (uint8_t *)OID_DOTMAC_CERT }, -CSSMOID_DOTMAC_CERT_REQ = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH, - (uint8_t *)OID_DOTMAC_CERT_REQ }, -/* This actually used to be for requesting an encrypted iChat cert; deprecated in Leopard */ -CSSMOID_DOTMAC_CERT_REQ_IDENTITY = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_IDENTITY}, -CSSMOID_DOTMAC_CERT_REQ_EMAIL_SIGN = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_EMAIL_SIGN}, -CSSMOID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT}, -CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_LIST = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_ARCHIVE_LIST}, -CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_STORE = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_ARCHIVE_STORE}, -CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_FETCH = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_ARCHIVE_FETCH}, -CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_REMOVE = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_ARCHIVE_REMOVE}, -CSSMOID_DOTMAC_CERT_REQ_SHARED_SERVICES = { APPLE_DOTMAC_CERT_REQ_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_SHARED_SERVICES}, -CSSMOID_DOTMAC_CERT_REQ_VALUE_USERNAME = { APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_VALUE_USERNAME}, -CSSMOID_DOTMAC_CERT_REQ_VALUE_PASSWORD = { APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_VALUE_PASSWORD}, -CSSMOID_DOTMAC_CERT_REQ_VALUE_HOSTNAME = { APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_VALUE_HOSTNAME}, -CSSMOID_DOTMAC_CERT_REQ_VALUE_RENEW = { APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_VALUE_RENEW}, -CSSMOID_DOTMAC_CERT_REQ_VALUE_ASYNC = { APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_VALUE_ASYNC}, -CSSMOID_DOTMAC_CERT_REQ_VALUE_IS_PENDING = { APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH + 1, - (uint8_t *)OID_DOTMAC_CERT_REQ_VALUE_IS_PENDING} -; - -/* PKCS5 algorithms */ - -static const uint8_t - OID_PKCS5_DIGEST_ALG[] = { OID_RSA_HASH }, - OID_PKCS5_ENCRYPT_ALG[] = { OID_RSA_ENCRYPT }, - OID_PKCS5_HMAC_SHA1[] = { OID_RSA_HASH, 7 }, - OID_PKCS5_pbeWithMD2AndDES[] = { OID_PKCS_5, 1 }, - OID_PKCS5_pbeWithMD5AndDES[] = { OID_PKCS_5, 3 }, - OID_PKCS5_pbeWithMD2AndRC2[] = { OID_PKCS_5, 4 }, - OID_PKCS5_pbeWithMD5AndRC2[] = { OID_PKCS_5, 6 }, - OID_PKCS5_pbeWithSHA1AndDES[] = { OID_PKCS_5, 10 }, - OID_PKCS5_pbeWithSHA1AndRC2[] = { OID_PKCS_5, 11 }, - OID_PKCS5_PBKDF2[] = { OID_PKCS_5, 12 }, - OID_PKCS5_PBES2[] = { OID_PKCS_5, 13 }, - OID_PKCS5_PBMAC1[] = { OID_PKCS_5, 14 }, - OID_PKCS5_RC2_CBC[] = { OID_RSA_ENCRYPT, 2 }, - OID_PKCS5_DES_EDE3_CBC[] = { OID_RSA_ENCRYPT, 7 }, - OID_PKCS5_RC5_CBC[] = { OID_RSA_ENCRYPT, 9 }; - -const SecAsn1Oid - CSSMOID_PKCS5_DIGEST_ALG = { OID_RSA_HASH_LENGTH, (uint8_t *)OID_PKCS5_DIGEST_ALG }, - CSSMOID_PKCS5_ENCRYPT_ALG = { OID_RSA_ENCRYPT_LENGTH, (uint8_t *)OID_PKCS5_ENCRYPT_ALG }, - CSSMOID_PKCS5_HMAC_SHA1 = { OID_RSA_HASH_LENGTH+1, (uint8_t *)OID_PKCS5_HMAC_SHA1 }, - CSSMOID_PKCS5_pbeWithMD2AndDES = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_pbeWithMD2AndDES }, - CSSMOID_PKCS5_pbeWithMD5AndDES = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_pbeWithMD5AndDES }, - CSSMOID_PKCS5_pbeWithMD2AndRC2 = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_pbeWithMD2AndRC2 }, - CSSMOID_PKCS5_pbeWithMD5AndRC2 = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_pbeWithMD5AndRC2 }, - CSSMOID_PKCS5_pbeWithSHA1AndDES = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_pbeWithSHA1AndDES }, - CSSMOID_PKCS5_pbeWithSHA1AndRC2 = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_pbeWithSHA1AndRC2 }, - CSSMOID_PKCS5_PBKDF2 = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_PBKDF2 }, - CSSMOID_PKCS5_PBES2 = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_PBES2 }, - CSSMOID_PKCS5_PBMAC1 = { OID_PKCS_5_LENGTH+1, (uint8_t *)OID_PKCS5_PBMAC1 }, - CSSMOID_PKCS5_RC2_CBC = { OID_RSA_ENCRYPT_LENGTH+1, (uint8_t *)OID_PKCS5_RC2_CBC }, - CSSMOID_PKCS5_DES_EDE3_CBC = { OID_RSA_ENCRYPT_LENGTH+1, (uint8_t *)OID_PKCS5_DES_EDE3_CBC }, - CSSMOID_PKCS5_RC5_CBC = { OID_RSA_ENCRYPT_LENGTH+1, (uint8_t *)OID_PKCS5_RC5_CBC }; - -/* PKCS12 algorithms */ -#define OID_PKCS12_PbeIds OID_PKCS_12,1 -#define OID_PKCS12_PbeIds_Length OID_PKCS_12_LENGTH+1 - -static const uint8_t - OID_PKCS12_pbeWithSHAAnd128BitRC4[] = { OID_PKCS12_PbeIds, 1 }, - OID_PKCS12_pbeWithSHAAnd40BitRC4[] = { OID_PKCS12_PbeIds, 2 }, - OID_PKCS12_pbeWithSHAAnd3Key3DESCBC[] = { OID_PKCS12_PbeIds, 3 }, - OID_PKCS12_pbeWithSHAAnd2Key3DESCBC[] = { OID_PKCS12_PbeIds, 4 }, - OID_PKCS12_pbeWithSHAAnd128BitRC2CBC[] ={ OID_PKCS12_PbeIds, 5 }, - OID_PKCS12_pbewithSHAAnd40BitRC2CBC[] = { OID_PKCS12_PbeIds, 6 }; - - -const SecAsn1Oid -CSSMOID_PKCS12_pbeWithSHAAnd128BitRC4 = {OID_PKCS12_PbeIds_Length + 1, - (uint8_t *)OID_PKCS12_pbeWithSHAAnd128BitRC4 }, -CSSMOID_PKCS12_pbeWithSHAAnd40BitRC4 = {OID_PKCS12_PbeIds_Length + 1, - (uint8_t *)OID_PKCS12_pbeWithSHAAnd40BitRC4 }, -CSSMOID_PKCS12_pbeWithSHAAnd3Key3DESCBC = {OID_PKCS12_PbeIds_Length + 1, - (uint8_t *)OID_PKCS12_pbeWithSHAAnd3Key3DESCBC }, -CSSMOID_PKCS12_pbeWithSHAAnd2Key3DESCBC = {OID_PKCS12_PbeIds_Length + 1, - (uint8_t *)OID_PKCS12_pbeWithSHAAnd2Key3DESCBC }, -CSSMOID_PKCS12_pbeWithSHAAnd128BitRC2CBC = {OID_PKCS12_PbeIds_Length + 1, - (uint8_t *)OID_PKCS12_pbeWithSHAAnd128BitRC2CBC }, -CSSMOID_PKCS12_pbewithSHAAnd40BitRC2CBC = {OID_PKCS12_PbeIds_Length + 1, - (uint8_t *)OID_PKCS12_pbewithSHAAnd40BitRC2CBC }; - -/* ANSI X9.62 and Certicom elliptic curve algorithms */ -static const uint8_t - OID_ecPublicKey[] = { OID_ANSI_X9_62_PUBKEY_TYPE, 1 }, - OID_ECDSA_WithSHA1[] = { OID_ANSI_X9_62_SIG_TYPE, 1 }, - OID_ECDSA_WithSHA224[] = { OID_ANSI_X9_62_SIG_TYPE, 3, 1 }, - OID_ECDSA_WithSHA256[] = { OID_ANSI_X9_62_SIG_TYPE, 3, 2 }, - OID_ECDSA_WithSHA384[] = { OID_ANSI_X9_62_SIG_TYPE, 3, 3 }, - OID_ECDSA_WithSHA512[] = { OID_ANSI_X9_62_SIG_TYPE, 3, 4 }, - OID_ECDSA_WithSpecified[] = { OID_ANSI_X9_62_SIG_TYPE, 3 }; - -const SecAsn1Oid -CSSMOID_ecPublicKey = {OID_ANSI_X9_62_LEN+2, (uint8_t *)OID_ecPublicKey}, -CSSMOID_ECDSA_WithSHA1 = {OID_ANSI_X9_62_SIG_TYPE_LEN+1, (uint8_t *)OID_ECDSA_WithSHA1 }, -CSSMOID_ECDSA_WithSHA224 = {OID_ANSI_X9_62_SIG_TYPE_LEN+2, (uint8_t *)OID_ECDSA_WithSHA224 }, -CSSMOID_ECDSA_WithSHA256 = {OID_ANSI_X9_62_SIG_TYPE_LEN+2, (uint8_t *)OID_ECDSA_WithSHA256 }, -CSSMOID_ECDSA_WithSHA384 = {OID_ANSI_X9_62_SIG_TYPE_LEN+2, (uint8_t *)OID_ECDSA_WithSHA384 }, -CSSMOID_ECDSA_WithSHA512 = {OID_ANSI_X9_62_SIG_TYPE_LEN+2, (uint8_t *)OID_ECDSA_WithSHA512 }, -CSSMOID_ECDSA_WithSpecified = {OID_ANSI_X9_62_SIG_TYPE_LEN+1, (uint8_t *)OID_ECDSA_WithSpecified }; diff --git a/OSX/include/security_asn1/oidsalg.h b/OSX/include/security_asn1/oidsalg.h deleted file mode 100644 index 301b7002..00000000 --- a/OSX/include/security_asn1/oidsalg.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 1999-2004,2008-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * oidsalg.h -- OIDs defining crypto algorithms - */ - -#ifndef _OIDS_ALG_H_ -#define _OIDS_ALG_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -extern const SecAsn1Oid - CSSMOID_MD2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_MD4 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_MD5 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_RSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_MD2WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_MD4WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_MD5WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA1WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA224WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA256WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA384WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA512WithRSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA1WithRSA_OIW DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_RSAWithOAEP DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_OAEP_MGF1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_OAEP_ID_PSPECIFIED DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DES_CBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_PUB_NUMBER DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_STATIC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_ONE_FLOW DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_EPHEM DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_HYBRID1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_HYBRID2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_HYBRID_ONEFLOW DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_MQV1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_MQV2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_STATIC_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_ONE_FLOW_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_EPHEM_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_HYBRID1_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_DH_HYBRID2_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_MQV1_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ANSI_MQV2_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS3 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DH DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, // BSAFE only - CSSMOID_DSA_CMS DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, // X509/CMS - CSSMOID_DSA_JDK DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, // JDK 1.1 - CSSMOID_SHA1WithDSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, // BSAFE - CSSMOID_SHA1WithDSA_CMS DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, // X509/CMS - CSSMOID_SHA1WithDSA_JDK DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, // JDK 1.1 - CSSMOID_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA224 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA256 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA384 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SHA512 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ecPublicKey DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ECDSA_WithSHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ECDSA_WithSHA224 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ECDSA_WithSHA256 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ECDSA_WithSHA384 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ECDSA_WithSHA512 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ECDSA_WithSpecified DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_ISIGN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_X509_BASIC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_SSL DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_LOCAL_CERT_GEN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_CSR_GEN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_REVOCATION_CRL DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_REVOCATION_OCSP DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_SMIME DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_EAP DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_CODE_SIGN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_SW_UPDATE_SIGNING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_IP_SEC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_ICHAT DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_RESOURCE_SIGN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_PKINIT_CLIENT DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_PKINIT_SERVER DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_CODE_SIGNING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_PACKAGE_SIGNING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_MACAPPSTORE_RECEIPT DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_APPLEID_SHARING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_TIMESTAMPING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_REVOCATION DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_PASSBOOK_SIGNING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_MOBILE_STORE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_ESCROW_SERVICE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_PROFILE_SIGNING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_QA_PROFILE_SIGNING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_TEST_MOBILE_STORE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_TP_PCS_ESCROW_SERVICE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_FEE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_ASC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_FEE_MD5 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_FEE_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_FEED DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_FEEDEXP DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_APPLE_ECDSA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_IDENTITY DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_EMAIL_SIGN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_LIST DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_STORE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_FETCH DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_ARCHIVE_REMOVE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_SHARED_SERVICES DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_VALUE_USERNAME DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_VALUE_PASSWORD DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_VALUE_HOSTNAME DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_VALUE_RENEW DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_VALUE_ASYNC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DOTMAC_CERT_REQ_VALUE_IS_PENDING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_DIGEST_ALG DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_ENCRYPT_ALG DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_HMAC_SHA1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_pbeWithMD2AndDES DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_pbeWithMD2AndRC2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_pbeWithMD5AndDES DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_pbeWithMD5AndRC2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_pbeWithSHA1AndDES DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_pbeWithSHA1AndRC2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_PBKDF2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_PBES2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_PBMAC1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_RC2_CBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_DES_EDE3_CBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS5_RC5_CBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_pbeWithSHAAnd128BitRC4 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_pbeWithSHAAnd40BitRC4 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_pbeWithSHAAnd3Key3DESCBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_pbeWithSHAAnd2Key3DESCBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_pbeWithSHAAnd128BitRC2CBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_pbewithSHAAnd40BitRC2CBC DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -#ifdef __cplusplus -} -#endif - -#endif /* _OIDS_ALG_H_ */ diff --git a/OSX/include/security_asn1/oidsattr.c b/OSX/include/security_asn1/oidsattr.c deleted file mode 100644 index be1625d6..00000000 --- a/OSX/include/security_asn1/oidsattr.c +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2008,2010,2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * oidsattr.c - Cert/CRL related OIDs. - */ - -#include -#include - - -/* - * Directory name component identifiers. - */ -static const uint8_t - OID_ObjectClass[] = { OID_ATTR_TYPE, 0 }, - OID_AliasedEntryName[] = { OID_ATTR_TYPE, 1 }, - OID_KnowledgeInformation[] = { OID_ATTR_TYPE, 2 }, - OID_CommonName[] = { OID_ATTR_TYPE, 3 }, - OID_Surname[] = { OID_ATTR_TYPE, 4 }, - OID_SerialNumber[] = { OID_ATTR_TYPE, 5 }, - OID_CountryName[] = { OID_ATTR_TYPE, 6 }, - OID_LocalityName[] = { OID_ATTR_TYPE, 7 }, - OID_StateProvinceName[] = { OID_ATTR_TYPE, 8 }, - OID_CollectiveStateProvinceName[] = { OID_ATTR_TYPE, 8, 1 }, - OID_StreetAddress[] = { OID_ATTR_TYPE, 9 }, - OID_CollectiveStreetAddress[] = { OID_ATTR_TYPE, 9, 1 }, - OID_OrganizationName[] = { OID_ATTR_TYPE, 10 }, - OID_CollectiveOrganizationName[] = { OID_ATTR_TYPE, 10, 1 }, - OID_OrganizationalUnitName[] = { OID_ATTR_TYPE, 11 }, - OID_CollectiveOrganizationalUnitName[] - = { OID_ATTR_TYPE, 11, 1 }, - OID_Title[] = { OID_ATTR_TYPE, 12 }, - OID_Description[] = { OID_ATTR_TYPE, 13 }, - OID_SearchGuide[] = { OID_ATTR_TYPE, 14 }, - OID_BusinessCategory[] = { OID_ATTR_TYPE, 15 }, - OID_PostalAddress[] = { OID_ATTR_TYPE, 16 }, - OID_CollectivePostalAddress[] = { OID_ATTR_TYPE, 16, 1 }, - OID_PostalCode[] = { OID_ATTR_TYPE, 17 }, - OID_CollectivePostalCode[] = { OID_ATTR_TYPE, 17, 1 }, - OID_PostOfficeBox[] = { OID_ATTR_TYPE, 18 }, - OID_CollectivePostOfficeBox[] = { OID_ATTR_TYPE, 18, 1 }, - OID_PhysicalDeliveryOfficeName[] = { OID_ATTR_TYPE, 19 }, - OID_CollectivePhysicalDeliveryOfficeName[] - = { OID_ATTR_TYPE, 19, 1 }, - OID_TelephoneNumber[] = { OID_ATTR_TYPE, 20 }, - OID_CollectiveTelephoneNumber[] = { OID_ATTR_TYPE, 20, 1 }, - OID_TelexNumber[] = { OID_ATTR_TYPE, 21 }, - OID_CollectiveTelexNumber[] = { OID_ATTR_TYPE, 21, 1 }, - OID_TelexTerminalIdentifier[] = { OID_ATTR_TYPE, 22 }, - OID_CollectiveTelexTerminalIdentifier[] - = { OID_ATTR_TYPE, 22, 1 }, - OID_FacsimileTelephoneNumber[] = { OID_ATTR_TYPE, 23 }, - OID_CollectiveFacsimileTelephoneNumber[] - = { OID_ATTR_TYPE, 23, 1 }, - OID_X_121Address[] = { OID_ATTR_TYPE, 24 }, - OID_InternationalISDNNumber[] = { OID_ATTR_TYPE, 25 }, - OID_CollectiveInternationalISDNNumber[] - = { OID_ATTR_TYPE, 25, 1 }, - OID_RegisteredAddress[] = { OID_ATTR_TYPE, 26 }, - OID_DestinationIndicator[] = { OID_ATTR_TYPE, 27 }, - OID_PreferredDeliveryMethod[] = { OID_ATTR_TYPE, 28 }, - OID_PresentationAddress[] = { OID_ATTR_TYPE, 29 }, - OID_SupportedApplicationContext[] = { OID_ATTR_TYPE, 30 }, - OID_Member[] = { OID_ATTR_TYPE, 31 }, - OID_Owner[] = { OID_ATTR_TYPE, 32 }, - OID_RoleOccupant[] = { OID_ATTR_TYPE, 33 }, - OID_SeeAlso[] = { OID_ATTR_TYPE, 34 }, - OID_UserPassword[] = { OID_ATTR_TYPE, 35 }, - OID_UserCertificate[] = { OID_ATTR_TYPE, 36 }, - OID_CACertificate[] = { OID_ATTR_TYPE, 37 }, - OID_AuthorityRevocationList[] = { OID_ATTR_TYPE, 38 }, - OID_CertificateRevocationList[] = { OID_ATTR_TYPE, 39 }, - OID_CrossCertificatePair[] = { OID_ATTR_TYPE, 40 }, - OID_Name[] = { OID_ATTR_TYPE, 41 }, - OID_GivenName[] = { OID_ATTR_TYPE, 42 }, - OID_Initials[] = { OID_ATTR_TYPE, 43 }, - OID_GenerationQualifier[] = { OID_ATTR_TYPE, 44 }, - OID_UniqueIdentifier[] = { OID_ATTR_TYPE, 45 }, - OID_DNQualifier[] = { OID_ATTR_TYPE, 46 }, - OID_EnhancedSearchGuide[] = { OID_ATTR_TYPE, 47 }, - OID_ProtocolInformation[] = { OID_ATTR_TYPE, 48 }, - OID_DistinguishedName[] = { OID_ATTR_TYPE, 49 }, - OID_UniqueMember[] = { OID_ATTR_TYPE, 50 }, - OID_HouseIdentifier[] = { OID_ATTR_TYPE, 51 } -; - -const SecAsn1Oid -CSSMOID_ObjectClass = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_ObjectClass}, -CSSMOID_AliasedEntryName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_AliasedEntryName}, -CSSMOID_KnowledgeInformation = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_KnowledgeInformation}, -CSSMOID_CommonName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_CommonName}, -CSSMOID_Surname = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Surname}, -CSSMOID_SerialNumber = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_SerialNumber}, -CSSMOID_CountryName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_CountryName}, -CSSMOID_LocalityName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_LocalityName}, -CSSMOID_StateProvinceName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_StateProvinceName}, -CSSMOID_CollectiveStateProvinceName - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveStateProvinceName}, -CSSMOID_StreetAddress = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_StreetAddress}, -CSSMOID_CollectiveStreetAddress = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveStreetAddress}, -CSSMOID_OrganizationName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_OrganizationName}, -CSSMOID_CollectiveOrganizationName - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveOrganizationName}, -CSSMOID_OrganizationalUnitName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_OrganizationalUnitName}, -CSSMOID_CollectiveOrganizationalUnitName - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveOrganizationalUnitName}, -CSSMOID_Title = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Title}, -CSSMOID_Description = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Description}, -CSSMOID_SearchGuide = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_SearchGuide}, -CSSMOID_BusinessCategory = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_BusinessCategory}, -CSSMOID_PostalAddress = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_PostalAddress}, -CSSMOID_CollectivePostalAddress = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectivePostalAddress}, -CSSMOID_PostalCode = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_PostalCode}, -CSSMOID_CollectivePostalCode = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectivePostalCode}, -CSSMOID_PostOfficeBox = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_PostOfficeBox}, -CSSMOID_CollectivePostOfficeBox = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectivePostOfficeBox}, -CSSMOID_PhysicalDeliveryOfficeName - = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_PhysicalDeliveryOfficeName}, -CSSMOID_CollectivePhysicalDeliveryOfficeName - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectivePhysicalDeliveryOfficeName}, -CSSMOID_TelephoneNumber = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_TelephoneNumber}, -CSSMOID_CollectiveTelephoneNumber - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveTelephoneNumber}, -CSSMOID_TelexNumber = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_TelexNumber}, -CSSMOID_CollectiveTelexNumber = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveTelexNumber}, -CSSMOID_TelexTerminalIdentifier = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_TelexTerminalIdentifier}, -CSSMOID_CollectiveTelexTerminalIdentifier - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveTelexTerminalIdentifier}, -CSSMOID_FacsimileTelephoneNumber= { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_FacsimileTelephoneNumber}, -CSSMOID_CollectiveFacsimileTelephoneNumber - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveFacsimileTelephoneNumber}, -CSSMOID_X_121Address = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_X_121Address}, -CSSMOID_InternationalISDNNumber = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_InternationalISDNNumber}, -CSSMOID_CollectiveInternationalISDNNumber - = { OID_ATTR_TYPE_LENGTH+2, (uint8_t *)OID_CollectiveInternationalISDNNumber}, -CSSMOID_RegisteredAddress = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_RegisteredAddress}, -CSSMOID_DestinationIndicator = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_DestinationIndicator}, -CSSMOID_PreferredDeliveryMethod = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_PreferredDeliveryMethod}, -CSSMOID_PresentationAddress = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_PresentationAddress}, -CSSMOID_SupportedApplicationContext - = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_SupportedApplicationContext}, -CSSMOID_Member = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Member}, -CSSMOID_Owner = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Owner}, -CSSMOID_RoleOccupant = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_RoleOccupant}, -CSSMOID_SeeAlso = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_SeeAlso}, -CSSMOID_UserPassword = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_UserPassword}, -CSSMOID_UserCertificate = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_UserCertificate}, -CSSMOID_CACertificate = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_CACertificate}, -CSSMOID_AuthorityRevocationList = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_AuthorityRevocationList}, -CSSMOID_CertificateRevocationList - = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_CertificateRevocationList}, -CSSMOID_CrossCertificatePair = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_CrossCertificatePair}, -CSSMOID_Name = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Name}, -CSSMOID_GivenName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_GivenName}, -CSSMOID_Initials = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_Initials}, -CSSMOID_GenerationQualifier = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_GenerationQualifier}, -CSSMOID_UniqueIdentifier = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_UniqueIdentifier}, -CSSMOID_DNQualifier = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_DNQualifier}, -CSSMOID_EnhancedSearchGuide = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_EnhancedSearchGuide}, -CSSMOID_ProtocolInformation = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_ProtocolInformation}, -CSSMOID_DistinguishedName = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_DistinguishedName}, -CSSMOID_UniqueMember = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_UniqueMember}, -CSSMOID_HouseIdentifier = { OID_ATTR_TYPE_LENGTH+1, (uint8_t *)OID_HouseIdentifier} -; - - -/* From PKCS 9 */ -static const uint8_t - OID_EmailAddress[] = { OID_PKCS_9, 1 }, - OID_UnstructuredName[] = { OID_PKCS_9, 2 }, - OID_ContentType[] = { OID_PKCS_9, 3 }, - OID_MessageDigest[] = { OID_PKCS_9, 4 }, - OID_SigningTime[] = { OID_PKCS_9, 5 }, - OID_CounterSignature[] = { OID_PKCS_9, 6 }, - OID_ChallengePassword[] = { OID_PKCS_9, 7 }, - OID_UnstructuredAddress[] = { OID_PKCS_9, 8 }, - OID_ExtendedCertificateAttributes[] = { OID_PKCS_9, 9 } -; - -const SecAsn1Oid -CSSMOID_EmailAddress = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_EmailAddress}, -CSSMOID_UnstructuredName = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_UnstructuredName}, -CSSMOID_ContentType = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_ContentType}, -CSSMOID_MessageDigest = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_MessageDigest}, -CSSMOID_SigningTime = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_SigningTime}, -CSSMOID_CounterSignature = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_CounterSignature}, -CSSMOID_ChallengePassword = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_ChallengePassword}, -CSSMOID_UnstructuredAddress = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_UnstructuredAddress}, -CSSMOID_ExtendedCertificateAttributes = {OID_PKCS_9_LENGTH+1, (uint8_t *)OID_ExtendedCertificateAttributes}; - -/* PKIX */ -static const uint8_t - OID_QT_CPS[] = { OID_QT, 1 }, - OID_QT_UNOTICE[] = { OID_QT, 2 }, - _OID_AD_OCSP[] = { OID_AD_OCSP }, - OID_AD_CA_ISSUERS[] = { OID_AD, 2 }, - OID_AD_TIME_STAMPING[] = { OID_AD, 3 }, - OID_AD_CA_REPOSITORY[] = { OID_AD, 5 }, - OID_PDA_DATE_OF_BIRTH[] = { OID_PDA, 1 }, - OID_PDA_PLACE_OF_BIRTH[] = { OID_PDA, 2 }, - OID_PDA_GENDER[] = { OID_PDA, 3 }, - OID_PDA_COUNTRY_CITIZEN[] = { OID_PDA, 4 }, - OID_PDA_COUNTRY_RESIDENCE[] = { OID_PDA, 5 }, - OID_QCS_SYNTAX_V1[] = { OID_QCS, 1 }, - OID_QCS_SYNTAX_V2[] = { OID_QCS, 2 } -; - -/* ETSI */ -static const uint8_t - OID_ETSI_QCS_QC_COMPLICANCE[] = { OID_ETSI_QCS, 1 }, - OID_ETSI_QCS_QC_LIMIT_VALUE[] = { OID_ETSI_QCS, 2 }, - __unused OID_ETSI_QCS_QC_RETENTION[] = { OID_ETSI_QCS, 3 }, - __unused OID_ETSI_QCS_QC_SSCD[] = { OID_ETSI_QCS, 4 } -; - -const SecAsn1Oid -CSSMOID_QT_CPS = {OID_QT_LENGTH+1, (uint8_t *)OID_QT_CPS}, -CSSMOID_QT_UNOTICE = {OID_QT_LENGTH+1, (uint8_t *)OID_QT_UNOTICE}, -CSSMOID_AD_OCSP = {OID_AD_LENGTH+1, (uint8_t *)_OID_AD_OCSP}, -CSSMOID_AD_CA_ISSUERS = {OID_AD_LENGTH+1, (uint8_t *)OID_AD_CA_ISSUERS}, -CSSMOID_AD_TIME_STAMPING = {OID_AD_LENGTH+1, (uint8_t *)OID_AD_TIME_STAMPING}, -CSSMOID_AD_CA_REPOSITORY = {OID_AD_LENGTH+1, (uint8_t *)OID_AD_CA_REPOSITORY}, -CSSMOID_PDA_DATE_OF_BIRTH = {OID_PDA_LENGTH+1, (uint8_t *)OID_PDA_DATE_OF_BIRTH}, -CSSMOID_PDA_PLACE_OF_BIRTH = {OID_PDA_LENGTH+1, (uint8_t *)OID_PDA_PLACE_OF_BIRTH}, -CSSMOID_PDA_GENDER = {OID_PDA_LENGTH+1, (uint8_t *)OID_PDA_GENDER}, -CSSMOID_PDA_COUNTRY_CITIZEN = {OID_PDA_LENGTH+1, (uint8_t *)OID_PDA_COUNTRY_CITIZEN}, -CSSMOID_PDA_COUNTRY_RESIDENCE = {OID_PDA_LENGTH+1, (uint8_t *)OID_PDA_COUNTRY_RESIDENCE}, -CSSMOID_OID_QCS_SYNTAX_V1 = {OID_QCS_LENGTH+1, (uint8_t *)OID_QCS_SYNTAX_V1}, -CSSMOID_OID_QCS_SYNTAX_V2 = {OID_QCS_LENGTH+1, (uint8_t *)OID_QCS_SYNTAX_V2} -; - -const SecAsn1Oid -CSSMOID_ETSI_QCS_QC_COMPLIANCE = {OID_ETSI_QCS_LENGTH + 1, - (uint8_t *)OID_ETSI_QCS_QC_COMPLICANCE}, -CSSMOID_ETSI_QCS_QC_LIMIT_VALUE = {OID_ETSI_QCS_LENGTH + 1, - (uint8_t *)OID_ETSI_QCS_QC_LIMIT_VALUE}, -CSSMOID_ETSI_QCS_QC_RETENTION = {OID_ETSI_QCS_LENGTH + 1, - (uint8_t *)OID_ETSI_QCS_QC_COMPLICANCE}, -CSSMOID_ETSI_QCS_QC_SSCD = {OID_ETSI_QCS_LENGTH + 1, - (uint8_t *)OID_ETSI_QCS_QC_COMPLICANCE} -; - -#define OID_PKCS12_BagTypes OID_PKCS_12,10,1 -#define OID_PKCS12_BagTypesLength OID_PKCS_12_LENGTH+2 - -#define ID_PKCS9_CertTypes OID_PKCS_9, 22 -#define OID_PKCS9_CertTypesLength OID_PKCS_9_LENGTH+1 -#define ID_PKCS9_CrlTypes OID_PKCS_9, 23 -#define OID_PKCS9_CrlTypesLength OID_PKCS_9_LENGTH+1 - -static const uint8_t - OID_PKCS7_Data[] = { OID_PKCS_7, 1}, - OID_PKCS7_SignedData[] = { OID_PKCS_7, 2}, - OID_PKCS7_EnvelopedData[] = { OID_PKCS_7, 3}, - OID_PKCS7_SignedAndEnvelopedData[] = { OID_PKCS_7, 4}, - OID_PKCS7_DigestedData[] = { OID_PKCS_7, 5}, - OID_PKCS7_EncryptedData[] = { OID_PKCS_7, 6}, - OID_PKCS7_DataWithAttributes[] = { OID_PKCS_7, 7}, - OID_PKCS7_EncryptedPrivateKeyInfo[] = { OID_PKCS_7, 8}, - - OID_PKCS9_FriendlyName[] = { OID_PKCS_9, 20}, - OID_PKCS9_LocalKeyId[] = { OID_PKCS_9, 21}, - OID_PKCS9_CertTypes[] = { ID_PKCS9_CertTypes }, - OID_PKCS9_CrlTypes[] = { ID_PKCS9_CrlTypes }, - OID_PKCS9_X509Certificate[] = { ID_PKCS9_CertTypes, 1 }, - OID_PKCS9_SdsiCertificate[] = { ID_PKCS9_CertTypes, 2 }, - OID_PKCS9_X509Crl[] = { ID_PKCS9_CrlTypes, 1 }, - - OID_PKCS12_keyBag[] = { OID_PKCS12_BagTypes, 1}, - OID_PKCS12_shroundedKeyBag[] = { OID_PKCS12_BagTypes, 2}, - OID_PKCS12_certBag[] = { OID_PKCS12_BagTypes, 3}, - OID_PKCS12_crlBag[] = { OID_PKCS12_BagTypes, 4}, - OID_PKCS12_secretBag[] = { OID_PKCS12_BagTypes, 5}, - OID_PKCS12_safeContentsBag[] = { OID_PKCS12_BagTypes, 6} -; - -/* - -- ContentTypes - {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)} - - -- Attributes - {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) aa(2)} - - -- eContentType for a time-stamp token - - id-ct-TSTInfo OBJECT IDENTIFIER ::= { iso(1) member-body(2) - us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1) 4} - - id-aa-timeStampToken OBJECT IDENTIFIER ::= { iso(1) member-body(2) - us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) aa(2) 14 } -*/ - -#define ID_PKCS9_SMIME OID_PKCS_9, 16 -#define OID_PKCS9_SMIMELength OID_PKCS_9_LENGTH+1 -#define ID_PKCS9_CONTENT_TYPES ID_PKCS9_SMIME, 1 -#define OID_PKCS9_CT_Length OID_PKCS9_SMIMELength+1 -#define ID_PKCS9_ATTRIBUTES ID_PKCS9_SMIME, 2 -#define OID_PKCS9_Attrs_Length OID_PKCS9_SMIMELength+1 - -static const uint8_t - OID_ID_CT_TSTInfo[] = { ID_PKCS9_CONTENT_TYPES, 4 }, - OID_TimeStampToken[] = { ID_PKCS9_ATTRIBUTES, 14 }; - -const SecAsn1Oid -CSSMOID_PKCS9_Id_Ct_TSTInfo = {OID_PKCS9_CT_Length + 1, - (uint8_t *)OID_ID_CT_TSTInfo }, -CSSMOID_PKCS9_TimeStampToken = {OID_PKCS9_Attrs_Length + 1, - (uint8_t *)OID_TimeStampToken }; - - -const SecAsn1Oid -CSSMOID_PKCS7_Data = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_Data }, -CSSMOID_PKCS7_SignedData = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_SignedData }, -CSSMOID_PKCS7_EnvelopedData = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_EnvelopedData }, -CSSMOID_PKCS7_SignedAndEnvelopedData = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_SignedAndEnvelopedData }, -CSSMOID_PKCS7_DigestedData = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_DigestedData }, -CSSMOID_PKCS7_EncryptedData = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_EncryptedData }, -CSSMOID_PKCS7_DataWithAttributes = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_DataWithAttributes }, -CSSMOID_PKCS7_EncryptedPrivateKeyInfo = {OID_PKCS_7_LENGTH + 1, - (uint8_t *)OID_PKCS7_EncryptedPrivateKeyInfo }, - -CSSMOID_PKCS9_FriendlyName = {OID_PKCS_9_LENGTH + 1, - (uint8_t *)OID_PKCS9_FriendlyName }, -CSSMOID_PKCS9_LocalKeyId = {OID_PKCS_9_LENGTH + 1, - (uint8_t *)OID_PKCS9_LocalKeyId }, -CSSMOID_PKCS9_CertTypes = {OID_PKCS_9_LENGTH + 1, - (uint8_t *)OID_PKCS9_CertTypes }, -CSSMOID_PKCS9_CrlTypes = {OID_PKCS_9_LENGTH + 1, - (uint8_t *)OID_PKCS9_CrlTypes }, -CSSMOID_PKCS9_X509Certificate = {OID_PKCS9_CertTypesLength + 1, - (uint8_t *)OID_PKCS9_X509Certificate }, -CSSMOID_PKCS9_SdsiCertificate = {OID_PKCS9_CertTypesLength + 1, - (uint8_t *)OID_PKCS9_SdsiCertificate }, -CSSMOID_PKCS9_X509Crl = {OID_PKCS9_CrlTypesLength + 1, - (uint8_t *)OID_PKCS9_X509Crl }, - - -CSSMOID_PKCS12_keyBag = {OID_PKCS12_BagTypesLength + 1, - (uint8_t *)OID_PKCS12_keyBag }, -CSSMOID_PKCS12_shroudedKeyBag = {OID_PKCS12_BagTypesLength + 1, - (uint8_t *)OID_PKCS12_shroundedKeyBag }, -CSSMOID_PKCS12_certBag = {OID_PKCS12_BagTypesLength + 1, - (uint8_t *)OID_PKCS12_certBag }, -CSSMOID_PKCS12_crlBag = {OID_PKCS12_BagTypesLength + 1, - (uint8_t *)OID_PKCS12_crlBag }, -CSSMOID_PKCS12_secretBag = {OID_PKCS12_BagTypesLength + 1, - (uint8_t *)OID_PKCS12_secretBag }, -CSSMOID_PKCS12_safeContentsBag = {OID_PKCS12_BagTypesLength + 1, - (uint8_t *)OID_PKCS12_safeContentsBag } - -; - -/* Kerberos PKINIT CMS ContentInfo types */ - -static const uint8_t - OID_KERBv5_PKINIT_AUTH_DATA[] = { OID_KERBv5_PKINIT, 1 }, - OID_KERBv5_PKINIT_DH_KEY_DATA[] = { OID_KERBv5_PKINIT, 2 }, - OID_KERBv5_PKINIT_RKEY_DATA[] = { OID_KERBv5_PKINIT, 3 }; - -const SecAsn1Oid -CSSMOID_KERBv5_PKINIT_AUTH_DATA = { OID_KERBv5_PKINIT_LEN + 1, - (uint8_t *)OID_KERBv5_PKINIT_AUTH_DATA }, -CSSMOID_KERBv5_PKINIT_DH_KEY_DATA = { OID_KERBv5_PKINIT_LEN + 1, - (uint8_t *)OID_KERBv5_PKINIT_DH_KEY_DATA }, -CSSMOID_KERBv5_PKINIT_RKEY_DATA = { OID_KERBv5_PKINIT_LEN + 1, - (uint8_t *)OID_KERBv5_PKINIT_RKEY_DATA }; - -/* - * Additional OIDS for LDAP support - */ - -static const uint8_t - OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_USERID_Data[] = {OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_USERID}; - -const SecAsn1Oid -CSSMOID_UserID = {OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_USERID_LENGTH, (uint8_t *)OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_USERID_Data}; - -static const uint8_t - OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_DOMAINCOMPONENT_Data[] = {OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_DOMAINCOMPONENT}; - -const SecAsn1Oid -CSSMOID_DomainComponent = {OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_DOMAINCOMPONENT_LENGTH, (uint8_t *)OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_DOMAINCOMPONENT_Data}; - -/* ANSI X9.62 and Certicom elliptic curve OIDs */ -static const uint8_t - OID_X9_62[] = { OID_ANSI_X9_62 }, - OID_X9_62_FieldType[] = { OID_ANSI_X9_62_FIELD_TYPE }, - OID_X9_62_PubKeyType[] = { OID_ANSI_X9_62_PUBKEY_TYPE }, - OID_X9_62_EllCurve[] = { OID_ANSI_X9_62_ELL_CURVE }, - OID_X9_62_C_TwoCurve[] = { OID_ANSI_X9_62_C_TWO_CURVE }, - OID_X9_62_PrimeCurve[] = { OID_ANSI_X9_62_PRIME_CURVE }, - OID_X9_62_SigType[] = { OID_ANSI_X9_62_SIG_TYPE }, - - /* these two defined in ANSI X9.62 but renamed in common usage */ - OID_secp192r1[] = { OID_ANSI_X9_62_PRIME_CURVE, 1 }, - OID_secp256r1[] = { OID_ANSI_X9_62_PRIME_CURVE, 7 }, - /* remainder defined in Certicom SEC 2 */ - OID_Certicom[] = { OID_CERTICOM }, - OID_CerticomEllCurve[] = { OID_CERTICOM_ELL_CURVE }, - /* curves over prime-order fields */ - OID_secp112r1[] = { OID_CERTICOM_ELL_CURVE, 6 }, - OID_secp112r2[] = { OID_CERTICOM_ELL_CURVE, 7 }, - OID_secp128r1[] = { OID_CERTICOM_ELL_CURVE, 28 }, - OID_secp128r2[] = { OID_CERTICOM_ELL_CURVE, 29 }, - OID_secp160k1[] = { OID_CERTICOM_ELL_CURVE, 9 }, - OID_secp160r1[] = { OID_CERTICOM_ELL_CURVE, 8 }, - OID_secp160r2[] = { OID_CERTICOM_ELL_CURVE, 30 }, - OID_secp192k1[] = { OID_CERTICOM_ELL_CURVE, 31 }, - OID_secp224k1[] = { OID_CERTICOM_ELL_CURVE, 32 }, - OID_secp224r1[] = { OID_CERTICOM_ELL_CURVE, 33 }, - OID_secp256k1[] = { OID_CERTICOM_ELL_CURVE, 10 }, - OID_secp384r1[] = { OID_CERTICOM_ELL_CURVE, 34 }, - OID_secp521r1[] = { OID_CERTICOM_ELL_CURVE, 35 }, - /* curves over characteristic 2 fields */ - OID_sect113r1[] = { OID_CERTICOM_ELL_CURVE, 4 }, - OID_sect113r2[] = { OID_CERTICOM_ELL_CURVE, 5 }, - OID_sect131r1[] = { OID_CERTICOM_ELL_CURVE, 22 }, - OID_sect131r2[] = { OID_CERTICOM_ELL_CURVE, 23 }, - OID_sect163k1[] = { OID_CERTICOM_ELL_CURVE, 1 }, - OID_sect163r1[] = { OID_CERTICOM_ELL_CURVE, 2 }, - OID_sect163r2[] = { OID_CERTICOM_ELL_CURVE, 15 }, - OID_sect193r1[] = { OID_CERTICOM_ELL_CURVE, 24 }, - OID_sect193r2[] = { OID_CERTICOM_ELL_CURVE, 25 }, - OID_sect233k1[] = { OID_CERTICOM_ELL_CURVE, 26 }, - OID_sect233r1[] = { OID_CERTICOM_ELL_CURVE, 27 }, - OID_sect239k1[] = { OID_CERTICOM_ELL_CURVE, 3 }, - OID_sect283k1[] = { OID_CERTICOM_ELL_CURVE, 16 }, - OID_sect283r1[] = { OID_CERTICOM_ELL_CURVE, 17 }, - OID_sect409k1[] = { OID_CERTICOM_ELL_CURVE, 36 }, - OID_sect409r1[] = { OID_CERTICOM_ELL_CURVE, 37 }, - OID_sect571k1[] = { OID_CERTICOM_ELL_CURVE, 38 }, - OID_sect571r1[] = { OID_CERTICOM_ELL_CURVE, 39 } -; - -const SecAsn1Oid - CSSMOID_X9_62 = {OID_ANSI_X9_42_LEN, (uint8_t *)OID_X9_62 }, - CSSMOID_X9_62_FieldType = {OID_ANSI_X9_42_LEN+1, (uint8_t *)OID_X9_62_FieldType }, - CSSMOID_X9_62_PubKeyType = {OID_ANSI_X9_42_LEN+1, (uint8_t *)OID_X9_62_PubKeyType }, - CSSMOID_X9_62_EllCurve = {OID_ANSI_X9_42_LEN+1, (uint8_t *)OID_X9_62_EllCurve }, - CSSMOID_X9_62_C_TwoCurve = {OID_ANSI_X9_62_ELL_CURVE_LEN+1, (uint8_t *)OID_X9_62_C_TwoCurve }, - CSSMOID_X9_62_PrimeCurve = {OID_ANSI_X9_62_ELL_CURVE_LEN+1, (uint8_t *)OID_X9_62_PrimeCurve }, - CSSMOID_X9_62_SigType = {OID_ANSI_X9_42_LEN+1, (uint8_t *)OID_X9_62_SigType }, - CSSMOID_secp192r1 = {OID_ANSI_X9_62_ELL_CURVE_LEN+2, (uint8_t *)OID_secp192r1 }, - CSSMOID_secp256r1 = {OID_ANSI_X9_62_ELL_CURVE_LEN+2, (uint8_t *)OID_secp256r1 }, - CSSMOID_Certicom = {OID_CERTICOM_LEN, (uint8_t *)OID_Certicom }, - CSSMOID_CerticomEllCurve = {OID_CERTICOM_ELL_CURVE_LEN, (uint8_t *)OID_CerticomEllCurve }, - CSSMOID_secp112r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp112r1 }, - CSSMOID_secp112r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp112r2 }, - CSSMOID_secp128r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp128r1 }, - CSSMOID_secp128r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp128r2 }, - CSSMOID_secp160k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp160k1 }, - CSSMOID_secp160r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp160r1 }, - CSSMOID_secp160r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp160r2 }, - CSSMOID_secp192k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp192k1 }, - CSSMOID_secp224k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp224k1 }, - CSSMOID_secp224r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp224r1 }, - CSSMOID_secp256k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp256k1 }, - CSSMOID_secp384r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp384r1 }, - CSSMOID_secp521r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_secp521r1 }, - CSSMOID_sect113r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect113r1 }, - CSSMOID_sect113r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect113r2 }, - CSSMOID_sect131r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect131r1 }, - CSSMOID_sect131r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect131r2 }, - CSSMOID_sect163k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect163k1 }, - CSSMOID_sect163r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect163r1 }, - CSSMOID_sect163r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect163r2 }, - CSSMOID_sect193r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect193r1 }, - CSSMOID_sect193r2 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect193r2 }, - CSSMOID_sect233k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect233k1 }, - CSSMOID_sect233r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect233r1 }, - CSSMOID_sect239k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect239k1 }, - CSSMOID_sect283k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect283k1 }, - CSSMOID_sect283r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect283r1 }, - CSSMOID_sect409k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect409k1 }, - CSSMOID_sect409r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect409r1 }, - CSSMOID_sect571k1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect571k1 }, - CSSMOID_sect571r1 = {OID_CERTICOM_ELL_CURVE_LEN+1, (uint8_t *)OID_sect571r1 }; diff --git a/OSX/include/security_asn1/oidsattr.h b/OSX/include/security_asn1/oidsattr.h deleted file mode 100644 index 10ced8e8..00000000 --- a/OSX/include/security_asn1/oidsattr.h +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 1999-2001,2003-2004,2008,2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * oidsattr.h -- Cert/CRL related OIDs. - */ - -#include -#include - -#ifndef _CDSA_OIDSATTR_H_ -#define _CDSA_OIDSATTR_H_ - -/* - * Directory name component identifiers. - */ -extern const SecAsn1Oid - CSSMOID_ObjectClass DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_AliasedEntryName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_KnowledgeInformation DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CommonName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Surname DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SerialNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CountryName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_LocalityName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_StateProvinceName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveStateProvinceName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_StreetAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveStreetAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_OrganizationName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveOrganizationName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_OrganizationalUnitName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveOrganizationalUnitName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Title DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Description DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SearchGuide DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_BusinessCategory DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PostalAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectivePostalAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PostalCode DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectivePostalCode DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PostOfficeBox DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectivePostOfficeBox DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PhysicalDeliveryOfficeName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectivePhysicalDeliveryOfficeName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_TelephoneNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveTelephoneNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_TelexNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveTelexNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_TelexTerminalIdentifier DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveTelexTerminalIdentifier DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_FacsimileTelephoneNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveFacsimileTelephoneNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X_121Address DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_InternationalISDNNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CollectiveInternationalISDNNumber DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_RegisteredAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DestinationIndicator DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PreferredDeliveryMethod DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PresentationAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SupportedApplicationContext DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Member DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Owner DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_RoleOccupant DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SeeAlso DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_UserPassword DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_UserCertificate DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CACertificate DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_AuthorityRevocationList DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CertificateRevocationList DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CrossCertificatePair DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Name DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_GivenName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Initials DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_GenerationQualifier DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_UniqueIdentifier DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DNQualifier DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_EnhancedSearchGuide DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ProtocolInformation DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_DistinguishedName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_UniqueMember DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_HouseIdentifier DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/* PKCS 9 */ -extern const SecAsn1Oid - CSSMOID_EmailAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_UnstructuredName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ContentType DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_MessageDigest DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_SigningTime DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CounterSignature DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ChallengePassword DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_UnstructuredAddress DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ExtendedCertificateAttributes DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -extern const SecAsn1Oid - CSSMOID_PKCS9_Id_Ct_TSTInfo DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_TimeStampToken DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/* PKIX */ -extern const SecAsn1Oid - CSSMOID_QT_CPS DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_QT_UNOTICE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_AD_OCSP DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_AD_CA_ISSUERS DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_AD_TIME_STAMPING DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_AD_CA_REPOSITORY DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PDA_DATE_OF_BIRTH DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PDA_PLACE_OF_BIRTH DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PDA_GENDER DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PDA_COUNTRY_CITIZEN DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PDA_COUNTRY_RESIDENCE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_OID_QCS_SYNTAX_V1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_OID_QCS_SYNTAX_V2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/* ETSI */ -extern const SecAsn1Oid - CSSMOID_ETSI_QCS_QC_COMPLIANCE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ETSI_QCS_QC_LIMIT_VALUE DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ETSI_QCS_QC_RETENTION DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_ETSI_QCS_QC_SSCD DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/* PKCS7 */ -extern const SecAsn1Oid - CSSMOID_PKCS7_Data DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_SignedData DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_EnvelopedData DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_SignedAndEnvelopedData DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_DigestedData DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_EncryptedData DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_DataWithAttributes DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS7_EncryptedPrivateKeyInfo DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - -/* PKCS8 */ - CSSMOID_PKCS9_FriendlyName DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_LocalKeyId DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_CertTypes DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_CrlTypes DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_X509Certificate DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_SdsiCertificate DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS9_X509Crl DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - -/* PKCS12 */ - CSSMOID_PKCS12_keyBag DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_shroudedKeyBag DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_certBag DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_crlBag DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_secretBag DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_PKCS12_safeContentsBag DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - -/* RFC 2798 (LDAP) */ - CSSMOID_UserID DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - -/* RFC 1275 (X.500) */ - CSSMOID_DomainComponent DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - -/* Kerberos PKINIT CMS ContentInfo types */ - CSSMOID_KERBv5_PKINIT_AUTH_DATA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_KERBv5_PKINIT_DH_KEY_DATA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_KERBv5_PKINIT_RKEY_DATA DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/* Elliptic Curve OIDs from X9.62 and Certicom SEC 2 */ -extern const SecAsn1Oid - CSSMOID_X9_62 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X9_62_FieldType DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X9_62_PubKeyType DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X9_62_EllCurve DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X9_62_C_TwoCurve DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X9_62_PrimeCurve DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_X9_62_SigType DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp192r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp256r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_Certicom DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_CerticomEllCurve DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp112r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp112r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp128r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp128r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp160k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp160r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp160r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp192k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp224k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp224r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp256k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp384r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_secp521r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect113r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect113r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect131r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect131r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect163k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect163r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect163r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect193r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect193r2 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect233k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect233r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect239k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect283k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect283r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect409k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect409r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect571k1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER, - CSSMOID_sect571r1 DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -#endif /* _CDSA_OIDSATTR_H_*/ diff --git a/OSX/include/security_asn1/oidsbase.h b/OSX/include/security_asn1/oidsbase.h deleted file mode 100644 index 4f723a47..00000000 --- a/OSX/include/security_asn1/oidsbase.h +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright (c) 1999-2001,2003-2004,2008-2010,2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * oidsbase.h -- Basic Object Identifier Macros and Data Types. - */ - -#include "SecAsn1Types.h" - -#ifndef _OIDSBASE_H_ -#define _OIDSBASE_H_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#define SECASN1OID_DEF(NAME, VALUE, ARGS...) \ -static const uint8_t _##NAME[] = { VALUE, ## ARGS }; \ -const SecAsn1Oid NAME = { sizeof(_##NAME), (uint8_t *)_##NAME } - -/* Intel CSSM */ - -#define INTEL 96, 134, 72, 1, 134, 248, 77 -#define INTEL_LENGTH 7 - -#define INTEL_CDSASECURITY INTEL, 2 -#define INTEL_CDSASECURITY_LENGTH (INTEL_LENGTH + 1) - -#define INTEL_SEC_FORMATS INTEL_CDSASECURITY, 1 -#define INTEL_SEC_FORMATS_LENGTH (INTEL_CDSASECURITY_LENGTH + 1) - -#define INTEL_SEC_ALGS INTEL_CDSASECURITY, 2, 5 -#define INTEL_SEC_ALGS_LENGTH (INTEL_CDSASECURITY_LENGTH + 2) - -#define INTEL_SEC_OBJECT_BUNDLE INTEL_SEC_FORMATS, 4 -#define INTEL_SEC_OBJECT_BUNDLE_LENGTH (INTEL_SEC_FORMATS_LENGTH + 1) - -#define INTEL_CERT_AND_PRIVATE_KEY_2_0 INTEL_SEC_OBJECT_BUNDLE, 1 -#define INTEL_CERT_AND_PRIVATE_KEY_2_0_LENGTH (INTEL_SEC_OBJECT_BUNDLE_LENGTH + 1) - -/* Suffix specifying format or representation of a field value */ -/* Note that if a format suffix is not specified, a flat data -representation is implied */ -#define INTEL_X509_C_DATATYPE 1 -#define INTEL_X509_LDAPSTRING_DATATYPE 2 - -#define OID_ISO_CCITT_DIR_SERVICE 85 -#define OID_DS OID_ISO_CCITT_DIR_SERVICE -#define OID_DS_LENGTH 1 -#define OID_ATTR_TYPE OID_DS, 4 -#define OID_ATTR_TYPE_LENGTH OID_DS_LENGTH + 1 -#define OID_EXTENSION OID_DS, 29 -#define OID_EXTENSION_LENGTH OID_DS_LENGTH + 1 -#define OID_ISO_STANDARD 40 -#define OID_ISO_MEMBER 42 -#define OID_US OID_ISO_MEMBER, 134, 72 - -#define OID_ISO_IDENTIFIED_ORG 43 -#define OID_OSINET OID_ISO_IDENTIFIED_ORG, 4 -#define OID_GOSIP OID_ISO_IDENTIFIED_ORG, 5 -#define OID_DOD OID_ISO_IDENTIFIED_ORG, 6 -#define OID_OIW OID_ISO_IDENTIFIED_ORG, 14 - -#define OID_ITU_RFCDATA_MEMBER_LENGTH 1 -#define OID_ITU_RFCDATA 9 - -/* From the PKCS Standards */ -#define OID_ISO_MEMBER_LENGTH 1 -#define OID_US_LENGTH OID_ISO_MEMBER_LENGTH + 2 -#define OID_RSA OID_US, 134, 247, 13 -#define OID_RSA_LENGTH OID_US_LENGTH + 3 -#define OID_RSA_HASH OID_RSA, 2 -#define OID_RSA_HASH_LENGTH OID_RSA_LENGTH + 1 -#define OID_RSA_ENCRYPT OID_RSA, 3 -#define OID_RSA_ENCRYPT_LENGTH OID_RSA_LENGTH + 1 -#define OID_PKCS OID_RSA, 1 -#define OID_PKCS_LENGTH OID_RSA_LENGTH +1 -#define OID_PKCS_1 OID_PKCS, 1 -#define OID_PKCS_1_LENGTH OID_PKCS_LENGTH +1 -#define OID_PKCS_2 OID_PKCS, 2 -#define OID_PKCS_3 OID_PKCS, 3 -#define OID_PKCS_3_LENGTH OID_PKCS_LENGTH +1 -#define OID_PKCS_4 OID_PKCS, 4 -#define OID_PKCS_5 OID_PKCS, 5 -#define OID_PKCS_5_LENGTH OID_PKCS_LENGTH +1 -#define OID_PKCS_6 OID_PKCS, 6 -#define OID_PKCS_7 OID_PKCS, 7 -#define OID_PKCS_7_LENGTH OID_PKCS_LENGTH +1 -#define OID_PKCS_8 OID_PKCS, 8 -#define OID_PKCS_9 OID_PKCS, 9 -#define OID_PKCS_9_LENGTH OID_PKCS_LENGTH +1 -#define OID_PKCS_10 OID_PKCS, 10 -#define OID_PKCS_11 OID_PKCS, 11 -#define OID_PKCS_11_LENGTH OID_PKCS_LENGTH +1 -#define OID_PKCS_12 OID_PKCS, 12 -#define OID_PKCS_12_LENGTH OID_PKCS_LENGTH +1 - -/* ANSI X9.42 */ -#define OID_ANSI_X9_42 OID_US, 206, 62, 2 -#define OID_ANSI_X9_42_LEN OID_US_LENGTH + 3 -#define OID_ANSI_X9_42_SCHEME OID_ANSI_X9_42, 3 -#define OID_ANSI_X9_42_SCHEME_LEN OID_ANSI_X9_42_LEN + 1 -#define OID_ANSI_X9_42_NAMED_SCHEME OID_ANSI_X9_42, 4 -#define OID_ANSI_X9_42_NAMED_SCHEME_LEN OID_ANSI_X9_42_LEN + 1 - -/* ANSI X9.62 (1 2 840 10045) */ -#define OID_ANSI_X9_62 0x2A, 0x86, 0x48, 0xCE, 0x3D -#define OID_ANSI_X9_62_LEN 5 -#define OID_ANSI_X9_62_FIELD_TYPE OID_ANSI_X9_62, 1 -#define OID_ANSI_X9_62_PUBKEY_TYPE OID_ANSI_X9_62, 2 -#define OID_ANSI_X9_62_ELL_CURVE OID_ANSI_X9_62, 3 -#define OID_ANSI_X9_62_ELL_CURVE_LEN OID_ANSI_X9_62_LEN+1 -#define OID_ANSI_X9_62_C_TWO_CURVE OID_ANSI_X9_62_ELL_CURVE, 0 -#define OID_ANSI_X9_62_PRIME_CURVE OID_ANSI_X9_62_ELL_CURVE, 1 -#define OID_ANSI_X9_62_SIG_TYPE OID_ANSI_X9_62, 4 -#define OID_ANSI_X9_62_SIG_TYPE_LEN OID_ANSI_X9_62_LEN+1 - -/* PKIX */ -#define OID_PKIX OID_DOD, 1, 5, 5, 7 -#define OID_PKIX_LENGTH 6 -#define OID_PE OID_PKIX, 1 -#define OID_PE_LENGTH OID_PKIX_LENGTH + 1 -#define OID_QT OID_PKIX, 2 -#define OID_QT_LENGTH OID_PKIX_LENGTH + 1 -#define OID_KP OID_PKIX, 3 -#define OID_KP_LENGTH OID_PKIX_LENGTH + 1 -#define OID_OTHER_NAME OID_PKIX, 8 -#define OID_OTHER_NAME_LENGTH OID_PKIX_LENGTH + 1 -#define OID_PDA OID_PKIX, 9 -#define OID_PDA_LENGTH OID_PKIX_LENGTH + 1 -#define OID_QCS OID_PKIX, 11 -#define OID_QCS_LENGTH OID_PKIX_LENGTH + 1 -#define OID_AD OID_PKIX, 48 -#define OID_AD_LENGTH OID_PKIX_LENGTH + 1 -#define OID_AD_OCSP OID_AD, 1 -#define OID_AD_OCSP_LENGTH OID_AD_LENGTH + 1 - -/* ETSI */ -#define OID_ETSI 0x04, 0x00 -#define OID_ETSI_LENGTH 2 -#define OID_ETSI_QCS 0x04, 0x00, 0x8E, 0x46, 0x01 -#define OID_ETSI_QCS_LENGTH 5 - -#define OID_OIW_SECSIG OID_OIW, 3 -#define OID_OIW_LENGTH 2 -#define OID_OIW_SECSIG_LENGTH OID_OIW_LENGTH +1 - -#define OID_OIW_ALGORITHM OID_OIW_SECSIG, 2 -#define OID_OIW_ALGORITHM_LENGTH OID_OIW_SECSIG_LENGTH +1 - -/* NIST defined digest algorithm arc (2, 16, 840, 1, 101, 3, 4, 2) */ -#define OID_NIST_HASHALG 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02 -#define OID_NIST_HASHALG_LENGTH 8 - -/* Kerberos PKINIT */ -#define OID_KERBv5 0x2b, 6, 1, 5, 2 -#define OID_KERBv5_LEN 5 -#define OID_KERBv5_PKINIT OID_KERBv5, 3 -#define OID_KERBv5_PKINIT_LEN OID_KERBv5_LEN + 1 - -/* Certicom (1 3 132) */ -#define OID_CERTICOM 0x2B, 0x81, 0x04 -#define OID_CERTICOM_LEN 3 -#define OID_CERTICOM_ELL_CURVE OID_CERTICOM, 0 -#define OID_CERTICOM_ELL_CURVE_LEN OID_CERTICOM_LEN+1 - -/* - * Apple-specific OID bases - */ - -/* - * apple OBJECT IDENTIFIER ::= - * { iso(1) member-body(2) US(840) 113635 } - * - * BER = 06 06 2A 86 48 86 F7 63 - */ -#define APPLE_OID OID_US, 0x86, 0xf7, 0x63 -#define APPLE_OID_LENGTH OID_US_LENGTH + 3 - -/* appleDataSecurity OBJECT IDENTIFIER ::= - * { apple 100 } - * { 1 2 840 113635 100 } - * - * BER = 06 07 2A 86 48 86 F7 63 64 - */ -#define APPLE_ADS_OID APPLE_OID, 0x64 -#define APPLE_ADS_OID_LENGTH APPLE_OID_LENGTH + 1 - -/* - * appleTrustPolicy OBJECT IDENTIFIER ::= - * { appleDataSecurity 1 } - * { 1 2 840 113635 100 1 } - * - * BER = 06 08 2A 86 48 86 F7 63 64 01 - */ -#define APPLE_TP_OID APPLE_ADS_OID, 1 -#define APPLE_TP_OID_LENGTH APPLE_ADS_OID_LENGTH + 1 - -/* - * appleSecurityAlgorithm OBJECT IDENTIFIER ::= - * { appleDataSecurity 2 } - * { 1 2 840 113635 100 2 } - * - * BER = 06 08 2A 86 48 86 F7 63 64 02 - */ -#define APPLE_ALG_OID APPLE_ADS_OID, 2 -#define APPLE_ALG_OID_LENGTH APPLE_ADS_OID_LENGTH + 1 - -/* - * appleDotMacCertificate OBJECT IDENTIFIER ::= - * { appleDataSecurity 3 } - * { 1 2 840 113635 100 3 } - */ -#define APPLE_DOTMAC_CERT_OID APPLE_ADS_OID, 3 -#define APPLE_DOTMAC_CERT_OID_LENGTH APPLE_ADS_OID_LENGTH + 1 - -/* - * Basis of Policy OIDs for .mac TP requests - * - * dotMacCertificateRequest OBJECT IDENTIFIER ::= - * { appleDotMacCertificate 1 } - * { 1 2 840 113635 100 3 1 } - */ -#define APPLE_DOTMAC_CERT_REQ_OID APPLE_DOTMAC_CERT_OID, 1 -#define APPLE_DOTMAC_CERT_REQ_OID_LENGTH APPLE_DOTMAC_CERT_OID_LENGTH + 1 - -/* - * Basis of .mac Certificate Extensions - * - * dotMacCertificateExtension OBJECT IDENTIFIER ::= - * { appleDotMacCertificate 2 } - * { 1 2 840 113635 100 3 2 } - */ -#define APPLE_DOTMAC_CERT_EXTEN_OID APPLE_DOTMAC_CERT_OID, 2 -#define APPLE_DOTMAC_CERT_EXTEN_OID_LENGTH APPLE_DOTMAC_CERT_OID_LENGTH + 1 - -/* - * Basis of .mac Certificate request OID/value identifiers - * - * dotMacCertificateRequestValues OBJECT IDENTIFIER ::= - * { appleDotMacCertificate 3 } - * { 1 2 840 113635 100 3 3 } - */ -#define APPLE_DOTMAC_CERT_REQ_VALUE_OID APPLE_DOTMAC_CERT_OID, 3 -#define APPLE_DOTMAC_CERT_REQ_VALUE_OID_LENGTH APPLE_DOTMAC_CERT_OID_LENGTH + 1 - -/* - * Basis of Apple-specific extended key usages - * - * appleExtendedKeyUsage OBJECT IDENTIFIER ::= - * { appleDataSecurity 4 } - * { 1 2 840 113635 100 4 } - */ -#define APPLE_EKU_OID APPLE_ADS_OID, 4 -#define APPLE_EKU_OID_LENGTH APPLE_ADS_OID_LENGTH + 1 - -/* - * Basis of Apple Code Signing extended key usages - * appleCodeSigning OBJECT IDENTIFIER ::= - * { appleExtendedKeyUsage 1 } - * { 1 2 840 113635 100 4 1 } - */ -#define APPLE_EKU_CODE_SIGNING APPLE_EKU_OID, 1 -#define APPLE_EKU_CODE_SIGNING_LENGTH APPLE_EKU_OID_LENGTH + 1 - -/* - * Basis of Apple-specific Certificate Policy identifiers - * appleCertificatePolicies OBJECT IDENTIFIER ::= - * { appleDataSecurity 5 } - * { 1 2 840 113635 100 5 } - */ -#define APPLE_CERT_POLICIES APPLE_ADS_OID, 5 -#define APPLE_CERT_POLICIES_LENGTH APPLE_ADS_OID_LENGTH + 1 - -/* - * Basis of Apple-specific certificate extensions - * appleCertificateExtensions OBJECT IDENTIFIER ::= - * { appleDataSecurity 6 } - * { 1 2 840 113635 100 6 } - */ -#define APPLE_EXTENSION_OID APPLE_ADS_OID, 6 -#define APPLE_EXTENSION_OID_LENGTH APPLE_ADS_OID_LENGTH + 1 - -/* - * Basis of Apple-specific Code Signing certificate extensions - * appleCertificateExtensionCodeSigning OBJECT IDENTIFIER ::= - * { appleCertificateExtensions 1 } - * { 1 2 840 113635 100 6 1 } - */ -#define APPLE_EXTENSION_CODE_SIGNING APPLE_EXTENSION_OID, 1 -#define APPLE_EXTENSION_CODE_SIGNING_LENGTH APPLE_EXTENSION_OID_LENGTH + 1 - -/* - * Netscape OIDs. - */ -#define NETSCAPE_BASE_OID 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42 -#define NETSCAPE_BASE_OID_LEN 7 - -/* - * Netscape cert extension. - * - * netscape-cert-extension OBJECT IDENTIFIER ::= - * { 2 16 840 1 113730 1 } - * - * BER = 06 08 60 86 48 01 86 F8 42 01 - */ -#define NETSCAPE_CERT_EXTEN NETSCAPE_BASE_OID, 0x01 -#define NETSCAPE_CERT_EXTEN_LENGTH NETSCAPE_BASE_OID_LEN + 1 - -#define NETSCAPE_CERT_POLICY NETSCAPE_BASE_OID, 0x04 -#define NETSCAPE_CERT_POLICY_LENGTH NETSCAPE_BASE_OID_LEN + 1 - - -/* Google OIDs: 1.3.6.1.4.1.11129. */ -#define GOOGLE_BASE_OID OID_DOD, 0x01, 0x04, 0x01, 0xD6, 0x79 -#define GOOGLE_BASE_OID_LEN OID_DOD_LEN + 5 -#define GOOGLE_EMBEDDED_SCT_OID GOOGLE_BASE_OID, 0x02, 0x04, 0x02 -#define GOOGLE_OCSP_SCT_OID GOOGLE_BASE_OID, 0x02, 0x04, 0x05 - -/* - * Domain Component OID - */ -#define OID_ITU_RFCDATA_2342 OID_ITU_RFCDATA, 0x49, 0x86 -#define OID_ITU_RFCDATA_2342_LENGTH OID_ITU_RFCDATA_MEMBER_LENGTH + 2 - -#define OID_ITU_RFCDATA_2342_UCL OID_ITU_RFCDATA_2342, 0x49, 0x1F, 0x12, 0x8C -#define OID_ITU_RFCDATA_2342_UCL_LENGTH OID_ITU_RFCDATA_2342_LENGTH + 4 - -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT OID_ITU_RFCDATA_2342_UCL, 0xE4 -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_LENGTH OID_ITU_RFCDATA_2342_UCL_LENGTH + 1 - -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT, 0x81 -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_LENGTH OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_LENGTH + 1 - -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_DOMAINCOMPONENT OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES, 0x99 -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_DOMAINCOMPONENT_LENGTH OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_LENGTH + 1 - -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_USERID OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES, 0x81 -#define OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_USERID_LENGTH OID_ITU_RFCDATA_2342_UCL_DIRECTORYPILOT_ATTRIBUTES_LENGTH + 1 - -#ifdef __cplusplus -} -#endif - -#endif /* _OIDSBASE_H_ */ diff --git a/OSX/include/security_asn1/oidsocsp.c b/OSX/include/security_asn1/oidsocsp.c deleted file mode 100644 index bb08e125..00000000 --- a/OSX/include/security_asn1/oidsocsp.c +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2009-2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - File: oidsocsp.cpp - - Contains: Object Identifiers for OCSP - */ - -#include "oidsbase.h" -#include "oidsocsp.h" - -SECASN1OID_DEF(OID_PKIX_OCSP, OID_AD_OCSP); -SECASN1OID_DEF(OID_PKIX_OCSP_BASIC, OID_AD_OCSP, 1); -SECASN1OID_DEF(OID_PKIX_OCSP_NONCE, OID_AD_OCSP, 2); -SECASN1OID_DEF(OID_PKIX_OCSP_CRL, OID_AD_OCSP, 3); -SECASN1OID_DEF(OID_PKIX_OCSP_RESPONSE, OID_AD_OCSP, 4); -SECASN1OID_DEF(OID_PKIX_OCSP_NOCHECK, OID_AD_OCSP, 5); -SECASN1OID_DEF(OID_PKIX_OCSP_ARCHIVE_CUTOFF, OID_AD_OCSP, 6); -SECASN1OID_DEF(OID_PKIX_OCSP_SERVICE_LOCATOR, OID_AD_OCSP, 7); - -SECASN1OID_DEF(OID_GOOGLE_OCSP_SCT, GOOGLE_OCSP_SCT_OID); diff --git a/OSX/include/security_asn1/oidsocsp.h b/OSX/include/security_asn1/oidsocsp.h deleted file mode 100644 index 82dde8f9..00000000 --- a/OSX/include/security_asn1/oidsocsp.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2009-2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * oidsocsp.h -- Object Identifiers for OCSP - */ - -#ifndef _OIDSOCSP_H_ -#define _OIDSOCSP_H_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -#include "SecAsn1Types.h" - -extern const SecAsn1Oid - /* OCSP */ - OID_PKIX_OCSP, - OID_PKIX_OCSP_BASIC, - OID_PKIX_OCSP_NONCE, - OID_PKIX_OCSP_CRL, - OID_PKIX_OCSP_RESPONSE, - OID_PKIX_OCSP_NOCHECK, - OID_PKIX_OCSP_ARCHIVE_CUTOFF, - OID_PKIX_OCSP_SERVICE_LOCATOR, - OID_GOOGLE_OCSP_SCT; - -#ifdef __cplusplus -} -#endif - -#endif /* _OIDSOCSP_H_ */ diff --git a/OSX/include/security_asn1/osKeyTemplates.c b/OSX/include/security_asn1/osKeyTemplates.c deleted file mode 100644 index 84c22aca..00000000 --- a/OSX/include/security_asn1/osKeyTemplates.c +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * osKeyTemplate.h - ASN1 templates for openssl asymmetric keys - */ - -#include "osKeyTemplates.h" -#include - -/**** - **** DSA support - ****/ - -/* X509 style DSA algorithm parameters */ -const SecAsn1Template kSecAsn1DSAAlgParamsTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAAlgParams) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParams,p) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParams,q) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParams,g) }, - { 0, } -}; - -/* BSAFE style DSA algorithm parameters */ -const SecAsn1Template kSecAsn1DSAAlgParamsBSAFETemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAAlgParamsBSAFE) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParamsBSAFE,keySizeInBits) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParamsBSAFE,p) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParamsBSAFE,q) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAAlgParamsBSAFE,g) }, - { 0, } -}; - -/* DSA X509-style AlgorithmID */ -const SecAsn1Template kSecAsn1DSAAlgorithmIdX509Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAAlgorithmIdX509) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSS_DSAAlgorithmIdX509, algorithm) }, - /* per CMS, this is optional */ - { SEC_ASN1_POINTER | SEC_ASN1_OPTIONAL, - offsetof(NSS_DSAAlgorithmIdX509,params), - kSecAsn1DSAAlgParamsTemplate }, - { 0, } -}; - -/* DSA BSAFE-style AlgorithmID */ -const SecAsn1Template kSecAsn1DSAAlgorithmIdBSAFETemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAAlgorithmIdBSAFE) }, - { SEC_ASN1_OBJECT_ID, offsetof(NSS_DSAAlgorithmIdBSAFE, algorithm) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DSAAlgorithmIdBSAFE,params), - kSecAsn1DSAAlgParamsBSAFETemplate }, - { 0, } -}; - -/**** - **** DSA public keys - ****/ - -/* DSA public key, openssl/X509 format */ -const SecAsn1Template kSecAsn1DSAPublicKeyX509Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAPublicKeyX509) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DSAPublicKeyX509, dsaAlg), - kSecAsn1DSAAlgorithmIdX509Template }, - { SEC_ASN1_BIT_STRING, - offsetof(NSS_DSAPublicKeyX509, publicKey), }, - { 0, } -}; - -/* DSA public key, BSAFE/FIPS186 format */ -const SecAsn1Template kSecAsn1DSAPublicKeyBSAFETemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAPublicKeyBSAFE) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DSAPublicKeyBSAFE, dsaAlg), - kSecAsn1DSAAlgorithmIdBSAFETemplate }, - { SEC_ASN1_BIT_STRING, - offsetof(NSS_DSAPublicKeyBSAFE, publicKey), }, - { 0, } -}; - -/**** - **** DSA private keys - ****/ - -/* DSA Private key, openssl custom format */ -const SecAsn1Template kSecAsn1DSAPrivateKeyOpensslTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAPrivateKeyOpenssl) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOpenssl,version) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOpenssl,p) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOpenssl,q) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOpenssl,g) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOpenssl,pub) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOpenssl,priv) }, - { 0, } -}; - -/* - * DSA private key, BSAFE/FIPS186 style. - * This is basically a DSA-specific NSS_PrivateKeyInfo. - * - * NSS_DSAPrivateKeyBSAFE.privateKey is an octet string containing - * the DER encoding of this. - */ -const SecAsn1Template kSecAsn1DSAPrivateKeyOctsTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAPrivateKeyOcts) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyOcts,privateKey) }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DSAPrivateKeyBSAFETemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAPrivateKeyBSAFE) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyBSAFE,version) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DSAPrivateKeyBSAFE, dsaAlg), - kSecAsn1DSAAlgorithmIdBSAFETemplate }, - { SEC_ASN1_OCTET_STRING, offsetof(NSS_DSAPrivateKeyBSAFE,privateKey) }, - { 0, } -}; - -/* - * DSA Private Key, PKCS8/SMIME style. - */ -const SecAsn1Template kSecAsn1DSAPrivateKeyPKCS8Template[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSAPrivateKeyPKCS8) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSAPrivateKeyPKCS8,version) }, - { SEC_ASN1_INLINE, - offsetof(NSS_DSAPrivateKeyPKCS8, dsaAlg), - kSecAsn1DSAAlgorithmIdX509Template }, - { SEC_ASN1_OCTET_STRING, offsetof(NSS_DSAPrivateKeyPKCS8,privateKey) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSS_DSAPrivateKeyPKCS8,attributes), - kSecAsn1SetOfAttributeTemplate }, - { 0, } -}; - -const SecAsn1Template kSecAsn1DSASignatureTemplate[] = { - { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSS_DSASignature) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSASignature,r) }, - { SEC_ASN1_INTEGER, offsetof(NSS_DSASignature,s) }, - { 0, } -}; - - diff --git a/OSX/include/security_asn1/osKeyTemplates.h b/OSX/include/security_asn1/osKeyTemplates.h deleted file mode 100644 index 2a018796..00000000 --- a/OSX/include/security_asn1/osKeyTemplates.h +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * osKeyTemplate.h - ASN1 templates for openssl asymmetric keys - */ - -#ifndef _OS_KEY_TEMPLATES_H_ -#define _OS_KEY_TEMPLATES_H_ - -#include - -/* - * Arrays of SecAsn1Template are always associated with a specific - * C struct. We attempt to use C structs which are defined in CDSA - * if at all possible; these always start with the CSSM_ prefix. - * Otherwise we define the struct here, with an NSS_ prefix. - * In either case, the name of the C struct is listed in comments - * along with the extern declaration of the SecAsn1Template array. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -/*** - *** Note: RSA and Diffie-Hellman keys and structs are in - *** security_asn1/keyTemplates.h. - ***/ - -// MARK: *** DSA *** - -/* - * Note that most of the DSA structs are hand rolled and are not - * expressed in ASN1 in any doc that I'm aware of. - */ - -/**** - **** DSA support - ****/ - -/* - * DSA algorithm parameters. Used in CDSA key generation context as - * well as the parameters in an X509-formatted DSA public key. - */ -typedef struct { - SecAsn1Item p; - SecAsn1Item q; - SecAsn1Item g; -} NSS_DSAAlgParams; - -extern const SecAsn1Template kSecAsn1DSAAlgParamsTemplate[]; - -/* - * DSA algorithm parameters, BSAFE style. Only used in FIPS186 format - * public and private keys. - */ -typedef struct { - SecAsn1Item keySizeInBits; - SecAsn1Item p; - SecAsn1Item q; - SecAsn1Item g; -} NSS_DSAAlgParamsBSAFE; - -extern const SecAsn1Template kSecAsn1DSAAlgParamsBSAFETemplate[]; - -/* - * DSA X509-style AlgorithmID. Avoids ASN_ANY processing via direct - * insertion of the appropriate parameters. - */ -typedef struct { - SecAsn1Oid algorithm; - NSS_DSAAlgParams *params; // optional -} NSS_DSAAlgorithmIdX509; - -extern const SecAsn1Template kSecAsn1DSAAlgorithmIdX509Template[]; - -/* - * DSA AlgorithmID, BSAFE style. Avoids ASN_ANY - * processing via direct insertion of the appropriate parameters. - */ -typedef struct { - SecAsn1Oid algorithm; - NSS_DSAAlgParamsBSAFE params; -} NSS_DSAAlgorithmIdBSAFE; - -extern const SecAsn1Template kSecAsn1DSAAlgorithmIdBSAFETemplate[]; - -/**** - **** DSA public keys - ****/ - -/* - * DSA public key, openssl/X509 format. - * - * The publicKey is actually the DER encoding of an ASN - * integer, wrapped in a BIT STRING. - */ -typedef struct { - NSS_DSAAlgorithmIdX509 dsaAlg; - SecAsn1Item publicKey; // BIT string - Length in bits -} NSS_DSAPublicKeyX509; - -extern const SecAsn1Template kSecAsn1DSAPublicKeyX509Template[]; - -/* - * DSA public key, BSAFE/FIPS186 format. - * The public key is the DER encoding of an ASN integer, wrapped - * in a bit string. - */ -typedef struct { - NSS_DSAAlgorithmIdBSAFE dsaAlg; - SecAsn1Item publicKey; // BIT string - Length in bits -} NSS_DSAPublicKeyBSAFE; - -extern const SecAsn1Template kSecAsn1DSAPublicKeyBSAFETemplate[]; - -/**** - **** DSA private keys - ****/ - -/* - * DSA Private key, openssl custom format. - */ -typedef struct { - SecAsn1Item version; - SecAsn1Item p; - SecAsn1Item q; - SecAsn1Item g; - SecAsn1Item pub; - SecAsn1Item priv; -} NSS_DSAPrivateKeyOpenssl; - -extern const SecAsn1Template kSecAsn1DSAPrivateKeyOpensslTemplate[]; - -/* - * DSA private key, BSAFE/FIPS186 style. - * This is basically a DSA-specific NSS_PrivateKeyInfo. - * - * NSS_DSAPrivateKeyBSAFE.privateKey is an octet string containing - * the DER encoding of this. - */ -typedef struct { - SecAsn1Item privateKey; -} NSS_DSAPrivateKeyOcts; - -extern const SecAsn1Template kSecAsn1DSAPrivateKeyOctsTemplate[]; - -typedef struct { - SecAsn1Item version; - NSS_DSAAlgorithmIdBSAFE dsaAlg; - /* octet string containing a DER-encoded NSS_DSAPrivateKeyOcts */ - SecAsn1Item privateKey; -} NSS_DSAPrivateKeyBSAFE; - -extern const SecAsn1Template kSecAsn1DSAPrivateKeyBSAFETemplate[]; - -/* - * DSA Private Key, PKCS8/SMIME style. Doesn't have keySizeInBits - * in the alg params; has version in the top-level struct; the - * private key itself is a DER-encoded integer wrapped in an - * octet string. - */ -typedef struct { - SecAsn1Item version; - NSS_DSAAlgorithmIdX509 dsaAlg; - /* octet string containing DER-encoded integer */ - SecAsn1Item privateKey; - NSS_Attribute **attributes; // optional -} NSS_DSAPrivateKeyPKCS8; - -extern const SecAsn1Template kSecAsn1DSAPrivateKeyPKCS8Template[]; - -/* - * DSA Signature. - */ -typedef struct { - SecAsn1Item r; - SecAsn1Item s; -} NSS_DSASignature; - -extern const SecAsn1Template kSecAsn1DSASignatureTemplate[]; - -#ifdef __cplusplus -} -#endif - - -#endif /* _OS_KEY_TEMPLATES_H_ */ diff --git a/OSX/include/security_asn1/pkcs12Templates.c b/OSX/include/security_asn1/pkcs12Templates.c deleted file mode 100644 index c9effec0..00000000 --- a/OSX/include/security_asn1/pkcs12Templates.c +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2003-2004,2008,2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * pkcs12Templates.cpp - */ - -#include -#include "pkcs12Templates.h" -#include "nssUtils.h" -#include "SecAsn1Templates.h" -#include "oidsattr.h" - -const SecAsn1Template NSS_P12_MacDataTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_MacData) }, - { SEC_ASN1_INLINE, - offsetof(NSS_P12_MacData,mac), - NSS_P7_DigestInfoTemplate }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSS_P12_MacData,macSalt) }, - /* iterations is unsigned - right? */ - { SEC_ASN1_INTEGER | SEC_ASN1_OPTIONAL, - offsetof(NSS_P12_MacData,iterations) }, - { 0, } -}; - -const SecAsn1Template pointerToMacDataTemplate[] = { - { SEC_ASN1_POINTER, 0, NSS_P12_MacDataTemplate } -}; - -/* raw PFX with unprocessed authSafe */ -const SecAsn1Template NSS_P12_RawPFXTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_RawPFX) }, - { SEC_ASN1_INTEGER, - offsetof(NSS_P12_RawPFX,version) }, - { SEC_ASN1_INLINE, - offsetof(NSS_P12_RawPFX, authSafe), - NSS_P7_RawContentInfoTemplate }, - { SEC_ASN1_POINTER | SEC_ASN1_OPTIONAL, - offsetof(NSS_P12_RawPFX, macData), - NSS_P12_MacDataTemplate }, - { 0, } -}; - -/* PFX with decoded authSafe */ -const SecAsn1Template NSS_P12_DecodedPFXTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_DecodedPFX) }, - { SEC_ASN1_INTEGER, - offsetof(NSS_P12_DecodedPFX,version) }, - { SEC_ASN1_INLINE, - offsetof(NSS_P12_DecodedPFX, authSafe), - NSS_P7_DecodedContentInfoTemplate }, - { SEC_ASN1_POINTER | SEC_ASN1_OPTIONAL, - offsetof(NSS_P12_DecodedPFX, macData), - NSS_P12_MacDataTemplate }, - { 0, } -}; - -/* AuthenticatedSafe */ -const SecAsn1Template NSS_P12_AuthenticatedSafeTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_P12_AuthenticatedSafe, info), - NSS_P7_DecodedContentInfoTemplate, - sizeof(NSS_P12_AuthenticatedSafe) } -}; - -/* - * Individual SafeBag type-specific templates here when we write 'em - */ -const SecAsn1Template NSS_P12_PtrToShroudedKeyBagTemplate[] = { - { SEC_ASN1_POINTER, 0, kSecAsn1EncryptedPrivateKeyInfoTemplate } -}; - -/* - * CertBag via SEC_ASN1_DYNAMIC - */ -static const SecAsn1Template * NSS_P12_CertBagChooser( - void *arg, // --> NSS_P12_CertBag - Boolean enc, - const char *buf, // on decode, tag byte - void *dest) // --> NSS_P12_CertBag.bagValue -{ - NSS_P12_CertBag *bag = (NSS_P12_CertBag *)arg; - const SecAsn1Template *templ = NULL; - NSS_P12_CertBagType type = CT_Unknown; - SecAsn1Oid *oid = &bag->bagType; - - if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS9_X509Certificate)) { - templ = kSecAsn1OctetStringTemplate; - type = CT_X509; - } - else if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS9_SdsiCertificate)) { - templ = kSecAsn1IA5StringTemplate; - type = CT_SDSI; - } - else { - /* punt */ - templ = kSecAsn1AnyTemplate; - } - if(!enc) { - bag->type = type; - } - return templ; -} - -static const SecAsn1TemplateChooserPtr NSS_P12_CertBagChooserPtr = - NSS_P12_CertBagChooser; - -const SecAsn1Template NSS_P12_CertBagTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_CertBag) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_P12_CertBag,bagType) }, - /* these come in with a tag of 0xA0, context/constructed, - * though I don't know why they are flagged as constructed */ - { SEC_ASN1_DYNAMIC | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | 0, - offsetof(NSS_P12_CertBag, certValue), - &NSS_P12_CertBagChooserPtr }, - { 0, } -}; - -const SecAsn1Template NSS_P12_PtrToCertBagTemplate[] = { - { SEC_ASN1_POINTER, 0, NSS_P12_CertBagTemplate } -}; - -/* - * CrlBag via SEC_ASN1_DYNAMIC - */ -static const SecAsn1Template * NSS_P12_CrlBagChooser( - void *arg, // --> NSS_P12_CrlBag - Boolean enc, - const char *buf, // on decode, tag byte - void *dest) // --> NSS_P12_CertBag.bagValue -{ - NSS_P12_CrlBag *bag = (NSS_P12_CrlBag *)arg; - const SecAsn1Template *templ = NULL; - NSS_P12_CrlBagType type = CRT_Unknown; - SecAsn1Oid *oid = &bag->bagType; - - if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS9_X509Crl)) { - templ = kSecAsn1OctetStringTemplate; - type = CRT_X509; - } - else { - /* punt */ - templ = kSecAsn1AnyTemplate; - } - if(!enc) { - bag->type = type; - } - return templ; -} - -static const SecAsn1TemplateChooserPtr NSS_P12_CrlBagChooserPtr = - NSS_P12_CrlBagChooser; - -const SecAsn1Template NSS_P12_CrlBagTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_CrlBag) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_P12_CrlBag,bagType) }, - /* these come in with a tag of 0xA0, context/constructed, - * though I don't know why they are flagged as constructed */ - { SEC_ASN1_DYNAMIC | SEC_ASN1_CONTEXT_SPECIFIC | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | 0, - offsetof(NSS_P12_CrlBag, crlValue), - &NSS_P12_CrlBagChooserPtr }, - { 0, } -}; - -const SecAsn1Template NSS_P12_PtrToCrlBagTemplate[] = { - { SEC_ASN1_POINTER, 0, NSS_P12_CrlBagTemplate } -}; - - -/* the stub templates for unimplemented BagTypes */ -#define NSS_P12_PtrToKeyBagTemplate kSecAsn1PointerToAnyTemplate -#define NSS_P12_PtrToSecretBagTemplate kSecAsn1PointerToAnyTemplate -#define NSS_P12_PtrToSafeContentsBagTemplate kSecAsn1PointerToAnyTemplate - - -/* - * SafeBag via SEC_ASN1_DYNAMIC - */ -static const SecAsn1Template * NSS_P12_SafeBagChooser( - void *arg, // --> NSS_P12_SafeBag - Boolean enc, - const char *buf, // on decode, tag byte - void *dest) // --> NSS_P12_SafeBag.bagValue -{ - NSS_P12_SafeBag *bag = (NSS_P12_SafeBag *)arg; - const SecAsn1Template *templ = NULL; - NSS_P12_SB_Type type = BT_None; - SecAsn1Oid *oid = &bag->bagId; - - if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS12_keyBag)) { - templ = NSS_P12_PtrToKeyBagTemplate; - type = BT_KeyBag; - } - else if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS12_shroudedKeyBag)) { - templ = NSS_P12_PtrToShroudedKeyBagTemplate; - type = BT_ShroudedKeyBag; - } - else if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS12_certBag)) { - templ = NSS_P12_PtrToCertBagTemplate; - type = BT_CertBag; - } - else if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS12_crlBag)) { - templ = NSS_P12_PtrToCrlBagTemplate; - type = BT_CrlBag; - } - else if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS12_secretBag)) { - templ = NSS_P12_PtrToSecretBagTemplate; - type = BT_SecretBag; - } - else if(nssCompareSecAsn1Items(oid, &CSSMOID_PKCS12_safeContentsBag)) { - templ = NSS_P12_PtrToSafeContentsBagTemplate; - type = BT_SafeContentsBag; - } - /* add more here when we implement them */ - else { - templ = kSecAsn1PointerToAnyTemplate; - } - if(!enc) { - bag->type = type; - } - return templ; -} - -static const SecAsn1TemplateChooserPtr NSS_P12_SafeBagChooserPtr = - NSS_P12_SafeBagChooser; - -const SecAsn1Template NSS_P12_SafeBagTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_SafeBag) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_P12_SafeBag,bagId) }, - { SEC_ASN1_DYNAMIC | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSS_P12_SafeBag,bagValue), - &NSS_P12_SafeBagChooserPtr }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_SET_OF, - offsetof(NSS_P12_SafeBag,bagAttrs), - kSecAsn1AttributeTemplate }, - { 0 } -}; - -const SecAsn1Template NSS_P12_SafeContentsTemplate[] = { - { SEC_ASN1_SEQUENCE_OF, - offsetof(NSS_P12_SafeContents, bags), - NSS_P12_SafeBagTemplate, - sizeof(NSS_P12_SafeContents) } -}; - -const SecAsn1Template NSS_P12_PBE_ParamsTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P12_PBE_Params) }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSS_P12_PBE_Params,salt) }, - /* iterations is unsigned - right? */ - { SEC_ASN1_INTEGER, - offsetof(NSS_P12_PBE_Params,iterations) }, - { 0 } -}; - - diff --git a/OSX/include/security_asn1/pkcs12Templates.h b/OSX/include/security_asn1/pkcs12Templates.h deleted file mode 100644 index ea2cc6f9..00000000 --- a/OSX/include/security_asn1/pkcs12Templates.h +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (c) 2003-2004,2008,2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * pkcs12Templates.h - * - ******************************************************************* - * - * In a probably vain attempt to clarify the structure of a PKCS12 - * PFX, here is a high-level summary. - * - * The top level item in P12 is a PFX. - * - * PFX = { - * int version; - * ContentInfo authSafe; -- from PKCS7 - * MacData mac; -- optional, password integrity version - * } - * - * The authSafe in a PFX has two legal contentTypes in the P12 - * world, CT_Data (password integrity mode) or CT_SignedData - * (public key integrity mode). The current version of this library - * only supports password integrity mode. Thus the integrity of - * the whole authSafe item is protected by a MAC in the PFX. - * - * The authSafe.content field is a BER-encoded AuthenticatedSafe. - * - * AuthenticatedSafe = { - * SEQUENCE OF ContentInfo; - * } - * - * OK. Each ContentInfo in an AuthenticatedSafe can either be type - * CT_Data, CT_EnvData, or CT_EncryptedData. In the latter cases the - * content is decrypted to produce an encoded SafeContents; in the - * former case the content *is* an encoded SafeContents. - * - * A SafeContents is a sequence of SafeBags. - * - * Each SafeBag can be of several types: - * - * BT_KeyBag - * BT_ShroudedKeyBag - * BT_CertBag - * BT_CrlBag - * BT_SecretBag - * BT_SafeContentsBag - * - */ - -#ifndef _PKCS12_TEMPLATES_H_ -#define _PKCS12_TEMPLATES_H_ - -#include /* for NSS_Attribute */ -#include /* will be lib-specific place */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * MacData ::= SEQUENCE { - * mac DigestInfo, - * macSalt OCTET STRING, - * iterations INTEGER DEFAULT 1 - * } - */ -typedef struct { - NSS_P7_DigestInfo mac; - SecAsn1Item macSalt; - SecAsn1Item iterations; // optional -} NSS_P12_MacData; - -extern const SecAsn1Template NSS_P12_MacDataTemplate[]; - -/* - * PFX ::= SEQUENCE { - * version INTEGER {v3(3)}(v3,...), - * authSafe ContentInfo, - * macData MacData OPTIONAL - * } - */ - -/* - * First the top level PFX with unparsed ContentInfo.content. - */ -typedef struct { - SecAsn1Item version; - NSS_P7_RawContentInfo authSafe; - NSS_P12_MacData *macData; -} NSS_P12_RawPFX; - -extern const SecAsn1Template NSS_P12_RawPFXTemplate[]; - -/* - * And a PFX with a decoded ContentInfo.content. - */ -typedef struct { - SecAsn1Item version; - NSS_P7_DecodedContentInfo authSafe; - NSS_P12_MacData *macData; -} NSS_P12_DecodedPFX; - -extern const SecAsn1Template NSS_P12_DecodedPFXTemplate[]; - -/* - * The CSSMOID_PKCS7_Data-style ContentInfo.content of a PFX - * contains an encoded AuthenticatedSafe. - * - * AuthenticatedSafe ::= SEQUENCE OF ContentInfo - * -- Data if unencrypted - * -- EncryptedData if password-encrypted - * -- EnvelopedData if public key-encrypted - */ -typedef struct { - NSS_P7_DecodedContentInfo **info; -} NSS_P12_AuthenticatedSafe; - -extern const SecAsn1Template NSS_P12_AuthenticatedSafeTemplate[]; - -/* - * Individual BagTypes. - * Code on demand. - */ -typedef SecAsn1Item NSS_P12_KeyBag; -typedef NSS_EncryptedPrivateKeyInfo NSS_P12_ShroudedKeyBag; -typedef SecAsn1Item NSS_P12_SecretBag; -typedef SecAsn1Item NSS_P12_SafeContentsBag; - -/* - * CertBag - * - * CertBag ::= SEQUENCE { - * certId BAG-TYPE.&id ({CertTypes}), - * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) - * } - * - * x509Certificate BAG-TYPE ::= - * {OCTET STRING IDENTIFIED BY {certTypes 1}} - * -- DER-encoded X.509 certificate stored in OCTET STRING - * sdsiCertificate BAG-TYPE ::= - * {IA5String IDENTIFIED BY {certTypes 2}} - * -- Base64-encoded SDSI certificate stored in IA5String - */ -typedef enum { - CT_Unknown, // --> ASN_ANY - CT_X509, - CT_SDSI, -} NSS_P12_CertBagType; - -typedef struct { - SecAsn1Oid bagType; - NSS_P12_CertBagType type; - SecAsn1Item certValue; -} NSS_P12_CertBag; - -extern const SecAsn1Template NSS_P12_CertBagTemplate[]; - -/* - * CRLBag - * - * CRLBag ::= SEQUENCE { - * certId BAG-TYPE.&id ({CertTypes}), - * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) - * } - * - * x509Certificate BAG-TYPE ::= - * {OCTET STRING IDENTIFIED BY {certTypes 1}} - * -- DER-encoded X.509 certificate stored in OCTET STRING - * sdsiCertificate BAG-TYPE ::= - * {IA5String IDENTIFIED BY {certTypes 2}} - * -- Base64-encoded SDSI certificate stored in IA5String - */ -typedef enum { - CRT_Unknown, // --> ASN_ANY - CRT_X509, -} NSS_P12_CrlBagType; - -typedef struct { - SecAsn1Oid bagType; - NSS_P12_CrlBagType type; - SecAsn1Item crlValue; -} NSS_P12_CrlBag; - -extern const SecAsn1Template NSS_P12_CrlBagTemplate[]; - -/* - * BagId OIDs map to one of these for convenience. Our dynamic - * template chooser drops one of these into NSS_P12_SafeBag.type - * on decode. - */ -typedef enum { - BT_None = 0, - BT_KeyBag, - BT_ShroudedKeyBag, - BT_CertBag, - BT_CrlBag, - BT_SecretBag, - BT_SafeContentsBag -} NSS_P12_SB_Type; - -/* - * The ContentInfo.content values of each element in - * an AuthenticatedSafe map to a sequence of these - either directly - * (contentType CSSMOID_PKCS7_Data, octet string contents are - * the DER encoding of this) or indirectly (encrypted or - * shrouded, the decrypted content is the DER encoding of this). - */ -typedef struct { - SecAsn1Oid bagId; - NSS_P12_SB_Type type; - union { - NSS_P12_KeyBag *keyBag; - NSS_P12_ShroudedKeyBag *shroudedKeyBag; - NSS_P12_CertBag *certBag; - NSS_P12_CrlBag *crlBag; - NSS_P12_SecretBag *secretBag; - NSS_P12_SafeContentsBag *safeContentsBag; - } bagValue; - NSS_Attribute **bagAttrs; // optional -} NSS_P12_SafeBag; - -extern const SecAsn1Template NSS_P12_SafeBagTemplate[]; - -/* - * SafeContents, the contents of an element in an AuthenticatedSafe. - */ -typedef struct { - NSS_P12_SafeBag **bags; -} -NSS_P12_SafeContents; - -extern const SecAsn1Template NSS_P12_SafeContentsTemplate[]; - -/* - * PKCS12-specific algorithm parameters. - * A DER encoded version of this is the parameters value of - * a CSSM_X509_ALGORITHM_IDENTIFIER used in a - * NSS_P7_EncrContentInfo.encrAlg in P12 password privacy mode. - * - * pkcs-12PbeParams ::= SEQUENCE { - * salt OCTET STRING, - * iterations INTEGER - * } - * - * NOTE the P12 spec does place a limit on the value of iterations. - * I guess we have to assume in actual usage that it's - * restricted to (0..MAX), i.e., uint32-sized. - * - * We're also assuming that it is explicitly an unsigned value, - * so that the value bytes in the encoding of 0xff would be - * (0, 255). - */ -typedef struct { - SecAsn1Item salt; - SecAsn1Item iterations; -} NSS_P12_PBE_Params; - -extern const SecAsn1Template NSS_P12_PBE_ParamsTemplate[]; - -#ifdef __cplusplus -} -#endif - -#endif /* _PKCS12_TEMPLATES_H_ */ - diff --git a/OSX/include/security_asn1/pkcs7Templates.c b/OSX/include/security_asn1/pkcs7Templates.c deleted file mode 100644 index 125fd6b3..00000000 --- a/OSX/include/security_asn1/pkcs7Templates.c +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2003-2004,2008,2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * pkcs7Templates.cpp - */ - -#include -#include "pkcs7Templates.h" -#include "keyTemplates.h" /* NSS_AlgorithmIDTemplate */ -#include "SecAsn1Templates.h" -#include "nssUtils.h" -#include "oidsattr.h" - -const SecAsn1Template NSS_P7_DigestInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P7_DigestInfo) }, - { SEC_ASN1_INLINE, - offsetof(NSS_P7_DigestInfo,digestAlgorithm), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_OCTET_STRING, - offsetof(NSS_P7_DigestInfo,digest) }, - { 0 } -}; - -/* - * Uninterpreted ContentInfo, with content stripped from its - * EXPLICIT CONTEXT_SPECIFIC wrapper - */ -const SecAsn1Template NSS_P7_RawContentInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P7_RawContentInfo) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_P7_RawContentInfo,contentType) }, - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_EXPLICIT | - SEC_ASN1_CONSTRUCTED | SEC_ASN1_OPTIONAL | 0, - offsetof(NSS_P7_RawContentInfo,content), - kSecAsn1AnyTemplate }, - { 0 } -}; - -/* - * Individual ContentInfo.content templates - */ -const SecAsn1Template NSS_P7_EncrContentInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P7_EncrContentInfo) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_P7_EncrContentInfo,contentType) }, - { SEC_ASN1_INLINE, - offsetof(NSS_P7_EncrContentInfo,encrAlg), - kSecAsn1AlgorithmIDTemplate }, - { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_OPTIONAL | 0, - offsetof(NSS_P7_EncrContentInfo,encrContent), - kSecAsn1OctetStringTemplate }, - { 0 } -}; - -const SecAsn1Template NSS_P7_EncryptedDataTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P7_EncryptedData) }, - { SEC_ASN1_INTEGER, - offsetof(NSS_P7_EncryptedData,version) }, - { SEC_ASN1_INLINE, - offsetof(NSS_P7_EncryptedData,contentInfo), - NSS_P7_EncrContentInfoTemplate }, - { 0 } -}; - -const SecAsn1Template NSS_P7_PtrToEncryptedDataTemplate[] = { - { SEC_ASN1_POINTER, 0, NSS_P7_EncryptedDataTemplate } -}; - -/* - * Decoded ContentInfo via SEC_ASN1_DYNAMIC - */ - -static const SecAsn1Template * NSS_P7_ContentInfoChooser( - void *arg, // --> NSS_P7_DecodedContentInfo - Boolean enc, - const char *buf, // on decode, tag byte - void *dest) // --> NSS_P7_DecodedContentInfo.content -{ - NSS_P7_DecodedContentInfo *dci = - (NSS_P7_DecodedContentInfo *)arg; - const SecAsn1Template *templ = NULL; - NSS_P7_CI_Type type = CT_None; - - if(nssCompareSecAsn1Items(&dci->contentType, - &CSSMOID_PKCS7_Data)) { - templ = kSecAsn1PointerToOctetStringTemplate; - type = CT_Data; - } - else if(nssCompareSecAsn1Items(&dci->contentType, - &CSSMOID_PKCS7_EncryptedData)) { - templ = NSS_P7_PtrToEncryptedDataTemplate; - type = CT_EncryptedData; - } - else if(nssCompareSecAsn1Items(&dci->contentType, - &CSSMOID_PKCS7_SignedData)) { - templ = NSS_P7_PtrToSignedDataTemplate; - type = CT_SignedData; - } - else if(nssCompareSecAsn1Items(&dci->contentType, - &CSSMOID_PKCS7_EnvelopedData)) { - templ = NSS_P7_PtrToEnvelDataTemplate; - type = CT_EnvData; - } - else if(nssCompareSecAsn1Items(&dci->contentType, - &CSSMOID_PKCS7_SignedAndEnvelopedData)) { - templ = NSS_P7_PtrToSignEnvelDataTemplate; - type = CT_SignedEnvData; - } - else if(nssCompareSecAsn1Items(&dci->contentType, - &CSSMOID_PKCS7_DigestedData)) { - templ = NSS_P7_PtrToDigestedDataTemplate; - type = CT_DigestData; - } - /* add more here when we implement them */ - else { - return kSecAsn1PointerToAnyTemplate; - } - if(!enc) { - dci->type = type; - } - return templ; -} - -static const SecAsn1TemplateChooserPtr NSS_P7_ContentInfoChooserPtr = - NSS_P7_ContentInfoChooser; - -const SecAsn1Template NSS_P7_DecodedContentInfoTemplate[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(NSS_P7_DecodedContentInfo) }, - { SEC_ASN1_OBJECT_ID, - offsetof(NSS_P7_DecodedContentInfo,contentType) }, - { SEC_ASN1_OPTIONAL | SEC_ASN1_DYNAMIC | - SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | - SEC_ASN1_CONTEXT_SPECIFIC | 0, - offsetof(NSS_P7_DecodedContentInfo,content), - &NSS_P7_ContentInfoChooserPtr }, - { 0 } -}; diff --git a/OSX/include/security_asn1/pkcs7Templates.h b/OSX/include/security_asn1/pkcs7Templates.h deleted file mode 100644 index b6f35e9c..00000000 --- a/OSX/include/security_asn1/pkcs7Templates.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2003-2004,2008,2010,2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * pkcs7Templates.h - */ - -#ifndef _PKCS7_TEMPLATES_H_ -#define _PKCS7_TEMPLATES_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * DigestInfo ::= SEQUENCE { - * digestAlgorithm DigestAlgorithmIdentifier, - * digest Digest - * } - * - * Digest ::= OCTET STRING - */ -typedef struct { - SecAsn1AlgId digestAlgorithm; - SecAsn1Item digest; -} NSS_P7_DigestInfo; - -extern const SecAsn1Template NSS_P7_DigestInfoTemplate[]; - -/* - * Uninterpreted ContentInfo, with content stripped from its - * EXPLICIT CONTEXT_SPECIFIC wrapper - * - * ContentInfo ::= SEQUENCE { - * contentType ContentType, - * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL - * } - */ -typedef struct { - SecAsn1Oid contentType; - SecAsn1Item content; -} NSS_P7_RawContentInfo; - -extern const SecAsn1Template NSS_P7_RawContentInfoTemplate[]; - -// MARK: ---- ContentInfo.content types ----- - -/* - * Expand beyond ASN_ANY/CSSM_DATA as needed - */ -typedef SecAsn1Item NSS_P7_SignedData; -typedef SecAsn1Item NSS_P7_EnvelData; -typedef SecAsn1Item NSS_P7_SignEnvelData; -typedef SecAsn1Item NSS_P7_DigestedData; - -/* EncryptedData */ - -/* - * EncryptedContentInfo ::= SEQUENCE { - * contentType ContentType, - * contentEncryptionAlgorithm - * ContentEncryptionAlgorithmIdentifier, - * encryptedContent - * [0] IMPLICIT EncryptedContent OPTIONAL - * } - * - * EncryptedContent ::= OCTET STRING - */ - -typedef struct { - SecAsn1Oid contentType; - SecAsn1AlgId encrAlg; - SecAsn1Item encrContent; -} NSS_P7_EncrContentInfo; - -/* - * EncryptedData ::= SEQUENCE { - * version Version, - * encryptedContentInfo EncryptedContentInfo - * } - */ -typedef struct { - SecAsn1Item version; - NSS_P7_EncrContentInfo contentInfo; -} NSS_P7_EncryptedData; - -extern const SecAsn1Template NSS_P7_EncrContentInfoTemplate[]; -extern const SecAsn1Template NSS_P7_EncryptedDataTemplate[]; -extern const SecAsn1Template NSS_P7_PtrToEncryptedDataTemplate[]; - -/* the stub templates for unimplemented contentTypes */ -#define NSS_P7_PtrToSignedDataTemplate kSecAsn1PointerToAnyTemplate -#define NSS_P7_PtrToEnvelDataTemplate kSecAsn1PointerToAnyTemplate -#define NSS_P7_PtrToSignEnvelDataTemplate kSecAsn1PointerToAnyTemplate -#define NSS_P7_PtrToDigestedDataTemplate kSecAsn1PointerToAnyTemplate - -// MARK: ---- decoded ContentInfo ----- - -/* - * For convenience, out dynamic template chooser for ContentInfo.content - * drops one of these into the decoded struct. Thus, higher level - * code doesn't have to grunge around comparing OIDs to figure out - * what's there. - */ -typedef enum { - CT_None = 0, - CT_Data, - CT_SignedData, - CT_EnvData, - CT_SignedEnvData, - CT_DigestData, - CT_EncryptedData -} NSS_P7_CI_Type; - -/* - * Decoded ContentInfo. Decoded via SEC_ASN1_DYNAMIC per contentType. - */ -typedef struct { - SecAsn1Oid contentType; - NSS_P7_CI_Type type; - union { - SecAsn1Item *data; // CSSMOID_PKCS7_Data - // contents of Octet String - NSS_P7_SignedData *signedData; - // CSSMOID_PKCS7_SignedData - NSS_P7_EnvelData *envData; // CSSMOID_PKCS7_EnvelopedData - NSS_P7_SignEnvelData *signEnvelData; - // CSSMOID_PKCS7_SignedAndEnvelopedData - NSS_P7_DigestedData *digestedData; - // CSSMOID_PKCS7_DigestedData - NSS_P7_EncryptedData *encryptData; - //CSSMOID_PKCS7_EncryptedData - - } content; -} NSS_P7_DecodedContentInfo; - -extern const SecAsn1Template NSS_P7_DecodedContentInfoTemplate[]; - -#ifdef __cplusplus -} -#endif - -#endif /* _PKCS7_TEMPLATES_H_ */ - diff --git a/OSX/include/security_asn1/plarena.c b/OSX/include/security_asn1/plarena.c deleted file mode 100644 index d7073980..00000000 --- a/OSX/include/security_asn1/plarena.c +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Lifetime-based fast allocation, inspired by much prior art, including - * "Fast Allocation and Deallocation of Memory Based on Object Lifetimes" - * David R. Hanson, Software -- Practice and Experience, Vol. 20(1). - */ -#include -#include -#include "plarena.h" -#include "prmem.h" -#include "prbit.h" -#include "prlog.h" -#include "prinit.h" - -#ifdef PL_ARENAMETER -static PLArenaStats *arena_stats_list; - -#define COUNT(pool,what) (pool)->stats.what++ -#else -#define COUNT(pool,what) /* nothing */ -#endif - -#define PL_ARENA_DEFAULT_ALIGN sizeof(double) - -PR_IMPLEMENT(void) PL_InitArenaPool( - PLArenaPool *pool, const char *name, PRUint32 size, PRUint32 align) -{ -#if !defined (__GNUC__) -#pragma unused (name) -#endif - - if (align == 0) - align = PL_ARENA_DEFAULT_ALIGN; - pool->mask = PR_BITMASK(PR_CeilingLog2(align)); - pool->first.next = NULL; - pool->first.base = pool->first.avail = pool->first.limit = - (PRUword)PL_ARENA_ALIGN(pool, &pool->first + 1); - pool->current = &pool->first; - pool->arenasize = size; -#ifdef PL_ARENAMETER - memset(&pool->stats, 0, sizeof pool->stats); - pool->stats.name = strdup(name); - pool->stats.next = arena_stats_list; - arena_stats_list = &pool->stats; -#endif -} - -#if __APPLE__ -#define MAX_SIZE (PR_UINT32_MAX >> 1) -#endif - -/* -** PL_ArenaAllocate() -- allocate space from an arena pool -** -** Description: PL_ArenaAllocate() allocates space from an arena -** pool. -** -** First, try to satisfy the request from arenas starting at -** pool->current. Then try to allocate a new arena from the heap. -** -** Returns: pointer to allocated space or NULL -** -** Notes: The original implementation had some difficult to -** solve bugs; the code was difficult to read. Sometimes it's -** just easier to rewrite it. I did that. larryh. -** -** See also: bugzilla: 45343. -** -*/ - -PR_IMPLEMENT(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb) -{ - PLArena *a; - char *rp; /* returned pointer */ - - PR_ASSERT((nb & pool->mask) == 0); -#ifdef __APPLE__ - nb = PL_ARENA_ALIGN(pool, nb); /* force alignment, cast is useless/causes warning. */ -#else - nb = (PRUword)PL_ARENA_ALIGN(pool, nb); /* force alignment */ -#endif - - /* attempt to allocate from arenas at pool->current */ - { - a = pool->current; - do { - if ( nb <= a->limit - a->avail ) { - pool->current = a; - rp = (char *)a->avail; - a->avail += nb; - return rp; - } - } while( NULL != (a = a->next) ); - } - - /* attempt to allocate from the heap */ - { - PRUint32 sz = PR_MAX(pool->arenasize, nb); - if (PR_UINT32_MAX - sz < sizeof *a + pool->mask) { - a = NULL; - } else { - sz += sizeof *a + pool->mask; /* header and alignment slop */ - a = (PLArena*)PR_MALLOC(sz); - } -#ifdef __APPLE__ - // Check for integer overflow on a->avail += nb - PRUword a_avail_tmp=(PRUword)PL_ARENA_ALIGN(pool, a + 1); - if (a_avail_tmp + nb < a_avail_tmp) - { - PR_FREEIF(a); // Set a back to NULL - } -#endif - if ( NULL != a ) { - a->limit = (PRUword)a + sz; -#ifdef __APPLE__ - a->base = a->avail = a_avail_tmp; -#else - a->base = a->avail = (PRUword)PL_ARENA_ALIGN(pool, a + 1); -#endif - rp = (char *)a->avail; - a->avail += nb; - /* the newly allocated arena is linked after pool->current - * and becomes pool->current */ - a->next = pool->current->next; - pool->current->next = a; - pool->current = a; - if ( NULL == pool->first.next ) - pool->first.next = a; - PL_COUNT_ARENA(pool,++); - COUNT(pool, nmallocs); - return(rp); - } - } - - /* we got to here, and there's no memory to allocate */ - return(NULL); -} /* --- end PL_ArenaAllocate() --- */ - -/* - * Grow, a.k.a. realloc. The PL_ARENA_GROW macro has already handled - * the possible grow-in-place action in which the current PLArena is the - * source of the incoming pointer, and there is room in that arena for - * the requested size. - */ -PR_IMPLEMENT(void *) PL_ArenaGrow( - PLArenaPool *pool, void *p, PRUint32 origSize, PRUint32 incr) -{ - void *newp; - PLArena *thisArena; - PLArena *lastArena; - PRUint32 origAlignSize; // bytes currently reserved for caller - PRUint32 newSize; // bytes actually mallocd here - - /* expand at least by 2x */ - origAlignSize = PL_ARENA_ALIGN(pool, origSize); - newSize = PR_MAX(origAlignSize+incr, 2*origAlignSize); - newSize = PL_ARENA_ALIGN(pool, newSize); -#if __APPLE__ - // Enforce maximal size before any potential implicit truncation - if (newSize>=MAX_SIZE || origSize>=MAX_SIZE || incr>=MAX_SIZE) { - return NULL; - } -#endif - PL_ARENA_ALLOCATE(newp, pool, newSize); - if (newp == NULL) { - return NULL; - } - /* - * Trim back the memory we just allocated to the amount our caller really - * needs, leaving the remainder for grow-in-place on subsequent calls - * to PL_ARENA_GROW. - */ - PRUint32 newAlignSize = PL_ARENA_ALIGN(pool, origSize+incr); - PR_ASSERT(pool->current->avail == ((PRUword)newp + newSize)); - pool->current->avail = (PRUword)newp + newAlignSize; - PR_ASSERT(pool->current->avail <= pool->current->limit); - - /* "realloc" */ - memcpy(newp, p, origSize); - - /* - * Free old memory only if it's the entire outstanding allocated - * memory associated with one of our known PLArenas. - */ - lastArena = &pool->first; /* pool->first always empty */ - thisArena = lastArena->next; /* so, start here */ - - PRUword origPtr = (PRUword)p; - while(thisArena != NULL) { - if(origPtr == thisArena->base) { - if((origPtr + origAlignSize) == thisArena->avail) { - /* unlink */ - lastArena->next = thisArena->next; - - /* and free */ - PL_CLEAR_ARENA(thisArena); - PL_COUNT_ARENA(pool,--); - PR_DELETE(thisArena); - break; - } - } - lastArena = thisArena; - thisArena = thisArena->next; - } - /* - * Note: inability to free is not an error; it just causes a temporary leak - * of the old buffer (until the arena pool is freed, of course). - */ - return newp; -} - -static void ClearArenaList(PLArena *a, PRInt32 pattern) -{ - - for (; a; a = a->next) { - PR_ASSERT(a->base <= a->avail && a->avail <= a->limit); - a->avail = a->base; - PL_CLEAR_UNUSED_PATTERN(a, pattern); - } -} - -PR_IMPLEMENT(void) PL_ClearArenaPool(PLArenaPool *pool, PRInt32 pattern) -{ - ClearArenaList(pool->first.next, pattern); -} - -/* - * Free tail arenas linked after head, which may not be the true list head. - * Reset pool->current to point to head in case it pointed at a tail arena. - */ -static void FreeArenaList(PLArenaPool *pool, PLArena *head, PRBool reallyFree) -{ - PLArena **ap, *a; - - ap = &head->next; - a = *ap; - if (!a) - return; - - do { - *ap = a->next; - PL_CLEAR_ARENA(a); - PL_COUNT_ARENA(pool,--); - PR_DELETE(a); - } while ((a = *ap) != 0); - - pool->current = head; -} - -PR_IMPLEMENT(void) PL_ArenaRelease(PLArenaPool *pool, char *mark) -{ - #if ARENA_MARK_ENABLE - PLArena *a; - - for (a = pool->first.next; a; a = a->next) { - if (PR_UPTRDIFF(mark, a->base) < PR_UPTRDIFF(a->avail, a->base)) { - a->avail = (PRUword)PL_ARENA_ALIGN(pool, mark); - FreeArenaList(pool, a, PR_FALSE); - return; - } - } - #endif /* ARENA_MARK_ENABLE */ -} - -PR_IMPLEMENT(void) PL_FreeArenaPool(PLArenaPool *pool) -{ - FreeArenaList(pool, &pool->first, PR_FALSE); - COUNT(pool, ndeallocs); -} - -PR_IMPLEMENT(void) PL_FinishArenaPool(PLArenaPool *pool) -{ - FreeArenaList(pool, &pool->first, PR_TRUE); -#ifdef PL_ARENAMETER - { - PLArenaStats *stats, **statsp; - - if (pool->stats.name) - PR_DELETE(pool->stats.name); - for (statsp = &arena_stats_list; (stats = *statsp) != 0; - statsp = &stats->next) { - if (stats == &pool->stats) { - *statsp = stats->next; - return; - } - } - } -#endif -} - -PR_IMPLEMENT(void) PL_CompactArenaPool(PLArenaPool *ap) -{ -} - -PR_IMPLEMENT(void) PL_ArenaFinish(void) -{ -} - -#ifdef PL_ARENAMETER -PR_IMPLEMENT(void) PL_ArenaCountAllocation(PLArenaPool *pool, PRUint32 nb) -{ - pool->stats.nallocs++; - pool->stats.nbytes += nb; - if (nb > pool->stats.maxalloc) - pool->stats.maxalloc = nb; - pool->stats.variance += nb * nb; -} - -PR_IMPLEMENT(void) PL_ArenaCountInplaceGrowth( - PLArenaPool *pool, PRUint32 size, PRUint32 incr) -{ - pool->stats.ninplace++; -} - -PR_IMPLEMENT(void) PL_ArenaCountGrowth( - PLArenaPool *pool, PRUint32 size, PRUint32 incr) -{ - pool->stats.ngrows++; - pool->stats.nbytes += incr; - pool->stats.variance -= size * size; - size += incr; - if (size > pool->stats.maxalloc) - pool->stats.maxalloc = size; - pool->stats.variance += size * size; -} - -PR_IMPLEMENT(void) PL_ArenaCountRelease(PLArenaPool *pool, char *mark) -{ - pool->stats.nreleases++; -} - -PR_IMPLEMENT(void) PL_ArenaCountRetract(PLArenaPool *pool, char *mark) -{ - pool->stats.nfastrels++; -} - -#include -#include - -PR_IMPLEMENT(void) PL_DumpArenaStats(FILE *fp) -{ - PLArenaStats *stats; - double mean, variance; - - for (stats = arena_stats_list; stats; stats = stats->next) { - if (stats->nallocs != 0) { - mean = (double)stats->nbytes / stats->nallocs; - variance = fabs(stats->variance / stats->nallocs - mean * mean); - } else { - mean = variance = 0; - } - - fprintf(fp, "\n%s allocation statistics:\n", stats->name); - fprintf(fp, " number of arenas: %u\n", stats->narenas); - fprintf(fp, " number of allocations: %u\n", stats->nallocs); - fprintf(fp, " number of free arena reclaims: %u\n", stats->nreclaims); - fprintf(fp, " number of malloc calls: %u\n", stats->nmallocs); - fprintf(fp, " number of deallocations: %u\n", stats->ndeallocs); - fprintf(fp, " number of allocation growths: %u\n", stats->ngrows); - fprintf(fp, " number of in-place growths: %u\n", stats->ninplace); - fprintf(fp, "number of released allocations: %u\n", stats->nreleases); - fprintf(fp, " number of fast releases: %u\n", stats->nfastrels); - fprintf(fp, " total bytes allocated: %u\n", stats->nbytes); - fprintf(fp, " mean allocation size: %g\n", mean); - fprintf(fp, " standard deviation: %g\n", sqrt(variance)); - fprintf(fp, " maximum allocation size: %u\n", stats->maxalloc); - } -} -#endif /* PL_ARENAMETER */ diff --git a/OSX/include/security_asn1/plarena.h b/OSX/include/security_asn1/plarena.h deleted file mode 100644 index 090ad107..00000000 --- a/OSX/include/security_asn1/plarena.h +++ /dev/null @@ -1,222 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef plarena_h___ -#define plarena_h___ -/* - * Lifetime-based fast allocation, inspired by much prior art, including - * "Fast Allocation and Deallocation of Memory Based on Object Lifetimes" - * David R. Hanson, Software -- Practice and Experience, Vol. 20(1). - * - * Also supports LIFO allocation (PL_ARENA_MARK/PL_ARENA_RELEASE). - */ -#include "prtypes.h" -#include "plarenas.h" - -PR_BEGIN_EXTERN_C - -typedef struct PLArena PLArena; - -struct PLArena { - PLArena *next; /* next arena for this lifetime */ - PRUword base; /* aligned base address, follows this header */ - PRUword limit; /* one beyond last byte in arena */ - PRUword avail; /* points to next available byte */ -}; - -#ifdef PL_ARENAMETER -typedef struct PLArenaStats PLArenaStats; - -struct PLArenaStats { - PLArenaStats *next; /* next in arenaStats list */ - char *name; /* name for debugging */ - PRUint32 narenas; /* number of arenas in pool */ - PRUint32 nallocs; /* number of PL_ARENA_ALLOCATE() calls */ - PRUint32 nreclaims; /* number of reclaims from freeArenas */ - PRUint32 nmallocs; /* number of malloc() calls */ - PRUint32 ndeallocs; /* number of lifetime deallocations */ - PRUint32 ngrows; /* number of PL_ARENA_GROW() calls */ - PRUint32 ninplace; /* number of in-place growths */ - PRUint32 nreleases; /* number of PL_ARENA_RELEASE() calls */ - PRUint32 nfastrels; /* number of "fast path" releases */ - PRUint32 nbytes; /* total bytes allocated */ - PRUint32 maxalloc; /* maximum allocation size in bytes */ - PRFloat64 variance; /* size variance accumulator */ -}; -#endif - -struct PLArenaPool { - PLArena first; /* first arena in pool list */ - PLArena *current; /* arena from which to allocate space */ - PRUint32 arenasize; /* net exact size of a new arena */ - PRUword mask; /* alignment mask (power-of-2 - 1) */ -#ifdef PL_ARENAMETER - PLArenaStats stats; -#endif -}; - -/* - * If the including .c file uses only one power-of-2 alignment, it may define - * PL_ARENA_CONST_ALIGN_MASK to the alignment mask and save a few instructions - * per ALLOCATE and GROW. - */ -#ifdef PL_ARENA_CONST_ALIGN_MASK -#define PL_ARENA_ALIGN(pool, n) (((PRUword)(n) + PL_ARENA_CONST_ALIGN_MASK) \ - & ~PL_ARENA_CONST_ALIGN_MASK) - -#define PL_INIT_ARENA_POOL(pool, name, size) \ - PL_InitArenaPool(pool, name, size, PL_ARENA_CONST_ALIGN_MASK + 1) -#else -#define PL_ARENA_ALIGN(pool, n) (typeof(n))(((PRUword)(n) + (pool)->mask) & ~(pool)->mask) -#endif - -#define PL_ARENA_ALLOCATE(p, pool, nb) \ - PR_BEGIN_MACRO \ - PLArena *_a = (pool)->current; \ - typeof((nb)) _nb = PL_ARENA_ALIGN(pool, nb); /* __APPLE__ more to be generic */ \ - PRUword _p = _a->avail; \ - PRUword _q = _p + _nb; \ - if (_nb > (_a->limit - _a->avail)) {/* __APPLE__ */ \ - _p = (PRUword)PL_ArenaAllocate(pool, _nb); \ - } else { \ - _a->avail = _q; \ - } \ - p = (void *)_p; \ - PL_ArenaCountAllocation(pool, nb); \ - PR_END_MACRO - -#define PL_ARENA_GROW(p, pool, size, incr) \ - PR_BEGIN_MACRO \ - PLArena *_a = (pool)->current; \ - PRUword _p = _a->avail; \ - PRUword _q = (PRUword)p + size + incr; /*__APPLE__ */ \ - if (_p == (PRUword)(p) + PL_ARENA_ALIGN(pool, size) && \ - _a->limit >= PL_ARENA_ALIGN(pool,_q)) { /* __APPLE__ */ \ - _a->avail = PL_ARENA_ALIGN(pool, _q); /*__APPLE__ */ \ - PL_ArenaCountInplaceGrowth(pool, size, incr); \ - } else { \ - p = PL_ArenaGrow(pool, p, size, incr); \ - } \ - PL_ArenaCountGrowth(pool, size, incr); \ - PR_END_MACRO - -#define PL_ARENA_MARK(pool) ((void *) (pool)->current->avail) -#define PR_UPTRDIFF(p,q) ((PRUword)(p) - (PRUword)(q)) - -#define PL_CLEAR_UNUSED_PATTERN(a, pattern) \ - PR_BEGIN_MACRO \ - PR_ASSERT((a)->avail <= (a)->limit); \ - memset((void*)(a)->avail, (pattern), (a)->limit - (a)->avail); \ - PR_END_MACRO -#ifdef DEBUG -#define PL_FREE_PATTERN 0xDA -#define PL_CLEAR_UNUSED(a) PL_CLEAR_UNUSED_PATTERN((a), PL_FREE_PATTERN) -#define PL_CLEAR_ARENA(a) \ - PR_BEGIN_MACRO \ - memset((void*)(a), PL_FREE_PATTERN, (a)->limit - (PRUword)(a)); \ - PR_END_MACRO -#else -#define PL_CLEAR_UNUSED(a) -#define PL_CLEAR_ARENA(a) -#endif - -#if ARENA_MARK_ENABLE - -#define PL_ARENA_RELEASE(pool, mark) \ - PR_BEGIN_MACRO \ - char *_m = (char *)(mark); \ - PLArena *_a = (pool)->current; \ - if (PR_UPTRDIFF(_m, _a->base) <= PR_UPTRDIFF(_a->avail, _a->base)) { \ - _a->avail = (PRUword)PL_ARENA_ALIGN(pool, _m); \ - PL_CLEAR_UNUSED(_a); \ - PL_ArenaCountRetract(pool, _m); \ - } else { \ - PL_ArenaRelease(pool, _m); \ - } \ - PL_ArenaCountRelease(pool, _m); \ - PR_END_MACRO - -#else /* !ARENA_MARK_ENABLE */ - -#define PL_ARENA_RELEASE(pool, mark) - -#endif /* ARENA_MARK_ENABLE */ - -#ifdef PL_ARENAMETER -#define PL_COUNT_ARENA(pool,op) ((pool)->stats.narenas op) -#else -#define PL_COUNT_ARENA(pool,op) -#endif - -#define PL_ARENA_DESTROY(pool, a, pnext) \ - PR_BEGIN_MACRO \ - PL_COUNT_ARENA(pool,--); \ - if ((pool)->current == (a)) (pool)->current = &(pool)->first; \ - *(pnext) = (a)->next; \ - PL_CLEAR_ARENA(a); \ - free(a); \ - (a) = 0; \ - PR_END_MACRO - -#ifdef PL_ARENAMETER - -#include - -PR_EXTERN(void) PL_ArenaCountAllocation(PLArenaPool *pool, PRUint32 nb); - -PR_EXTERN(void) PL_ArenaCountInplaceGrowth( - PLArenaPool *pool, PRUint32 size, PRUint32 incr); - -PR_EXTERN(void) PL_ArenaCountGrowth( - PLArenaPool *pool, PRUint32 size, PRUint32 incr); - -PR_EXTERN(void) PL_ArenaCountRelease(PLArenaPool *pool, char *mark); - -PR_EXTERN(void) PL_ArenaCountRetract(PLArenaPool *pool, char *mark); - -PR_EXTERN(void) PL_DumpArenaStats(FILE *fp); - -#else /* !PL_ARENAMETER */ - -#define PL_ArenaCountAllocation(ap, nb) /* nothing */ -#define PL_ArenaCountInplaceGrowth(ap, size, incr) /* nothing */ -#define PL_ArenaCountGrowth(ap, size, incr) /* nothing */ -#define PL_ArenaCountRelease(ap, mark) /* nothing */ -#define PL_ArenaCountRetract(ap, mark) /* nothing */ - -#endif /* !PL_ARENAMETER */ - -PR_END_EXTERN_C - -#endif /* plarena_h___ */ diff --git a/OSX/include/security_asn1/plarenas.h b/OSX/include/security_asn1/plarenas.h deleted file mode 100644 index fa78eecb..00000000 --- a/OSX/include/security_asn1/plarenas.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions requiored by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#if defined(PLARENAS_H) -#else /* defined(PLARENAS_H) */ -#define PLARENAS_H - -#include - -/* global enable/disable of mark/release mechanism */ -#define ARENA_MARK_ENABLE 0 - -PR_BEGIN_EXTERN_C - -typedef struct PLArenaPool PLArenaPool; - -/* -** Allocate an arena pool as specified by the parameters. -** -** This is equivelant to allocating the space yourself and then -** calling PL_InitArenaPool(). -** -** This function may fail (and return a NULL) for a variety of -** reasons. The reason for a particular failure can be discovered -** by calling PR_GetError(). -*/ -#if 0 /* Not implemented */ -PR_EXTERN(PLArenaPool*) PL_AllocArenaPool( - const char *name, PRUint32 size, PRUint32 align); -#endif - -/* -** Destroy an arena pool previously allocated by PL_AllocArenaPool(). -** -** This function may fail if the arena is not empty and the caller -** wishes to check for empty upon descruction. -*/ -#if 0 /* Not implemented */ -PR_EXTERN(PRStatus) PL_DestroyArenaPool(PLArenaPool *pool, PRBool checkEmpty); -#endif - - -/* -** Initialize an arena pool with the given name for debugging and metering, -** with a minimum size per arena of size bytes. -**/ -PR_EXTERN(void) PL_InitArenaPool( - PLArenaPool *pool, const char *name, PRUint32 size, PRUint32 align); - -/* -** Finish using arenas, freeing all memory associated with them. -**/ -PR_EXTERN(void) PL_ArenaFinish(void); - -/* -** Free the arenas in pool. The user may continue to allocate from pool -** after calling this function. There is no need to call PL_InitArenaPool() -** again unless PL_FinishArenaPool(pool) has been called. -**/ -PR_EXTERN(void) PL_FreeArenaPool(PLArenaPool *pool); - -/* -** Free the arenas in pool and finish using it altogether. -**/ -PR_EXTERN(void) PL_FinishArenaPool(PLArenaPool *pool); - -/* -** Compact all of the arenas in a pool so that no space is wasted. -** NOT IMPLEMENTED. Do not use. -**/ -PR_EXTERN(void) PL_CompactArenaPool(PLArenaPool *pool); - -/* -** Friend functions used by the PL_ARENA_*() macros. -** -** WARNING: do not call these functions directly. Always use the -** PL_ARENA_*() macros. -**/ -PR_EXTERN(void *) PL_ArenaAllocate(PLArenaPool *pool, PRUint32 nb); - -PR_EXTERN(void *) PL_ArenaGrow( - PLArenaPool *pool, void *p, PRUint32 size, PRUint32 incr); - -PR_EXTERN(void) PL_ArenaRelease(PLArenaPool *pool, char *mark); - -/* - ** memset contents of all arenas in pool to pattern - */ -PR_EXTERN(void) PL_ClearArenaPool(PLArenaPool *pool, PRInt32 pattern); - -PR_END_EXTERN_C - -#endif /* defined(PLARENAS_H) */ - -/* plarenas */ diff --git a/OSX/include/security_asn1/plstr.h b/OSX/include/security_asn1/plstr.h deleted file mode 100644 index 928b25bc..00000000 --- a/OSX/include/security_asn1/plstr.h +++ /dev/null @@ -1,467 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * Roland Mainz - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef _plstr_h -#define _plstr_h - -/* - * plstr.h - * - * This header file exports the API to the NSPR portable library or string- - * handling functions. - * - * This API was not designed as an "optimal" or "ideal" string library; it - * was based on the good ol' unix string.3 functions, and was written to - * - * 1) replace the libc functions, for cross-platform consistancy, - * 2) complete the API on platforms lacking common functions (e.g., - * strcase*), and - * 3) to implement some obvious "closure" functions that I've seen - * people hacking around in our code. - * - * Point number three largely means that most functions have an "strn" - * limited-length version, and all comparison routines have a non-case- - * sensitive version available. - */ - -#include - -PR_BEGIN_EXTERN_C -/* - * PL_strlen - * - * Returns the length of the provided string, not including the trailing '\0'. - */ - -PR_EXTERN(PRUint32) -PL_strlen(const char *str); - -/* - * PL_strnlen - * - * Returns the length of the provided string, not including the trailing '\0', - * up to the indicated maximum. The string will not be examined beyond the - * maximum; if no terminating '\0' is found, the maximum will be returned. - */ - -PR_EXTERN(PRUint32) -PL_strnlen(const char *str, PRUint32 max); - -/* - * PL_strcpy - * - * Copies the source string, up to and including the trailing '\0', into the - * destination buffer. It does not (can not) verify that the destination - * buffer is large enough. It returns the "dest" argument. - */ - -PR_EXTERN(char *) -PL_strcpy(char *dest, const char *src); - -/* - * PL_strncpy - * - * Copies the source string into the destination buffer, up to and including - * the trailing '\0' or up to and including the max'th character, whichever - * comes first. It does not (can not) verify that the destination buffer is - * large enough. If the source string is longer than the maximum length, - * the result will *not* be null-terminated (JLRU). - */ - -PR_EXTERN(char *) -PL_strncpy(char *dest, const char *src, PRUint32 max); - -/* - * PL_strncpyz - * - * Copies the source string into the destination buffer, up to and including - * the trailing '\0' or up but not including the max'th character, whichever - * comes first. It does not (can not) verify that the destination buffer is - * large enough. The destination string is always terminated with a '\0', - * unlike the traditional libc implementation. It returns the "dest" argument. - * - * NOTE: If you call this with a source "abcdefg" and a max of 5, the - * destination will end up with "abcd\0" (i.e., it's strlen length will be 4)! - * - * This means you can do this: - * - * char buffer[ SOME_SIZE ]; - * PL_strncpyz(buffer, src, sizeof(buffer)); - * - * and the result will be properly terminated. - */ - -PR_EXTERN(char *) -PL_strncpyz(char *dest, const char *src, PRUint32 max); - -/* - * PL_strdup - * - * Returns a pointer to a malloc'd extent of memory containing a duplicate - * of the argument string. The size of the allocated extent is one greater - * than the length of the argument string, because of the terminator. A - * null argument, like a zero-length argument, will result in a pointer to - * a one-byte extent containing the null value. This routine returns null - * upon malloc failure. - */ - -PR_EXTERN(char *) -PL_strdup(const char *s); - -/* - * PL_strfree - * - * Free memory allocated by PL_strdup - */ - -PR_EXTERN(void) -PL_strfree(char *s); - -/* - * PL_strndup - * - * Returns a pointer to a malloc'd extent of memory containing a duplicate - * of the argument string, up to the maximum specified. If the argument - * string has a length greater than the value of the specified maximum, the - * return value will be a pointer to an extent of memory of length one - * greater than the maximum specified. A null string, a zero-length string, - * or a zero maximum will all result in a pointer to a one-byte extent - * containing the null value. This routine returns null upon malloc failure. - */ - -PR_EXTERN(char *) -PL_strndup(const char *s, PRUint32 max); - -/* - * PL_strcat - * - * Appends a copy of the string pointed to by the second argument to the - * end of the string pointed to by the first. The destination buffer is - * not (can not be) checked for sufficient size. A null destination - * argument returns null; otherwise, the first argument is returned. - */ - -PR_EXTERN(char *) -PL_strcat(char *dst, const char *src); - -/* - * PL_strncat - * - * Appends a copy of the string pointed to by the second argument, up to - * the maximum size specified, to the end of the string pointed to by the - * first. The destination buffer is not (can not be) checked for sufficient - * size. A null destination argument returns null; otherwise, the first - * argument is returned. If the maximum size limits the copy, then the - * result will *not* be null-terminated (JLRU). A null destination - * returns null; otherwise, the destination argument is returned. - */ - -PR_EXTERN(char *) -PL_strncat(char *dst, const char *src, PRUint32 max); - -/* - * PL_strcatn - * - * Appends a copy of the string pointed to by the third argument, to the - * end of the string pointed to by the first. The second argument specifies - * the maximum size of the destination buffer, including the null termination. - * If the existing string in dst is longer than the max, no action is taken. - * The resulting string will be null-terminated. A null destination returns - * null; otherwise, the destination argument is returned. - */ - -PR_EXTERN(char *) -PL_strcatn(char *dst, PRUint32 max, const char *src); - -/* - * PL_strcmp - * - * Returns an integer, the sign of which -- positive, zero, or negative -- - * reflects the lexical sorting order of the two strings indicated. The - * result is positive if the first string comes after the second. The - * NSPR implementation is not i18n. - */ - -PR_EXTERN(PRIntn) -PL_strcmp(const char *a, const char *b); - -/* - * PL_strncmp - * - * Returns an integer, the sign of which -- positive, zero, or negative -- - * reflects the lexical sorting order of the two strings indicated, up to - * the maximum specified. The result is positive if the first string comes - * after the second. The NSPR implementation is not i18n. If the maximum - * is zero, only the existance or non-existance (pointer is null) of the - * strings is compared. - */ - -PR_EXTERN(PRIntn) -PL_strncmp(const char *a, const char *b, PRUint32 max); - -/* - * PL_strcasecmp - * - * Returns an integer, the sign of which -- positive, zero or negative -- - * reflects the case-insensitive lexical sorting order of the two strings - * indicated. The result is positive if the first string comes after the - * second. The NSPR implementation is not i18n. - */ - -PR_EXTERN(PRIntn) -PL_strcasecmp(const char *a, const char *b); - -/* - * PL_strncasecmp - * - * Returns an integer, the sign of which -- positive, zero or negative -- - * reflects the case-insensitive lexical sorting order of the first n characters - * of the two strings indicated. The result is positive if the first string comes - * after the second. The NSPR implementation is not i18n. - */ - -PR_EXTERN(PRIntn) -PL_strncasecmp(const char *a, const char *b, PRUint32 max); - -/* - * PL_strchr - * - * Returns a pointer to the first instance of the specified character in the - * provided string. It returns null if the character is not found, or if the - * provided string is null. The character may be the null character. - */ - -PR_EXTERN(char *) -PL_strchr(const char *s, char c); - -/* - * PL_strrchr - * - * Returns a pointer to the last instance of the specified character in the - * provided string. It returns null if the character is not found, or if the - * provided string is null. The character may be the null character. - */ - -PR_EXTERN(char *) -PL_strrchr(const char *s, char c); - -/* - * PL_strnchr - * - * Returns a pointer to the first instance of the specified character within the - * first n characters of the provided string. It returns null if the character - * is not found, or if the provided string is null. The character may be the - * null character. - */ - -PR_EXTERN(char *) -PL_strnchr(const char *s, char c, PRUint32 n); - -/* - * PL_strnrchr - * - * Returns a pointer to the last instance of the specified character within the - * first n characters of the provided string. It returns null if the character is - * not found, or if the provided string is null. The character may be the null - * character. - */ - -PR_EXTERN(char *) -PL_strnrchr(const char *s, char c, PRUint32 n); - -/* - * NOTE: Looking for strcasechr, strcaserchr, strncasechr, or strncaserchr? - * Use strpbrk, strprbrk, strnpbrk or strnprbrk. - */ - -/* - * PL_strpbrk - * - * Returns a pointer to the first instance in the first string of any character - * (not including the terminating null character) of the second string. It returns - * null if either string is null. - */ - -PR_EXTERN(char *) -PL_strpbrk(const char *s, const char *list); - -/* - * PL_strprbrk - * - * Returns a pointer to the last instance in the first string of any character - * (not including the terminating null character) of the second string. It returns - * null if either string is null. - */ - -PR_EXTERN(char *) -PL_strprbrk(const char *s, const char *list); - -/* - * PL_strnpbrk - * - * Returns a pointer to the first instance (within the first n characters) of any - * character (not including the terminating null character) of the second string. - * It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strnpbrk(const char *s, const char *list, PRUint32 n); - -/* - * PL_strnprbrk - * - * Returns a pointer to the last instance (within the first n characters) of any - * character (not including the terminating null character) of the second string. - * It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strnprbrk(const char *s, const char *list, PRUint32 n); - -/* - * PL_strstr - * - * Returns a pointer to the first instance of the little string within the - * big one. It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strstr(const char *big, const char *little); - -/* - * PL_strrstr - * - * Returns a pointer to the last instance of the little string within the big one. - * It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strrstr(const char *big, const char *little); - -/* - * PL_strnstr - * - * Returns a pointer to the first instance of the little string within the first - * n characters of the big one. It returns null if either string is null. It - * returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strnstr(const char *big, const char *little, PRUint32 n); - -/* - * PL_strnrstr - * - * Returns a pointer to the last instance of the little string within the first - * n characters of the big one. It returns null if either string is null. It - * returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strnrstr(const char *big, const char *little, PRUint32 max); - -/* - * PL_strcasestr - * - * Returns a pointer to the first instance of the little string within the big one, - * ignoring case. It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strcasestr(const char *big, const char *little); - -/* - * PL_strcaserstr - * - * Returns a pointer to the last instance of the little string within the big one, - * ignoring case. It returns null if either string is null. - */ - -PR_EXTERN(char *) -PL_strcaserstr(const char *big, const char *little); - -/* - * PL_strncasestr - * - * Returns a pointer to the first instance of the listtle string within the first - * n characters of the big one, ignoring case. It returns null if either string is - * null. It returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strncasestr(const char *big, const char *little, PRUint32 max); - -/* - * PL_strncaserstr - * - * Returns a pointer to the last instance of the little string within the first - * n characters of the big one, ignoring case. It returns null if either string is - * null. It returns null if the length of the little string is greater than n. - */ - -PR_EXTERN(char *) -PL_strncaserstr(const char *big, const char *little, PRUint32 max); - -/* - * PL_strtok_r - * - * Splits the string s1 into tokens, separated by one or more characters - * from the separator string s2. The argument lasts points to a - * user-supplied char * pointer in which PL_strtok_r stores information - * for it to continue scanning the same string. - * - * In the first call to PL_strtok_r, s1 points to a string and the value - * of *lasts is ignored. PL_strtok_r returns a pointer to the first - * token, writes '\0' into the character following the first token, and - * updates *lasts. - * - * In subsequent calls, s1 is null and lasts must stay unchanged from the - * previous call. The separator string s2 may be different from call to - * call. PL_strtok_r returns a pointer to the next token in s1. When no - * token remains in s1, PL_strtok_r returns null. - */ - -PR_EXTERN(char *) -PL_strtok_r(char *s1, const char *s2, char **lasts); - -/* - * Things not (yet?) included: strspn/strcspn, strsep. - * memchr, memcmp, memcpy, memccpy, index, rindex, bcmp, bcopy, bzero. - * Any and all i18n/l10n stuff. - */ - -PR_END_EXTERN_C - -#endif /* _plstr_h */ diff --git a/OSX/include/security_asn1/prbit.h b/OSX/include/security_asn1/prbit.h deleted file mode 100644 index b1600f07..00000000 --- a/OSX/include/security_asn1/prbit.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prbit_h___ -#define prbit_h___ - -#include "prtypes.h" -PR_BEGIN_EXTERN_C - -/* -** A prbitmap_t is a long integer that can be used for bitmaps -*/ -typedef unsigned long prbitmap_t; - -#define PR_TEST_BIT(_map,_bit) \ - ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] & (1L << ((_bit) & (PR_BITS_PER_LONG-1)))) -#define PR_SET_BIT(_map,_bit) \ - ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] |= (1L << ((_bit) & (PR_BITS_PER_LONG-1)))) -#define PR_CLEAR_BIT(_map,_bit) \ - ((_map)[(_bit)>>PR_BITS_PER_LONG_LOG2] &= ~(1L << ((_bit) & (PR_BITS_PER_LONG-1)))) - -/* -** Compute the log of the least power of 2 greater than or equal to n -*/ -NSPR_API(PRIntn) PR_CeilingLog2(PRUint32 i); - -/* -** Compute the log of the greatest power of 2 less than or equal to n -*/ -NSPR_API(PRIntn) PR_FloorLog2(PRUint32 i); - -/* -** Macro version of PR_CeilingLog2: Compute the log of the least power of -** 2 greater than or equal to _n. The result is returned in _log2. -*/ -#define PR_CEILING_LOG2(_log2,_n) \ - PR_BEGIN_MACRO \ - PRUint32 j_ = (PRUint32)(_n); \ - (_log2) = 0; \ - if ((j_) & ((j_)-1)) \ - (_log2) += 1; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - PR_END_MACRO - -/* -** Macro version of PR_FloorLog2: Compute the log of the greatest power of -** 2 less than or equal to _n. The result is returned in _log2. -** -** This is equivalent to finding the highest set bit in the word. -*/ -#define PR_FLOOR_LOG2(_log2,_n) \ - PR_BEGIN_MACRO \ - PRUint32 j_ = (PRUint32)(_n); \ - (_log2) = 0; \ - if ((j_) >> 16) \ - (_log2) += 16, (j_) >>= 16; \ - if ((j_) >> 8) \ - (_log2) += 8, (j_) >>= 8; \ - if ((j_) >> 4) \ - (_log2) += 4, (j_) >>= 4; \ - if ((j_) >> 2) \ - (_log2) += 2, (j_) >>= 2; \ - if ((j_) >> 1) \ - (_log2) += 1; \ - PR_END_MACRO - -PR_END_EXTERN_C -#endif /* prbit_h___ */ diff --git a/OSX/include/security_asn1/prcpucfg.h b/OSX/include/security_asn1/prcpucfg.h deleted file mode 100644 index 799dc52b..00000000 --- a/OSX/include/security_asn1/prcpucfg.h +++ /dev/null @@ -1,192 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998-2000 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#ifndef nspr_cpucfg___ -#define nspr_cpucfg___ - -#ifndef XP_MAC -#define XP_MAC -#endif - -#undef IS_LITTLE_ENDIAN -#define IS_BIG_ENDIAN 1 - -#define HAVE_LONG_LONG - -#define PR_AF_INET6 30 /* same as AF_INET6 */ -#ifdef __x86_64__ -#define IS_64 -#endif - -#ifndef HAVE_LONG_LONG -#define HAVE_LONG_LONG -#endif -#undef HAVE_ALIGNED_DOUBLES -#define HAVE_ALIGNED_LONGLONGS 1 - -#ifdef IS_64 - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 8 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 8 -#define PR_BYTES_PER_DWORD 8 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 64 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 64 -#define PR_BITS_PER_DWORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 6 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 6 -#define PR_BITS_PER_DWORD_LOG2 6 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 8 -#define PR_ALIGN_OF_INT64 8 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 8 -#define PR_ALIGN_OF_POINTER 8 -#define PR_ALIGN_OF_WORD 8 -#define PR_ALIGN_OF_DWORD 8 - -#else /* IS_64 */ - -#define PR_BYTES_PER_BYTE 1 -#define PR_BYTES_PER_SHORT 2 -#define PR_BYTES_PER_INT 4 -#define PR_BYTES_PER_INT64 8 -#define PR_BYTES_PER_LONG 4 -#define PR_BYTES_PER_FLOAT 4 -#define PR_BYTES_PER_DOUBLE 8 -#define PR_BYTES_PER_WORD 4 -#define PR_BYTES_PER_DWORD 8 -#define PR_BYTES_PER_WORD_LOG2 2 -#define PR_BYTES_PER_DWORD_LOG2 3 - -#define PR_BITS_PER_BYTE 8 -#define PR_BITS_PER_SHORT 16 -#define PR_BITS_PER_INT 32 -#define PR_BITS_PER_INT64 64 -#define PR_BITS_PER_LONG 32 -#define PR_BITS_PER_FLOAT 32 -#define PR_BITS_PER_DOUBLE 64 -#define PR_BITS_PER_WORD 32 -#define PR_BITS_PER_DWORD 64 - -#define PR_BITS_PER_BYTE_LOG2 3 -#define PR_BITS_PER_SHORT_LOG2 4 -#define PR_BITS_PER_INT_LOG2 5 -#define PR_BITS_PER_INT64_LOG2 6 -#define PR_BITS_PER_LONG_LOG2 5 -#define PR_BITS_PER_FLOAT_LOG2 5 -#define PR_BITS_PER_DOUBLE_LOG2 6 -#define PR_BITS_PER_WORD_LOG2 5 - -#define PR_ALIGN_OF_SHORT 2 -#define PR_ALIGN_OF_INT 4 -#define PR_ALIGN_OF_LONG 4 -#define PR_ALIGN_OF_INT64 4 -#define PR_ALIGN_OF_FLOAT 4 -#define PR_ALIGN_OF_DOUBLE 4 -#define PR_ALIGN_OF_POINTER 4 -#define PR_ALIGN_OF_WORD 4 - -#endif /* IS_64 */ - -#ifndef NO_NSPR_10_SUPPORT - -#define BYTES_PER_BYTE PR_BYTES_PER_BYTE -#define BYTES_PER_SHORT PR_BYTES_PER_SHORT -#define BYTES_PER_INT PR_BYTES_PER_INT -#define BYTES_PER_INT64 PR_BYTES_PER_INT64 -#define BYTES_PER_LONG PR_BYTES_PER_LONG -#define BYTES_PER_FLOAT PR_BYTES_PER_FLOAT -#define BYTES_PER_DOUBLE PR_BYTES_PER_DOUBLE -#define BYTES_PER_WORD PR_BYTES_PER_WORD -#define BYTES_PER_DWORD PR_BYTES_PER_DWORD - -#define BITS_PER_BYTE PR_BITS_PER_BYTE -#define BITS_PER_SHORT PR_BITS_PER_SHORT -#define BITS_PER_INT PR_BITS_PER_INT -#define BITS_PER_INT64 PR_BITS_PER_INT64 -#define BITS_PER_LONG PR_BITS_PER_LONG -#define BITS_PER_FLOAT PR_BITS_PER_FLOAT -#define BITS_PER_DOUBLE PR_BITS_PER_DOUBLE -#define BITS_PER_WORD PR_BITS_PER_WORD - -#define BITS_PER_BYTE_LOG2 PR_BITS_PER_BYTE_LOG2 -#define BITS_PER_SHORT_LOG2 PR_BITS_PER_SHORT_LOG2 -#define BITS_PER_INT_LOG2 PR_BITS_PER_INT_LOG2 -#define BITS_PER_INT64_LOG2 PR_BITS_PER_INT64_LOG2 -#define BITS_PER_LONG_LOG2 PR_BITS_PER_LONG_LOG2 -#define BITS_PER_FLOAT_LOG2 PR_BITS_PER_FLOAT_LOG2 -#define BITS_PER_DOUBLE_LOG2 PR_BITS_PER_DOUBLE_LOG2 -#define BITS_PER_WORD_LOG2 PR_BITS_PER_WORD_LOG2 - -#define ALIGN_OF_SHORT PR_ALIGN_OF_SHORT -#define ALIGN_OF_INT PR_ALIGN_OF_INT -#define ALIGN_OF_LONG PR_ALIGN_OF_LONG -#define ALIGN_OF_INT64 PR_ALIGN_OF_INT64 -#define ALIGN_OF_FLOAT PR_ALIGN_OF_FLOAT -#define ALIGN_OF_DOUBLE PR_ALIGN_OF_DOUBLE -#define ALIGN_OF_POINTER PR_ALIGN_OF_POINTER -#define ALIGN_OF_WORD PR_ALIGN_OF_WORD - -#define BYTES_PER_WORD_LOG2 PR_BYTES_PER_WORD_LOG2 -#define BYTES_PER_DWORD_LOG2 PR_BYTES_PER_DWORD_LOG2 -#define WORDS_PER_DWORD_LOG2 PR_WORDS_PER_DWORD_LOG2 - -#endif /* NO_NSPR_10_SUPPORT */ - -#endif /* nspr_cpucfg___ */ diff --git a/OSX/include/security_asn1/prcvar.h b/OSX/include/security_asn1/prcvar.h deleted file mode 100644 index 9657415f..00000000 --- a/OSX/include/security_asn1/prcvar.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prcvar_h___ -#define prcvar_h___ - -#include -#include - -PR_BEGIN_EXTERN_C - -typedef struct PRCondVar PRCondVar; - -/* -** Create a new condition variable. -** -** "lock" is the lock used to protect the condition variable. -** -** Condition variables are synchronization objects that threads can use -** to wait for some condition to occur. -** -** This may fail if memory is tight or if some operating system resource -** is low. In such cases, a NULL will be returned. -*/ -NSPR_API(PRCondVar*) PR_NewCondVar(PRLock *lock); - -/* -** Destroy a condition variable. There must be no thread -** waiting on the condvar. The caller is responsible for guaranteeing -** that the condvar is no longer in use. -** -*/ -NSPR_API(void) PR_DestroyCondVar(PRCondVar *cvar); - -/* -** The thread that waits on a condition is blocked in a "waiting on -** condition" state until another thread notifies the condition or a -** caller specified amount of time expires. The lock associated with -** the condition variable will be released, which must have be held -** prior to the call to wait. -** -** Logically a notified thread is moved from the "waiting on condition" -** state and made "ready." When scheduled, it will attempt to reacquire -** the lock that it held when wait was called. -** -** The timeout has two well known values, PR_INTERVAL_NO_TIMEOUT and -** PR_INTERVAL_NO_WAIT. The former value requires that a condition be -** notified (or the thread interrupted) before it will resume from the -** wait. If the timeout has a value of PR_INTERVAL_NO_WAIT, the effect -** is to release the lock, possibly causing a rescheduling within the -** runtime, then immediately attempting to reacquire the lock and resume. -** -** Any other value for timeout will cause the thread to be rescheduled -** either due to explicit notification or an expired interval. The latter -** must be determined by treating time as one part of the monitored data -** being protected by the lock and tested explicitly for an expired -** interval. -** -** Returns PR_FAILURE if the caller has not locked the lock associated -** with the condition variable or the thread was interrupted (PR_Interrupt()). -** The particular reason can be extracted with PR_GetError(). -*/ -NSPR_API(PRStatus) PR_WaitCondVar(PRCondVar *cvar, PRIntervalTime timeout); - -/* -** Notify ONE thread that is currently waiting on 'cvar'. Which thread is -** dependent on the implementation of the runtime. Common sense would dictate -** that all threads waiting on a single condition have identical semantics, -** therefore which one gets notified is not significant. -** -** The calling thead must hold the lock that protects the condition, as -** well as the invariants that are tightly bound to the condition, when -** notify is called. -** -** Returns PR_FAILURE if the caller has not locked the lock associated -** with the condition variable. -*/ -NSPR_API(PRStatus) PR_NotifyCondVar(PRCondVar *cvar); - -/* -** Notify all of the threads waiting on the condition variable. The order -** that the threads are notified is indeterminant. The lock that protects -** the condition must be held. -** -** Returns PR_FAILURE if the caller has not locked the lock associated -** with the condition variable. -*/ -NSPR_API(PRStatus) PR_NotifyAllCondVar(PRCondVar *cvar); - -PR_END_EXTERN_C - -#endif /* prcvar_h___ */ diff --git a/OSX/include/security_asn1/prenv.h b/OSX/include/security_asn1/prenv.h deleted file mode 100644 index acf79522..00000000 --- a/OSX/include/security_asn1/prenv.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions requiored by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prenv_h___ -#define prenv_h___ - -#include - -/*******************************************************************************/ -/*******************************************************************************/ -/****************** THESE FUNCTIONS MAY NOT BE THREAD SAFE *********************/ -/*******************************************************************************/ -/*******************************************************************************/ - -PR_BEGIN_EXTERN_C - -/* -** PR_GetEnv() -- Retrieve value of environment variable -** -** Description: -** PR_GetEnv() is modeled on Unix getenv(). -** -** -** Inputs: -** var -- The name of the environment variable -** -** Returns: -** The value of the environment variable 'var' or NULL if -** the variable is undefined. -** -** Restrictions: -** You'd think that a POSIX getenv(), putenv() would be -** consistently implemented everywhere. Surprise! It is not. On -** some platforms, a putenv() where the argument is of -** the form "name" causes the named environment variable to -** be un-set; that is: a subsequent getenv() returns NULL. On -** other platforms, the putenv() fails, on others, it is a -** no-op. Similarly, a putenv() where the argument is of the -** form "name=" causes the named environment variable to be -** un-set; a subsequent call to getenv() returns NULL. On -** other platforms, a subsequent call to getenv() returns a -** pointer to a null-string (a byte of zero). -** -** PR_GetEnv(), PR_SetEnv() provide a consistent behavior -** across all supported platforms. There are, however, some -** restrictions and some practices you must use to achieve -** consistent results everywhere. -** -** When manipulating the environment there is no way to un-set -** an environment variable across all platforms. We suggest -** you interpret the return of a pointer to null-string to -** mean the same as a return of NULL from PR_GetEnv(). -** -** A call to PR_SetEnv() where the parameter is of the form -** "name" will return PR_FAILURE; the environment remains -** unchanged. A call to PR_SetEnv() where the parameter is -** of the form "name=" may un-set the envrionment variable on -** some platforms; on others it may set the value of the -** environment variable to the null-string. -** -** For example, to test for NULL return or return of the -** null-string from PR_GetEnv(), use the following code -** fragment: -** -** char *val = PR_GetEnv("foo"); -** if ((NULL == val) || ('\0' == *val)) { -** ... interpret this as un-set ... -** } -** -** The caller must ensure that the string passed -** to PR_SetEnv() is persistent. That is: The string should -** not be on the stack, where it can be overwritten -** on return from the function calling PR_SetEnv(). -** Similarly, the string passed to PR_SetEnv() must not be -** overwritten by other actions of the process. ... Some -** platforms use the string by reference rather than copying -** it into the environment space. ... You have been warned! -** -** Use of platform-native functions that manipulate the -** environment (getenv(), putenv(), -** SetEnvironmentVariable(), etc.) must not be used with -** NSPR's similar functions. The platform-native functions -** may not be thread safe and/or may operate on different -** conceptual environment space than that operated upon by -** NSPR's functions or other environment manipulating -** functions on the same platform. (!) -** -*/ -NSPR_API(char*) PR_GetEnv(const char *var); - -/* -** PR_SetEnv() -- set, unset or change an environment variable -** -** Description: -** PR_SetEnv() is modeled on the Unix putenv() function. -** -** Inputs: -** string -- pointer to a caller supplied -** constant, persistent string of the form name=value. Where -** name is the name of the environment variable to be set or -** changed; value is the value assigned to the variable. -** -** Returns: -** PRStatus. -** -** Restrictions: -** See the Restrictions documented in the description of -** PR_GetEnv() in this header file. -** -** -*/ -NSPR_API(PRStatus) PR_SetEnv(const char *string); - -/* -** DEPRECATED. Use PR_SetEnv() instead. -*/ -#ifdef XP_MAC -NSPR_API(PRIntn) PR_PutEnv(const char *string); -#endif - -PR_END_EXTERN_C - -#endif /* prenv_h___ */ diff --git a/OSX/include/security_asn1/prerr.h b/OSX/include/security_asn1/prerr.h deleted file mode 100644 index 5bb6c9e8..00000000 --- a/OSX/include/security_asn1/prerr.h +++ /dev/null @@ -1,275 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prerr_h___ -#define prerr_h___ - -/* - * - * prerr.h - * This file is automatically generated; please do not edit it. - */ - -/* Memory allocation attempt failed */ -#define PR_OUT_OF_MEMORY_ERROR (-6000L) - -/* Invalid file descriptor */ -#define PR_BAD_DESCRIPTOR_ERROR (-5999L) - -/* The operation would have blocked */ -#define PR_WOULD_BLOCK_ERROR (-5998L) - -/* Invalid memory address argument */ -#define PR_ACCESS_FAULT_ERROR (-5997L) - -/* Invalid function for file type */ -#define PR_INVALID_METHOD_ERROR (-5996L) - -/* Invalid memory address argument */ -#define PR_ILLEGAL_ACCESS_ERROR (-5995L) - -/* Some unknown error has occurred */ -#define PR_UNKNOWN_ERROR (-5994L) - -/* Operation interrupted by another thread */ -#define PR_PENDING_INTERRUPT_ERROR (-5993L) - -/* function not implemented */ -#define PR_NOT_IMPLEMENTED_ERROR (-5992L) - -/* I/O function error */ -#define PR_IO_ERROR (-5991L) - -/* I/O operation timed out */ -#define PR_IO_TIMEOUT_ERROR (-5990L) - -/* I/O operation on busy file descriptor */ -#define PR_IO_PENDING_ERROR (-5989L) - -/* The directory could not be opened */ -#define PR_DIRECTORY_OPEN_ERROR (-5988L) - -/* Invalid function argument */ -#define PR_INVALID_ARGUMENT_ERROR (-5987L) - -/* Network address not available (in use?) */ -#define PR_ADDRESS_NOT_AVAILABLE_ERROR (-5986L) - -/* Network address type not supported */ -#define PR_ADDRESS_NOT_SUPPORTED_ERROR (-5985L) - -/* Already connected */ -#define PR_IS_CONNECTED_ERROR (-5984L) - -/* Network address is invalid */ -#define PR_BAD_ADDRESS_ERROR (-5983L) - -/* Local Network address is in use */ -#define PR_ADDRESS_IN_USE_ERROR (-5982L) - -/* Connection refused by peer */ -#define PR_CONNECT_REFUSED_ERROR (-5981L) - -/* Network address is presently unreachable */ -#define PR_NETWORK_UNREACHABLE_ERROR (-5980L) - -/* Connection attempt timed out */ -#define PR_CONNECT_TIMEOUT_ERROR (-5979L) - -/* Network file descriptor is not connected */ -#define PR_NOT_CONNECTED_ERROR (-5978L) - -/* Failure to load dynamic library */ -#define PR_LOAD_LIBRARY_ERROR (-5977L) - -/* Failure to unload dynamic library */ -#define PR_UNLOAD_LIBRARY_ERROR (-5976L) - -/* Symbol not found in any of the loaded dynamic libraries */ -#define PR_FIND_SYMBOL_ERROR (-5975L) - -/* Insufficient system resources */ -#define PR_INSUFFICIENT_RESOURCES_ERROR (-5974L) - -/* A directory lookup on a network address has failed */ -#define PR_DIRECTORY_LOOKUP_ERROR (-5973L) - -/* Attempt to access a TPD key that is out of range */ -#define PR_TPD_RANGE_ERROR (-5972L) - -/* Process open FD table is full */ -#define PR_PROC_DESC_TABLE_FULL_ERROR (-5971L) - -/* System open FD table is full */ -#define PR_SYS_DESC_TABLE_FULL_ERROR (-5970L) - -/* Network operation attempted on non-network file descriptor */ -#define PR_NOT_SOCKET_ERROR (-5969L) - -/* TCP-specific function attempted on a non-TCP file descriptor */ -#define PR_NOT_TCP_SOCKET_ERROR (-5968L) - -/* TCP file descriptor is already bound */ -#define PR_SOCKET_ADDRESS_IS_BOUND_ERROR (-5967L) - -/* Access Denied */ -#define PR_NO_ACCESS_RIGHTS_ERROR (-5966L) - -/* The requested operation is not supported by the platform */ -#define PR_OPERATION_NOT_SUPPORTED_ERROR (-5965L) - -/* The host operating system does not support the protocol requested */ -#define PR_PROTOCOL_NOT_SUPPORTED_ERROR (-5964L) - -/* Access to the remote file has been severed */ -#define PR_REMOTE_FILE_ERROR (-5963L) - -/* The value requested is too large to be stored in the data buffer provided */ -#define PR_BUFFER_OVERFLOW_ERROR (-5962L) - -/* TCP connection reset by peer */ -#define PR_CONNECT_RESET_ERROR (-5961L) - -/* Unused */ -#define PR_RANGE_ERROR (-5960L) - -/* The operation would have deadlocked */ -#define PR_DEADLOCK_ERROR (-5959L) - -/* The file is already locked */ -#define PR_FILE_IS_LOCKED_ERROR (-5958L) - -/* Write would result in file larger than the system allows */ -#define PR_FILE_TOO_BIG_ERROR (-5957L) - -/* The device for storing the file is full */ -#define PR_NO_DEVICE_SPACE_ERROR (-5956L) - -/* Unused */ -#define PR_PIPE_ERROR (-5955L) - -/* Unused */ -#define PR_NO_SEEK_DEVICE_ERROR (-5954L) - -/* Cannot perform a normal file operation on a directory */ -#define PR_IS_DIRECTORY_ERROR (-5953L) - -/* Symbolic link loop */ -#define PR_LOOP_ERROR (-5952L) - -/* File name is too long */ -#define PR_NAME_TOO_LONG_ERROR (-5951L) - -/* File not found */ -#define PR_FILE_NOT_FOUND_ERROR (-5950L) - -/* Cannot perform directory operation on a normal file */ -#define PR_NOT_DIRECTORY_ERROR (-5949L) - -/* Cannot write to a read-only file system */ -#define PR_READ_ONLY_FILESYSTEM_ERROR (-5948L) - -/* Cannot delete a directory that is not empty */ -#define PR_DIRECTORY_NOT_EMPTY_ERROR (-5947L) - -/* Cannot delete or rename a file object while the file system is busy */ -#define PR_FILESYSTEM_MOUNTED_ERROR (-5946L) - -/* Cannot rename a file to a file system on another device */ -#define PR_NOT_SAME_DEVICE_ERROR (-5945L) - -/* The directory object in the file system is corrupted */ -#define PR_DIRECTORY_CORRUPTED_ERROR (-5944L) - -/* Cannot create or rename a filename that already exists */ -#define PR_FILE_EXISTS_ERROR (-5943L) - -/* Directory is full. No additional filenames may be added */ -#define PR_MAX_DIRECTORY_ENTRIES_ERROR (-5942L) - -/* The required device was in an invalid state */ -#define PR_INVALID_DEVICE_STATE_ERROR (-5941L) - -/* The device is locked */ -#define PR_DEVICE_IS_LOCKED_ERROR (-5940L) - -/* No more entries in the directory */ -#define PR_NO_MORE_FILES_ERROR (-5939L) - -/* Encountered end of file */ -#define PR_END_OF_FILE_ERROR (-5938L) - -/* Seek error */ -#define PR_FILE_SEEK_ERROR (-5937L) - -/* The file is busy */ -#define PR_FILE_IS_BUSY_ERROR (-5936L) - -/* The I/O operation was aborted */ -#define PR_OPERATION_ABORTED_ERROR (-5935L) - -/* Operation is still in progress (probably a non-blocking connect) */ -#define PR_IN_PROGRESS_ERROR (-5934L) - -/* Operation has already been initiated (probably a non-blocking connect) */ -#define PR_ALREADY_INITIATED_ERROR (-5933L) - -/* The wait group is empty */ -#define PR_GROUP_EMPTY_ERROR (-5932L) - -/* Object state improper for request */ -#define PR_INVALID_STATE_ERROR (-5931L) - -/* Network is down */ -#define PR_NETWORK_DOWN_ERROR (-5930L) - -/* Socket shutdown */ -#define PR_SOCKET_SHUTDOWN_ERROR (-5929L) - -/* Connection aborted */ -#define PR_CONNECT_ABORTED_ERROR (-5928L) - -/* Host is unreachable */ -#define PR_HOST_UNREACHABLE_ERROR (-5927L) - -/* The library is not loaded */ -#define PR_LIBRARY_NOT_LOADED_ERROR (-5926L) - -/* Placeholder for the end of the list */ -#define PR_MAX_ERROR (-5925L) - -extern void nspr_InitializePRErrorTable(void); -#define ERROR_TABLE_BASE_nspr (-6000L) - -#endif /* prerr_h___ */ diff --git a/OSX/include/security_asn1/prerror.h b/OSX/include/security_asn1/prerror.h deleted file mode 100644 index 0db93fb0..00000000 --- a/OSX/include/security_asn1/prerror.h +++ /dev/null @@ -1,323 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prerror_h___ -#define prerror_h___ - -#include - -PR_BEGIN_EXTERN_C - -typedef PRInt32 PRErrorCode; - -#define PR_NSPR_ERROR_BASE -6000 - -#include "prerr.h" - -/* -** Set error will preserve an error condition within a thread context. -** The values stored are the NSPR (platform independent) translation of -** the error. Also, if available, the platform specific oserror is stored. -** If there is no appropriate OS error number, a zero my be supplied. -*/ -NSPR_API(void) PR_SetError(PRErrorCode errorCode, PRInt32 oserr); - -/* -** The text value specified may be NULL. If it is not NULL and the text length -** is zero, the string is assumed to be a null terminated C string. Otherwise -** the text is assumed to be the length specified and possibly include NULL -** characters (e.g., a multi-national string). -** -** The text will be copied into to thread structure and remain there -** until the next call to PR_SetError. -*/ -NSPR_API(void) PR_SetErrorText( - PRIntn textLength, const char *text); - -/* -** Return the current threads last set error code. -*/ -NSPR_API(PRErrorCode) PR_GetError(void); - -/* -** Return the current threads last set os error code. This is used for -** machine specific code that desires the underlying os error. -*/ -NSPR_API(PRInt32) PR_GetOSError(void); - -/* -** Get the length of the error text. If a zero is returned, then there -** is no text. Otherwise, the value returned is sufficient to contain -** the error text currently available. -*/ -NSPR_API(PRInt32) PR_GetErrorTextLength(void); - -/* -** Copy the current threads current error text. Then actual number of bytes -** copied is returned as the result. If the result is zero, the 'text' area -** is unaffected. -*/ -NSPR_API(PRInt32) PR_GetErrorText(char *text); - - -/* -Copyright (C) 1987, 1988 Student Information Processing Board of the -Massachusetts Institute of Technology. - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, provided -that the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be -used in advertising or publicity pertaining to distribution of the software -without specific, written prior permission. M.I.T. and the M.I.T. S.I.P.B. -make no representations about the suitability of this software for any -purpose. It is provided "as is" without express or implied warranty. -*/ - - -/* - * NOTE: - * The interfaces for error-code-translation described in the rest of - * this file are preliminary in the 3.1 release of nspr and are subject - * to change in future releases. - */ - -/* -** Description: Localizable error code to string function. -** -** -** NSPR provides a mechanism for converting an error code to a -** descriptive string, in a caller-specified language. -** -** Error codes themselves are 32 bit (signed) integers. Typically, -** the high order 24 bits are an identifier of which error table the -** error code is from, and the low order 8 bits are a sequential error -** number within the table. NSPR supports error tables whose first -** error code is not a multiple of 256, such error code assignments -** should be avoided when possible. -** -** Error table 0 is defined to match the UNIX system call error table -** (sys_errlist); this allows errno values to be used directly in the -** library. Other error table numbers are typically formed by -** compacting together the first four characters of the error table -** name. The mapping between characters in the name and numeric -** values in the error code are defined in a system-independent -** fashion, so that two systems that can pass integral values between -** them can reliably pass error codes without loss of meaning; this -** should work even if the character sets used are not the -** same. (However, if this is to be done, error table 0 should be -** avoided, since the local system call error tables may differ.) -** -** Libraries defining error codes need only provide a table mapping -** error code numbers to names and default English descriptions, -** calling a routine to install the table, making it ``known'' to NSPR -** library. Once installed, a table may not be removed. Any error -** code the library generates can be converted to the corresponding -** error message. There is also a default format for error codes -** accidentally returned before making the table known, which is of -** the form "unknown code foo 32", where "foo" would be the name of -** the table. -** -** Normally, the error code conversion routine only supports the -** languages "i-default" and "en", returning the error-table-provided -** English description for both languages. The application may -** provide a localization plugin, allowing support for additional -** languages. -** -**/ - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -/* - * PRLanguageCode -- - * - * NSPR represents a language code as a non-negative integer. - * Languages 0 is always "i-default" the language you get without - * explicit negotiation. Language 1 is always "en", English - * which has been explicitly negotiated. Additional language - * codes are defined by an application-provided localization plugin. - */ -typedef PRUint32 PRLanguageCode; -#define PR_LANGUAGE_I_DEFAULT 0 /* i-default, the default language */ -#define PR_LANGUAGE_EN 1 /* English, explicitly negotiated */ - -/* - * struct PRErrorMessage -- - * - * An error message in an error table. - */ -struct PRErrorMessage { - const char * name; /* Macro name for error */ - const char * en_text; /* Default English text */ -}; - -/* - * struct PRErrorTable -- - * - * An error table, provided by a library. - */ -struct PRErrorTable { - const struct PRErrorMessage * msgs; /* Array of error information */ - const char *name; /* Name of error table source */ - PRErrorCode base; /* Error code for first error in table */ - int n_msgs; /* Number of codes in table */ -}; - -/* - * struct PRErrorCallbackPrivate -- - * - * A private structure for the localization plugin - */ -struct PRErrorCallbackPrivate; - -/* - * struct PRErrorCallbackTablePrivate -- - * - * A data structure under which the localization plugin may store information, - * associated with an error table, that is private to itself. - */ -struct PRErrorCallbackTablePrivate; - -/* - * PRErrorCallbackLookupFn -- - * - * A function of PRErrorCallbackLookupFn type is a localization - * plugin callback which converts an error code into a description - * in the requested language. The callback is provided the - * appropriate error table, private data for the plugin and the table. - * The callback returns the appropriate UTF-8 encoded description, or NULL - * if no description can be found. - */ -typedef const char * -PRErrorCallbackLookupFn(PRErrorCode code, PRLanguageCode language, - const struct PRErrorTable *table, - struct PRErrorCallbackPrivate *cb_private, - struct PRErrorCallbackTablePrivate *table_private); - -/* - * PRErrorCallbackNewTableFn -- - * - * A function PRErrorCallbackNewTableFn type is a localization plugin - * callback which is called once with each error table registered - * with NSPR. The callback is provided with the error table and - * the plugin's private structure. The callback returns any table private - * data it wishes to associate with the error table. Does not need to be thread - * safe. - */ -typedef struct PRErrorCallbackTablePrivate * -PRErrorCallbackNewTableFn(const struct PRErrorTable *table, - struct PRErrorCallbackPrivate *cb_private); - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/*********************************************************************** -** FUNCTION: PR_ErrorToString -** DESCRIPTION: -** Returns the UTF-8 message for an error code in -** the requested language. May return the message -** in the default language if a translation in the requested -** language is not available. The returned string is -** valid for the duration of the process. Never returns NULL. -** -***********************************************************************/ -NSPR_API(const char *) PR_ErrorToString(PRErrorCode code, - PRLanguageCode language); - - -/*********************************************************************** -** FUNCTION: PR_ErrorToName -** DESCRIPTION: -** Returns the macro name for an error code, or NULL -** if the error code is not known. The returned string is -** valid for the duration of the process. -** -** Does not work for error table 0, the system error codes. -** -***********************************************************************/ -NSPR_API(const char *) PR_ErrorToName(PRErrorCode code); - - -/*********************************************************************** -** FUNCTION: PR_ErrorLanguages -** DESCRIPTION: -** Returns the RFC 1766 language tags for the language -** codes PR_ErrorToString() supports. The returned array is valid -** for the duration of the process. Never returns NULL. The first -** item in the returned array is the language tag for PRLanguageCode 0, -** the second is for PRLanguageCode 1, and so on. The array is terminated -** with a null pointer. -** -***********************************************************************/ -NSPR_API(const char * const *) PR_ErrorLanguages(void); - - -/*********************************************************************** -** FUNCTION: PR_ErrorInstallTable -** DESCRIPTION: -** Registers an error table with NSPR. Must be done exactly once per -** table. Memory pointed to by `table' must remain valid for the life -** of the process. -** -** NOT THREAD SAFE! -** -***********************************************************************/ -NSPR_API(PRErrorCode) PR_ErrorInstallTable(const struct PRErrorTable *table); - - -/*********************************************************************** -** FUNCTION: PR_ErrorInstallCallback -** DESCRIPTION: -** Registers an error localization plugin with NSPR. May be called -** at most one time. `languages' contains the language codes supported -** by this plugin. Languages 0 and 1 must be "i-default" and "en" -** respectively. `lookup' and `newtable' contain pointers to -** the plugin callback functions. `cb_private' contains any information -** private to the plugin functions. -** -** NOT THREAD SAFE! -** -***********************************************************************/ -NSPR_API(void) PR_ErrorInstallCallback(const char * const * languages, - PRErrorCallbackLookupFn *lookup, - PRErrorCallbackNewTableFn *newtable, - struct PRErrorCallbackPrivate *cb_private); - -PR_END_EXTERN_C - -#endif /* prerror_h___ */ diff --git a/OSX/include/security_asn1/prinit.h b/OSX/include/security_asn1/prinit.h deleted file mode 100644 index adfb76f4..00000000 --- a/OSX/include/security_asn1/prinit.h +++ /dev/null @@ -1,240 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prinit_h___ -#define prinit_h___ - -#include "prthread.h" -#include "prtypes.h" -/* dmitch - WHY THIS!? #include "prwin16.h" */ -#include - -PR_BEGIN_EXTERN_C - -/************************************************************************/ -/**************************IDENTITY AND VERSIONING***********************/ -/************************************************************************/ - -/* -** NSPR's name, this should persist until at least the turn of the -** century. -*/ -#define PR_NAME "NSPR" - -/* -** NSPR's version is used to determine the likelihood that the version you -** used to build your component is anywhere close to being compatible with -** what is in the underlying library. -** -** The format of the version string is -** ".[.] []" -*/ -#define PR_VERSION "4.3 Beta" -#define PR_VMAJOR 4 -#define PR_VMINOR 3 -#define PR_VPATCH 0 -#define PR_BETA PR_TRUE - -/* -** PRVersionCheck -** -** The basic signature of the function that is called to provide version -** checking. The result will be a boolean that indicates the likelihood -** that the underling library will perform as the caller expects. -** -** The only argument is a string, which should be the verson identifier -** of the library in question. That string will be compared against an -** equivalent string that represents the actual build version of the -** exporting library. -** -** The result will be the logical union of the directly called library -** and all dependent libraries. -*/ - -typedef PRBool (*PRVersionCheck)(const char*); - -/* -** PR_VersionCheck -** -** NSPR's existance proof of the version check function. -** -** Note that NSPR has no cooperating dependencies. -*/ - -NSPR_API(PRBool) PR_VersionCheck(const char *importedVersion); - - -/************************************************************************/ -/*******************************INITIALIZATION***************************/ -/************************************************************************/ - -/* -** Initialize the runtime. Attach a thread object to the currently -** executing native thread of type "type". -** -** The specificaiton of 'maxPTDs' is ignored. -*/ -NSPR_API(void) PR_Init( - PRThreadType type, PRThreadPriority priority, PRUintn maxPTDs); - -/* -** And alternate form of initialization, one that may become the default if -** not the only mechanism, provides a method to get the NSPR runtime init- -** ialized and place NSPR between the caller and the runtime library. This -** allows main() to be treated as any other thread root function, signalling -** its compeletion by returning and allowing the runtime to coordinate the -** completion of the other threads of the runtime. -** -** The priority of the main (or primordial) thread will be PR_PRIORITY_NORMAL. -** The thread may adjust its own priority by using PR_SetPriority(), though -** at this time the support for priorities is somewhat weak. -** -** The specificaiton of 'maxPTDs' is ignored. -** -** The value returned by PR_Initialize is the value returned from the root -** function, 'prmain'. -*/ - -typedef PRIntn (PR_CALLBACK *PRPrimordialFn)(PRIntn argc, char **argv); - -NSPR_API(PRIntn) PR_Initialize( - PRPrimordialFn prmain, PRIntn argc, char **argv, PRUintn maxPTDs); - -/* -** Return PR_TRUE if PR_Init has already been called. -*/ -NSPR_API(PRBool) PR_Initialized(void); - -/* - * Perform a graceful shutdown of NSPR. PR_Cleanup() may be called by - * the primordial thread near the end of the main() function. - * - * PR_Cleanup() attempts to synchronize the natural termination of - * process. It does that by blocking the caller, if and only if it is - * the primordial thread, until the number of user threads has dropped - * to zero. When the primordial thread returns from main(), the process - * will immediately and silently exit. That is, it will (if necessary) - * forcibly terminate any existing threads and exit without significant - * blocking and there will be no error messages or core files. - * - * PR_Cleanup() returns PR_SUCCESS if NSPR is successfully shutdown, - * or PR_FAILURE if the calling thread of this function is not the - * primordial thread. - */ -NSPR_API(PRStatus) PR_Cleanup(void); - -/* -** Disable Interrupts -** Disables timer signals used for pre-emptive scheduling. -*/ -NSPR_API(void) PR_DisableClockInterrupts(void); - -/* -** Enables Interrupts -** Enables timer signals used for pre-emptive scheduling. -*/ -NSPR_API(void) PR_EnableClockInterrupts(void); - -/* -** Block Interrupts -** Blocks the timer signal used for pre-emptive scheduling -*/ -NSPR_API(void) PR_BlockClockInterrupts(void); - -/* -** Unblock Interrupts -** Unblocks the timer signal used for pre-emptive scheduling -*/ -NSPR_API(void) PR_UnblockClockInterrupts(void); - -/* -** Create extra virtual processor threads. Generally used with MP systems. -*/ -NSPR_API(void) PR_SetConcurrency(PRUintn numCPUs); - -/* -** Control the method and size of the file descriptor (PRFileDesc*) -** cache used by the runtime. Setting 'high' to zero is for performance, -** any other value probably for debugging (see memo on FD caching). -*/ -NSPR_API(PRStatus) PR_SetFDCacheSize(PRIntn low, PRIntn high); - -/* - * Cause an immediate, nongraceful, forced termination of the process. - * It takes a PRIntn argument, which is the exit status code of the - * process. - */ -NSPR_API(void) PR_ProcessExit(PRIntn status); - -/* -** Abort the process in a non-graceful manner. This will cause a core file, -** call to the debugger or other moral equivalent as well as causing the -** entire process to stop. -*/ -NSPR_API(void) PR_Abort(void); - -/* - **************************************************************** - * - * Module initialization: - * - **************************************************************** - */ -#ifndef __APPLE__ -/* deleted in favor of ModuleNexus */ -typedef struct PRCallOnceType { - PRIntn initialized; - PRInt32 inProgress; - PRStatus status; -} PRCallOnceType; - -typedef PRStatus (PR_CALLBACK *PRCallOnceFN)(void); - -typedef PRStatus (PR_CALLBACK *PRCallOnceWithArgFN)(void *arg); - -NSPR_API(PRStatus) PR_CallOnce( - PRCallOnceType *once, - PRCallOnceFN func -); - -NSPR_API(PRStatus) PR_CallOnceWithArg( - PRCallOnceType *once, - PRCallOnceWithArgFN func, - void *arg -); -#endif /* __APPLE__ */ - -PR_END_EXTERN_C - -#endif /* prinit_h___ */ diff --git a/OSX/include/security_asn1/prinrval.h b/OSX/include/security_asn1/prinrval.h deleted file mode 100644 index 298c3ad6..00000000 --- a/OSX/include/security_asn1/prinrval.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** File: prinrval.h -** Description: API to interval timing functions of NSPR. -** -** -** NSPR provides interval times that are independent of network time -** of day values. Interval times are (in theory) accurate regardless -** of host processing requirements and also very cheap to acquire. It -** is expected that getting an interval time while in a synchronized -** function (holding one's lock). -**/ - -#if !defined(prinrval_h) -#define prinrval_h - -#include - -PR_BEGIN_EXTERN_C - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -typedef PRUint32 PRIntervalTime; - -/*********************************************************************** -** DEFINES: PR_INTERVAL_MIN -** PR_INTERVAL_MAX -** DESCRIPTION: -** These two constants define the range (in ticks / second) of the -** platform dependent type, PRIntervalTime. These constants bound both -** the period and the resolution of a PRIntervalTime. -***********************************************************************/ -#define PR_INTERVAL_MIN 1000UL -#define PR_INTERVAL_MAX 100000UL - -/*********************************************************************** -** DEFINES: PR_INTERVAL_NO_WAIT -** PR_INTERVAL_NO_TIMEOUT -** DESCRIPTION: -** Two reserved constants are defined in the PRIntervalTime namespace. -** They are used to indicate that the process should wait no time (return -** immediately) or wait forever (never time out), respectively. -***********************************************************************/ -#define PR_INTERVAL_NO_WAIT 0UL -#define PR_INTERVAL_NO_TIMEOUT 0xffffffffUL - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/*********************************************************************** -** FUNCTION: PR_IntervalNow -** DESCRIPTION: -** Return the value of NSPR's free running interval timer. That timer -** can be used to establish epochs and determine intervals (be computing -** the difference between two times). -** INPUTS: void -** OUTPUTS: void -** RETURN: PRIntervalTime -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** The units of PRIntervalTime are platform dependent. They are chosen -** such that they are appropriate for the host OS, yet provide sufficient -** resolution and period to be useful to clients. -** MEMORY: N/A -** ALGORITHM: Platform dependent -***********************************************************************/ -NSPR_API(PRIntervalTime) PR_IntervalNow(void); - -/*********************************************************************** -** FUNCTION: PR_TicksPerSecond -** DESCRIPTION: -** Return the number of ticks per second for PR_IntervalNow's clock. -** The value will be in the range [PR_INTERVAL_MIN..PR_INTERVAL_MAX]. -** INPUTS: void -** OUTPUTS: void -** RETURN: PRUint32 -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** None -** MEMORY: N/A -** ALGORITHM: N/A -***********************************************************************/ -NSPR_API(PRUint32) PR_TicksPerSecond(void); - -/*********************************************************************** -** FUNCTION: PR_SecondsToInterval -** PR_MillisecondsToInterval -** PR_MicrosecondsToInterval -** DESCRIPTION: -** Convert standard clock units to platform dependent intervals. -** INPUTS: PRUint32 -** OUTPUTS: void -** RETURN: PRIntervalTime -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** Conversion may cause overflow, which is not reported. -** MEMORY: N/A -** ALGORITHM: N/A -***********************************************************************/ -NSPR_API(PRIntervalTime) PR_SecondsToInterval(PRUint32 seconds); -NSPR_API(PRIntervalTime) PR_MillisecondsToInterval(PRUint32 milli); -NSPR_API(PRIntervalTime) PR_MicrosecondsToInterval(PRUint32 micro); - -/*********************************************************************** -** FUNCTION: PR_IntervalToSeconds -** PR_IntervalToMilliseconds -** PR_IntervalToMicroseconds -** DESCRIPTION: -** Convert platform dependent intervals to standard clock units. -** INPUTS: PRIntervalTime -** OUTPUTS: void -** RETURN: PRUint32 -** -** SIDE EFFECTS: -** None -** RESTRICTIONS: -** Conversion may cause overflow, which is not reported. -** MEMORY: N/A -** ALGORITHM: N/A -***********************************************************************/ -NSPR_API(PRUint32) PR_IntervalToSeconds(PRIntervalTime ticks); -NSPR_API(PRUint32) PR_IntervalToMilliseconds(PRIntervalTime ticks); -NSPR_API(PRUint32) PR_IntervalToMicroseconds(PRIntervalTime ticks); - -PR_END_EXTERN_C - - -#endif /* !defined(prinrval_h) */ - -/* prinrval.h */ diff --git a/OSX/include/security_asn1/prlock.h b/OSX/include/security_asn1/prlock.h deleted file mode 100644 index f37e1fca..00000000 --- a/OSX/include/security_asn1/prlock.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** File: prlock.h -** Description: API to basic locking functions of NSPR. -** -** -** NSPR provides basic locking mechanisms for thread synchronization. Locks -** are lightweight resource contention controls that prevent multiple threads -** from accessing something (code/data) simultaneously. -**/ - -#ifndef prlock_h___ -#define prlock_h___ - -#include - -PR_BEGIN_EXTERN_C - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -/* - * PRLock -- - * - * NSPR represents the lock as an opaque entity to the client of the - * API. All routines operate on a pointer to this opaque entity. - */ - -#if defined(__APPLE_) & defined(__GNUC__) -/* dmitch - actually a pthread_mutex_t */ -typedef void PRLock; -#else -typedef struct PRLock PRLock; -#endif - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/*********************************************************************** -** FUNCTION: PR_NewLock -** DESCRIPTION: -** Returns a pointer to a newly created opaque lock object. -** INPUTS: void -** OUTPUTS: void -** RETURN: PRLock* -** If the lock can not be created because of resource constraints, NULL -** is returned. -** -***********************************************************************/ -NSPR_API(PRLock*) PR_NewLock(void); - -/*********************************************************************** -** FUNCTION: PR_DestroyLock -** DESCRIPTION: -** Destroys a given opaque lock object. -** INPUTS: PRLock *lock -** Lock to be freed. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_DestroyLock(PRLock *lock); - -/*********************************************************************** -** FUNCTION: PR_Lock -** DESCRIPTION: -** Lock a lock. -** INPUTS: PRLock *lock -** Lock to locked. -** OUTPUTS: void -** RETURN: None -***********************************************************************/ -NSPR_API(void) PR_Lock(PRLock *lock); - -/*********************************************************************** -** FUNCTION: PR_Unlock -** DESCRIPTION: -** Unlock a lock. Unlocking an unlocked lock has undefined results. -** INPUTS: PRLock *lock -** Lock to unlocked. -** OUTPUTS: void -** RETURN: PR_STATUS -** Returns PR_FAILURE if the caller does not own the lock. -***********************************************************************/ -NSPR_API(PRStatus) PR_Unlock(PRLock *lock); - -PR_END_EXTERN_C - -#endif /* prlock_h___ */ diff --git a/OSX/include/security_asn1/prlog.h b/OSX/include/security_asn1/prlog.h deleted file mode 100644 index c0b3b841..00000000 --- a/OSX/include/security_asn1/prlog.h +++ /dev/null @@ -1,262 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prlog_h___ -#define prlog_h___ - -#include - -PR_BEGIN_EXTERN_C - -/* -** prlog.h -- Declare interfaces to NSPR's Logging service -** -** NSPR provides a logging service that is used by NSPR itself and is -** available to client programs. -** -** To use the service from a client program, you should create a -** PRLogModuleInfo structure by calling PR_NewLogModule(). After -** creating the LogModule, you can write to the log using the PR_LOG() -** macro. -** -** Initialization of the log service is handled by NSPR initialization. -** -** At execution time, you must enable the log service. To enable the -** log service, set the environment variable: NSPR_LOG_MODULES -** variable. -** -** NSPR_LOG_MODULES variable has the form: -** -** :[, :]* -** -** Where: -** is the name passed to PR_NewLogModule(). -** is a numeric constant, e.g. 5. This value is the maximum -** value of a log event, enumerated by PRLogModuleLevel, that you want -** written to the log. -** -** For example: to record all events of greater value than or equal to -** PR_LOG_ERROR for a LogModule names "gizmo", say: -** -** set NSPR_LOG_MODULES=gizmo:2 -** -** Note that you must specify the numeric value of PR_LOG_ERROR. -** -** Special LogModule names are provided for controlling NSPR's log -** service at execution time. These controls should be set in the -** NSPR_LOG_MODULES environment variable at execution time to affect -** NSPR's log service for your application. -** -** The special LogModule "all" enables all LogModules. To enable all -** LogModule calls to PR_LOG(), say: -** -** set NSPR_LOG_MODULES=all:5 -** -** The special LogModule name "sync" tells the NSPR log service to do -** unbuffered logging. -** -** The special LogModule name "bufsize:" tells NSPR to set the -** log buffer to . -** -** The environment variable NSPR_LOG_FILE specifies the log file to use -** unless the default of "stderr" is acceptable. For MS Windows -** systems, NSPR_LOG_FILE can be set to a special value: "WinDebug" -** (case sensitive). This value causes PR_LOG() output to be written -** using the Windows API OutputDebugString(). OutputDebugString() -** writes to the debugger window; some people find this helpful. -** -** -** To put log messages in your programs, use the PR_LOG macro: -** -** PR_LOG(, , (, *)); -** -** Where is the address of a PRLogModuleInfo structure, and -** is one of the levels defined by the enumeration: -** PRLogModuleLevel. is a printf() style of argument list. That -** is: (fmtstring, ...). -** -** Example: -** -** main() { -** PRIntn one = 1; -** PRLogModuleInfo * myLm = PR_NewLogModule("gizmo"); -** PR_LOG( myLm, PR_LOG_ALWAYS, ("Log this! %d\n", one)); -** return; -** } -** -** Note the use of printf() style arguments as the third agrument(s) to -** PR_LOG(). -** -** After compiling and linking you application, set the environment: -** -** set NSPR_LOG_MODULES=gizmo:5 -** set NSPR_LOG_FILE=logfile.txt -** -** When you execute your application, the string "Log this! 1" will be -** written to the file "logfile.txt". -** -** Note to NSPR engineers: a number of PRLogModuleInfo structures are -** defined and initialized in prinit.c. See this module for ideas on -** what to log where. -** -*/ - -typedef enum PRLogModuleLevel { - PR_LOG_NONE = 0, /* nothing */ - PR_LOG_ALWAYS = 1, /* always printed */ - PR_LOG_ERROR = 2, /* error messages */ - PR_LOG_WARNING = 3, /* warning messages */ - PR_LOG_DEBUG = 4, /* debug messages */ - - PR_LOG_NOTICE = PR_LOG_DEBUG, /* notice messages */ - PR_LOG_WARN = PR_LOG_WARNING, /* warning messages */ - PR_LOG_MIN = PR_LOG_DEBUG, /* minimal debugging messages */ - PR_LOG_MAX = PR_LOG_DEBUG /* maximal debugging messages */ -} PRLogModuleLevel; - -/* -** One of these structures is created for each module that uses logging. -** "name" is the name of the module -** "level" is the debugging level selected for that module -*/ -typedef struct PRLogModuleInfo { - const char *name; - PRLogModuleLevel level; - struct PRLogModuleInfo *next; -} PRLogModuleInfo; - -/* -** Create a new log module. -*/ -NSPR_API(PRLogModuleInfo*) PR_NewLogModule(const char *name); - -/* -** Set the file to use for logging. Returns PR_FALSE if the file cannot -** be created -*/ -NSPR_API(PRBool) PR_SetLogFile(const char *name); - -/* -** Set the size of the logging buffer. If "buffer_size" is zero then the -** logging becomes "synchronous" (or unbuffered). -*/ -NSPR_API(void) PR_SetLogBuffering(PRIntn buffer_size); - -/* -** Print a string to the log. "fmt" is a PR_snprintf format type. All -** messages printed to the log are preceeded by the name of the thread -** and a time stamp. Also, the routine provides a missing newline if one -** is not provided. -*/ -NSPR_API(void) PR_LogPrint(const char *fmt, ...); - -/* -** Flush the log to its file. -*/ -NSPR_API(void) PR_LogFlush(void); - -/* -** Windoze 16 can't support a large static string space for all of the -** various debugging strings so logging is not enabled for it. -*/ -#if (defined(DEBUG) || defined(FORCE_PR_LOG)) && !defined(WIN16) -#define PR_LOGGING 1 - -#define PR_LOG_TEST(_module,_level) \ - ((_module)->level >= (_level)) - -/* -** Log something. -** "module" is the address of a PRLogModuleInfo structure -** "level" is the desired logging level -** "args" is a variable length list of arguments to print, in the following -** format: ("printf style format string", ...) -*/ -#define PR_LOG(_module,_level,_args) \ - PR_BEGIN_MACRO \ - if (PR_LOG_TEST(_module,_level)) { \ - PR_LogPrint _args; \ - } \ - PR_END_MACRO - -#else /* (defined(DEBUG) || defined(FORCE_PR_LOG)) && !defined(WIN16) */ - -#undef PR_LOGGING -#define PR_LOG_TEST(module,level) 0 -#define PR_LOG(module,level,args) - -#endif /* (defined(DEBUG) || defined(FORCE_PR_LOG)) && !defined(WIN16) */ - -#ifndef NO_NSPR_10_SUPPORT - -#ifdef PR_LOGGING -#define PR_LOG_BEGIN PR_LOG -#define PR_LOG_END PR_LOG -#define PR_LOG_DEFINE PR_NewLogModule -#else -#define PR_LOG_BEGIN(module,level,args) -#define PR_LOG_END(module,level,args) -#define PR_LOG_DEFINE(_name) NULL -#endif /* PR_LOGGING */ - -#endif /* NO_NSPR_10_SUPPORT */ - -#if !defined(NDEBUG) || defined(FORCE_PR_ASSERT) - -#ifdef __APPLE__ - -#include - -#define PR_ASSERT(_exp) assert(_exp) -#define PR_NOT_REACHED(_reas) assert(0) - -#else -NSPR_API(void) PR_Assert(const char *s, const char *file, PRIntn ln); -#define PR_ASSERT(_expr) \ - ((_expr)?((void)0):PR_Assert(# _expr,__FILE__,__LINE__)) - -#define PR_NOT_REACHED(_reasonStr) \ - PR_Assert(_reasonStr,__FILE__,__LINE__) -#endif - -#else - -#define PR_ASSERT(expr) ((void) 0) -#define PR_NOT_REACHED(reasonStr) - -#endif /* defined(DEBUG) || defined(FORCE_PR_ASSERT) */ - -PR_END_EXTERN_C - -#endif /* prlog_h___ */ diff --git a/OSX/include/security_asn1/prlong.h b/OSX/include/security_asn1/prlong.h deleted file mode 100644 index dd45456c..00000000 --- a/OSX/include/security_asn1/prlong.h +++ /dev/null @@ -1,425 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** File: prlong.h -** Description: Portable access to 64 bit numerics -** -** Long-long (64-bit signed integer type) support. Some C compilers -** don't support 64 bit integers yet, so we use these macros to -** support both machines that do and don't. -**/ -#ifndef prlong_h___ -#define prlong_h___ - -#include - -PR_BEGIN_EXTERN_C - -/*********************************************************************** -** DEFINES: LL_MaxInt -** LL_MinInt -** LL_Zero -** DESCRIPTION: -** Various interesting constants and static variable -** initializer -***********************************************************************/ -#if defined(HAVE_WATCOM_BUG_2) -PRInt64 __pascal __loadds __export - LL_MaxInt(void); -PRInt64 __pascal __loadds __export - LL_MinInt(void); -PRInt64 __pascal __loadds __export - LL_Zero(void); -#else -NSPR_API(PRInt64) LL_MaxInt(void); -NSPR_API(PRInt64) LL_MinInt(void); -NSPR_API(PRInt64) LL_Zero(void); -#endif - -#define LL_MAXINT LL_MaxInt() -#define LL_MININT LL_MinInt() -#define LL_ZERO LL_Zero() - -#if defined(HAVE_LONG_LONG) - -#if PR_BYTES_PER_LONG == 8 -#define LL_INIT(hi, lo) ((hi ## L << 32) + lo ## L) -#elif (defined(WIN32) || defined(WIN16)) && !defined(__GNUC__) -#define LL_INIT(hi, lo) ((hi ## i64 << 32) + lo ## i64) -#else -#define LL_INIT(hi, lo) ((hi ## LL << 32) + lo ## LL) -#endif - -/*********************************************************************** -** MACROS: LL_* -** DESCRIPTION: -** The following macros define portable access to the 64 bit -** math facilities. -** -***********************************************************************/ - -/*********************************************************************** -** MACROS: LL_ -** -** LL_IS_ZERO Test for zero -** LL_EQ Test for equality -** LL_NE Test for inequality -** LL_GE_ZERO Test for zero or positive -** LL_CMP Compare two values -***********************************************************************/ -#define LL_IS_ZERO(a) ((a) == 0) -#define LL_EQ(a, b) ((a) == (b)) -#define LL_NE(a, b) ((a) != (b)) -#define LL_GE_ZERO(a) ((a) >= 0) -#define LL_CMP(a, op, b) ((PRInt64)(a) op (PRInt64)(b)) -#define LL_UCMP(a, op, b) ((PRUint64)(a) op (PRUint64)(b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_AND Logical and -** LL_OR Logical or -** LL_XOR Logical exclusion -** LL_OR2 A disgusting deviation -** LL_NOT Negation (one's complement) -***********************************************************************/ -#define LL_AND(r, a, b) ((r) = (a) & (b)) -#define LL_OR(r, a, b) ((r) = (a) | (b)) -#define LL_XOR(r, a, b) ((r) = (a) ^ (b)) -#define LL_OR2(r, a) ((r) = (r) | (a)) -#define LL_NOT(r, a) ((r) = ~(a)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_NEG Negation (two's complement) -** LL_ADD Summation (two's complement) -** LL_SUB Difference (two's complement) -***********************************************************************/ -#define LL_NEG(r, a) ((r) = -(a)) -#define LL_ADD(r, a, b) ((r) = (a) + (b)) -#define LL_SUB(r, a, b) ((r) = (a) - (b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_MUL Product (two's complement) -** LL_DIV Quotient (two's complement) -** LL_MOD Modulus (two's complement) -***********************************************************************/ -#define LL_MUL(r, a, b) ((r) = (a) * (b)) -#define LL_DIV(r, a, b) ((r) = (a) / (b)) -#define LL_MOD(r, a, b) ((r) = (a) % (b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_SHL Shift left [0..64] bits -** LL_SHR Shift right [0..64] bits with sign extension -** LL_USHR Unsigned shift right [0..64] bits -** LL_ISHL Signed shift left [0..64] bits -***********************************************************************/ -#define LL_SHL(r, a, b) ((r) = (PRInt64)(a) << (b)) -#define LL_SHR(r, a, b) ((r) = (PRInt64)(a) >> (b)) -#define LL_USHR(r, a, b) ((r) = (PRUint64)(a) >> (b)) -#define LL_ISHL(r, a, b) ((r) = (PRInt64)(a) << (b)) - -/*********************************************************************** -** MACROS: LL_ -** -** LL_L2I Convert to signed 32 bit -** LL_L2UI Convert to unsigned 32 bit -** LL_L2F Convert to floating point -** LL_L2D Convert to floating point -** LL_I2L Convert signed to 64 bit -** LL_UI2L Convert unsigned to 64 bit -** LL_F2L Convert float to 64 bit -** LL_D2L Convert float to 64 bit -***********************************************************************/ -#define LL_L2I(i, l) ((i) = (PRInt32)(l)) -#define LL_L2UI(ui, l) ((ui) = (PRUint32)(l)) -#define LL_L2F(f, l) ((f) = (PRFloat64)(l)) -#define LL_L2D(d, l) ((d) = (PRFloat64)(l)) - -#define LL_I2L(l, i) ((l) = (PRInt64)(i)) -#define LL_UI2L(l, ui) ((l) = (PRInt64)(ui)) -#define LL_F2L(l, f) ((l) = (PRInt64)(f)) -#define LL_D2L(l, d) ((l) = (PRInt64)(d)) - -/*********************************************************************** -** MACROS: LL_UDIVMOD -** DESCRIPTION: -** Produce both a quotient and a remainder given an unsigned -** INPUTS: PRUint64 a: The dividend of the operation -** PRUint64 b: The quotient of the operation -** OUTPUTS: PRUint64 *qp: pointer to quotient -** PRUint64 *rp: pointer to remainder -***********************************************************************/ -#define LL_UDIVMOD(qp, rp, a, b) \ - (*(qp) = ((PRUint64)(a) / (b)), \ - *(rp) = ((PRUint64)(a) % (b))) - -#else /* !HAVE_LONG_LONG */ - -#ifdef IS_LITTLE_ENDIAN -#define LL_INIT(hi, lo) {PR_INT32(lo), PR_INT32(hi)} -#else -#define LL_INIT(hi, lo) {PR_INT32(hi), PR_INT32(lo)} -#endif - -#define LL_IS_ZERO(a) (((a).hi == 0) && ((a).lo == 0)) -#define LL_EQ(a, b) (((a).hi == (b).hi) && ((a).lo == (b).lo)) -#define LL_NE(a, b) (((a).hi != (b).hi) || ((a).lo != (b).lo)) -#define LL_GE_ZERO(a) (((a).hi >> 31) == 0) - -#define LL_CMP(a, op, b) (((a).hi == (b).hi) ? ((a).lo op (b).lo) : \ - ((PRInt32)(a).hi op (PRInt32)(b).hi)) -#define LL_UCMP(a, op, b) (((a).hi == (b).hi) ? ((a).lo op (b).lo) : \ - ((a).hi op (b).hi)) - -#define LL_AND(r, a, b) ((r).lo = (a).lo & (b).lo, \ - (r).hi = (a).hi & (b).hi) -#define LL_OR(r, a, b) ((r).lo = (a).lo | (b).lo, \ - (r).hi = (a).hi | (b).hi) -#define LL_XOR(r, a, b) ((r).lo = (a).lo ^ (b).lo, \ - (r).hi = (a).hi ^ (b).hi) -#define LL_OR2(r, a) ((r).lo = (r).lo | (a).lo, \ - (r).hi = (r).hi | (a).hi) -#define LL_NOT(r, a) ((r).lo = ~(a).lo, \ - (r).hi = ~(a).hi) - -#define LL_NEG(r, a) ((r).lo = -(PRInt32)(a).lo, \ - (r).hi = -(PRInt32)(a).hi - ((r).lo != 0)) -#define LL_ADD(r, a, b) { \ - PRInt64 _a, _b; \ - _a = a; _b = b; \ - (r).lo = _a.lo + _b.lo; \ - (r).hi = _a.hi + _b.hi + ((r).lo < _b.lo); \ -} - -#define LL_SUB(r, a, b) { \ - PRInt64 _a, _b; \ - _a = a; _b = b; \ - (r).lo = _a.lo - _b.lo; \ - (r).hi = _a.hi - _b.hi - (_a.lo < _b.lo); \ -} - -#define LL_MUL(r, a, b) { \ - PRInt64 _a, _b; \ - _a = a; _b = b; \ - LL_MUL32(r, _a.lo, _b.lo); \ - (r).hi += _a.hi * _b.lo + _a.lo * _b.hi; \ -} - -#define _lo16(a) ((a) & PR_BITMASK(16)) -#define _hi16(a) ((a) >> 16) - -#define LL_MUL32(r, a, b) { \ - PRUint32 _a1, _a0, _b1, _b0, _y0, _y1, _y2, _y3; \ - _a1 = _hi16(a), _a0 = _lo16(a); \ - _b1 = _hi16(b), _b0 = _lo16(b); \ - _y0 = _a0 * _b0; \ - _y1 = _a0 * _b1; \ - _y2 = _a1 * _b0; \ - _y3 = _a1 * _b1; \ - _y1 += _hi16(_y0); /* can't carry */ \ - _y1 += _y2; /* might carry */ \ - if (_y1 < _y2) \ - _y3 += (PRUint32)(PR_BIT(16)); /* propagate */ \ - (r).lo = (_lo16(_y1) << 16) + _lo16(_y0); \ - (r).hi = _y3 + _hi16(_y1); \ -} - -#define LL_UDIVMOD(qp, rp, a, b) ll_udivmod(qp, rp, a, b) - -NSPR_API(void) ll_udivmod(PRUint64 *qp, PRUint64 *rp, PRUint64 a, PRUint64 b); - -#define LL_DIV(r, a, b) { \ - PRInt64 _a, _b; \ - PRUint32 _negative = (PRInt32)(a).hi < 0; \ - if (_negative) { \ - LL_NEG(_a, a); \ - } else { \ - _a = a; \ - } \ - if ((PRInt32)(b).hi < 0) { \ - _negative ^= 1; \ - LL_NEG(_b, b); \ - } else { \ - _b = b; \ - } \ - LL_UDIVMOD(&(r), 0, _a, _b); \ - if (_negative) \ - LL_NEG(r, r); \ -} - -#define LL_MOD(r, a, b) { \ - PRInt64 _a, _b; \ - PRUint32 _negative = (PRInt32)(a).hi < 0; \ - if (_negative) { \ - LL_NEG(_a, a); \ - } else { \ - _a = a; \ - } \ - if ((PRInt32)(b).hi < 0) { \ - LL_NEG(_b, b); \ - } else { \ - _b = b; \ - } \ - LL_UDIVMOD(0, &(r), _a, _b); \ - if (_negative) \ - LL_NEG(r, r); \ -} - -#define LL_SHL(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a = a; \ - if ((b) < 32) { \ - (r).lo = _a.lo << ((b) & 31); \ - (r).hi = (_a.hi << ((b) & 31)) | (_a.lo >> (32 - (b))); \ - } else { \ - (r).lo = 0; \ - (r).hi = _a.lo << ((b) & 31); \ - } \ - } else { \ - (r) = (a); \ - } \ -} - -/* a is an PRInt32, b is PRInt32, r is PRInt64 */ -#define LL_ISHL(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a.lo = (a); \ - _a.hi = 0; \ - if ((b) < 32) { \ - (r).lo = (a) << ((b) & 31); \ - (r).hi = ((a) >> (32 - (b))); \ - } else { \ - (r).lo = 0; \ - (r).hi = (a) << ((b) & 31); \ - } \ - } else { \ - (r).lo = (a); \ - (r).hi = 0; \ - } \ -} - -#define LL_SHR(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a = a; \ - if ((b) < 32) { \ - (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \ - (r).hi = (PRInt32)_a.hi >> ((b) & 31); \ - } else { \ - (r).lo = (PRInt32)_a.hi >> ((b) & 31); \ - (r).hi = (PRInt32)_a.hi >> 31; \ - } \ - } else { \ - (r) = (a); \ - } \ -} - -#define LL_USHR(r, a, b) { \ - if (b) { \ - PRInt64 _a; \ - _a = a; \ - if ((b) < 32) { \ - (r).lo = (_a.hi << (32 - (b))) | (_a.lo >> ((b) & 31)); \ - (r).hi = _a.hi >> ((b) & 31); \ - } else { \ - (r).lo = _a.hi >> ((b) & 31); \ - (r).hi = 0; \ - } \ - } else { \ - (r) = (a); \ - } \ -} - -#define LL_L2I(i, l) ((i) = (l).lo) -#define LL_L2UI(ui, l) ((ui) = (l).lo) -#define LL_L2F(f, l) { double _d; LL_L2D(_d, l); (f) = (PRFloat64)_d; } - -#define LL_L2D(d, l) { \ - int _negative; \ - PRInt64 _absval; \ - \ - _negative = (l).hi >> 31; \ - if (_negative) { \ - LL_NEG(_absval, l); \ - } else { \ - _absval = l; \ - } \ - (d) = (double)_absval.hi * 4.294967296e9 + _absval.lo; \ - if (_negative) \ - (d) = -(d); \ -} - -#define LL_I2L(l, i) { PRInt32 _i = ((PRInt32)(i)) >> 31; (l).lo = (i); (l).hi = _i; } -#define LL_UI2L(l, ui) ((l).lo = (ui), (l).hi = 0) -#define LL_F2L(l, f) { double _d = (double)f; LL_D2L(l, _d); } - -#define LL_D2L(l, d) { \ - int _negative; \ - double _absval, _d_hi; \ - PRInt64 _lo_d; \ - \ - _negative = ((d) < 0); \ - _absval = _negative ? -(d) : (d); \ - \ - (l).hi = _absval / 4.294967296e9; \ - (l).lo = 0; \ - LL_L2D(_d_hi, l); \ - _absval -= _d_hi; \ - _lo_d.hi = 0; \ - if (_absval < 0) { \ - _lo_d.lo = -_absval; \ - LL_SUB(l, l, _lo_d); \ - } else { \ - _lo_d.lo = _absval; \ - LL_ADD(l, l, _lo_d); \ - } \ - \ - if (_negative) \ - LL_NEG(l, l); \ -} - -#endif /* !HAVE_LONG_LONG */ - -PR_END_EXTERN_C - -#endif /* prlong_h___ */ diff --git a/OSX/include/security_asn1/prmem.h b/OSX/include/security_asn1/prmem.h deleted file mode 100644 index 937dac79..00000000 --- a/OSX/include/security_asn1/prmem.h +++ /dev/null @@ -1,156 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** File: prmem.h -** Description: API to NSPR 2.0 memory management functions -** -*/ -#ifndef prmem_h___ -#define prmem_h___ - -#include -#include -#include - -PR_BEGIN_EXTERN_C - -/* -** Thread safe memory allocation. -** -** NOTE: pr wraps up malloc, free, calloc, realloc so they are already -** thread safe (and are not declared here - look in stdlib.h). -*/ - -/* -** PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free have the same signatures -** as their libc equivalent malloc, calloc, realloc, and free, and have -** the same semantics. (Note that the argument type size_t is replaced -** by PRUint32.) Memory allocated by PR_Malloc, PR_Calloc, or PR_Realloc -** must be freed by PR_Free. -*/ - -NSPR_API(void *) PR_Malloc(PRSize size); - -NSPR_API(void *) PR_Calloc(PRSize nelem, PRSize elsize); - -NSPR_API(void *) PR_Realloc(void *ptr, PRSize size); - -NSPR_API(void) PR_Free(void *ptr); - -/* -** The following are some convenience macros defined in terms of -** PR_Malloc, PR_Calloc, PR_Realloc, and PR_Free. -*/ - -/*********************************************************************** -** FUNCTION: PR_MALLOC() -** DESCRIPTION: -** PR_NEW() allocates an untyped item of size _size from the heap. -** INPUTS: _size: size in bytes of item to be allocated -** OUTPUTS: untyped pointer to the node allocated -** RETURN: pointer to node or error returned from malloc(). -***********************************************************************/ -#define PR_MALLOC(_bytes) (PR_Malloc((_bytes))) - -/*********************************************************************** -** FUNCTION: PR_NEW() -** DESCRIPTION: -** PR_NEW() allocates an item of type _struct from the heap. -** INPUTS: _struct: a data type -** OUTPUTS: pointer to _struct -** RETURN: pointer to _struct or error returns from malloc(). -***********************************************************************/ -#define PR_NEW(_struct) ((_struct *) PR_MALLOC(sizeof(_struct))) - -/*********************************************************************** -** FUNCTION: PR_REALLOC() -** DESCRIPTION: -** PR_REALLOC() re-allocates _ptr bytes from the heap as a _size -** untyped item. -** INPUTS: _ptr: pointer to node to reallocate -** _size: size of node to allocate -** OUTPUTS: pointer to node allocated -** RETURN: pointer to node allocated -***********************************************************************/ -#define PR_REALLOC(_ptr, _size) (PR_Realloc((_ptr), (_size))) - -/*********************************************************************** -** FUNCTION: PR_CALLOC() -** DESCRIPTION: -** PR_CALLOC() allocates a _size bytes untyped item from the heap -** and sets the allocated memory to all 0x00. -** INPUTS: _size: size of node to allocate -** OUTPUTS: pointer to node allocated -** RETURN: pointer to node allocated -***********************************************************************/ -#define PR_CALLOC(_size) (PR_Calloc(1, (_size))) - -/*********************************************************************** -** FUNCTION: PR_NEWZAP() -** DESCRIPTION: -** PR_NEWZAP() allocates an item of type _struct from the heap -** and sets the allocated memory to all 0x00. -** INPUTS: _struct: a data type -** OUTPUTS: pointer to _struct -** RETURN: pointer to _struct -***********************************************************************/ -#define PR_NEWZAP(_struct) ((_struct*)PR_Calloc(1, sizeof(_struct))) - -/*********************************************************************** -** FUNCTION: PR_DELETE() -** DESCRIPTION: -** PR_DELETE() unallocates an object previosly allocated via PR_NEW() -** or PR_NEWZAP() to the heap. -** INPUTS: pointer to previously allocated object -** OUTPUTS: the referenced object is returned to the heap -** RETURN: void -***********************************************************************/ -#define PR_DELETE(_ptr) { PR_Free(_ptr); (_ptr) = NULL; } - -/*********************************************************************** -** FUNCTION: PR_FREEIF() -** DESCRIPTION: -** PR_FREEIF() conditionally unallocates an object previously allocated -** vial PR_NEW() or PR_NEWZAP(). If the pointer to the object is -** equal to zero (0), the object is not released. -** INPUTS: pointer to previously allocated object -** OUTPUTS: the referenced object is conditionally returned to the heap -** RETURN: void -***********************************************************************/ -#define PR_FREEIF(_ptr) if (_ptr) PR_DELETE(_ptr) - -PR_END_EXTERN_C - -#endif /* prmem_h___ */ diff --git a/OSX/include/security_asn1/prmon.h b/OSX/include/security_asn1/prmon.h deleted file mode 100644 index a457f624..00000000 --- a/OSX/include/security_asn1/prmon.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prmon_h___ -#define prmon_h___ - -#include -#include - -PR_BEGIN_EXTERN_C - -typedef struct PRMonitor PRMonitor; - -/* -** Create a new monitor. Monitors are re-entrant locks with a single built-in -** condition variable. -** -** This may fail if memory is tight or if some operating system resource -** is low. -*/ -NSPR_API(PRMonitor*) PR_NewMonitor(void); - -/* -** Destroy a monitor. The caller is responsible for guaranteeing that the -** monitor is no longer in use. There must be no thread waiting on the monitor's -** condition variable and that the lock is not held. -** -*/ -NSPR_API(void) PR_DestroyMonitor(PRMonitor *mon); - -/* -** Enter the lock associated with the monitor. If the calling thread currently -** is in the monitor, the call to enter will silently succeed. In either case, -** it will increment the entry count by one. -*/ -NSPR_API(void) PR_EnterMonitor(PRMonitor *mon); - -/* -** Decrement the entry count associated with the monitor. If the decremented -** entry count is zero, the monitor is exited. Returns PR_FAILURE if the -** calling thread has not entered the monitor. -*/ -NSPR_API(PRStatus) PR_ExitMonitor(PRMonitor *mon); - -/* -** Wait for a notify on the monitor's condition variable. Sleep for "ticks" -** amount of time (if "ticks" is PR_INTERVAL_NO_TIMEOUT then the sleep is -** indefinite). -** -** While the thread is waiting it exits the monitor (as if it called -** PR_ExitMonitor as many times as it had called PR_EnterMonitor). When -** the wait has finished the thread regains control of the monitors lock -** with the same entry count as before the wait began. -** -** The thread waiting on the monitor will be resumed when the monitor is -** notified (assuming the thread is the next in line to receive the -** notify) or when the "ticks" timeout elapses. -** -** Returns PR_FAILURE if the caller has not entered the monitor. -*/ -NSPR_API(PRStatus) PR_Wait(PRMonitor *mon, PRIntervalTime ticks); - -/* -** Notify a thread waiting on the monitor's condition variable. If a thread -** is waiting on the condition variable (using PR_Wait) then it is awakened -** and attempts to reenter the monitor. -*/ -NSPR_API(PRStatus) PR_Notify(PRMonitor *mon); - -/* -** Notify all of the threads waiting on the monitor's condition variable. -** All of threads waiting on the condition are scheduled to reenter the -** monitor. -*/ -NSPR_API(PRStatus) PR_NotifyAll(PRMonitor *mon); - -PR_END_EXTERN_C - -#endif /* prmon_h___ */ diff --git a/OSX/include/security_asn1/protypes.h b/OSX/include/security_asn1/protypes.h deleted file mode 100644 index 33ef7a3a..00000000 --- a/OSX/include/security_asn1/protypes.h +++ /dev/null @@ -1,251 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * This header typedefs the old 'native' types to the new PRs. - * These definitions are scheduled to be eliminated at the earliest - * possible time. The NSPR API is implemented and documented using - * the new definitions. - */ - -#if !defined(PROTYPES_H) -#define PROTYPES_H - -typedef PRUintn uintn; -#ifndef _XP_Core_ -typedef PRIntn intn; -#endif - -/* - * It is trickier to define uint, int8, uint8, int16, uint16, - * int32, uint32, int64, and uint64 because some of these int - * types are defined by standard header files on some platforms. - * Our strategy here is to include all such standard headers - * first, and then define these int types only if they are not - * defined by those standard headers. - */ - -/* - * BeOS defines all the int types below in its standard header - * file SupportDefs.h. - */ -#ifdef XP_BEOS -#include -#endif - -/* - * OpenVMS defines all the int types below in its standard - * header files ints.h and types.h. - */ -#ifdef VMS -#include -#include -#endif - -/* - * SVR4 typedef of uint is commonly found on UNIX machines. - * - * On AIX 4.3, sys/inttypes.h (which is included by sys/types.h) - * defines the types int8, int16, int32, and int64. - */ -#ifdef XP_UNIX -#include -#endif - -/* model.h on HP-UX defines int8, int16, and int32. */ -#ifdef HPUX -#include -#endif - -/* - * uint - */ - -#if !defined(XP_BEOS) && !defined(VMS) \ - && !defined(XP_UNIX) & !defined(__APPLE__) || defined(NTO) -typedef PRUintn uint; -#endif - -/* - * uint64 - */ - -#if !defined(XP_BEOS) && !defined(VMS) && !defined(__APPLE__) -typedef PRUint64 uint64; -#endif - -/* - * uint32 - */ - -#if !defined(XP_BEOS) && !defined(VMS) && !defined(__APPLE__) -#if !defined(XP_MAC) && !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO) -typedef PRUint32 uint32; -#else -typedef unsigned long uint32; -#endif -#endif - -/* - * uint16 - */ - -#if !defined(XP_BEOS) && !defined(VMS) && !defined(__APPLE__) -typedef PRUint16 uint16; -#endif - -/* - * uint8 - */ - -#if !defined(XP_BEOS) && !defined(VMS) && !defined(__APPLE__) -typedef PRUint8 uint8; -#endif - -/* - * int64 - */ - -#if !defined(XP_BEOS) && !defined(VMS) \ - && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) -typedef PRInt64 int64; -#endif - -/* - * int32 - */ - -#if !defined(XP_BEOS) && !defined(VMS) \ - && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \ - && !defined(HPUX) -#if !defined(WIN32) || !defined(_WINSOCK2API_) /* defines its own "int32" */ -#if !defined(XP_MAC) && !defined(_WIN32) && !defined(XP_OS2) && !defined(NTO) -typedef PRInt32 int32; -#else -typedef long int32; -#endif -#endif -#endif - -/* - * int16 - */ - -#if !defined(XP_BEOS) && !defined(VMS) \ - && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \ - && !defined(HPUX) -typedef PRInt16 int16; -#endif - -/* - * int8 - */ - -#if !defined(XP_BEOS) && !defined(VMS) \ - && !defined(_PR_AIX_HAVE_BSD_INT_TYPES) \ - && !defined(HPUX) -typedef PRInt8 int8; -#endif - -typedef PRFloat64 float64; -typedef PRUptrdiff uptrdiff_t; -typedef PRUword uprword_t; -typedef PRWord prword_t; - - -/* Re: prbit.h */ -#define TEST_BIT PR_TEST_BIT -#define SET_BIT PR_SET_BIT -#define CLEAR_BIT PR_CLEAR_BIT - -/* Re: prarena.h->plarena.h */ -#define PRArena PLArena -#define PRArenaPool PLArenaPool -#define PRArenaStats PLArenaStats -#define PR_ARENA_ALIGN PL_ARENA_ALIGN -#define PR_INIT_ARENA_POOL PL_INIT_ARENA_POOL -#define PR_ARENA_ALLOCATE PL_ARENA_ALLOCATE -#define PR_ARENA_GROW PL_ARENA_GROW -#define PR_ARENA_MARK PL_ARENA_MARK -#define PR_CLEAR_UNUSED PL_CLEAR_UNUSED -#define PR_CLEAR_ARENA PL_CLEAR_ARENA -#define PR_ARENA_RELEASE PL_ARENA_RELEASE -#define PR_COUNT_ARENA PL_COUNT_ARENA -#define PR_ARENA_DESTROY PL_ARENA_DESTROY -#define PR_InitArenaPool PL_InitArenaPool -#define PR_FreeArenaPool PL_FreeArenaPool -#define PR_FinishArenaPool PL_FinishArenaPool -#define PR_CompactArenaPool PL_CompactArenaPool -#define PR_ArenaFinish PL_ArenaFinish -#define PR_ArenaAllocate PL_ArenaAllocate -#define PR_ArenaGrow PL_ArenaGrow -#define PR_ArenaRelease PL_ArenaRelease -#define PR_ArenaCountAllocation PL_ArenaCountAllocation -#define PR_ArenaCountInplaceGrowth PL_ArenaCountInplaceGrowth -#define PR_ArenaCountGrowth PL_ArenaCountGrowth -#define PR_ArenaCountRelease PL_ArenaCountRelease -#define PR_ArenaCountRetract PL_ArenaCountRetract - -/* Re: prhash.h->plhash.h */ -#define PRHashEntry PLHashEntry -#define PRHashTable PLHashTable -#define PRHashNumber PLHashNumber -#define PRHashFunction PLHashFunction -#define PRHashComparator PLHashComparator -#define PRHashEnumerator PLHashEnumerator -#define PRHashAllocOps PLHashAllocOps -#define PR_NewHashTable PL_NewHashTable -#define PR_HashTableDestroy PL_HashTableDestroy -#define PR_HashTableRawLookup PL_HashTableRawLookup -#define PR_HashTableRawAdd PL_HashTableRawAdd -#define PR_HashTableRawRemove PL_HashTableRawRemove -#define PR_HashTableAdd PL_HashTableAdd -#define PR_HashTableRemove PL_HashTableRemove -#define PR_HashTableEnumerateEntries PL_HashTableEnumerateEntries -#define PR_HashTableLookup PL_HashTableLookup -#define PR_HashTableDump PL_HashTableDump -#define PR_HashString PL_HashString -#define PR_CompareStrings PL_CompareStrings -#define PR_CompareValues PL_CompareValues - -#if defined(XP_MAC) -#ifndef TRUE /* Mac standard is lower case true */ - #define TRUE 1 -#endif -#ifndef FALSE /* Mac standard is lower case false */ - #define FALSE 0 -#endif -#endif - -#endif /* !defined(PROTYPES_H) */ diff --git a/OSX/include/security_asn1/prthread.h b/OSX/include/security_asn1/prthread.h deleted file mode 100644 index 334116ce..00000000 --- a/OSX/include/security_asn1/prthread.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef prthread_h___ -#define prthread_h___ - -/* -** API for NSPR threads. On some architectures (MAC and WIN16 -** notably) pre-emptibility is not guaranteed. Hard priority scheduling -** is not guaranteed, so programming using priority based synchronization -** is a no-no. -** -** NSPR threads are scheduled based loosly on their client set priority. -** In general, a thread of a higher priority has a statistically better -** chance of running relative to threads of lower priority. However, -** NSPR uses multiple strategies to provide execution vehicles for thread -** abstraction of various host platforms. As it turns out, there is little -** NSPR can do to affect the scheduling attributes of "GLOBAL" threads. -** However, a semblance of GLOBAL threads is used to implement "LOCAL" -** threads. An arbitrary number of such LOCAL threads can be assigned to -** a single GLOBAL thread. -** -** For scheduling, NSPR will attempt to run the highest priority LOCAL -** thread associated with a given GLOBAL thread. It is further assumed -** that the host OS will apply some form of "fair" scheduling on the -** GLOBAL threads. -** -** Threads have a "system flag" which when set indicates the thread -** doesn't count for determining when the process should exit (the -** process exits when the last user thread exits). -** -** Threads also have a "scope flag" which controls whether the threads -** are scheduled in the local scope or scheduled by the OS globally. This -** indicates whether a thread is permanently bound to a native OS thread. -** An unbound thread competes for scheduling resources in the same process. -** -** Another flag is "state flag" which control whether the thread is joinable. -** It allows other threads to wait for the created thread to reach completion. -** -** Threads can have "per-thread-data" attached to them. Each thread has a -** per-thread error number and error string which are updated when NSPR -** operations fail. -*/ -#include "prtypes.h" -#include "prinrval.h" - -PR_BEGIN_EXTERN_C - -typedef struct PRThread PRThread; -typedef struct PRThreadStack PRThreadStack; - -typedef enum PRThreadType { - PR_USER_THREAD, - PR_SYSTEM_THREAD -} PRThreadType; - -typedef enum PRThreadScope { - PR_LOCAL_THREAD, - PR_GLOBAL_THREAD, - PR_GLOBAL_BOUND_THREAD -} PRThreadScope; - -typedef enum PRThreadState { - PR_JOINABLE_THREAD, - PR_UNJOINABLE_THREAD -} PRThreadState; - -typedef enum PRThreadPriority -{ - PR_PRIORITY_FIRST = 0, /* just a placeholder */ - PR_PRIORITY_LOW = 0, /* the lowest possible priority */ - PR_PRIORITY_NORMAL = 1, /* most common expected priority */ - PR_PRIORITY_HIGH = 2, /* slightly more aggressive scheduling */ - PR_PRIORITY_URGENT = 3, /* it does little good to have more than one */ - PR_PRIORITY_LAST = 3 /* this is just a placeholder */ -} PRThreadPriority; - -/* -** Create a new thread: -** "type" is the type of thread to create -** "start(arg)" will be invoked as the threads "main" -** "priority" will be created thread's priority -** "scope" will specify whether the thread is local or global -** "state" will specify whether the thread is joinable or not -** "stackSize" the size of the stack, in bytes. The value can be zero -** and then a machine specific stack size will be chosen. -** -** This can return NULL if some kind of error occurs, such as if memory is -** tight. -** -** If you want the thread to start up waiting for the creator to do -** something, enter a lock before creating the thread and then have the -** threads start routine enter and exit the same lock. When you are ready -** for the thread to run, exit the lock. -** -** If you want to detect the completion of the created thread, the thread -** should be created joinable. Then, use PR_JoinThread to synchrnoize the -** termination of another thread. -** -** When the start function returns the thread exits. If it is the last -** PR_USER_THREAD to exit then the process exits. -*/ -NSPR_API(PRThread*) PR_CreateThread(PRThreadType type, - void (PR_CALLBACK *start)(void *arg), - void *arg, - PRThreadPriority priority, - PRThreadScope scope, - PRThreadState state, - PRUint32 stackSize); - -/* -** Wait for thread termination: -** "thread" is the target thread -** -** This can return PR_FAILURE if no joinable thread could be found -** corresponding to the specified target thread. -** -** The calling thread is blocked until the target thread completes. -** Several threads cannot wait for the same thread to complete; one thread -** will operate successfully and others will terminate with an error PR_FAILURE. -** The calling thread will not be blocked if the target thread has already -** terminated. -*/ -NSPR_API(PRStatus) PR_JoinThread(PRThread *thread); - -/* -** Return the current thread object for the currently running code. -** Never returns NULL. -*/ -NSPR_API(PRThread*) PR_GetCurrentThread(void); -#ifndef NO_NSPR_10_SUPPORT -#define PR_CurrentThread() PR_GetCurrentThread() /* for nspr1.0 compat. */ -#endif /* NO_NSPR_10_SUPPORT */ - -/* -** Get the priority of "thread". -*/ -NSPR_API(PRThreadPriority) PR_GetThreadPriority(const PRThread *thread); - -/* -** Change the priority of the "thread" to "priority". -*/ -NSPR_API(void) PR_SetThreadPriority(PRThread *thread, PRThreadPriority priority); - -/* -** This routine returns a new index for per-thread-private data table. -** The index is visible to all threads within a process. This index can -** be used with the PR_SetThreadPrivate() and PR_GetThreadPrivate() routines -** to save and retrieve data associated with the index for a thread. -** -** Each index is associationed with a destructor function ('dtor'). The function -** may be specified as NULL when the index is created. If it is not NULL, the -** function will be called when: -** - the thread exits and the private data for the associated index -** is not NULL, -** - new thread private data is set and the current private data is -** not NULL. -** -** The index independently maintains specific values for each binding thread. -** A thread can only get access to its own thread-specific-data. -** -** Upon a new index return the value associated with the index for all threads -** is NULL, and upon thread creation the value associated with all indices for -** that thread is NULL. -** -** Returns PR_FAILURE if the total number of indices will exceed the maximun -** allowed. -*/ -typedef void (PR_CALLBACK *PRThreadPrivateDTOR)(void *priv); - -NSPR_API(PRStatus) PR_NewThreadPrivateIndex( - PRUintn *newIndex, PRThreadPrivateDTOR destructor); - -/* -** Define some per-thread-private data. -** "tpdIndex" is an index into the per-thread private data table -** "priv" is the per-thread-private data -** -** If the per-thread private data table has a previously registered -** destructor function and a non-NULL per-thread-private data value, -** the destructor function is invoked. -** -** This can return PR_FAILURE if the index is invalid. -*/ -NSPR_API(PRStatus) PR_SetThreadPrivate(PRUintn tpdIndex, void *priv); - -/* -** Recover the per-thread-private data for the current thread. "tpdIndex" is -** the index into the per-thread private data table. -** -** The returned value may be NULL which is indistinguishable from an error -** condition. -** -** A thread can only get access to its own thread-specific-data. -*/ -NSPR_API(void*) PR_GetThreadPrivate(PRUintn tpdIndex); - -/* -** This routine sets the interrupt request for a target thread. The interrupt -** request remains in the thread's state until it is delivered exactly once -** or explicitly canceled. -** -** A thread that has been interrupted will fail all NSPR blocking operations -** that return a PRStatus (I/O, waiting on a condition, etc). -** -** PR_Interrupt may itself fail if the target thread is invalid. -*/ -NSPR_API(PRStatus) PR_Interrupt(PRThread *thread); - -/* -** Clear the interrupt request for the calling thread. If no such request -** is pending, this operation is a noop. -*/ -NSPR_API(void) PR_ClearInterrupt(void); - -/* -** Block the interrupt for the calling thread. -*/ -NSPR_API(void) PR_BlockInterrupt(void); - -/* -** Unblock the interrupt for the calling thread. -*/ -NSPR_API(void) PR_UnblockInterrupt(void); - -/* -** Make the current thread sleep until "ticks" time amount of time -** has expired. If "ticks" is PR_INTERVAL_NO_WAIT then the call is -** equivalent to calling PR_Yield. Calling PR_Sleep with an argument -** equivalent to PR_INTERVAL_NO_TIMEOUT is an error and will result -** in a PR_FAILURE error return. -*/ -NSPR_API(PRStatus) PR_Sleep(PRIntervalTime ticks); - -/* -** Get the scoping of this thread. -*/ -NSPR_API(PRThreadScope) PR_GetThreadScope(const PRThread *thread); - -/* -** Get the type of this thread. -*/ -NSPR_API(PRThreadType) PR_GetThreadType(const PRThread *thread); - -/* -** Get the join state of this thread. -*/ -NSPR_API(PRThreadState) PR_GetThreadState(const PRThread *thread); - -PR_END_EXTERN_C - -#endif /* prthread_h___ */ diff --git a/OSX/include/security_asn1/prtime.h b/OSX/include/security_asn1/prtime.h deleted file mode 100644 index 0e09f2f3..00000000 --- a/OSX/include/security_asn1/prtime.h +++ /dev/null @@ -1,295 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - *---------------------------------------------------------------------- - * - * prtime.h -- - * - * NSPR date and time functions - * - *----------------------------------------------------------------------- - */ - -#ifndef prtime_h___ -#define prtime_h___ - -#include - -PR_BEGIN_EXTERN_C - -/**********************************************************************/ -/************************* TYPES AND CONSTANTS ************************/ -/**********************************************************************/ - -#define PR_MSEC_PER_SEC 1000UL -#define PR_USEC_PER_SEC 1000000UL -#define PR_NSEC_PER_SEC 1000000000UL -#define PR_USEC_PER_MSEC 1000UL -#define PR_NSEC_PER_MSEC 1000000UL - -/* - * PRTime -- - * - * NSPR represents basic time as 64-bit signed integers relative - * to midnight (00:00:00), January 1, 1970 Greenwich Mean Time (GMT). - * (GMT is also known as Coordinated Universal Time, UTC.) - * The units of time are in microseconds. Negative times are allowed - * to represent times prior to the January 1970 epoch. Such values are - * intended to be exported to other systems or converted to human - * readable form. - * - * Notes on porting: PRTime corresponds to time_t in ANSI C. NSPR 1.0 - * simply uses PRInt64. - */ - -typedef PRInt64 PRTime; - -/* - * Time zone and daylight saving time corrections applied to GMT to - * obtain the local time of some geographic location - */ - -typedef struct PRTimeParameters { - PRInt32 tp_gmt_offset; /* the offset from GMT in seconds */ - PRInt32 tp_dst_offset; /* contribution of DST in seconds */ -} PRTimeParameters; - -/* - * PRExplodedTime -- - * - * Time broken down into human-readable components such as year, month, - * day, hour, minute, second, and microsecond. Time zone and daylight - * saving time corrections may be applied. If they are applied, the - * offsets from the GMT must be saved in the 'tm_params' field so that - * all the information is available to reconstruct GMT. - * - * Notes on porting: PRExplodedTime corrresponds to struct tm in - * ANSI C, with the following differences: - * - an additional field tm_usec; - * - replacing tm_isdst by tm_params; - * - the month field is spelled tm_month, not tm_mon; - * - we use absolute year, AD, not the year since 1900. - * The corresponding type in NSPR 1.0 is called PRTime. Below is - * a table of date/time type correspondence in the three APIs: - * API time since epoch time in components - * ANSI C time_t struct tm - * NSPR 1.0 PRInt64 PRTime - * NSPR 2.0 PRTime PRExplodedTime - */ - -typedef struct PRExplodedTime { - PRInt32 tm_usec; /* microseconds past tm_sec (0-99999) */ - PRInt32 tm_sec; /* seconds past tm_min (0-61, accomodating - up to two leap seconds) */ - PRInt32 tm_min; /* minutes past tm_hour (0-59) */ - PRInt32 tm_hour; /* hours past tm_day (0-23) */ - PRInt32 tm_mday; /* days past tm_mon (1-31, note that it - starts from 1) */ - PRInt32 tm_month; /* months past tm_year (0-11, Jan = 0) */ - PRInt16 tm_year; /* absolute year, AD (note that we do not - count from 1900) */ - - PRInt8 tm_wday; /* calculated day of the week - (0-6, Sun = 0) */ - PRInt16 tm_yday; /* calculated day of the year - (0-365, Jan 1 = 0) */ - - PRTimeParameters tm_params; /* time parameters used by conversion */ -} PRExplodedTime; - -/* - * PRTimeParamFn -- - * - * A function of PRTimeParamFn type returns the time zone and - * daylight saving time corrections for some geographic location, - * given the current time in GMT. The input argument gmt should - * point to a PRExplodedTime that is in GMT, i.e., whose - * tm_params contains all 0's. - * - * For any time zone other than GMT, the computation is intended to - * consist of two steps: - * - Figure out the time zone correction, tp_gmt_offset. This number - * usually depends on the geographic location only. But it may - * also depend on the current time. For example, all of China - * is one time zone right now. But this situation may change - * in the future. - * - Figure out the daylight saving time correction, tp_dst_offset. - * This number depends on both the geographic location and the - * current time. Most of the DST rules are expressed in local - * current time. If so, one should apply the time zone correction - * to GMT before applying the DST rules. - */ - -typedef PRTimeParameters (PR_CALLBACK *PRTimeParamFn)(const PRExplodedTime *gmt); - -/**********************************************************************/ -/****************************** FUNCTIONS *****************************/ -/**********************************************************************/ - -/* - * The PR_Now routine returns the current time relative to the - * epoch, midnight, January 1, 1970 UTC. The units of the returned - * value are microseconds since the epoch. - * - * The values returned are not guaranteed to advance in a linear fashion - * due to the application of time correction protocols which synchronize - * computer clocks to some external time source. Consequently it should - * not be depended on for interval timing. - * - * The implementation is machine dependent. - * Cf. time_t time(time_t *tp) in ANSI C. - */ -#if defined(HAVE_WATCOM_BUG_2) -PRTime __pascal __export __loadds -#else -NSPR_API(PRTime) -#endif -PR_Now(void); - -/* - * Expand time binding it to time parameters provided by PRTimeParamFn. - * The calculation is envisoned to proceed in the following steps: - * - From given PRTime, calculate PRExplodedTime in GMT - * - Apply the given PRTimeParamFn to the GMT that we just calculated - * to obtain PRTimeParameters. - * - Add the PRTimeParameters offsets to GMT to get the local time - * as PRExplodedTime. - */ - -NSPR_API(void) PR_ExplodeTime( - PRTime usecs, PRTimeParamFn params, PRExplodedTime *exploded); - -/* Reverse operation of PR_ExplodeTime */ -#if defined(HAVE_WATCOM_BUG_2) -PRTime __pascal __export __loadds -#else -NSPR_API(PRTime) -#endif -PR_ImplodeTime(const PRExplodedTime *exploded); - -/* - * Adjust exploded time to normalize field overflows after manipulation. - * Note that the following fields of PRExplodedTime should not be - * manipulated: - * - tm_month and tm_year: because the number of days in a month and - * number of days in a year are not constant, it is ambiguous to - * manipulate the month and year fields, although one may be tempted - * to. For example, what does "a month from January 31st" mean? - * - tm_wday and tm_yday: these fields are calculated by NSPR. Users - * should treat them as "read-only". - */ - -NSPR_API(void) PR_NormalizeTime( - PRExplodedTime *exploded, PRTimeParamFn params); - -/**********************************************************************/ -/*********************** TIME PARAMETER FUNCTIONS *********************/ -/**********************************************************************/ - -/* Time parameters that suit current host machine */ -NSPR_API(PRTimeParameters) PR_LocalTimeParameters(const PRExplodedTime *gmt); - -/* Time parameters that represent Greenwich Mean Time */ -NSPR_API(PRTimeParameters) PR_GMTParameters(const PRExplodedTime *gmt); - -/* - * Time parameters that represent the US Pacific Time Zone, with the - * current daylight saving time rules (for testing only) - */ -NSPR_API(PRTimeParameters) PR_USPacificTimeParameters(const PRExplodedTime *gmt); - -/* - * This parses a time/date string into a PRTime - * (microseconds after "1-Jan-1970 00:00:00 GMT"). - * It returns PR_SUCCESS on success, and PR_FAILURE - * if the time/date string can't be parsed. - * - * Many formats are handled, including: - * - * 14 Apr 89 03:20:12 - * 14 Apr 89 03:20 GMT - * Fri, 17 Mar 89 4:01:33 - * Fri, 17 Mar 89 4:01 GMT - * Mon Jan 16 16:12 PDT 1989 - * Mon Jan 16 16:12 +0130 1989 - * 6 May 1992 16:41-JST (Wednesday) - * 22-AUG-1993 10:59:12.82 - * 22-AUG-1993 10:59pm - * 22-AUG-1993 12:59am - * 22-AUG-1993 12:59 PM - * Friday, August 04, 1995 3:54 PM - * 06/21/95 04:24:34 PM - * 20/06/95 21:07 - * 95-06-08 19:32:48 EDT - * - * If the input string doesn't contain a description of the timezone, - * we consult the `default_to_gmt' to decide whether the string should - * be interpreted relative to the local time zone (PR_FALSE) or GMT (PR_TRUE). - * The correct value for this argument depends on what standard specified - * the time string which you are parsing. - */ - -NSPR_API(PRStatus) PR_ParseTimeString ( - const char *string, - PRBool default_to_gmt, - PRTime *result); - -/* - * FIXME: should we also have a formatting function, such as asctime, ctime, - * and strftime in standard C library? But this would involve - * internationalization issues. Might want to provide a US English version. - */ - -/**********************************************************************/ -/*********************** OLD COMPATIBILITYFUNCTIONS *******************/ -/**********************************************************************/ -#ifndef NO_NSPR_10_SUPPORT - -/* Format a time value into a buffer. Same semantics as strftime() */ -NSPR_API(PRUint32) PR_FormatTime(char *buf, int buflen, const char *fmt, - const PRExplodedTime *tm); - -/* Format a time value into a buffer. Time is always in US English format, regardless - * of locale setting. - */ -NSPR_API(PRUint32) -PR_FormatTimeUSEnglish( char* buf, PRUint32 bufSize, - const char* format, const PRExplodedTime* tm ); - -#endif /* NO_NSPR_10_SUPPORT */ - -PR_END_EXTERN_C - -#endif /* prtime_h___ */ diff --git a/OSX/include/security_asn1/prtypes.h b/OSX/include/security_asn1/prtypes.h deleted file mode 100644 index 441ca696..00000000 --- a/OSX/include/security_asn1/prtypes.h +++ /dev/null @@ -1,570 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* -** File: prtypes.h -** Description: Definitions of NSPR's basic types -** -** Prototypes and macros used to make up for deficiencies in ANSI environments -** that we have found. -** -** Since we do not wrap and all the other standard headers, authors -** of portable code will not know in general that they need these definitions. -** Instead of requiring these authors to find the dependent uses in their code -** and take the following steps only in those C files, we take steps once here -** for all C files. -**/ - -#ifndef prtypes_h___ -#define prtypes_h___ - -#ifdef MDCPUCFG -#include MDCPUCFG -#else -#include -#endif - -#include - -#ifdef __APPLE__ -#include // for uintptr_t -#endif - -/*********************************************************************** -** MACROS: PR_EXTERN -** PR_IMPLEMENT -** DESCRIPTION: -** These are only for externally visible routines and globals. For -** internal routines, just use "extern" for type checking and that -** will not export internal cross-file or forward-declared symbols. -** Define a macro for declaring procedures return types. We use this to -** deal with windoze specific type hackery for DLL definitions. Use -** PR_EXTERN when the prototype for the method is declared. Use -** PR_IMPLEMENT for the implementation of the method. -** -** Example: -** in dowhim.h -** PR_EXTERN( void ) DoWhatIMean( void ); -** in dowhim.c -** PR_IMPLEMENT( void ) DoWhatIMean( void ) { return; } -** -** -***********************************************************************/ -#if defined(WIN32) - -#if defined(__GNUC__) -#undef _declspec -#define _declspec(x) __declspec(x) -#endif - -#define PR_EXPORT(__type) extern _declspec(dllexport) __type -#define PR_EXPORT_DATA(__type) extern _declspec(dllexport) __type -#define PR_IMPORT(__type) _declspec(dllimport) __type -#define PR_IMPORT_DATA(__type) _declspec(dllimport) __type - -#define PR_EXTERN(__type) extern _declspec(dllexport) __type -#define PR_IMPLEMENT(__type) _declspec(dllexport) __type -#define PR_EXTERN_DATA(__type) extern _declspec(dllexport) __type -#define PR_IMPLEMENT_DATA(__type) _declspec(dllexport) __type - -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#elif defined(XP_BEOS) - -#define PR_EXPORT(__type) extern __declspec(dllexport) __type -#define PR_EXPORT_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPORT(__type) extern __declspec(dllexport) __type -#define PR_IMPORT_DATA(__type) extern __declspec(dllexport) __type - -#define PR_EXTERN(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT(__type) __declspec(dllexport) __type -#define PR_EXTERN_DATA(__type) extern __declspec(dllexport) __type -#define PR_IMPLEMENT_DATA(__type) __declspec(dllexport) __type - -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#elif defined(WIN16) - -#define PR_CALLBACK_DECL __cdecl - -#if defined(_WINDLL) -#define PR_EXPORT(__type) extern __type _cdecl _export _loadds -#define PR_IMPORT(__type) extern __type _cdecl _export _loadds -#define PR_EXPORT_DATA(__type) extern __type _export -#define PR_IMPORT_DATA(__type) extern __type _export - -#define PR_EXTERN(__type) extern __type _cdecl _export _loadds -#define PR_IMPLEMENT(__type) __type _cdecl _export _loadds -#define PR_EXTERN_DATA(__type) extern __type _export -#define PR_IMPLEMENT_DATA(__type) __type _export - -#define PR_CALLBACK __cdecl __loadds -#define PR_STATIC_CALLBACK(__x) static __x PR_CALLBACK - -#else /* this must be .EXE */ -#define PR_EXPORT(__type) extern __type _cdecl _export -#define PR_IMPORT(__type) extern __type _cdecl _export -#define PR_EXPORT_DATA(__type) extern __type _export -#define PR_IMPORT_DATA(__type) extern __type _export - -#define PR_EXTERN(__type) extern __type _cdecl _export -#define PR_IMPLEMENT(__type) __type _cdecl _export -#define PR_EXTERN_DATA(__type) extern __type _export -#define PR_IMPLEMENT_DATA(__type) __type _export - -#define PR_CALLBACK __cdecl __loadds -#define PR_STATIC_CALLBACK(__x) __x PR_CALLBACK -#endif /* _WINDLL */ - -#elif defined(XP_MAC) - - #if defined __GNUC__ - /* Darwin */ - #define PR_EXPORT(__type) extern __type - #define PR_EXPORT_DATA(__type) extern __type - #define PR_IMPORT(__type) extern __type - #define PR_IMPORT_DATA(__type) extern __type - - #define PR_EXTERN(__type) extern __type - #define PR_IMPLEMENT(__type) __type - #define PR_EXTERN_DATA(__type) extern __type - #define PR_IMPLEMENT_DATA(__type) __type - #define PR_CALLBACK - #define PR_CALLBACK_DECL - #define PR_STATIC_CALLBACK(__x) static __x - - #else - /* MacOS 9 */ - #define PR_EXPORT(__type) extern __declspec(export) __type - #define PR_EXPORT_DATA(__type) extern __declspec(export) __type - #define PR_IMPORT(__type) extern __declspec(export) __type - #define PR_IMPORT_DATA(__type) extern __declspec(export) __type - - #define PR_EXTERN(__type) extern __declspec(export) __type - #define PR_IMPLEMENT(__type) __declspec(export) __type - #define PR_EXTERN_DATA(__type) extern __declspec(export) __type - #define PR_IMPLEMENT_DATA(__type) __declspec(export) __type - - #define PR_CALLBACK - #define PR_CALLBACK_DECL - #define PR_STATIC_CALLBACK(__x) static __x - #endif /* __GNUC__ */ -#elif defined(XP_OS2_VACPP) - -#define PR_EXPORT(__type) extern __type -#define PR_EXPORT_DATA(__type) extern __type -#define PR_IMPORT(__type) extern __type -#define PR_IMPORT_DATA(__type) extern __type - -#define PR_EXTERN(__type) extern __type -#define PR_IMPLEMENT(__type) __type -#define PR_EXTERN_DATA(__type) extern __type -#define PR_IMPLEMENT_DATA(__type) __type -#define PR_CALLBACK _Optlink -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x PR_CALLBACK - -#else /* Unix */ - -#define PR_EXPORT(__type) extern __type -#define PR_EXPORT_DATA(__type) extern __type -#define PR_IMPORT(__type) extern __type -#define PR_IMPORT_DATA(__type) extern __type - -#define PR_EXTERN(__type) extern __type -#define PR_IMPLEMENT(__type) __type -#define PR_EXTERN_DATA(__type) extern __type -#define PR_IMPLEMENT_DATA(__type) __type -#define PR_CALLBACK -#define PR_CALLBACK_DECL -#define PR_STATIC_CALLBACK(__x) static __x - -#endif - -#if defined(_NSPR_BUILD_) -#define NSPR_API(__type) PR_EXPORT(__type) -#define NSPR_DATA_API(__type) PR_EXPORT_DATA(__type) -#else -#define NSPR_API(__type) PR_IMPORT(__type) -#define NSPR_DATA_API(__type) PR_IMPORT_DATA(__type) -#endif - -/*********************************************************************** -** MACROS: PR_BEGIN_MACRO -** PR_END_MACRO -** DESCRIPTION: -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -***********************************************************************/ -#define PR_BEGIN_MACRO do { -#define PR_END_MACRO } while (0) - -/*********************************************************************** -** MACROS: PR_BEGIN_EXTERN_C -** PR_END_EXTERN_C -** DESCRIPTION: -** Macro shorthands for conditional C++ extern block delimiters. -***********************************************************************/ -#ifdef __cplusplus -#define PR_BEGIN_EXTERN_C extern "C" { -#define PR_END_EXTERN_C } -#else -#define PR_BEGIN_EXTERN_C -#define PR_END_EXTERN_C -#endif - -/*********************************************************************** -** MACROS: PR_BIT -** PR_BITMASK -** DESCRIPTION: -** Bit masking macros. XXX n must be <= 31 to be portable -***********************************************************************/ -#define PR_BIT(n) ((PRUint32)1 << (n)) -#define PR_BITMASK(n) (PR_BIT(n) - 1) - -/*********************************************************************** -** MACROS: PR_ROUNDUP -** PR_MIN -** PR_MAX -** PR_ABS -** DESCRIPTION: -** Commonly used macros for operations on compatible types. -***********************************************************************/ -#define PR_ROUNDUP(x,y) ((((x)+((y)-1))/(y))*(y)) -#define PR_MIN(x,y) ((x)<(y)?(x):(y)) -#define PR_MAX(x,y) ((x)>(y)?(x):(y)) -#define PR_ABS(x) ((x)<0?-(x):(x)) - -PR_BEGIN_EXTERN_C - -/************************************************************************ -** TYPES: PRUint8 -** PRInt8 -** DESCRIPTION: -** The int8 types are known to be 8 bits each. There is no type that -** is equivalent to a plain "char". -************************************************************************/ -#if PR_BYTES_PER_BYTE == 1 -typedef unsigned char PRUint8; -/* -** Some cfront-based C++ compilers do not like 'signed char' and -** issue the warning message: -** warning: "signed" not implemented (ignored) -** For these compilers, we have to define PRInt8 as plain 'char'. -** Make sure that plain 'char' is indeed signed under these compilers. -*/ -#if (defined(HPUX) && defined(__cplusplus) \ - && !defined(__GNUC__) && __cplusplus < 199707L) \ - || (defined(SCO) && defined(__cplusplus) \ - && !defined(__GNUC__) && __cplusplus == 1L) -typedef char PRInt8; -#else -typedef signed char PRInt8; -#endif -#else -#error No suitable type for PRInt8/PRUint8 -#endif - -/************************************************************************ - * MACROS: PR_INT8_MAX - * PR_INT8_MIN - * PR_UINT8_MAX - * DESCRIPTION: - * The maximum and minimum values of a PRInt8 or PRUint8. -************************************************************************/ - -#define PR_INT8_MAX 127 -#define PR_INT8_MIN (-128) -#define PR_UINT8_MAX 255U - -/************************************************************************ -** TYPES: PRUint16 -** PRInt16 -** DESCRIPTION: -** The int16 types are known to be 16 bits each. -************************************************************************/ -#if PR_BYTES_PER_SHORT == 2 -typedef unsigned short PRUint16; -typedef short PRInt16; -#else -#error No suitable type for PRInt16/PRUint16 -#endif - -/************************************************************************ - * MACROS: PR_INT16_MAX - * PR_INT16_MIN - * PR_UINT16_MAX - * DESCRIPTION: - * The maximum and minimum values of a PRInt16 or PRUint16. -************************************************************************/ - -#define PR_INT16_MAX 32767 -#define PR_INT16_MIN (-32768) -#define PR_UINT16_MAX 65535U - -/************************************************************************ -** TYPES: PRUint32 -** PRInt32 -** DESCRIPTION: -** The int32 types are known to be 32 bits each. -************************************************************************/ -#if PR_BYTES_PER_INT == 4 -typedef unsigned int PRUint32; -typedef int PRInt32; -#define PR_INT32(x) x -#define PR_UINT32(x) x ## U -#elif PR_BYTES_PER_LONG == 4 -typedef unsigned long PRUint32; -typedef long PRInt32; -#define PR_INT32(x) x ## L -#define PR_UINT32(x) x ## UL -#else -#error No suitable type for PRInt32/PRUint32 -#endif - -/************************************************************************ - * MACROS: PR_INT32_MAX - * PR_INT32_MIN - * PR_UINT32_MAX - * DESCRIPTION: - * The maximum and minimum values of a PRInt32 or PRUint32. -************************************************************************/ - -#define PR_INT32_MAX PR_INT32(2147483647) -#define PR_INT32_MIN (-PR_INT32_MAX - 1) -#define PR_UINT32_MAX PR_UINT32(4294967295) - -/************************************************************************ -** TYPES: PRUint64 -** PRInt64 -** DESCRIPTION: -** The int64 types are known to be 64 bits each. Care must be used when -** declaring variables of type PRUint64 or PRInt64. Different hardware -** architectures and even different compilers have varying support for -** 64 bit values. The only guaranteed portability requires the use of -** the LL_ macros (see prlong.h). -************************************************************************/ -#ifdef HAVE_LONG_LONG -#if PR_BYTES_PER_LONG == 8 -typedef long PRInt64; -typedef unsigned long PRUint64; -#elif defined(WIN16) -typedef __int64 PRInt64; -typedef unsigned __int64 PRUint64; -#elif defined(WIN32) && !defined(__GNUC__) -typedef __int64 PRInt64; -typedef unsigned __int64 PRUint64; -#else -typedef long long PRInt64; -typedef unsigned long long PRUint64; -#endif /* PR_BYTES_PER_LONG == 8 */ -#else /* !HAVE_LONG_LONG */ -typedef struct { -#ifdef IS_LITTLE_ENDIAN - PRUint32 lo, hi; -#else - PRUint32 hi, lo; -#endif -} PRInt64; -typedef PRInt64 PRUint64; -#endif /* !HAVE_LONG_LONG */ - -/************************************************************************ -** TYPES: PRUintn -** PRIntn -** DESCRIPTION: -** The PRIntn types are most appropriate for automatic variables. They are -** guaranteed to be at least 16 bits, though various architectures may -** define them to be wider (e.g., 32 or even 64 bits). These types are -** never valid for fields of a structure. -************************************************************************/ -#if PR_BYTES_PER_INT >= 2 -typedef int PRIntn; -typedef unsigned int PRUintn; -#else -#error 'sizeof(int)' not sufficient for platform use -#endif - -/************************************************************************ -** TYPES: PRFloat64 -** DESCRIPTION: -** NSPR's floating point type is always 64 bits. -************************************************************************/ -typedef double PRFloat64; - -/************************************************************************ -** TYPES: PRSize -** DESCRIPTION: -** A type for representing the size of objects. -************************************************************************/ -typedef size_t PRSize; - - -/************************************************************************ -** TYPES: PROffset32, PROffset64 -** DESCRIPTION: -** A type for representing byte offsets from some location. -************************************************************************/ -typedef PRInt32 PROffset32; -typedef PRInt64 PROffset64; - -/************************************************************************ -** TYPES: PRPtrDiff -** DESCRIPTION: -** A type for pointer difference. Variables of this type are suitable -** for storing a pointer or pointer sutraction. -************************************************************************/ -typedef ptrdiff_t PRPtrdiff; - -/************************************************************************ -** TYPES: PRUptrdiff -** DESCRIPTION: -** A type for pointer difference. Variables of this type are suitable -** for storing a pointer or pointer sutraction. -************************************************************************/ -typedef unsigned long PRUptrdiff; - -/************************************************************************ -** TYPES: PRBool -** DESCRIPTION: -** Use PRBool for variables and parameter types. Use PR_FALSE and PR_TRUE -** for clarity of target type in assignments and actual arguments. Use -** 'if (bool)', 'while (!bool)', '(bool) ? x : y' etc., to test booleans -** juast as you would C int-valued conditions. -************************************************************************/ -typedef PRIntn PRBool; -#define PR_TRUE 1 -#define PR_FALSE 0 - -/************************************************************************ -** TYPES: PRPackedBool -** DESCRIPTION: -** Use PRPackedBOol within structs where bitfields are not desireable -** but minimum and consistant overhead matters. -************************************************************************/ -typedef PRUint8 PRPackedBool; - -/* -** Status code used by some routines that have a single point of failure or -** special status return. -*/ -typedef enum { PR_FAILURE = -1, PR_SUCCESS = 0 } PRStatus; - -#ifdef MOZ_UNICODE -/* - * EXPERIMENTAL: This type may be removed in a future release. - */ -#ifndef __PRUNICHAR__ -#define __PRUNICHAR__ -#if defined(WIN32) || defined(XP_MAC) -typedef wchar_t PRUnichar; -#else -typedef PRUint16 PRUnichar; -#endif -#endif -#endif /* MOZ_UNICODE */ - -/* -** WARNING: The undocumented data types PRWord and PRUword are -** only used in the garbage collection and arena code. Do not -** use PRWord and PRUword in new code. -** -** A PRWord is an integer that is the same size as a void*. -** It implements the notion of a "word" in the Java Virtual -** Machine. (See Sec. 3.4 "Words", The Java Virtual Machine -** Specification, Addison-Wesley, September 1996. -** http://java.sun.com/docs/books/vmspec/index.html.) -*/ - -#ifdef __APPLE__ -typedef intptr_t PRWord; -typedef uintptr_t PRUword; -#else -typedef long PRWord; -typedef unsigned long PRUword; -#endif - -#if defined(NO_NSPR_10_SUPPORT) -#else -/********* ???????????????? FIX ME ??????????????????????????? *****/ -/********************** Some old definitions until pr=>ds transition is done ***/ -/********************** Also, we are still using NSPR 1.0. GC ******************/ -/* -** Fundamental NSPR macros, used nearly everywhere. -*/ - -#define PR_PUBLIC_API PR_IMPLEMENT - -/* -** Macro body brackets so that macros with compound statement definitions -** behave syntactically more like functions when called. -*/ -#define NSPR_BEGIN_MACRO do { -#define NSPR_END_MACRO } while (0) - -/* -** Macro shorthands for conditional C++ extern block delimiters. -*/ -#ifdef NSPR_BEGIN_EXTERN_C -#undef NSPR_BEGIN_EXTERN_C -#endif -#ifdef NSPR_END_EXTERN_C -#undef NSPR_END_EXTERN_C -#endif - -#ifdef __cplusplus -#define NSPR_BEGIN_EXTERN_C extern "C" { -#define NSPR_END_EXTERN_C } -#else -#define NSPR_BEGIN_EXTERN_C -#define NSPR_END_EXTERN_C -#endif - -#ifdef XP_MAC -#include "protypes.h" -#else -#include "obsolete/protypes.h" -#endif - -/********* ????????????? End Fix me ?????????????????????????????? *****/ -#endif /* NO_NSPR_10_SUPPORT */ - -PR_END_EXTERN_C - -#endif /* prtypes_h___ */ - diff --git a/OSX/include/security_asn1/prvrsion.h b/OSX/include/security_asn1/prvrsion.h deleted file mode 100644 index 3bb3b144..00000000 --- a/OSX/include/security_asn1/prvrsion.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape Portable Runtime (NSPR). - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1998-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - - -/* author: jstewart */ - -#if defined(_PRVERSION_H) -#else -#define _PRVERSION_H - -#include - -PR_BEGIN_EXTERN_C - -/* All components participating in the PR version protocol must expose - * a structure and a function. The structure is defined below and named - * according to the naming conventions outlined further below. The function - * is called libVersionPoint and returns a pointer to this structure. - */ - -/* on NT, always pack the structure the same. */ -#ifdef _WIN32 -#pragma pack(push, 8) -#endif - -typedef struct { - /* - * The first field defines which version of this structure is in use. - * At this time, only version 2 is specified. If this value is not - * 2, you must read no further into the structure. - */ - PRInt32 version; - - /* for Version 2, this is the body format. */ - PRInt64 buildTime; /* 64 bits - usecs since midnight, 1/1/1970 */ - char * buildTimeString;/* a human readable version of the time */ - - PRUint8 vMajor; /* Major version of this component */ - PRUint8 vMinor; /* Minor version of this component */ - PRUint8 vPatch; /* Patch level of this component */ - - PRBool beta; /* true if this is a beta component */ - PRBool debug; /* true if this is a debug component */ - PRBool special; /* true if this component is a special build */ - - char * filename; /* The original filename */ - char * description; /* description of this component */ - char * security; /* level of security in this component */ - char * copyright; /* The copyright for this file */ - char * comment; /* free form field for misc usage */ - char * specialString; /* the special variant for this build */ -} PRVersionDescription; - -/* on NT, restore the previous packing */ -#ifdef _WIN32 -#pragma pack(pop) -#endif - -/* - * All components must define an entrypoint named libVersionPoint which - * is of type versionEntryPointType. - * - * For example, for a library named libfoo, we would have: - * - * PRVersionDescription prVersionDescription_libfoo = - * { - * ... - * }; - * - * PR_IMPLEMENT(const PRVersionDescription*) libVersionPoint(void) - * { - * return &prVersionDescription_libfoo; - * } - */ -typedef const PRVersionDescription *(*versionEntryPointType)(void); - -/* - * Where you declare your libVersionPoint, do it like this: - * PR_IMPLEMENT(const PRVersionDescription *) libVersionPoint(void) { - * fill it in... - * } - */ - -/* - * NAMING CONVENTION FOR struct - * - * all components should also expose a static PRVersionDescription - * The name of the struct should be calculated as follows: - * Take the value of filename. (If filename is not specified, calculate - * a short, unique string.) Convert all non-alphanumeric characters - * to '_'. To this, prepend "PRVersionDescription_". Thus for libfoo.so, - * the symbol name is "PRVersionDescription_libfoo_so". - * so the file should have - * PRVersionDescription PRVersionDescription_libfoo_so { fill it in }; - * on NT, this file should be declspec export. - */ - -PR_END_EXTERN_C - -#endif /* defined(_PRVERSION_H) */ - -/* prvrsion.h */ - diff --git a/OSX/include/security_asn1/secErrorStr.c b/OSX/include/security_asn1/secErrorStr.c deleted file mode 100644 index 138dbc14..00000000 --- a/OSX/include/security_asn1/secErrorStr.c +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright (c) 2003-2006,2008,2010-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * secErrorStr.c - ASCII string version of NSS Sec layer error codes - */ -#include "secerr.h" -#include - -typedef struct { - PRErrorCode value; - const char *name; -} SecErrorNameValuePair; - -/* one entry in an array of SecErrorNameValuePairs */ -#define SNVP(err) {err, #err} - -/* the NULL entry which terminates the SecErrorNameValuePair list */ -#define SNVP_END {0, NULL} - -static const SecErrorNameValuePair errValues[] = -{ - /* FIXME: we really don't need all of these, but they're not - * compiled for NDEBUG builds. */ - #ifndef NDEBUG - SNVP(SEC_ERROR_IO), - SNVP(SEC_ERROR_LIBRARY_FAILURE), - SNVP(SEC_ERROR_BAD_DATA ), - SNVP(SEC_ERROR_OUTPUT_LEN), - SNVP(SEC_ERROR_INPUT_LEN), - SNVP(SEC_ERROR_INVALID_ARGS), - SNVP(SEC_ERROR_INVALID_ALGORITHM), - SNVP(SEC_ERROR_INVALID_AVA), - SNVP(SEC_ERROR_INVALID_TIME), - SNVP(SEC_ERROR_BAD_DER), - SNVP(SEC_ERROR_BAD_SIGNATURE ), - SNVP(SEC_ERROR_EXPIRED_CERTIFICATE), - SNVP(SEC_ERROR_REVOKED_CERTIFICATE), - SNVP(SEC_ERROR_UNKNOWN_ISSUER ), - SNVP(SEC_ERROR_BAD_KEY), - SNVP(SEC_ERROR_BAD_PASSWORD), - SNVP(SEC_ERROR_RETRY_PASSWORD), - SNVP(SEC_ERROR_NO_NODELOCK ), - SNVP(SEC_ERROR_BAD_DATABASE), - SNVP(SEC_ERROR_NO_MEMORY), - SNVP(SEC_ERROR_UNTRUSTED_ISSUER), - SNVP(SEC_ERROR_UNTRUSTED_CERT), - SNVP(SEC_ERROR_DUPLICATE_CERT), - SNVP(SEC_ERROR_DUPLICATE_CERT_NAME), - SNVP(SEC_ERROR_ADDING_CERT), - SNVP(SEC_ERROR_FILING_KEY), - SNVP(SEC_ERROR_NO_KEY), - SNVP(SEC_ERROR_CERT_VALID), - SNVP(SEC_ERROR_CERT_NOT_VALID), - SNVP(SEC_ERROR_CERT_NO_RESPONSE), - SNVP(SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE), - SNVP(SEC_ERROR_CRL_EXPIRED), - SNVP(SEC_ERROR_CRL_BAD_SIGNATURE), - SNVP(SEC_ERROR_CRL_INVALID), - SNVP(SEC_ERROR_EXTENSION_VALUE_INVALID), - SNVP(SEC_ERROR_EXTENSION_NOT_FOUND), - SNVP(SEC_ERROR_CA_CERT_INVALID), - SNVP(SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID), - SNVP(SEC_ERROR_CERT_USAGES_INVALID), - SNVP(SEC_INTERNAL_ONLY), - SNVP(SEC_ERROR_INVALID_KEY), - SNVP(SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION), - SNVP(SEC_ERROR_OLD_CRL), - SNVP(SEC_ERROR_NO_EMAIL_CERT), - SNVP(SEC_ERROR_NO_RECIPIENT_CERTS_QUERY), - SNVP(SEC_ERROR_NOT_A_RECIPIENT), - SNVP(SEC_ERROR_PKCS7_KEYALG_MISMATCH), - SNVP(SEC_ERROR_PKCS7_BAD_SIGNATURE), - SNVP(SEC_ERROR_UNSUPPORTED_KEYALG), - SNVP(SEC_ERROR_DECRYPTION_DISALLOWED), - SNVP(XP_SEC_FORTEZZA_BAD_CARD), - SNVP(XP_SEC_FORTEZZA_NO_CARD), - SNVP(XP_SEC_FORTEZZA_NONE_SELECTED ), - SNVP(XP_SEC_FORTEZZA_MORE_INFO ), - SNVP(XP_SEC_FORTEZZA_PERSON_NOT_FOUND ), - SNVP(XP_SEC_FORTEZZA_NO_MORE_INFO), - SNVP(XP_SEC_FORTEZZA_BAD_PIN), - SNVP(XP_SEC_FORTEZZA_PERSON_ERROR), - SNVP(SEC_ERROR_NO_KRL), - SNVP(SEC_ERROR_KRL_EXPIRED), - SNVP(SEC_ERROR_KRL_BAD_SIGNATURE), - SNVP(SEC_ERROR_REVOKED_KEY ), - SNVP(SEC_ERROR_KRL_INVALID), - SNVP(SEC_ERROR_NEED_RANDOM), - SNVP(SEC_ERROR_NO_MODULE), - SNVP(SEC_ERROR_NO_TOKEN), - SNVP(SEC_ERROR_READ_ONLY), - SNVP(SEC_ERROR_NO_SLOT_SELECTED), - SNVP(SEC_ERROR_CERT_NICKNAME_COLLISION), - SNVP(SEC_ERROR_KEY_NICKNAME_COLLISION), - SNVP(SEC_ERROR_SAFE_NOT_CREATED), - SNVP(SEC_ERROR_BAGGAGE_NOT_CREATED), - SNVP(XP_JAVA_REMOVE_PRINCIPAL_ERROR), - SNVP(XP_JAVA_DELETE_PRIVILEGE_ERROR), - SNVP(XP_JAVA_CERT_NOT_EXISTS_ERROR ), - SNVP(SEC_ERROR_BAD_EXPORT_ALGORITHM), - SNVP(SEC_ERROR_EXPORTING_CERTIFICATES), - SNVP(SEC_ERROR_IMPORTING_CERTIFICATES), - SNVP(SEC_ERROR_PKCS12_DECODING_PFX), - SNVP(SEC_ERROR_PKCS12_INVALID_MAC), - SNVP(SEC_ERROR_PKCS12_UNSUPPORTED_MAC_ALGORITHM), - SNVP(SEC_ERROR_PKCS12_UNSUPPORTED_TRANSPORT_MODE), - SNVP(SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE), - SNVP(SEC_ERROR_PKCS12_UNSUPPORTED_PBE_ALGORITHM), - SNVP(SEC_ERROR_PKCS12_UNSUPPORTED_VERSION ), - SNVP(SEC_ERROR_PKCS12_PRIVACY_PASSWORD_INCORRECT), - SNVP(SEC_ERROR_PKCS12_CERT_COLLISION), - SNVP(SEC_ERROR_USER_CANCELLED), - SNVP(SEC_ERROR_PKCS12_DUPLICATE_DATA), - SNVP(SEC_ERROR_MESSAGE_SEND_ABORTED), - SNVP(SEC_ERROR_INADEQUATE_KEY_USAGE), - SNVP(SEC_ERROR_INADEQUATE_CERT_TYPE), - SNVP(SEC_ERROR_CERT_ADDR_MISMATCH), - SNVP(SEC_ERROR_PKCS12_UNABLE_TO_IMPORT_KEY), - SNVP(SEC_ERROR_PKCS12_IMPORTING_CERT_CHAIN), - SNVP(SEC_ERROR_PKCS12_UNABLE_TO_LOCATE_OBJECT_BY_NAME), - SNVP(SEC_ERROR_PKCS12_UNABLE_TO_EXPORT_KEY), - SNVP(SEC_ERROR_PKCS12_UNABLE_TO_WRITE), - SNVP(SEC_ERROR_PKCS12_UNABLE_TO_READ), - SNVP(SEC_ERROR_PKCS12_KEY_DATABASE_NOT_INITIALIZED), - SNVP(SEC_ERROR_KEYGEN_FAIL), - SNVP(SEC_ERROR_INVALID_PASSWORD), - SNVP(SEC_ERROR_RETRY_OLD_PASSWORD), - SNVP(SEC_ERROR_BAD_NICKNAME), - SNVP(SEC_ERROR_NOT_FORTEZZA_ISSUER), - SNVP(SEC_ERROR_CANNOT_MOVE_SENSITIVE_KEY), - SNVP(SEC_ERROR_JS_INVALID_MODULE_NAME), - SNVP(SEC_ERROR_JS_INVALID_DLL), - SNVP(SEC_ERROR_JS_ADD_MOD_FAILURE), - SNVP(SEC_ERROR_JS_DEL_MOD_FAILURE), - SNVP(SEC_ERROR_OLD_KRL), - SNVP(SEC_ERROR_CKL_CONFLICT), - SNVP(SEC_ERROR_CERT_NOT_IN_NAME_SPACE), - SNVP(SEC_ERROR_KRL_NOT_YET_VALID), - SNVP(SEC_ERROR_CRL_NOT_YET_VALID), - SNVP(SEC_ERROR_UNKNOWN_CERT), - SNVP(SEC_ERROR_UNKNOWN_SIGNER), - SNVP(SEC_ERROR_CERT_BAD_ACCESS_LOCATION ), - SNVP(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE), - SNVP(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE), - SNVP(SEC_ERROR_OCSP_MALFORMED_REQUEST), - SNVP(SEC_ERROR_OCSP_SERVER_ERROR), - SNVP(SEC_ERROR_OCSP_TRY_SERVER_LATER), - SNVP(SEC_ERROR_OCSP_REQUEST_NEEDS_SIG), - SNVP(SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST), - SNVP(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS), - SNVP(SEC_ERROR_OCSP_UNKNOWN_CERT), - SNVP(SEC_ERROR_OCSP_NOT_ENABLED), - SNVP(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER), - SNVP(SEC_ERROR_OCSP_MALFORMED_RESPONSE ), - SNVP(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE), - SNVP(SEC_ERROR_OCSP_FUTURE_RESPONSE ), - SNVP(SEC_ERROR_OCSP_OLD_RESPONSE), - SNVP(SEC_ERROR_DIGEST_NOT_FOUND), - SNVP(SEC_ERROR_UNSUPPORTED_MESSAGE_TYPE), - SNVP(SEC_ERROR_MODULE_STUCK), - SNVP(SEC_ERROR_BAD_TEMPLATE), - SNVP(SEC_ERROR_CRL_NOT_FOUND), - SNVP(SEC_ERROR_REUSED_ISSUER_AND_SERIAL ), - SNVP(SEC_ERROR_BUSY), - #endif /* NDEBUG */ - SNVP_END -}; - -/* - * Given a PRErrorCode, obtain a const C string. Not copied, not - * to be freed by caller. - */ -const char *SECErrorString(PRErrorCode err) -{ - static char badStr[100]; - const SecErrorNameValuePair *nvp = errValues; - - while(nvp->name != NULL) { - if(nvp->value == err) { - return nvp->name; - } - nvp++; - } - - /* Not found, not thread safe */ - sprintf(badStr, "UNKNOWN (%d(d)", err); - return badStr; - -} diff --git a/OSX/include/security_asn1/secasn1.h b/OSX/include/security_asn1/secasn1.h deleted file mode 100644 index 6ff361f2..00000000 --- a/OSX/include/security_asn1/secasn1.h +++ /dev/null @@ -1,219 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Support for encoding/decoding of ASN.1 using BER/DER (Basic/Distinguished - * Encoding Rules). The routines are found in and used extensively by the - * security library, but exported for other use. - * - * $Id: secasn1.h,v 1.8 2004/05/13 15:29:13 dmitch Exp $ - */ - -#ifndef _SECASN1_H_ -#define _SECASN1_H_ - -#include - -#include -#include -#include - - -/************************************************************************/ -SEC_BEGIN_PROTOS - -/* - * XXX These function prototypes need full, explanatory comments. - */ - -/* -** Decoding. -*/ - -extern SEC_ASN1DecoderContext *SEC_ASN1DecoderStart(PRArenaPool *pool, - void *dest, - const SecAsn1Template *t, - /* - * __APPLE__ addenda: - * - * Only needed if first element will - * be SEC_ASN1_DYNAMIC - */ - const char *buf); - -/* XXX char or unsigned char? */ -extern SECStatus SEC_ASN1DecoderUpdate(SEC_ASN1DecoderContext *cx, - const char *buf, - size_t len); - -extern SECStatus SEC_ASN1DecoderFinish(SEC_ASN1DecoderContext *cx); - -/* Higher level code detected an error, abort the rest of the processing */ -extern void SEC_ASN1DecoderAbort(SEC_ASN1DecoderContext *cx, int error); - -extern void SEC_ASN1DecoderSetFilterProc(SEC_ASN1DecoderContext *cx, - SEC_ASN1WriteProc fn, - void *arg, PRBool no_store); - -extern void SEC_ASN1DecoderClearFilterProc(SEC_ASN1DecoderContext *cx); - -extern void SEC_ASN1DecoderSetNotifyProc(SEC_ASN1DecoderContext *cx, - SEC_ASN1NotifyProc fn, - void *arg); - -extern void SEC_ASN1DecoderClearNotifyProc(SEC_ASN1DecoderContext *cx); - -extern SECStatus SEC_ASN1Decode(PRArenaPool *pool, void *dest, - const SecAsn1Template *t, - const char *buf, size_t len); - -extern SECStatus SEC_ASN1DecodeItem(PRArenaPool *pool, void *dest, - const SecAsn1Template *t, - const SecAsn1Item *item); - -extern SECStatus SEC_QuickDERDecodeItem(PRArenaPool* arena, void* dest, - const SecAsn1Template* templateEntry, - SecAsn1Item* src); - -/* -** Encoding. -*/ - -extern SEC_ASN1EncoderContext *SEC_ASN1EncoderStart(const void *src, - const SecAsn1Template *t, - SEC_ASN1WriteProc fn, - void *output_arg); - -/* XXX char or unsigned char? */ -extern SECStatus SEC_ASN1EncoderUpdate(SEC_ASN1EncoderContext *cx, - const char *buf, - unsigned long len); - -extern void SEC_ASN1EncoderFinish(SEC_ASN1EncoderContext *cx); - -/* Higher level code detected an error, abort the rest of the processing */ -extern void SEC_ASN1EncoderAbort(SEC_ASN1EncoderContext *cx, int error); - -extern void SEC_ASN1EncoderSetNotifyProc(SEC_ASN1EncoderContext *cx, - SEC_ASN1NotifyProc fn, - void *arg); - -extern void SEC_ASN1EncoderClearNotifyProc(SEC_ASN1EncoderContext *cx); - -extern void SEC_ASN1EncoderSetStreaming(SEC_ASN1EncoderContext *cx); - -extern void SEC_ASN1EncoderClearStreaming(SEC_ASN1EncoderContext *cx); - -extern void sec_ASN1EncoderSetDER(SEC_ASN1EncoderContext *cx); - -extern void sec_ASN1EncoderClearDER(SEC_ASN1EncoderContext *cx); - -extern void SEC_ASN1EncoderSetTakeFromBuf(SEC_ASN1EncoderContext *cx); - -extern void SEC_ASN1EncoderClearTakeFromBuf(SEC_ASN1EncoderContext *cx); - -extern SECStatus SEC_ASN1Encode(const void *src, - const SecAsn1Template *t, - SEC_ASN1WriteProc output_proc, - void *output_arg); - -extern SecAsn1Item * SEC_ASN1EncodeItem(PRArenaPool *pool, SecAsn1Item *dest, - const void *src, const SecAsn1Template *t); - -extern SecAsn1Item * SEC_ASN1EncodeInteger(PRArenaPool *pool, - SecAsn1Item *dest, long value); - -extern SecAsn1Item * SEC_ASN1EncodeUnsignedInteger(PRArenaPool *pool, - SecAsn1Item *dest, - unsigned long value); - -extern SECStatus SEC_ASN1DecodeInteger(SecAsn1Item *src, - unsigned long *value); - -/* -** Utilities. -*/ - -/* - * We have a length that needs to be encoded; how many bytes will the - * encoding take? - */ -extern int SEC_ASN1LengthLength (unsigned long len); - -/* encode the length and return the number of bytes we encoded. Buffer - * must be pre allocated */ -extern int SEC_ASN1EncodeLength(unsigned char *buf,unsigned long value); - -/* - * Find the appropriate subtemplate for the given template. - * This may involve calling a "chooser" function, or it may just - * be right there. In either case, it is expected to *have* a - * subtemplate; this is asserted in debug builds (in non-debug - * builds, NULL will be returned). - * - * "thing" is a pointer to the structure being encoded/decoded - * "encoding", when true, means that we are in the process of encoding - * (as opposed to in the process of decoding) - */ -extern const SecAsn1Template * -SEC_ASN1GetSubtemplate ( - const SecAsn1Template *inTemplate, - void *thing, - PRBool encoding, - const char *buf); /* __APPLE__ addenda: for decode only */ - -extern SecAsn1Item *sec_asn1e_allocate_item ( - PRArenaPool *poolp, - SecAsn1Item *dest, - unsigned long len); - -/* - * These two are exported for use by SecNssEncodeItem() - */ -extern void sec_asn1e_encode_item_count ( - void *arg, - const char *buf, - size_t len, - int depth, - SEC_ASN1EncodingPart data_kind); - -extern void sec_asn1e_encode_item_store ( - void *arg, - const char *buf, - size_t len, - int depth, - SEC_ASN1EncodingPart data_kind); - - -SEC_END_PROTOS -#endif /* _SECASN1_H_ */ diff --git a/OSX/include/security_asn1/secasn1d.c b/OSX/include/security_asn1/secasn1d.c deleted file mode 100644 index c3971d0e..00000000 --- a/OSX/include/security_asn1/secasn1d.c +++ /dev/null @@ -1,3167 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Support for DEcoding ASN.1 data based on BER/DER (Basic/Distinguished - * Encoding Rules). - * - * $Id: secasn1d.c,v 1.16 2004/05/13 15:29:13 dmitch Exp $ - */ - -#include "secasn1.h" -#include "secerr.h" -#include "assert.h" - -#ifdef NDEBUG -#define DEBUG_DECASN1 0 -#else -#define DEBUG_DECASN1 1 -#endif - -#if DEBUG_DECASN1 -#include -#define dprintf(args...) printf(args) -#else -#define dprintf(args...) -#endif /* DEBUG_DECASN1 */ - -typedef enum { - beforeIdentifier, - duringIdentifier, - afterIdentifier, - beforeLength, - duringLength, - afterLength, - beforeBitString, - duringBitString, - duringConstructedString, - duringGroup, - duringLeaf, - duringSaveEncoding, - duringSequence, - afterConstructedString, - afterGroup, - afterExplicit, - afterImplicit, - afterInline, - afterPointer, - afterSaveEncoding, - beforeEndOfContents, - duringEndOfContents, - afterEndOfContents, - beforeChoice, - duringChoice, - afterChoice, - notInUse -} sec_asn1d_parse_place; - -#ifndef NDEBUG -#define DEBUG_ASN1D_STATES 1 -/* tweakable by debugger, debug only */ -int doDumpStates = 0; -#else /* DEBUG_ASN1D_STATES 0 */ -#endif /* DEBUG_ASN1D_STATES */ - -#if DEBUG_ASN1D_STATES -static const char *place_names[] = { - "beforeIdentifier", - "duringIdentifier", - "afterIdentifier", - "beforeLength", - "duringLength", - "afterLength", - "beforeBitString", - "duringBitString", - "duringConstructedString", - "duringGroup", - "duringLeaf", - "duringSaveEncoding", - "duringSequence", - "afterConstructedString", - "afterGroup", - "afterExplicit", - "afterImplicit", - "afterInline", - "afterPointer", - "afterSaveEncoding", - "beforeEndOfContents", - "duringEndOfContents", - "afterEndOfContents", - "beforeChoice", - "duringChoice", - "afterChoice", - "notInUse" -}; - -static const char * const class_names[] = { - "UNIVERSAL", - "APPLICATION", - "CONTEXT_SPECIFIC", - "PRIVATE" -}; - -static const char * const method_names[] = { "PRIMITIVE", "CONSTRUCTED" }; - -static const char * const type_names[] = { - "END_OF_CONTENTS", - "BOOLEAN", - "INTEGER", - "BIT_STRING", - "OCTET_STRING", - "NULL", - "OBJECT_ID", - "OBJECT_DESCRIPTOR", - "(type 08)", - "REAL", - "ENUMERATED", - "EMBEDDED", - "UTF8_STRING", - "(type 0d)", - "(type 0e)", - "(type 0f)", - "SEQUENCE", - "SET", - "NUMERIC_STRING", - "PRINTABLE_STRING", - "T61_STRING", - "VIDEOTEXT_STRING", - "IA5_STRING", - "UTC_TIME", - "GENERALIZED_TIME", - "GRAPHIC_STRING", - "VISIBLE_STRING", - "GENERAL_STRING", - "UNIVERSAL_STRING", - "(type 1d)", - "BMP_STRING", - "HIGH_TAG_VALUE" -}; - -static const char * const flag_names[] = { /* flags, right to left */ - "OPTIONAL", - "EXPLICIT", - "ANY", - "INLINE", - "POINTER", - "GROUP", - "DYNAMIC", - "SKIP", - "INNER", - "SAVE", - "", /* decoder ignores "MAY_STREAM", */ - "SKIP_REST", - "CHOICE", - "NO_STREAM", - "DEBUG_BREAK", - "unknown 08", - "unknown 10", - "unknown 20", - "unknown 40", - "unknown 80" -}; - -static int /* bool */ -formatKind(unsigned long kind, char * buf) -{ - int i; - unsigned long k = kind & SEC_ASN1_TAGNUM_MASK; - unsigned long notag = kind & (SEC_ASN1_CHOICE | SEC_ASN1_POINTER | - SEC_ASN1_INLINE | SEC_ASN1_ANY | SEC_ASN1_SAVE); - - buf[0] = 0; - if ((kind & SEC_ASN1_CLASS_MASK) != SEC_ASN1_UNIVERSAL) { - sprintf(buf, " %s", class_names[(kind & SEC_ASN1_CLASS_MASK) >> 6] ); - buf += strlen(buf); - } - if (kind & SEC_ASN1_METHOD_MASK) { - sprintf(buf, " %s", method_names[1]); - buf += strlen(buf); - } - if ((kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) { - if (k || !notag) { - sprintf(buf, " %s", type_names[k] ); - if ((k == SEC_ASN1_SET || k == SEC_ASN1_SEQUENCE) && - (kind & SEC_ASN1_GROUP)) { - buf += strlen(buf); - sprintf(buf, "_OF"); - } - } - } else { - sprintf(buf, " [%lu]", k); - } - buf += strlen(buf); - - for (k = kind >> 8, i = 0; k; k >>= 1, ++i) { - if (k & 1) { - sprintf(buf, " %s", flag_names[i]); - buf += strlen(buf); - } - } - return notag != 0; -} - -#endif /* DEBUG_ASN1D_STATES */ - -typedef enum { - allDone, - decodeError, - keepGoing, - needBytes -} sec_asn1d_parse_status; - -struct subitem { - const void *data; - unsigned long len; /* only used for substrings */ - struct subitem *next; -}; - -typedef struct sec_asn1d_state_struct { - SEC_ASN1DecoderContext *top; - const SecAsn1Template *theTemplate; - void *dest; - - void *our_mark; /* free on completion */ - - struct sec_asn1d_state_struct *parent; /* aka prev */ - struct sec_asn1d_state_struct *child; /* aka next */ - - sec_asn1d_parse_place place; - - /* - * XXX explain the next fields as clearly as possible... - */ - unsigned char found_tag_modifiers; - unsigned char expect_tag_modifiers; - unsigned long check_tag_mask; - unsigned long found_tag_number; - unsigned long expect_tag_number; - unsigned long underlying_kind; - - unsigned long contents_length; - unsigned long pending; - unsigned long consumed; - - int depth; - - /* - * Bit strings have their length adjusted -- the first octet of the - * contents contains a value between 0 and 7 which says how many bits - * at the end of the octets are not actually part of the bit string; - * when parsing bit strings we put that value here because we need it - * later, for adjustment of the length (when the whole string is done). - */ - unsigned int bit_string_unused_bits; - - /* - * The following are used for indefinite-length constructed strings. - */ - struct subitem *subitems_head; - struct subitem *subitems_tail; - - PRPackedBool - allocate, /* when true, need to allocate the destination */ - endofcontents, /* this state ended up parsing end-of-contents octets */ - explicit, /* we are handling an explicit header */ - indefinite, /* the current item has indefinite-length encoding */ - missing, /* an optional field that was not present */ - optional, /* the template says this field may be omitted */ - substring; /* this is a substring of a constructed string */ -} sec_asn1d_state; - -#define IS_HIGH_TAG_NUMBER(n) ((n) == SEC_ASN1_HIGH_TAG_NUMBER) -#define LAST_TAG_NUMBER_BYTE(b) (((b) & 0x80) == 0) -#define TAG_NUMBER_BITS 7 -#define TAG_NUMBER_MASK 0x7f - -#define LENGTH_IS_SHORT_FORM(b) (((b) & 0x80) == 0) -#define LONG_FORM_LENGTH(b) ((b) & 0x7f) - -#define HIGH_BITS(field,cnt) ((field) >> ((sizeof(field) * 8) - (cnt))) - - -/* - * An "outsider" will have an opaque pointer to this, created by calling - * SEC_ASN1DecoderStart(). It will be passed back in to all subsequent - * calls to SEC_ASN1DecoderUpdate(), and when done it is passed to - * SEC_ASN1DecoderFinish(). - */ -struct sec_DecoderContext_struct { - PRArenaPool *our_pool; /* for our internal allocs */ - PRArenaPool *their_pool; /* for destination structure allocs */ -#ifdef SEC_ASN1D_FREE_ON_ERROR /* - * XXX see comment below (by same - * ifdef) that explains why this - * does not work (need more smarts - * in order to free back to mark) - */ - /* - * XXX how to make their_mark work in the case where they do NOT - * give us a pool pointer? - */ - void *their_mark; /* free on error */ -#endif - - sec_asn1d_state *current; - sec_asn1d_parse_status status; - - SEC_ASN1NotifyProc notify_proc; /* call before/after handling field */ - void *notify_arg; /* argument to notify_proc */ - PRBool during_notify; /* true during call to notify_proc */ - - SEC_ASN1WriteProc filter_proc; /* pass field bytes to this */ - void *filter_arg; /* argument to that function */ - PRBool filter_only; /* do not allocate/store fields */ -}; - - -/* - * XXX this is a fairly generic function that may belong elsewhere - */ -static void * -sec_asn1d_alloc (PRArenaPool *poolp, unsigned long len) -{ - void *thing; - - if (poolp != NULL) { - /* - * Allocate from the pool. - */ - thing = PORT_ArenaAlloc (poolp, len); - } else { - /* - * Allocate generically. - */ - thing = PORT_Alloc (len); - } - - return thing; -} - - -/* - * XXX this is a fairly generic function that may belong elsewhere - */ -static void * -sec_asn1d_zalloc (PRArenaPool *poolp, unsigned long len) -{ - void *thing; - - thing = sec_asn1d_alloc (poolp, len); - if (thing != NULL) - PORT_Memset (thing, 0, len); - return thing; -} - - -static sec_asn1d_state * -sec_asn1d_push_state (SEC_ASN1DecoderContext *cx, - const SecAsn1Template *theTemplate, - void *dest, PRBool new_depth) -{ - sec_asn1d_state *state, *new_state; - - state = cx->current; - - PORT_Assert (state == NULL || state->child == NULL); - - if (state != NULL) { - PORT_Assert (state->our_mark == NULL); - state->our_mark = PORT_ArenaMark (cx->our_pool); - } - - new_state = (sec_asn1d_state*)sec_asn1d_zalloc (cx->our_pool, - sizeof(*new_state)); - if (new_state == NULL) { - dprintf("decodeError: zalloc failure\n"); - goto loser; - } - - new_state->top = cx; - new_state->parent = state; - new_state->theTemplate = theTemplate; - new_state->place = notInUse; - if (dest != NULL) - new_state->dest = (char *)dest + theTemplate->offset; - - if (state != NULL) { - new_state->depth = state->depth; - if (new_depth) { - if (++new_state->depth > SEC_ASN1D_MAX_DEPTH) { - PORT_SetError (SEC_ERROR_BAD_DER); - goto loser; - } - } - state->child = new_state; - } - - cx->current = new_state; - return new_state; - -loser: - cx->status = decodeError; - if (state != NULL) { - PORT_ArenaRelease(cx->our_pool, state->our_mark); - state->our_mark = NULL; - } - return NULL; -} - - -static void -sec_asn1d_scrub_state (sec_asn1d_state *state) -{ - /* - * Some default "scrubbing". - * XXX right set of initializations? - */ - state->place = beforeIdentifier; - state->endofcontents = PR_FALSE; - state->indefinite = PR_FALSE; - state->missing = PR_FALSE; - - PORT_Assert (state->consumed == 0); -} - - -static sec_asn1d_state * -sec_asn1d_get_enclosing_construct(sec_asn1d_state *state) -{ - for (state = state->parent; state; state = state->parent) { - sec_asn1d_parse_place place = state->place; - if (place != afterImplicit && - place != afterPointer && - place != afterInline && - place != afterSaveEncoding && - place != duringSaveEncoding && - place != duringChoice) { - - /* we've walked up the stack to a state that represents - ** the enclosing construct. - */ - break; - } - } - return state; -} - - -static PRBool -sec_asn1d_parent_allows_EOC(sec_asn1d_state *state) -{ - /* get state of enclosing construct. */ - state = sec_asn1d_get_enclosing_construct(state); - if (state) { - sec_asn1d_parse_place place = state->place; - /* Is it one of the types that permits an unexpected EOC? */ - int eoc_permitted = - (place == duringGroup || - place == duringConstructedString || - state->child->optional); - return (state->indefinite && eoc_permitted) ? PR_TRUE : PR_FALSE; - } - return PR_FALSE; -} - - -static void -sec_asn1d_notify_before (SEC_ASN1DecoderContext *cx, void *dest, int depth) -{ - if (cx->notify_proc == NULL) - return; - - cx->during_notify = PR_TRUE; - (* cx->notify_proc) (cx->notify_arg, PR_TRUE, dest, depth); - cx->during_notify = PR_FALSE; -} - - -static void -sec_asn1d_notify_after (SEC_ASN1DecoderContext *cx, void *dest, int depth) -{ - if (cx->notify_proc == NULL) - return; - - cx->during_notify = PR_TRUE; - (* cx->notify_proc) (cx->notify_arg, PR_FALSE, dest, depth); - cx->during_notify = PR_FALSE; -} - - -static sec_asn1d_state * -sec_asn1d_init_state_based_on_template (sec_asn1d_state *state, - #ifdef __APPLE__ - const char *buf /* for SEC_ASN1GetSubtemplate() */ - #endif - ) -{ - PRBool explicit, optional, universal; - unsigned char expect_tag_modifiers; - unsigned long encode_kind, under_kind; - unsigned long check_tag_mask, expect_tag_number; - #ifdef __APPLE__ - unsigned long dynamic; - #endif - - - /* XXX Check that both of these tests are really needed/appropriate. */ - if (state == NULL || state->top->status == decodeError || state->theTemplate == NULL) - return state; - - encode_kind = state->theTemplate->kind; - - if (encode_kind & SEC_ASN1_SAVE) { - /* - * This is a "magic" field that saves away all bytes, allowing - * the immediately following field to still be decoded from this - * same spot -- sort of a fork. - */ - /* check that there are no extraneous bits */ - PORT_Assert (encode_kind == SEC_ASN1_SAVE); - if (state->top->filter_only) { - /* - * If we are not storing, then we do not do the SAVE field - * at all. Just move ahead to the "real" field instead, - * doing the appropriate notify calls before and after. - */ - sec_asn1d_notify_after (state->top, state->dest, state->depth); - /* - * Since we are not storing, allow for our current dest value - * to be NULL. (This might not actually occur, but right now I - * cannot convince myself one way or the other.) If it is NULL, - * assume that our parent dest can help us out. - */ - if (state->dest == NULL) - state->dest = state->parent->dest; - else - state->dest = - (char *)state->dest - state->theTemplate->offset; - state->theTemplate++; - if (state->dest != NULL) - state->dest = - (char *)state->dest + state->theTemplate->offset; - sec_asn1d_notify_before (state->top, state->dest, state->depth); - encode_kind = state->theTemplate->kind; - PORT_Assert ((encode_kind & SEC_ASN1_SAVE) == 0); - } else { - sec_asn1d_scrub_state (state); - state->place = duringSaveEncoding; - state = sec_asn1d_push_state (state->top, kSecAsn1AnyTemplate, - state->dest, PR_FALSE); - if (state != NULL) - state = sec_asn1d_init_state_based_on_template (state, - buf /* __APPLE__ */); - return state; - } - } - - - universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) - ? PR_TRUE : PR_FALSE; - - explicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_EXPLICIT; - - optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_OPTIONAL; - - #ifdef __APPLE__ - dynamic = (encode_kind & SEC_ASN1_DYNAMIC) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_DYNAMIC; - #endif - - PORT_Assert (!(explicit && universal)); /* bad templates */ - - encode_kind &= ~SEC_ASN1_DYNAMIC; - encode_kind &= ~SEC_ASN1_MAY_STREAM; - - if( encode_kind & SEC_ASN1_CHOICE ) { -#if 0 /* XXX remove? */ - sec_asn1d_state *child = sec_asn1d_push_state(state->top, state->theTemplate, state->dest, PR_FALSE); - if( (sec_asn1d_state *)NULL == child ) { - return (sec_asn1d_state *)NULL; - } - - child->allocate = state->allocate; - child->place = beforeChoice; - return child; -#else - state->place = beforeChoice; - return state; -#endif - } - - if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || (!universal - && !explicit)) { - const SecAsn1Template *subt; - void *dest; - PRBool child_allocate; - void *subDest; - - PORT_Assert ((encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) == 0); - - sec_asn1d_scrub_state (state); - child_allocate = PR_FALSE; - - if (encode_kind & SEC_ASN1_POINTER) { - /* - * A POINTER means we need to allocate the destination for - * this field. But, since it may also be an optional field, - * we defer the allocation until later; we just record that - * it needs to be done. - * - * There are two possible scenarios here -- one is just a - * plain POINTER (kind of like INLINE, except with allocation) - * and the other is an implicitly-tagged POINTER. We don't - * need to do anything special here for the two cases, but - * since the template definition can be tricky, we do check - * that there are no extraneous bits set in encode_kind. - * - * XXX The same conditions which assert should set an error. - */ - if (universal) { - /* - * "universal" means this entry is a standalone POINTER; - * there should be no other bits set in encode_kind. - */ - PORT_Assert (encode_kind == SEC_ASN1_POINTER); - } else { - /* - * If we get here we have an implicitly-tagged field - * that needs to be put into a POINTER. The subtemplate - * will determine how to decode the field, but encode_kind - * describes the (implicit) tag we are looking for. - * The non-tag bits of encode_kind will be ignored by - * the code below; none of them should be set, however, - * except for the POINTER bit itself -- so check that. - */ - PORT_Assert ((encode_kind & ~SEC_ASN1_TAG_MASK) - == SEC_ASN1_POINTER); - } - if (!state->top->filter_only) - child_allocate = PR_TRUE; - dest = NULL; - state->place = afterPointer; - } else { - dest = state->dest; - if (encode_kind & SEC_ASN1_INLINE) { - /* check that there are no extraneous bits */ - /* FIXME - why are optional and inline mutually - * exclusive? Delete this assert and see what happens... - PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional); - */ - state->place = afterInline; - } else { - state->place = afterImplicit; - } - } - - state->optional = optional; - - subDest = state->dest; - #if defined(__APPLE__) - /* - * We might be starting the processing of a group or a - * set, in which case state->dest is NULL. Get parent's dest, - * or grandparent's, etc... just for the use by - * SEC_ASN1GetSubtemplate (specifically, by dynamic - * choosers) - */ - sec_asn1d_state *tempState = state; - while(subDest == NULL) { - sec_asn1d_state *parent = tempState->parent; - if(parent == NULL) { - /* Oh well. Not going to work for this template. */ - break; - } - subDest = parent->dest; - tempState = parent; - } - #endif /* __APPLE__ */ - subt = SEC_ASN1GetSubtemplate (state->theTemplate, subDest, - PR_FALSE, buf /* __APPLE__ */); - state = sec_asn1d_push_state (state->top, subt, dest, PR_FALSE); - if (state == NULL) - return NULL; - - state->allocate = child_allocate; - - if (universal - #ifdef __APPLE__ - /* Dynamic: restart with new template */ - || dynamic - #endif - ) { - state = sec_asn1d_init_state_based_on_template (state, - buf /* __APPLE__ */); - if (state != NULL) { - /* - * If this field is optional, we need to record that on - * the pushed child so it won't fail if the field isn't - * found. I can't think of a way that this new state - * could already have optional set (which we would wipe - * out below if our local optional is not set) -- but - * just to be sure, assert that it isn't set. - */ - PORT_Assert (!state->optional); - state->optional = optional; - } - return state; - } - - under_kind = state->theTemplate->kind; - under_kind &= ~SEC_ASN1_MAY_STREAM; - } else if (explicit) { - /* - * For explicit, we only need to match the encoding tag next, - * then we will push another state to handle the entire inner - * part. In this case, there is no underlying kind which plays - * any part in the determination of the outer, explicit tag. - * So we just set under_kind to 0, which is not a valid tag, - * and the rest of the tag matching stuff should be okay. - */ - under_kind = 0; - } else { - /* - * Nothing special; the underlying kind and the given encoding - * information are the same. - */ - under_kind = encode_kind; - } - - /* XXX is this the right set of bits to test here? */ - PORT_Assert ((under_kind & (SEC_ASN1_EXPLICIT - | SEC_ASN1_MAY_STREAM - | SEC_ASN1_INLINE | SEC_ASN1_POINTER)) == 0); - - if (encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) { - PORT_Assert (encode_kind == under_kind); - if (encode_kind & SEC_ASN1_SKIP) { - PORT_Assert (!optional); - PORT_Assert (encode_kind == SEC_ASN1_SKIP); - state->dest = NULL; - } - check_tag_mask = 0; - expect_tag_modifiers = 0; - expect_tag_number = 0; - } else { - check_tag_mask = SEC_ASN1_TAG_MASK; - expect_tag_modifiers = (unsigned char)encode_kind & SEC_ASN1_TAG_MASK - & ~SEC_ASN1_TAGNUM_MASK; - /* - * XXX This assumes only single-octet identifiers. To handle - * the HIGH TAG form we would need to do some more work, especially - * in how to specify them in the template, because right now we - * do not provide a way to specify more *tag* bits in encode_kind. - */ - expect_tag_number = encode_kind & SEC_ASN1_TAGNUM_MASK; - - switch (under_kind & SEC_ASN1_TAGNUM_MASK) { - case SEC_ASN1_SET: - /* - * XXX A plain old SET (as opposed to a SET OF) is not - * implemented. - * If it ever is, remove this assert... - */ - PORT_Assert ((under_kind & SEC_ASN1_GROUP) != 0); - /* fallthru */ - case SEC_ASN1_SEQUENCE: - expect_tag_modifiers |= SEC_ASN1_CONSTRUCTED; - break; - case SEC_ASN1_BIT_STRING: - case SEC_ASN1_BMP_STRING: - case SEC_ASN1_GENERALIZED_TIME: - case SEC_ASN1_IA5_STRING: - case SEC_ASN1_OCTET_STRING: - case SEC_ASN1_PRINTABLE_STRING: - case SEC_ASN1_T61_STRING: - case SEC_ASN1_UNIVERSAL_STRING: - case SEC_ASN1_UTC_TIME: - case SEC_ASN1_UTF8_STRING: - case SEC_ASN1_VISIBLE_STRING: - check_tag_mask &= ~SEC_ASN1_CONSTRUCTED; - break; - } - } - - state->check_tag_mask = check_tag_mask; - state->expect_tag_modifiers = expect_tag_modifiers; - state->expect_tag_number = expect_tag_number; - state->underlying_kind = under_kind; - state->explicit = explicit; - state->optional = optional; - sec_asn1d_scrub_state (state); - - return state; -} - - -static unsigned long -sec_asn1d_parse_identifier (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - unsigned char byte; - unsigned char tag_number; - - PORT_Assert (state->place == beforeIdentifier); - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - byte = (unsigned char) *buf; -#ifdef DEBUG_ASN1D_STATES - if (doDumpStates > 0) { - char kindBuf[256]; - formatKind(byte, kindBuf); - printf("Found tag %02x %s\n", byte, kindBuf); - } -#endif - tag_number = byte & SEC_ASN1_TAGNUM_MASK; - - if (IS_HIGH_TAG_NUMBER (tag_number)) { - state->place = duringIdentifier; - state->found_tag_number = 0; - /* - * Actually, we have no idea how many bytes are pending, but we - * do know that it is at least 1. That is all we know; we have - * to look at each byte to know if there is another, etc. - */ - state->pending = 1; - } else { - if (byte == 0 && sec_asn1d_parent_allows_EOC(state)) { - /* - * Our parent has indefinite-length encoding, and the - * entire tag found is 0, so it seems that we have hit the - * end-of-contents octets. To handle this, we just change - * our state to that which expects to get the bytes of the - * end-of-contents octets and let that code re-read this byte - * so that our categorization of field types is correct. - * After that, our parent will then deal with everything else. - */ - state->place = duringEndOfContents; - state->pending = 2; - state->found_tag_number = 0; - state->found_tag_modifiers = 0; - /* - * We might be an optional field that is, as we now find out, - * missing. Give our parent a clue that this happened. - */ - if (state->optional) - state->missing = PR_TRUE; - return 0; - } - state->place = afterIdentifier; - state->found_tag_number = tag_number; - } - state->found_tag_modifiers = byte & ~SEC_ASN1_TAGNUM_MASK; - - return 1; -} - - -static unsigned long -sec_asn1d_parse_more_identifier (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - unsigned char byte; - int count; - - PORT_Assert (state->pending == 1); - PORT_Assert (state->place == duringIdentifier); - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - count = 0; - - while (len && state->pending) { - if (HIGH_BITS (state->found_tag_number, TAG_NUMBER_BITS) != 0) { - /* - * The given high tag number overflows our container; - * just give up. This is not likely to *ever* happen. - */ - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - dprintf("decodeError: parse_more_id high bits oflow\n"); - return 0; - } - - state->found_tag_number <<= TAG_NUMBER_BITS; - - byte = (unsigned char) buf[count++]; - state->found_tag_number |= (byte & TAG_NUMBER_MASK); - - len--; - if (LAST_TAG_NUMBER_BYTE (byte)) - state->pending = 0; - } - - if (state->pending == 0) - state->place = afterIdentifier; - - return count; -} - - -static void -sec_asn1d_confirm_identifier (sec_asn1d_state *state) -{ - PRBool match; - - PORT_Assert (state->place == afterIdentifier); - - match = (PRBool)(((state->found_tag_modifiers & state->check_tag_mask) - == state->expect_tag_modifiers) - && ((state->found_tag_number & state->check_tag_mask) - == state->expect_tag_number)); - if (match) { - state->place = beforeLength; - } else { - if (state->optional) { - state->missing = PR_TRUE; - state->place = afterEndOfContents; - } else { - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - //dprintf("decodeError: sec_asn1d_confirm_identifier\n"); - } - } -} - - -static unsigned long -sec_asn1d_parse_length (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - unsigned char byte; - - PORT_Assert (state->place == beforeLength); - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - /* - * The default/likely outcome. It may get adjusted below. - */ - state->place = afterLength; - - byte = (unsigned char) *buf; - - if (LENGTH_IS_SHORT_FORM (byte)) { - state->contents_length = byte; - } else { - state->contents_length = 0; - state->pending = LONG_FORM_LENGTH (byte); - if (state->pending == 0) { - state->indefinite = PR_TRUE; - } else { - state->place = duringLength; - } - } - - /* If we're parsing an ANY, SKIP, or SAVE template, and - ** the object being saved is definite length encoded and constructed, - ** there's no point in decoding that construct's members. - ** So, just forget it's constructed and treat it as primitive. - ** (SAVE appears as an ANY at this point) - */ - if (!state->indefinite && - (state->underlying_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP))) { - state->found_tag_modifiers &= ~SEC_ASN1_CONSTRUCTED; - } - - return 1; -} - - -static unsigned long -sec_asn1d_parse_more_length (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - int count; - - PORT_Assert (state->pending > 0); - PORT_Assert (state->place == duringLength); - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - count = 0; - - while (len && state->pending) { - if (HIGH_BITS (state->contents_length, 9) != 0) { - /* - * The given full content length overflows our container; - * just give up. - */ - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - dprintf("decodeError: sec_asn1d_parse_more_length\n"); - return 0; - } - - state->contents_length <<= 8; - state->contents_length |= (unsigned char) buf[count++]; - - len--; - state->pending--; - } - - if (state->pending == 0) - state->place = afterLength; - - return count; -} - - -static void -sec_asn1d_prepare_for_contents (sec_asn1d_state *state, - #ifdef __APPLE__ - const char *buf /* needed for SEC_ASN1GetSubtemplate */ - #endif - ) -{ - SecAsn1Item *item=NULL; - PRArenaPool *poolp; - unsigned long alloc_len; - -#ifdef DEBUG_ASN1D_STATES - if (doDumpStates > 0) { - printf("Found Length %lu %s\n", state->contents_length, - state->indefinite ? "indefinite" : ""); - } -#endif - - /* - * XXX I cannot decide if this allocation should exclude the case - * where state->endofcontents is true -- figure it out! - */ - if (state->allocate) { - void *dest; - - PORT_Assert (state->dest == NULL); - /* - * We are handling a POINTER or a member of a GROUP, and need to - * allocate for the data structure. - */ - dest = sec_asn1d_zalloc (state->top->their_pool, - state->theTemplate->size); - if (dest == NULL) { - dprintf("decodeError: sec_asn1d_prepare_for_contents zalloc\n"); - state->top->status = decodeError; - return; - } - /* FIXME _ we're losing the dest pointer after this! */ - state->dest = (char *)dest + state->theTemplate->offset; - - /* - * For a member of a GROUP, our parent will later put the - * pointer wherever it belongs. But for a POINTER, we need - * to record the destination now, in case notify or filter - * procs need access to it -- they cannot find it otherwise, - * until it is too late (for one-pass processing). - */ - if (state->parent->place == afterPointer) { - void **placep; - - placep = state->parent->dest; - *placep = dest; - } - } - - /* - * Remember, length may be indefinite here! In that case, - * both contents_length and pending will be zero. - */ - state->pending = state->contents_length; - - /* If this item has definite length encoding, and - ** is enclosed by a definite length constructed type, - ** make sure it isn't longer than the remaining space in that - ** constructed type. - */ - if (state->contents_length > 0) { - sec_asn1d_state *parent = sec_asn1d_get_enclosing_construct(state); - if (parent && !parent->indefinite && - state->consumed + state->contents_length > parent->pending) { - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - } - - /* - * An EXPLICIT is nothing but an outer header, which we have - * already parsed and accepted. Now we need to do the inner - * header and its contents. - */ - if (state->explicit) { - state->place = afterExplicit; - state = sec_asn1d_push_state (state->top, - SEC_ASN1GetSubtemplate(state->theTemplate, - state->dest, - PR_FALSE, - buf /* __APPLE__ */), - state->dest, PR_TRUE); - if (state != NULL) - state = sec_asn1d_init_state_based_on_template (state, - buf /* __APPLE__ */); - (void) state; - return; - } - - /* - * For GROUP (SET OF, SEQUENCE OF), even if we know the length here - * we cannot tell how many items we will end up with ... so push a - * state that can keep track of "children" (the individual members - * of the group; we will allocate as we go and put them all together - * at the end. - */ - if (state->underlying_kind & SEC_ASN1_GROUP) { - /* XXX If this assertion holds (should be able to confirm it via - * inspection, too) then move this code into the switch statement - * below under cases SET_OF and SEQUENCE_OF; it will be cleaner. - */ - PORT_Assert (state->underlying_kind == SEC_ASN1_SET_OF - || state->underlying_kind == SEC_ASN1_SEQUENCE_OF - || state->underlying_kind == (SEC_ASN1_SEQUENCE_OF|SEC_ASN1_DYNAMIC) - || state->underlying_kind == (SEC_ASN1_SET_OF|SEC_ASN1_DYNAMIC) - ); - if (state->contents_length != 0 || state->indefinite) { - const SecAsn1Template *subt; - - state->place = duringGroup; - subt = SEC_ASN1GetSubtemplate (state->theTemplate, state->dest, - PR_FALSE, buf /* __APPLE__ */); - state = sec_asn1d_push_state (state->top, subt, NULL, PR_TRUE); - if (state != NULL) { - if (!state->top->filter_only) - state->allocate = PR_TRUE; /* XXX propogate this? */ - /* - * Do the "before" field notification for next in group. - */ - sec_asn1d_notify_before (state->top, state->dest, state->depth); - state = sec_asn1d_init_state_based_on_template (state, - buf /* __APPLE__ */); - } - } else { - /* - * A group of zero; we are done. - * Set state to afterGroup and let that code plant the NULL. - */ - state->place = afterGroup; - } - (void) state; - return; - } - - switch (state->underlying_kind) { - case SEC_ASN1_SEQUENCE: - /* - * We need to push a child to handle the individual fields. - */ - state->place = duringSequence; - state = sec_asn1d_push_state (state->top, state->theTemplate + 1, - state->dest, PR_TRUE); - if (state != NULL) { - /* - * Do the "before" field notification. - */ - sec_asn1d_notify_before (state->top, state->dest, state->depth); - state = sec_asn1d_init_state_based_on_template (state, - buf /* __APPLE__ */); - } - (void) state; - break; - - case SEC_ASN1_SET: /* XXX SET is not really implemented */ - /* - * XXX A plain SET requires special handling; scanning of a - * template to see where a field should go (because by definition, - * they are not in any particular order, and you have to look at - * each tag to disambiguate what the field is). We may never - * implement this because in practice, it seems to be unused. - */ - dprintf("decodeError: prepare for contents SEC_ASN1_SET\n"); - PORT_Assert(0); - PORT_SetError (SEC_ERROR_BAD_DER); /* XXX */ - state->top->status = decodeError; - break; - - case SEC_ASN1_NULL: - /* - * The NULL type, by definition, is "nothing", content length of zero. - * An indefinite-length encoding is not alloweed. - */ - if (state->contents_length || state->indefinite) { - dprintf("decodeError: prepare for contents indefinite NULL\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - break; - } - if (state->dest != NULL) { - item = (SecAsn1Item *)(state->dest); - item->Data = NULL; - item->Length = 0; - } - state->place = afterEndOfContents; - break; - - case SEC_ASN1_BMP_STRING: - /* Error if length is not divisable by 2 */ - if (state->contents_length % 2) { - dprintf("decodeError: prepare for contents odd length BMP_STRING\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - break; - } - /* otherwise, handle as other string types */ - goto regular_string_type; - - case SEC_ASN1_UNIVERSAL_STRING: - /* Error if length is not divisable by 4 */ - if (state->contents_length % 4) { - dprintf("decodeError: prepare for contents odd length UNIV_STRING\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - break; - } - /* otherwise, handle as other string types */ - goto regular_string_type; - - case SEC_ASN1_SKIP: - case SEC_ASN1_ANY: - case SEC_ASN1_ANY_CONTENTS: - /* - * These are not (necessarily) strings, but they need nearly - * identical handling (especially when we need to deal with - * constructed sub-pieces), so we pretend they are. - */ - /* fallthru */ -regular_string_type: - case SEC_ASN1_BIT_STRING: - case SEC_ASN1_IA5_STRING: - case SEC_ASN1_OCTET_STRING: - case SEC_ASN1_PRINTABLE_STRING: - case SEC_ASN1_T61_STRING: - case SEC_ASN1_UTC_TIME: - case SEC_ASN1_UTF8_STRING: - case SEC_ASN1_VISIBLE_STRING: - /* - * We are allocating for a primitive or a constructed string. - * If it is a constructed string, it may also be indefinite-length. - * If it is primitive, the length can (legally) be zero. - * Our first order of business is to allocate the memory for - * the string, if we can (if we know the length). - */ - item = (SecAsn1Item *)(state->dest); - - /* - * If the item is a definite-length constructed string, then - * the contents_length is actually larger than what we need - * (because it also counts each intermediate header which we - * will be throwing away as we go), but it is a perfectly good - * upper bound that we just allocate anyway, and then concat - * as we go; we end up wasting a few extra bytes but save a - * whole other copy. - */ - alloc_len = state->contents_length; - poolp = NULL; /* quiet compiler warnings about unused... */ - - if (item == NULL || state->top->filter_only) { - if (item != NULL) { - item->Data = NULL; - item->Length = 0; - } - alloc_len = 0; - } else if (state->substring) { - /* - * If we are a substring of a constructed string, then we may - * not have to allocate anything (because our parent, the - * actual constructed string, did it for us). If we are a - * substring and we *do* have to allocate, that means our - * parent is an indefinite-length, so we allocate from our pool; - * later our parent will copy our string into the aggregated - * whole and free our pool allocation. - */ - if (item->Data == NULL) { - PORT_Assert (item->Length == 0); - poolp = state->top->our_pool; - } else { - alloc_len = 0; - } - } else { - item->Length = 0; - item->Data = NULL; - poolp = state->top->their_pool; - } - - if (alloc_len || ((! state->indefinite) - && (state->subitems_head != NULL))) { - struct subitem *subitem; - unsigned long len; - - PORT_Assert (item!=NULL); - if (item==NULL) { - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - PORT_Assert (item->Length == 0 && item->Data == NULL); - /* - * Check for and handle an ANY which has stashed aside the - * header (identifier and length) bytes for us to include - * in the saved contents. - */ - if (state->subitems_head != NULL) { - PORT_Assert (state->underlying_kind == SEC_ASN1_ANY); - for (subitem = state->subitems_head; - subitem != NULL; subitem = subitem->next) - alloc_len += subitem->len; - } - - item->Data = (unsigned char*)sec_asn1d_zalloc (poolp, alloc_len); - if (item->Data == NULL) { - dprintf("decodeError: prepare for contents zalloc\n"); - state->top->status = decodeError; - break; - } - - len = 0; - for (subitem = state->subitems_head; - subitem != NULL; subitem = subitem->next) { - PORT_Memcpy (item->Data + len, subitem->data, subitem->len); - len += subitem->len; - } - item->Length = len; - - /* - * Because we use arenas and have a mark set, we later free - * everything we have allocated, so this does *not* present - * a memory leak (it is just temporarily left dangling). - */ - state->subitems_head = state->subitems_tail = NULL; - } - - if (state->contents_length == 0 && (! state->indefinite)) { - /* - * A zero-length simple or constructed string; we are done. - */ - state->place = afterEndOfContents; - } else if (state->found_tag_modifiers & SEC_ASN1_CONSTRUCTED) { - const SecAsn1Template *sub; - - switch (state->underlying_kind) { - case SEC_ASN1_ANY: - case SEC_ASN1_ANY_CONTENTS: - sub = kSecAsn1AnyTemplate; - break; - case SEC_ASN1_BIT_STRING: - sub = kSecAsn1BitStringTemplate; - break; - case SEC_ASN1_BMP_STRING: - sub = kSecAsn1BMPStringTemplate; - break; - case SEC_ASN1_GENERALIZED_TIME: - sub = kSecAsn1GeneralizedTimeTemplate; - break; - case SEC_ASN1_IA5_STRING: - sub = kSecAsn1IA5StringTemplate; - break; - case SEC_ASN1_OCTET_STRING: - sub = kSecAsn1OctetStringTemplate; - break; - case SEC_ASN1_PRINTABLE_STRING: - sub = kSecAsn1PrintableStringTemplate; - break; - case SEC_ASN1_T61_STRING: - sub = kSecAsn1T61StringTemplate; - break; - case SEC_ASN1_UNIVERSAL_STRING: - sub = kSecAsn1UniversalStringTemplate; - break; - case SEC_ASN1_UTC_TIME: - sub = kSecAsn1UTCTimeTemplate; - break; - case SEC_ASN1_UTF8_STRING: - sub = kSecAsn1UTF8StringTemplate; - break; - case SEC_ASN1_VISIBLE_STRING: - sub = kSecAsn1VisibleStringTemplate; - break; - case SEC_ASN1_SKIP: - sub = kSecAsn1SkipTemplate; - break; - default: /* redundant given outer switch cases, but */ - PORT_Assert(0); /* the compiler does not seem to know that, */ - sub = NULL; /* so just do enough to quiet it. */ - break; - } - - state->place = duringConstructedString; - state = sec_asn1d_push_state (state->top, sub, item, PR_TRUE); - if (state != NULL) { - state->substring = PR_TRUE; /* XXX propogate? */ - state = sec_asn1d_init_state_based_on_template (state, - buf /* __APPLE__ */); - } - } else if (state->indefinite) { - /* - * An indefinite-length string *must* be constructed! - */ - dprintf("decodeError: prepare for contents indefinite not construncted\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } else { - /* - * A non-zero-length simple string. - */ - if (state->underlying_kind == SEC_ASN1_BIT_STRING) - state->place = beforeBitString; - else - state->place = duringLeaf; - } - (void) state; - break; - - default: - /* - * We are allocating for a simple leaf item. - */ - if (state->contents_length) { - if (state->dest != NULL) { - item = (SecAsn1Item *)(state->dest); - item->Length = 0; - if (state->top->filter_only) { - item->Data = NULL; - } else { - item->Data = (unsigned char*) - sec_asn1d_zalloc (state->top->their_pool, - state->contents_length); - if (item->Data == NULL) { - dprintf("decodeError: prepare for contents zalloc\n"); - state->top->status = decodeError; - return; - } - } - } - state->place = duringLeaf; - } else { - /* - * An indefinite-length or zero-length item is not allowed. - * (All legal cases of such were handled above.) - */ - dprintf("decodeError: prepare for contents indefinite zero len \n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } - } -} - - -static void -sec_asn1d_free_child (sec_asn1d_state *state, PRBool error) -{ - if (state->child != NULL) { - PORT_Assert (error || state->child->consumed == 0); - PORT_Assert (state->our_mark != NULL); - PORT_ArenaRelease (state->top->our_pool, state->our_mark); - if (error && state->top->their_pool == NULL) { - /* - * XXX We need to free anything allocated. - * At this point, we failed in the middle of decoding. But we - * can't free the data we previously allocated with PR_Malloc - * unless we keep track of every pointer. So instead we have a - * memory leak when decoding fails half-way, unless an arena is - * used. See bug 95311 . - */ - } - state->child = NULL; - state->our_mark = NULL; - } else { - /* - * It is important that we do not leave a mark unreleased/unmarked. - * But I do not think we should ever have one set in this case, only - * if we had a child (handled above). So check for that. If this - * assertion should ever get hit, then we probably need to add code - * here to release back to our_mark (and then set our_mark to NULL). - */ - PORT_Assert (state->our_mark == NULL); - } - state->place = beforeEndOfContents; -} - - -/* We have just saved an entire encoded ASN.1 object (type) for a SAVE -** template, and now in the next template, we are going to decode that -** saved data by calling SEC_ASN1DecoderUpdate recursively. -** If that recursive call fails with needBytes, it is a fatal error, -** because the encoded object should have been complete. -** If that recursive call fails with decodeError, it will have already -** cleaned up the state stack, so we must bail out quickly. -** -** These checks of the status returned by the recursive call are now -** done in the caller of this function, immediately after it returns. -*/ -static void -sec_asn1d_reuse_encoding (sec_asn1d_state *state) -{ - sec_asn1d_state *child; - unsigned long consumed; - SecAsn1Item *item; - void *dest; - - - child = state->child; - PORT_Assert (child != NULL); - - consumed = child->consumed; - child->consumed = 0; - - item = (SecAsn1Item *)(state->dest); - PORT_Assert (item != NULL); - - PORT_Assert (item->Length == consumed); - - /* - * Free any grandchild. - */ - sec_asn1d_free_child (child, PR_FALSE); - - /* - * Notify after the SAVE field. - */ - sec_asn1d_notify_after (state->top, state->dest, state->depth); - - /* - * Adjust to get new dest and move forward. - */ - dest = (char *)state->dest - state->theTemplate->offset; - state->theTemplate++; - child->dest = (char *)dest + state->theTemplate->offset; - child->theTemplate = state->theTemplate; - - /* - * Notify before the "real" field. - */ - PORT_Assert (state->depth == child->depth); - sec_asn1d_notify_before (state->top, child->dest, child->depth); - - /* - * This will tell DecoderUpdate to return when it is done. - */ - state->place = afterSaveEncoding; - - /* - * We already have a child; "push" it by making it current. - */ - state->top->current = child; - - /* - * And initialize it so it is ready to parse. - */ - (void) sec_asn1d_init_state_based_on_template(child, - (char *) item->Data /* __APPLE__ */); - - /* - * Now parse that out of our data. - */ - if (SEC_ASN1DecoderUpdate (state->top, - (char *) item->Data, item->Length) != SECSuccess) - return; - if (state->top->status == needBytes) { - return; - } - - PORT_Assert (state->top->current == state); - PORT_Assert (state->child == child); - - /* - * That should have consumed what we consumed before. - */ - PORT_Assert (consumed == child->consumed); - child->consumed = 0; - - /* - * Done. - */ - state->consumed += consumed; - child->place = notInUse; - state->place = afterEndOfContents; -} - - -static unsigned long -sec_asn1d_parse_leaf (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - SecAsn1Item *item; - unsigned long bufLen; - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - if (state->pending < len) - len = state->pending; - - bufLen = len; - - item = (SecAsn1Item *)(state->dest); - if (item != NULL && item->Data != NULL) { - /* Strip leading zeroes when target is unsigned integer */ - if (state->underlying_kind == SEC_ASN1_INTEGER && /* INTEGER */ - item->Length == 0 && /* MSB */ - #ifdef __APPLE__ - !(state->underlying_kind & SEC_ASN1_SIGNED_INT)) - #else - item->type == siUnsignedInteger) /* unsigned */ - #endif - { - while (len > 1 && buf[0] == 0) { /* leading 0 */ - buf++; - len--; - } - } - PORT_Memcpy (item->Data + item->Length, buf, len); - item->Length += len; - } - state->pending -= bufLen; - if (state->pending == 0) - state->place = beforeEndOfContents; - - return bufLen; -} - - -static unsigned long -sec_asn1d_parse_bit_string (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - unsigned char byte; - - /*PORT_Assert (state->pending > 0); */ - PORT_Assert (state->place == beforeBitString); - - if ((state->pending == 0) || (state->contents_length == 1)) { - if (state->dest != NULL) { - SecAsn1Item *item = (SecAsn1Item *)(state->dest); - item->Data = NULL; - item->Length = 0; - state->place = beforeEndOfContents; - } - if(state->contents_length == 1) { - /* skip over (unused) remainder byte */ - return 1; - } - else { - return 0; - } - } - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - byte = (unsigned char) *buf; - if (byte > 7) { - dprintf("decodeError: parse_bit_string remainder oflow\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return 0; - } - - state->bit_string_unused_bits = byte; - state->place = duringBitString; - state->pending -= 1; - - return 1; -} - - -static unsigned long -sec_asn1d_parse_more_bit_string (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - PORT_Assert (state->place == duringBitString); - if (state->pending == 0) { - /* An empty bit string with some unused bits is invalid. */ - if (state->bit_string_unused_bits) { - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } else { - /* An empty bit string with no unused bits is OK. */ - state->place = beforeEndOfContents; - } - return 0; - } - - len = sec_asn1d_parse_leaf (state, buf, len); - if (state->place == beforeEndOfContents && state->dest != NULL) { - SecAsn1Item *item; - - item = (SecAsn1Item *)(state->dest); - if (item->Length) - item->Length = (item->Length << 3) - state->bit_string_unused_bits; - } - - return len; -} - - -/* - * XXX All callers should be looking at return value to detect - * out-of-memory errors (and stop!). - */ -static struct subitem * -sec_asn1d_add_to_subitems (sec_asn1d_state *state, - const void *data, unsigned long len, - PRBool copy_data) -{ - struct subitem *thing; - - thing = (struct subitem*)sec_asn1d_zalloc (state->top->our_pool, - sizeof (struct subitem)); - if (thing == NULL) { - dprintf("decodeError: zalloc\n"); - state->top->status = decodeError; - return NULL; - } - - if (copy_data) { - void *copy; - copy = sec_asn1d_alloc (state->top->our_pool, len); - if (copy == NULL) { - dprintf("decodeError: alloc\n"); - state->top->status = decodeError; - if (!state->top->our_pool) - PORT_Free(thing); - return NULL; - } - PORT_Memcpy (copy, data, len); - thing->data = copy; - } else { - thing->data = data; - } - thing->len = len; - thing->next = NULL; - - if (state->subitems_head == NULL) { - PORT_Assert (state->subitems_tail == NULL); - state->subitems_head = state->subitems_tail = thing; - } else { - state->subitems_tail->next = thing; - state->subitems_tail = thing; - } - - return thing; -} - - -static void -sec_asn1d_record_any_header (sec_asn1d_state *state, - const char *buf, - unsigned long len) -{ - SecAsn1Item *item; - - item = (SecAsn1Item *)(state->dest); - if (item != NULL && item->Data != NULL) { - PORT_Assert (state->substring); - PORT_Memcpy (item->Data + item->Length, buf, len); - item->Length += len; - } else { - sec_asn1d_add_to_subitems (state, buf, len, PR_TRUE); - } -} - - -/* - * We are moving along through the substrings of a constructed string, - * and have just finished parsing one -- we need to save our child data - * (if the child was not already writing directly into the destination) - * and then move forward by one. - * - * We also have to detect when we are done: - * - a definite-length encoding stops when our pending value hits 0 - * - an indefinite-length encoding stops when our child is empty - * (which means it was the end-of-contents octets) - */ -static void -sec_asn1d_next_substring (sec_asn1d_state *state) -{ - sec_asn1d_state *child; - SecAsn1Item *item; - unsigned long child_consumed; - PRBool done; - - PORT_Assert (state->place == duringConstructedString); - PORT_Assert (state->child != NULL); - - child = state->child; - - child_consumed = child->consumed; - child->consumed = 0; - state->consumed += child_consumed; - - done = PR_FALSE; - - if (state->pending) { - PORT_Assert (!state->indefinite); - if( child_consumed > state->pending ) { - dprintf("decodeError: next_substring consumed > pend\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - - state->pending -= child_consumed; - if (state->pending == 0) - done = PR_TRUE; - } else { - PORT_Assert (state->indefinite); - - item = (SecAsn1Item *)(child->dest); - if (item != NULL && item->Data != NULL) { - /* - * Save the string away for later concatenation. - */ - PORT_Assert (item->Data != NULL); - sec_asn1d_add_to_subitems (state, item->Data, item->Length, PR_FALSE); - /* - * Clear the child item for the next round. - */ - item->Data = NULL; - item->Length = 0; - } - - /* - * If our child was just our end-of-contents octets, we are done. - */ - if (child->endofcontents) - done = PR_TRUE; - } - - /* - * Stop or do the next one. - */ - if (done) { - child->place = notInUse; - state->place = afterConstructedString; - } else { - sec_asn1d_scrub_state (child); - state->top->current = child; - } -} - - -/* - * We are doing a SET OF or SEQUENCE OF, and have just finished an item. - */ -static void -sec_asn1d_next_in_group (sec_asn1d_state *state, - const char *buf /* __APPLE__ */) -{ - sec_asn1d_state *child; - unsigned long child_consumed; - - PORT_Assert (state->place == duringGroup); - PORT_Assert (state->child != NULL); - - child = state->child; - - child_consumed = child->consumed; - child->consumed = 0; - state->consumed += child_consumed; - - /* - * If our child was just our end-of-contents octets, we are done. - */ - #ifdef __APPLE__ - /* - * Without the check for !child->indefinite, this path could - * be taken erroneously if the child is indefinite! - */ - if(child->endofcontents && !child->indefinite) { - #else - if (child->endofcontents) { - #endif /* __APPLE__ */ - /* XXX I removed the PORT_Assert (child->dest == NULL) because there - * was a bug in that a template that was a sequence of which also had - * a child of a sequence of, in an indefinite group was not working - * properly. This fix seems to work, (added the if statement below), - * and nothing appears broken, but I am putting this note here just - * in case. */ - /* - * XXX No matter how many times I read that comment, - * I cannot figure out what case he was fixing. I believe what he - * did was deliberate, so I am loathe to touch it. I need to - * understand how it could ever be that child->dest != NULL but - * child->endofcontents is true, and why it is important to check - * that state->subitems_head is NULL. This really needs to be - * figured out, as I am not sure if the following code should be - * compensating for "offset", as is done a little farther below - * in the more normal case. - */ - PORT_Assert (state->indefinite); - PORT_Assert (state->pending == 0); - if(child->dest && !state->subitems_head) { - sec_asn1d_add_to_subitems (state, child->dest, 0, PR_FALSE); - child->dest = NULL; - } - - child->place = notInUse; - state->place = afterGroup; - return; - } - - /* - * Do the "after" field notification for next in group. - */ - sec_asn1d_notify_after (state->top, child->dest, child->depth); - - /* - * Save it away (unless we are not storing). - */ - if (child->dest != NULL) { - void *dest; - - dest = child->dest; - dest = (char *)dest - child->theTemplate->offset; - sec_asn1d_add_to_subitems (state, dest, 0, PR_FALSE); - child->dest = NULL; - } - - /* - * Account for those bytes; see if we are done. - */ - if (state->pending) { - PORT_Assert (!state->indefinite); - if( child_consumed > state->pending ) { - dprintf("decodeError: next_in_group consumed > pend\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - - state->pending -= child_consumed; - if (state->pending == 0) { - child->place = notInUse; - state->place = afterGroup; - return; - } - } - - /* - * Do the "before" field notification for next item in group. - */ - sec_asn1d_notify_before (state->top, child->dest, child->depth); - - /* - * Now we do the next one. - */ - sec_asn1d_scrub_state (child); - - /* Initialize child state from the template */ - sec_asn1d_init_state_based_on_template(child, buf /* __APPLE__ */); - - state->top->current = child; -} - - -/* - * We are moving along through a sequence; move forward by one, - * (detecting end-of-sequence when it happens). - * XXX The handling of "missing" is ugly. Fix it. - */ -static void -sec_asn1d_next_in_sequence (sec_asn1d_state *state, - const char *buf /* __APPLE__ */) -{ - sec_asn1d_state *child; - unsigned long child_consumed; - PRBool child_missing; - - PORT_Assert (state->place == duringSequence); - PORT_Assert (state->child != NULL); - - child = state->child; - - /* - * Do the "after" field notification. - */ - sec_asn1d_notify_after (state->top, child->dest, child->depth); - - child_missing = (PRBool) child->missing; - child_consumed = child->consumed; - child->consumed = 0; - - /* - * Take care of accounting. - */ - if (child_missing) { - PORT_Assert (child->optional); - } else { - state->consumed += child_consumed; - /* - * Free any grandchild. - */ - sec_asn1d_free_child (child, PR_FALSE); - if (state->pending) { - PORT_Assert (!state->indefinite); - if( child_consumed > state->pending ) { - dprintf("decodeError: next_in_seq consumed > pend\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - state->pending -= child_consumed; - if (state->pending == 0) { - child->theTemplate++; - while (child->theTemplate->kind != 0) { - if ((child->theTemplate->kind & SEC_ASN1_OPTIONAL) == 0) { - dprintf("decodeError: next_in_seq child not opt\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - child->theTemplate++; - } - child->place = notInUse; - state->place = afterEndOfContents; - return; - } - } - } - - /* - * Move forward. - */ - child->theTemplate++; - if (child->theTemplate->kind == 0) { - /* - * We are done with this sequence. - */ - child->place = notInUse; - if (state->pending) { - dprintf("decodeError: next_in_seq notInUse still pending\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } else if (child_missing) { - /* - * We got to the end, but have a child that started parsing - * and ended up "missing". The only legitimate reason for - * this is that we had one or more optional fields at the - * end of our sequence, and we were encoded indefinite-length, - * so when we went looking for those optional fields we - * found our end-of-contents octets instead. - * (Yes, this is ugly; dunno a better way to handle it.) - * So, first confirm the situation, and then mark that we - * are done. - */ - if (state->indefinite && child->endofcontents) { - PORT_Assert (child_consumed == 2); - if( child_consumed != 2 ) { - dprintf("decodeError: next_in_seq indef len != 2\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } else { - state->consumed += child_consumed; - state->place = afterEndOfContents; - } - } else { - dprintf("decodeError: next_in_seq !indef, child missing\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } - } else { - /* - * We have to finish out, maybe reading end-of-contents octets; - * let the normal logic do the right thing. - */ - state->place = beforeEndOfContents; - } - } else { - unsigned char child_found_tag_modifiers = 0; - unsigned long child_found_tag_number = 0; - - /* - * Reset state and push. - */ - if (state->dest != NULL) - child->dest = (char *)state->dest + child->theTemplate->offset; - - /* - * Do the "before" field notification. - */ - sec_asn1d_notify_before (state->top, child->dest, child->depth); - - if (child_missing) { /* if previous child was missing, copy the tag data we already have */ - child_found_tag_modifiers = child->found_tag_modifiers; - child_found_tag_number = child->found_tag_number; - } - state->top->current = child; - child = sec_asn1d_init_state_based_on_template (child, - buf /* __APPLE__ */); - if (child_missing && child) { - child->place = afterIdentifier; - child->found_tag_modifiers = child_found_tag_modifiers; - child->found_tag_number = child_found_tag_number; - child->consumed = child_consumed; - if (child->underlying_kind == SEC_ASN1_ANY - && !child->top->filter_only) { - /* - * If the new field is an ANY, and we are storing, then - * we need to save the tag out. We would have done this - * already in the normal case, but since we were looking - * for an optional field, and we did not find it, we only - * now realize we need to save the tag. - */ - unsigned char identifier; - - /* - * Check that we did not end up with a high tag; for that - * we need to re-encode the tag into multiple bytes in order - * to store it back to look like what we parsed originally. - * In practice this does not happen, but for completeness - * sake it should probably be made to work at some point. - */ - PORT_Assert (child_found_tag_number < SEC_ASN1_HIGH_TAG_NUMBER); - identifier = (unsigned char)(child_found_tag_modifiers | child_found_tag_number); - sec_asn1d_record_any_header (child, (char *) &identifier, 1); - } - } - } -} - - -static void -sec_asn1d_concat_substrings (sec_asn1d_state *state) -{ - PORT_Assert (state->place == afterConstructedString); - - if (state->subitems_head != NULL) { - struct subitem *substring; - unsigned long alloc_len, item_len; - unsigned char *where; - SecAsn1Item *item; - PRBool is_bit_string; - - item_len = 0; - is_bit_string = (state->underlying_kind == SEC_ASN1_BIT_STRING) - ? PR_TRUE : PR_FALSE; - - substring = state->subitems_head; - while (substring != NULL) { - /* - * All bit-string substrings except the last one should be - * a clean multiple of 8 bits. - */ - if (is_bit_string && (substring->next == NULL) - && (substring->len & 0x7)) { - dprintf("decodeError: sec_asn1d_concat_substrings align\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - item_len += substring->len; - substring = substring->next; - } - - if (is_bit_string) { -#ifdef XP_WIN16 /* win16 compiler gets an internal error otherwise */ - alloc_len = (((long)item_len + 7) / 8); -#else - alloc_len = ((item_len + 7) >> 3); -#endif - } else { - /* - * Add 2 for the end-of-contents octets of an indefinite-length - * ANY that is *not* also an INNER. Because we zero-allocate - * below, all we need to do is increase the length here. - */ - if (state->underlying_kind == SEC_ASN1_ANY && state->indefinite) - item_len += 2; - alloc_len = item_len; - } - - item = (SecAsn1Item *)(state->dest); - PORT_Assert (item != NULL); - PORT_Assert (item->Data == NULL); - item->Data = (unsigned char*)sec_asn1d_zalloc (state->top->their_pool, - alloc_len); - if (item->Data == NULL) { - dprintf("decodeError: zalloc\n"); - state->top->status = decodeError; - return; - } - item->Length = item_len; - - where = item->Data; - substring = state->subitems_head; - while (substring != NULL) { - if (is_bit_string) - item_len = (substring->len + 7) >> 3; - else - item_len = substring->len; - PORT_Memcpy (where, substring->data, item_len); - where += item_len; - substring = substring->next; - } - - /* - * Because we use arenas and have a mark set, we later free - * everything we have allocated, so this does *not* present - * a memory leak (it is just temporarily left dangling). - */ - state->subitems_head = state->subitems_tail = NULL; - } - - state->place = afterEndOfContents; -} - - -static void -sec_asn1d_concat_group (sec_asn1d_state *state) -{ - const void ***placep; - - PORT_Assert (state->place == afterGroup); - - placep = (const void***)state->dest; - PORT_Assert(state->subitems_head == NULL || placep != NULL); - if (placep != NULL) { - struct subitem *item; - const void **group; - int count; - - count = 0; - item = state->subitems_head; - while (item != NULL) { - PORT_Assert (item->next != NULL || item == state->subitems_tail); - count++; - item = item->next; - } - - group = (const void**)sec_asn1d_zalloc (state->top->their_pool, - (count + 1) * (sizeof(void *))); - if (group == NULL) { - dprintf("decodeError: zalloc\n"); - state->top->status = decodeError; - return; - } - - *placep = group; - - item = state->subitems_head; - while (item != NULL) { - *group++ = item->data; - item = item->next; - } - *group = NULL; - - /* - * Because we use arenas and have a mark set, we later free - * everything we have allocated, so this does *not* present - * a memory leak (it is just temporarily left dangling). - */ - state->subitems_head = state->subitems_tail = NULL; - } - - state->place = afterEndOfContents; -} - -/* - * For those states that push a child to handle a subtemplate, - * "absorb" that child (transfer necessary information). - */ -static void -sec_asn1d_absorb_child (sec_asn1d_state *state) -{ - /* - * There is absolutely supposed to be a child there. - */ - PORT_Assert (state->child != NULL); - - /* - * Inherit the missing status of our child, and do the ugly - * backing-up if necessary. - */ - state->missing = state->child->missing; - if (state->missing) { - state->found_tag_number = state->child->found_tag_number; - state->found_tag_modifiers = state->child->found_tag_modifiers; - state->endofcontents = state->child->endofcontents; - } - - /* - * Add in number of bytes consumed by child. - * (Only EXPLICIT should have already consumed bytes itself.) - */ - PORT_Assert (state->place == afterExplicit || state->consumed == 0); - state->consumed += state->child->consumed; - - /* - * Subtract from bytes pending; this only applies to a definite-length - * EXPLICIT field. - */ - if (state->pending) { - PORT_Assert (!state->indefinite); - PORT_Assert (state->place == afterExplicit); - - /* - * If we had a definite-length explicit, then what the child - * consumed should be what was left pending. - */ - if (state->pending != state->child->consumed) { - if (state->pending < state->child->consumed) { - dprintf("decodeError: absorb_child pending < consumed\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return; - } - /* - * Okay, this is a hack. It *should* be an error whether - * pending is too big or too small, but it turns out that - * we had a bug in our *old* DER encoder that ended up - * counting an explicit header twice in the case where - * the underlying type was an ANY. So, because we cannot - * prevent receiving these (our own certificate server can - * send them to us), we need to be lenient and accept them. - * To do so, we need to pretend as if we read all of the - * bytes that the header said we would find, even though - * we actually came up short. - */ - state->consumed += (state->pending - state->child->consumed); - } - state->pending = 0; - } - - /* - * Indicate that we are done with child. - */ - state->child->consumed = 0; - - /* - * And move on to final state. - * (Technically everybody could move to afterEndOfContents except - * for an indefinite-length EXPLICIT; for simplicity though we assert - * that but let the end-of-contents code do the real determination.) - */ - PORT_Assert (state->place == afterExplicit || (! state->indefinite)); - state->place = beforeEndOfContents; -} - - -static void -sec_asn1d_prepare_for_end_of_contents (sec_asn1d_state *state) -{ - PORT_Assert (state->place == beforeEndOfContents); - - if (state->indefinite) { - state->place = duringEndOfContents; - state->pending = 2; - } else { - state->place = afterEndOfContents; - } -} - - -static unsigned long -sec_asn1d_parse_end_of_contents (sec_asn1d_state *state, - const char *buf, unsigned long len) -{ - unsigned int i; - - PORT_Assert (state->pending <= 2); - PORT_Assert (state->place == duringEndOfContents); - - if (len == 0) { - state->top->status = needBytes; - return 0; - } - - if (state->pending < len) - len = state->pending; - - for (i = 0; i < len; i++) { - if (buf[i] != 0) { - /* - * We expect to find only zeros; if not, just give up. - */ - dprintf("decodeError: end of contents non zero\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return 0; - } - } - - state->pending -= len; - - if (state->pending == 0) { - state->place = afterEndOfContents; - state->endofcontents = PR_TRUE; - } - - return len; -} - - -static void -sec_asn1d_pop_state (sec_asn1d_state *state) -{ -#if 0 /* XXX I think this should always be handled explicitly by parent? */ - /* - * Account for our child. - */ - if (state->child != NULL) { - state->consumed += state->child->consumed; - if (state->pending) { - PORT_Assert (!state->indefinite); - if( state->child->consumed > state->pending ) { - dprintf("decodeError: pop_state pending < consumed\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - } else { - state->pending -= state->child->consumed; - } - } - state->child->consumed = 0; - } -#endif /* XXX */ - - /* - * Free our child. - */ - sec_asn1d_free_child (state, PR_FALSE); - - /* - * Just make my parent be the current state. It will then clean - * up after me and free me (or reuse me). - */ - state->top->current = state->parent; -} - -static sec_asn1d_state * -sec_asn1d_before_choice (sec_asn1d_state *state, const char *buf /* __APPLE__ */) -{ - sec_asn1d_state *child; - - if( state->allocate ) { - void *dest; - - dest = sec_asn1d_zalloc(state->top->their_pool, - state->theTemplate->size); - if( (void *)NULL == dest ) { - dprintf("decodeError: zalloc\n"); - state->top->status = decodeError; - return (sec_asn1d_state *)NULL; - } - - state->dest = (char *)dest + state->theTemplate->offset; - } - - child = sec_asn1d_push_state(state->top, state->theTemplate + 1, - (char *)state->dest - state->theTemplate->offset, - PR_FALSE); - if( (sec_asn1d_state *)NULL == child ) { - return (sec_asn1d_state *)NULL; - } - - sec_asn1d_scrub_state(child); - child = sec_asn1d_init_state_based_on_template(child, - buf /* __APPLE__ */); - if( (sec_asn1d_state *)NULL == child ) { - return (sec_asn1d_state *)NULL; - } - - child->optional = PR_TRUE; - - state->place = duringChoice; - - return child; -} - -static sec_asn1d_state * -sec_asn1d_during_choice (sec_asn1d_state *state, const char *buf /* __APPLE__ */) -{ - sec_asn1d_state *child = state->child; - - PORT_Assert((sec_asn1d_state *)NULL != child); - - if( child->missing ) { - unsigned char child_found_tag_modifiers = 0; - unsigned long child_found_tag_number = 0; - void * dest; - - state->consumed += child->consumed; - - if (child->endofcontents) { - /* This choice is probably the first item in a GROUP - ** (e.g. SET_OF) that was indefinite-length encoded. - ** We're actually at the end of that GROUP. - ** We look up the stack to be sure that we find - ** a state with indefinite length encoding before we - ** find a state (like a SEQUENCE) that is definite. - */ - child->place = notInUse; - state->place = afterChoice; - state->endofcontents = PR_TRUE; /* propagate this up */ - if (sec_asn1d_parent_allows_EOC(state)) - return state; - dprintf("decodeError: during_choice child at EOC by parent does not allow EOC\n"); - PORT_SetError(SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return NULL; - } - - dest = (char *)child->dest - child->theTemplate->offset; - child->theTemplate++; - - if( 0 == child->theTemplate->kind ) { - /* Ran out of choices */ - dprintf("decodeError: during_choice ran out of choice\n"); - PORT_SetError(SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return (sec_asn1d_state *)NULL; - } - child->dest = (char *)dest + child->theTemplate->offset; - - /* cargo'd from next_in_sequence innards */ - if( state->pending ) { - PORT_Assert(!state->indefinite); - if( child->consumed > state->pending ) { - dprintf("decodeError: during_choice consumed > pending\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - state->top->status = decodeError; - return NULL; - } - state->pending -= child->consumed; - if( 0 == state->pending ) { - /* XXX uh.. not sure if I should have stopped this - * from happening before. */ - PORT_Assert(0); - PORT_SetError(SEC_ERROR_BAD_DER); - dprintf("decodeError: during_choice !pending\n"); - state->top->status = decodeError; - return (sec_asn1d_state *)NULL; - } - } - - child->consumed = 0; - sec_asn1d_scrub_state(child); - - /* move it on top again */ - state->top->current = child; - - child_found_tag_modifiers = child->found_tag_modifiers; - child_found_tag_number = child->found_tag_number; - - child = sec_asn1d_init_state_based_on_template(child, buf /* __APPLE__*/); - if( (sec_asn1d_state *)NULL == child ) { - return (sec_asn1d_state *)NULL; - } - - /* copy our findings to the new top */ - child->found_tag_modifiers = child_found_tag_modifiers; - child->found_tag_number = child_found_tag_number; - - child->optional = PR_TRUE; - child->place = afterIdentifier; - - return child; - } - if( (void *)NULL != state->dest ) { - /* Store the enum */ - int *which = (int *)state->dest; - *which = (int)child->theTemplate->size; - } - - child->place = notInUse; - - state->place = afterChoice; - return state; -} - -static void -sec_asn1d_after_choice (sec_asn1d_state *state) -{ - state->consumed += state->child->consumed; - state->child->consumed = 0; - state->place = afterEndOfContents; - sec_asn1d_pop_state(state); -} - -#if 0 -unsigned long -sec_asn1d_uinteger(SecAsn1Item *src) -{ - unsigned long value; - int len; - - if (src->Length > 5 || (src->Length > 4 && src->Data[0] == 0)) - return 0; - - value = 0; - len = src->Length; - while (len) { - value <<= 8; - value |= src->Data[--len]; - } - return value; -} -#endif - -SECStatus -SEC_ASN1DecodeInteger(SecAsn1Item *src, unsigned long *value) -{ - unsigned long v; - unsigned int i; - - if (src == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - if (src->Length > sizeof(unsigned long)) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - if (src->Data == NULL) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - if (src->Data[0] & 0x80) - v = -1; /* signed and negative - start with all 1's */ - else - v = 0; - - for (i= 0; i < src->Length; i++) { - /* shift in next byte */ - v <<= 8; - v |= src->Data[i]; - } - *value = v; - return SECSuccess; -} - -#ifdef DEBUG_ASN1D_STATES -static void -dump_states(SEC_ASN1DecoderContext *cx) -{ - sec_asn1d_state *state; - char kindBuf[256]; - - for (state = cx->current; state->parent; state = state->parent) { - ; - } - - for (; state; state = state->child) { - int i; - for (i = 0; i < state->depth; i++) { - printf(" "); - } - - i = formatKind(state->theTemplate->kind, kindBuf); - printf("%s: tmpl %p, kind%s", - (state == cx->current) ? "STATE" : "State", - state->theTemplate, - kindBuf); - printf(" %s", (state->place <= notInUse) - ? place_names[ state->place ] - : "(undefined)"); - if (!i) - printf(", expect 0x%02lx", - state->expect_tag_number | state->expect_tag_modifiers); - - printf("%s%s%s %lu\n", - state->indefinite ? ", indef" : "", - state->missing ? ", miss" : "", - state->endofcontents ? ", EOC" : "", - state->pending - ); - } - - return; -} -#endif /* DEBUG_ASN1D_STATES */ - -SECStatus -SEC_ASN1DecoderUpdate (SEC_ASN1DecoderContext *cx, - const char *buf, size_t len) -{ - sec_asn1d_state *state = NULL; - unsigned long consumed; - SEC_ASN1EncodingPart what; - sec_asn1d_state *stateEnd = cx->current; - - if (cx->status == needBytes) - cx->status = keepGoing; - - while (cx->status == keepGoing) { - state = cx->current; - what = SEC_ASN1_Contents; - consumed = 0; - #if DEBUG_ASN1D_STATES - if (doDumpStates > 1) { - printf("\nPLACE = %s, next byte = 0x%02x, %p[%lu]\n", - (state->place <= notInUse) ? - place_names[ state->place ] : "(undefined)", - (unsigned int)((unsigned char *)buf)[ consumed ], - buf, consumed); - dump_states(cx); - } - #endif /* DEBUG_ASN1D_STATES */ - switch (state->place) { - case beforeIdentifier: - consumed = sec_asn1d_parse_identifier (state, buf, len); - what = SEC_ASN1_Identifier; - break; - case duringIdentifier: - consumed = sec_asn1d_parse_more_identifier (state, buf, len); - what = SEC_ASN1_Identifier; - break; - case afterIdentifier: - sec_asn1d_confirm_identifier (state); - break; - case beforeLength: - consumed = sec_asn1d_parse_length (state, buf, len); - what = SEC_ASN1_Length; - break; - case duringLength: - consumed = sec_asn1d_parse_more_length (state, buf, len); - what = SEC_ASN1_Length; - break; - case afterLength: - sec_asn1d_prepare_for_contents (state, buf); - break; - case beforeBitString: - consumed = sec_asn1d_parse_bit_string (state, buf, len); - break; - case duringBitString: - consumed = sec_asn1d_parse_more_bit_string (state, buf, len); - break; - case duringConstructedString: - sec_asn1d_next_substring (state); - break; - case duringGroup: - sec_asn1d_next_in_group (state, buf); - break; - case duringLeaf: - consumed = sec_asn1d_parse_leaf (state, buf, len); - break; - case duringSaveEncoding: - sec_asn1d_reuse_encoding (state); - if (cx->status == decodeError) { - /* recursive call has already popped all states from stack. - ** Bail out quickly. - */ - return SECFailure; - } - if (cx->status == needBytes) { - /* recursive call wanted more data. Fatal. Clean up below. */ - PORT_SetError (SEC_ERROR_BAD_DER); - cx->status = decodeError; - } - break; - case duringSequence: - sec_asn1d_next_in_sequence (state, buf); - break; - case afterConstructedString: - sec_asn1d_concat_substrings (state); - break; - case afterExplicit: - case afterImplicit: - case afterInline: - case afterPointer: - sec_asn1d_absorb_child (state); - break; - case afterGroup: - sec_asn1d_concat_group (state); - break; - case afterSaveEncoding: - /* SEC_ASN1DecoderUpdate has called itself recursively to - ** decode SAVEd encoded data, and now is done decoding that. - ** Return to the calling copy of SEC_ASN1DecoderUpdate. - */ - return SECSuccess; - case beforeEndOfContents: - sec_asn1d_prepare_for_end_of_contents (state); - break; - case duringEndOfContents: - consumed = sec_asn1d_parse_end_of_contents (state, buf, len); - what = SEC_ASN1_EndOfContents; - break; - case afterEndOfContents: - sec_asn1d_pop_state (state); - break; - case beforeChoice: - state = sec_asn1d_before_choice(state, buf); - break; - case duringChoice: - state = sec_asn1d_during_choice(state, buf); - break; - case afterChoice: - sec_asn1d_after_choice(state); - break; - case notInUse: - default: - /* This is not an error, but rather a plain old BUG! */ - PORT_Assert (0); - PORT_SetError (SEC_ERROR_BAD_DER); - dprintf("decodeError: decoder update bad state->place\n"); - cx->status = decodeError; - break; - } - - if (cx->status == decodeError) - break; - - /* We should not consume more than we have. */ - PORT_Assert (consumed <= len); - if( consumed > len ) { - dprintf("decodeError: decoder update consumed > len\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - cx->status = decodeError; - break; - } - - /* It might have changed, so we have to update our local copy. */ - state = cx->current; - - /* If it is NULL, we have popped all the way to the top. */ - if (state == NULL) { - PORT_Assert (consumed == 0); - #if 0 - /* XXX I want this here, but it seems that we have situations (like - * downloading a pkcs7 cert chain from some issuers) that give us a - * length which is greater than the entire encoding. So, we cannot - * have this be an error. - */ - if (len > 0) { - dprintf("decodeError: decoder update nonzero len\n"); - PORT_SetError (SEC_ERROR_BAD_DER); - cx->status = decodeError; - } - else - #endif - cx->status = allDone; - break; - } - else if (state->theTemplate->kind == SEC_ASN1_SKIP_REST) { - cx->status = allDone; - break; - } - - if (consumed == 0) - continue; - - /* - * The following check is specifically looking for an ANY - * that is *not* also an INNER, because we need to save aside - * all bytes in that case -- the contents parts will get - * handled like all other contents, and the end-of-contents - * bytes are added by the concat code, but the outer header - * bytes need to get saved too, so we do them explicitly here. - */ - if (state->underlying_kind == SEC_ASN1_ANY - && !cx->filter_only && (what == SEC_ASN1_Identifier - || what == SEC_ASN1_Length)) { - sec_asn1d_record_any_header (state, buf, consumed); - } - - /* - * We had some number of good, accepted bytes. If the caller - * has registered to see them, pass them along. - */ - if (state->top->filter_proc != NULL) { - int depth; - - depth = state->depth; - if (what == SEC_ASN1_EndOfContents && !state->indefinite) { - PORT_Assert (state->parent != NULL - && state->parent->indefinite); - depth--; - PORT_Assert (depth == state->parent->depth); - } - (* state->top->filter_proc) (state->top->filter_arg, - buf, consumed, depth, what); - } - - state->consumed += consumed; - buf += consumed; - len -= consumed; - } /* main decode loop */ - - if (cx->status == decodeError) { - while (state != NULL && stateEnd->parent!=state) { - sec_asn1d_free_child (state, PR_TRUE); - state = state->parent; - } -#ifdef SEC_ASN1D_FREE_ON_ERROR /* - * XXX This does not work because we can - * end up leaving behind dangling pointers - * to stuff that was allocated. In order - * to make this really work (which would - * be a good thing, I think), we need to - * keep track of every place/pointer that - * was allocated and make sure to NULL it - * out before we then free back to the mark. - */ - if (cx->their_pool != NULL) { - PORT_Assert (cx->their_mark != NULL); - PORT_ArenaRelease (cx->their_pool, cx->their_mark); - } -#endif - return SECFailure; - } - -#if 0 - /* XXX This is what I want, but cannot have because it seems we - * have situations (like when downloading a pkcs7 cert chain from - * some issuers) that give us a total length which is greater than - * the entire encoding. So, we have to allow allDone to have a - * remaining length greater than zero. I wanted to catch internal - * bugs with this, noticing when we do not have the right length. - * Oh well. - */ - PORT_Assert (len == 0 - && (cx->status == needBytes || cx->status == allDone)); -#else - PORT_Assert ((len == 0 && cx->status == needBytes) - || cx->status == allDone); -#endif - return SECSuccess; -} - - -SECStatus -SEC_ASN1DecoderFinish (SEC_ASN1DecoderContext *cx) -{ - SECStatus rv; - - if (cx->status == needBytes) { - #ifdef __APPLE__ - /* - * Special case: need more bytes, but this field and all - * subsequent fields are optional. I'm surprised this case is - * not handled in the original NSS code, and this workaround - * is a bit of a hack... - */ - sec_asn1d_state *state = cx->current; - assert(state != NULL); - if(state->place == beforeIdentifier) { - int allOptional = 1; - const SecAsn1Template *templ = state->theTemplate; - while(templ->kind != 0) { - if(!(templ->kind & SEC_ASN1_OPTIONAL)) { - allOptional = 0; - break; - } - templ++; - } - if(allOptional) { - /* letting this one slide */ - rv = SECSuccess; - } - else { - PORT_SetError (SEC_ERROR_BAD_DER); - rv = SECFailure; - } - } - else { - PORT_SetError (SEC_ERROR_BAD_DER); - rv = SECFailure; - } - #else - PORT_SetError (SEC_ERROR_BAD_DER); - rv = SECFailure; - #endif /* __APPLE__ */ - } else { - rv = SECSuccess; - } - - /* - * XXX anything else that needs to be finished? - */ - - PORT_FreeArena (cx->our_pool, PR_FALSE); - - return rv; -} - - -SEC_ASN1DecoderContext * -SEC_ASN1DecoderStart (PRArenaPool *their_pool, void *dest, - const SecAsn1Template *theTemplate - #ifdef __APPLE__ - , - /* only needed if first element will be SEC_ASN1_DYNAMIC */ - const char *buf - #endif - ) -{ - PRArenaPool *our_pool; - SEC_ASN1DecoderContext *cx; - - our_pool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); - if (our_pool == NULL) - return NULL; - - cx = (SEC_ASN1DecoderContext*)PORT_ArenaZAlloc (our_pool, sizeof(*cx)); - if (cx == NULL) { - PORT_FreeArena (our_pool, PR_FALSE); - return NULL; - } - - cx->our_pool = our_pool; - if (their_pool != NULL) { - cx->their_pool = their_pool; -#ifdef SEC_ASN1D_FREE_ON_ERROR - cx->their_mark = PORT_ArenaMark (their_pool); -#endif - } - - cx->status = needBytes; - - if (sec_asn1d_push_state(cx, theTemplate, dest, PR_FALSE) == NULL - || sec_asn1d_init_state_based_on_template (cx->current, - buf /* __APPLE__ */) == NULL) { - /* - * Trouble initializing (probably due to failed allocations) - * requires that we just give up. - */ - PORT_FreeArena (our_pool, PR_FALSE); - return NULL; - } - - return cx; -} - - -void -SEC_ASN1DecoderSetFilterProc (SEC_ASN1DecoderContext *cx, - SEC_ASN1WriteProc fn, void *arg, - PRBool only) -{ - /* check that we are "between" fields here */ - PORT_Assert (cx->during_notify); - - cx->filter_proc = fn; - cx->filter_arg = arg; - cx->filter_only = only; -} - - -void -SEC_ASN1DecoderClearFilterProc (SEC_ASN1DecoderContext *cx) -{ - /* check that we are "between" fields here */ - PORT_Assert (cx->during_notify); - - cx->filter_proc = NULL; - cx->filter_arg = NULL; - cx->filter_only = PR_FALSE; -} - - -void -SEC_ASN1DecoderSetNotifyProc (SEC_ASN1DecoderContext *cx, - SEC_ASN1NotifyProc fn, void *arg) -{ - cx->notify_proc = fn; - cx->notify_arg = arg; -} - - -void -SEC_ASN1DecoderClearNotifyProc (SEC_ASN1DecoderContext *cx) -{ - cx->notify_proc = NULL; - cx->notify_arg = NULL; /* not necessary; just being clean */ -} - - -void -SEC_ASN1DecoderAbort(SEC_ASN1DecoderContext *cx, int error) -{ - PORT_Assert(cx); - PORT_SetError(error); - cx->status = decodeError; -} - - -SECStatus -SEC_ASN1Decode (PRArenaPool *poolp, void *dest, - const SecAsn1Template *theTemplate, - const char *buf, size_t len) -{ - SEC_ASN1DecoderContext *dcx; - SECStatus urv, frv; - - dcx = SEC_ASN1DecoderStart (poolp, dest, theTemplate, - buf /* __APPLE__ */); - if (dcx == NULL) - return SECFailure; - - urv = SEC_ASN1DecoderUpdate (dcx, buf, len); - frv = SEC_ASN1DecoderFinish (dcx); - - if (urv != SECSuccess) - return urv; - - return frv; -} - - -SECStatus -SEC_ASN1DecodeItem (PRArenaPool *poolp, void *dest, - const SecAsn1Template *theTemplate, - const SecAsn1Item *item) -{ - return SEC_ASN1Decode (poolp, dest, theTemplate, - (const char *) item->Data, item->Length); -} - - diff --git a/OSX/include/security_asn1/secasn1e.c b/OSX/include/security_asn1/secasn1e.c deleted file mode 100644 index 0dee92c6..00000000 --- a/OSX/include/security_asn1/secasn1e.c +++ /dev/null @@ -1,1646 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Support for ENcoding ASN.1 data based on BER/DER (Basic/Distinguished - * Encoding Rules). - * - * $Id: secasn1e.c,v 1.7 2004/05/13 15:29:13 dmitch Exp $ - */ - -#include "secasn1.h" - -typedef enum { - beforeHeader, - duringContents, - duringGroup, - duringSequence, - afterContents, - afterImplicit, - afterInline, - afterPointer, - afterChoice, - notInUse -} sec_asn1e_parse_place; - -typedef enum { - allDone, - encodeError, - keepGoing, - needBytes -} sec_asn1e_parse_status; - -typedef struct sec_asn1e_state_struct { - SEC_ASN1EncoderContext *top; - const SecAsn1Template *theTemplate; - void *src; - - struct sec_asn1e_state_struct *parent; /* aka prev */ - struct sec_asn1e_state_struct *child; /* aka next */ - - sec_asn1e_parse_place place; /* where we are in encoding process */ - - /* - * XXX explain the next fields as clearly as possible... - */ - unsigned char tag_modifiers; - unsigned char tag_number; - unsigned long underlying_kind; - - int depth; - - PRBool explicit, /* we are handling an explicit header */ - indefinite, /* need end-of-contents */ - is_string, /* encoding a simple string or an ANY */ - may_stream, /* when streaming, do indefinite encoding */ - optional, /* omit field if it has no contents */ - ignore_stream /* ignore streaming value of sub-template */ - #ifdef __APPLE__ - , - signedInt /* signed alternate to SEC_ASN1_INTEGER */ - #endif - ; -} sec_asn1e_state; - -/* - * An "outsider" will have an opaque pointer to this, created by calling - * SEC_ASN1EncoderStart(). It will be passed back in to all subsequent - * calls to SEC_ASN1EncoderUpdate() and related routines, and when done - * it is passed to SEC_ASN1EncoderFinish(). - */ -struct sec_EncoderContext_struct { - PRArenaPool *our_pool; /* for our internal allocs */ - - sec_asn1e_state *current; - sec_asn1e_parse_status status; - - PRBool streaming; - PRBool from_buf; - - SEC_ASN1NotifyProc notify_proc; /* call before/after handling field */ - void *notify_arg; /* argument to notify_proc */ - PRBool during_notify; /* true during call to notify_proc */ - - SEC_ASN1WriteProc output_proc; /* pass encoded bytes to this */ - void *output_arg; /* argument to that function */ -}; - - -static sec_asn1e_state * -sec_asn1e_push_state (SEC_ASN1EncoderContext *cx, - const SecAsn1Template *theTemplate, - const void *src, PRBool new_depth) -{ - sec_asn1e_state *state, *new_state; - - state = cx->current; - - new_state = (sec_asn1e_state*)PORT_ArenaZAlloc (cx->our_pool, - sizeof(*new_state)); - if (new_state == NULL) { - cx->status = encodeError; - return NULL; - } - - new_state->top = cx; - new_state->parent = state; - new_state->theTemplate = theTemplate; - new_state->place = notInUse; - if (src != NULL) - new_state->src = (char *)src + theTemplate->offset; - - if (state != NULL) { - new_state->depth = state->depth; - if (new_depth) - new_state->depth++; - state->child = new_state; - } - - cx->current = new_state; - return new_state; -} - - -static void -sec_asn1e_scrub_state (sec_asn1e_state *state) -{ - /* - * Some default "scrubbing". - * XXX right set of initializations? - */ - state->place = beforeHeader; - state->indefinite = PR_FALSE; -} - - -static void -sec_asn1e_notify_before (SEC_ASN1EncoderContext *cx, void *src, int depth) -{ - if (cx->notify_proc == NULL) - return; - - cx->during_notify = PR_TRUE; - (* cx->notify_proc) (cx->notify_arg, PR_TRUE, src, depth); - cx->during_notify = PR_FALSE; -} - - -static void -sec_asn1e_notify_after (SEC_ASN1EncoderContext *cx, void *src, int depth) -{ - if (cx->notify_proc == NULL) - return; - - cx->during_notify = PR_TRUE; - (* cx->notify_proc) (cx->notify_arg, PR_FALSE, src, depth); - cx->during_notify = PR_FALSE; -} - - -static sec_asn1e_state * -sec_asn1e_init_state_based_on_template (sec_asn1e_state *state) -{ - PRBool explicit, is_string, may_stream, optional, universal, ignore_stream; - unsigned char tag_modifiers; - unsigned long encode_kind, under_kind; - unsigned long tag_number; - #ifdef __APPLE__ - PRBool signedInt, dynamic; - #endif - - encode_kind = state->theTemplate->kind; - - universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) - ? PR_TRUE : PR_FALSE; - - explicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_EXPLICIT; - - optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_OPTIONAL; - - PORT_Assert (!(explicit && universal)); /* bad templates */ - - may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_MAY_STREAM; - - ignore_stream = (encode_kind & SEC_ASN1_NO_STREAM) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_NO_STREAM; - - #ifdef __APPLE__ - signedInt = (encode_kind & SEC_ASN1_SIGNED_INT) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_SIGNED_INT; - #endif - - #ifdef __APPLE__ - dynamic = (encode_kind & SEC_ASN1_DYNAMIC) ? PR_TRUE : PR_FALSE; - #endif - encode_kind &= ~SEC_ASN1_DYNAMIC; - - if( encode_kind & SEC_ASN1_CHOICE ) { - under_kind = SEC_ASN1_CHOICE; - } else - - if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || (!universal - && !explicit)) { - const SecAsn1Template *subt; - void *src; - - PORT_Assert ((encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) == 0); - - sec_asn1e_scrub_state (state); - - if (encode_kind & SEC_ASN1_POINTER) { - /* - * XXX This used to PORT_Assert (encode_kind == SEC_ASN1_POINTER); - * but that was too restrictive. This needs to be fixed, - * probably copying what the decoder now checks for, and - * adding a big comment here to explain what the checks mean. - */ - src = *(void **)state->src; - state->place = afterPointer; - if (src == NULL) { - /* - * If this is optional, but NULL, then the field does - * not need to be encoded. In this case we are done; - * we do not want to push a subtemplate. - */ - if (optional) - return state; - - /* - * XXX this is an error; need to figure out - * how to handle this - */ - } - } else { - src = state->src; - if (encode_kind & SEC_ASN1_INLINE) { - /* check that there are no extraneous bits */ - PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional); - state->place = afterInline; - } else { - /* - * Save the tag modifiers and tag number here before moving - * on to the next state in case this is a member of a - * SEQUENCE OF - */ - state->tag_modifiers = (unsigned char)encode_kind & SEC_ASN1_TAG_MASK - & ~SEC_ASN1_TAGNUM_MASK; - state->tag_number = (unsigned char)encode_kind & SEC_ASN1_TAGNUM_MASK; - - state->place = afterImplicit; - state->optional = optional; - } - } - - subt = SEC_ASN1GetSubtemplate (state->theTemplate, state->src, PR_TRUE, - NULL /* __APPLE__ */); - state = sec_asn1e_push_state (state->top, subt, src, PR_FALSE); - if (state == NULL) - return NULL; - - if (universal) { - /* - * This is a POINTER or INLINE; just init based on that - * and we are done. - */ - return sec_asn1e_init_state_based_on_template (state); - } - - /* - * This is an implicit, non-universal (meaning, application-private - * or context-specific) field. This results in a "magic" tag but - * encoding based on the underlying type. We pushed a new state - * that is based on the subtemplate (the underlying type), but - * now we will sort of alias it to give it some of our properties - * (tag, optional status, etc.). - */ - - under_kind = state->theTemplate->kind; - if (under_kind & SEC_ASN1_MAY_STREAM) { - if (!ignore_stream) - may_stream = PR_TRUE; - under_kind &= ~SEC_ASN1_MAY_STREAM; - } - } else { - under_kind = encode_kind; - } - - /* - * Sanity check that there are no unwanted bits marked in under_kind. - * These bits were either removed above (after we recorded them) or - * they simply should not be found (signalling a bad/broken template). - * XXX is this the right set of bits to test here? (i.e. need to add - * or remove any?) - */ - PORT_Assert ((under_kind & (/*SEC_ASN1_EXPLICIT | */SEC_ASN1_OPTIONAL - | SEC_ASN1_SKIP | SEC_ASN1_INNER - | SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM - | SEC_ASN1_INLINE | SEC_ASN1_POINTER)) == 0); - - if (encode_kind & SEC_ASN1_ANY) { - PORT_Assert (encode_kind == under_kind); - tag_modifiers = 0; - tag_number = 0; - is_string = PR_TRUE; - } else { - tag_modifiers = (unsigned char)encode_kind & SEC_ASN1_TAG_MASK & - ~SEC_ASN1_TAGNUM_MASK; - /* - * XXX This assumes only single-octet identifiers. To handle - * the HIGH TAG form we would need to do some more work, especially - * in how to specify them in the template, because right now we - * do not provide a way to specify more *tag* bits in encode_kind. - */ - - #ifdef __APPLE__ - /* - * Apple change: if this is a DYNAMIC template, use the tag number - * from the subtemplate's kind - */ - if(dynamic) { - tag_number = state->theTemplate->kind & SEC_ASN1_TAGNUM_MASK; - explicit = (state->theTemplate->kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE; - tag_modifiers |= (state->theTemplate->kind & SEC_ASN1_CONSTRUCTED); - } - else - #endif /* __APPLE__ */ - tag_number = encode_kind & SEC_ASN1_TAGNUM_MASK; - - is_string = PR_FALSE; - switch (under_kind & SEC_ASN1_TAGNUM_MASK) { - case SEC_ASN1_SET: - /* - * XXX A plain old SET (as opposed to a SET OF) is not implemented. - * If it ever is, remove this assert... - */ - PORT_Assert ((under_kind & SEC_ASN1_GROUP) != 0); - /* fallthru */ - case SEC_ASN1_SEQUENCE: - tag_modifiers |= SEC_ASN1_CONSTRUCTED; - break; - case SEC_ASN1_BIT_STRING: - case SEC_ASN1_BMP_STRING: - case SEC_ASN1_GENERALIZED_TIME: - case SEC_ASN1_IA5_STRING: - case SEC_ASN1_OCTET_STRING: - case SEC_ASN1_PRINTABLE_STRING: - case SEC_ASN1_T61_STRING: - case SEC_ASN1_UNIVERSAL_STRING: - case SEC_ASN1_UTC_TIME: - case SEC_ASN1_UTF8_STRING: - case SEC_ASN1_VISIBLE_STRING: - /* - * We do not yet know if we will be constructing the string, - * so we have to wait to do this final tag modification. - */ - is_string = PR_TRUE; - break; - } - } - - state->tag_modifiers = tag_modifiers; - state->tag_number = (unsigned char)tag_number; - state->underlying_kind = under_kind; - state->explicit = explicit; - state->may_stream = may_stream; - state->is_string = is_string; - state->optional = optional; - state->ignore_stream = ignore_stream; - #ifdef __APPLE__ - state->signedInt = signedInt; - #endif - - sec_asn1e_scrub_state (state); - - return state; -} - - -static void -sec_asn1e_write_part (sec_asn1e_state *state, - const char *buf, size_t len, - SEC_ASN1EncodingPart part) -{ - SEC_ASN1EncoderContext *cx; - - cx = state->top; - (* cx->output_proc) (cx->output_arg, buf, len, state->depth, part); -} - - -/* - * XXX This assumes only single-octet identifiers. To handle - * the HIGH TAG form we would need to modify this interface and - * teach it to properly encode the special form. - */ -static void -sec_asn1e_write_identifier_bytes (sec_asn1e_state *state, unsigned char value) -{ - char byte; - - byte = (char) value; - sec_asn1e_write_part (state, &byte, 1, SEC_ASN1_Identifier); -} - -int -SEC_ASN1EncodeLength(unsigned char *buf,unsigned long value) { - int lenlen; - - lenlen = SEC_ASN1LengthLength (value); - if (lenlen == 1) { - buf[0] = value; - } else { - int i; - - i = lenlen - 1; - buf[0] = 0x80 | i; - while (i) { - buf[i--] = value; - value >>= 8; - } - PORT_Assert (value == 0); - } - return lenlen; -} - -static void -sec_asn1e_write_length_bytes (sec_asn1e_state *state, unsigned long value, - PRBool indefinite) -{ - int lenlen; - unsigned char buf[sizeof(unsigned long) + 1]; - - if (indefinite) { - PORT_Assert (value == 0); - buf[0] = 0x80; - lenlen = 1; - } else { - lenlen = SEC_ASN1EncodeLength(buf,value); - } - - sec_asn1e_write_part (state, (char *) buf, lenlen, SEC_ASN1_Length); -} - - -static void -sec_asn1e_write_contents_bytes (sec_asn1e_state *state, - const char *buf, unsigned long len) -{ - sec_asn1e_write_part (state, buf, len, SEC_ASN1_Contents); -} - - -static void -sec_asn1e_write_end_of_contents_bytes (sec_asn1e_state *state) -{ - const char eoc[2] = {0, 0}; - - sec_asn1e_write_part (state, eoc, 2, SEC_ASN1_EndOfContents); -} - -static int -sec_asn1e_which_choice -( - void *src, - const SecAsn1Template *theTemplate -) -{ - int rv; - unsigned int which = *(unsigned int *)src; - - for( rv = 1, theTemplate++; theTemplate->kind != 0; rv++, theTemplate++ ) { - if( which == theTemplate->size ) { - return rv; - } - } - - return 0; -} - -static unsigned long -sec_asn1e_contents_length (const SecAsn1Template *theTemplate, void *src, - PRBool ignoresubstream, PRBool *noheaderp) -{ - unsigned long encode_kind, underlying_kind; - PRBool explicit, optional, universal, may_stream; - unsigned long len; - #ifdef __APPLE__ - PRBool signedInt; - #endif - - /* - * This function currently calculates the length in all cases - * except the following: when writing out the contents of a - * template that belongs to a state where it was a sub-template - * with the SEC_ASN1_MAY_STREAM bit set and it's parent had the - * optional bit set. The information that the parent is optional - * and that we should return the length of 0 when that length is - * present since that means the optional field is no longer present. - * So we add the ignoresubstream flag which is passed in when - * writing the contents, but for all recursive calls to - * sec_asn1e_contents_length, we pass PR_FALSE, because this - * function correctly calculates the length for children templates - * from that point on. Confused yet? At least you didn't have - * to figure it out. ;) -javi - */ - encode_kind = theTemplate->kind; - - universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) - ? PR_TRUE : PR_FALSE; - - explicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_EXPLICIT; - - optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_OPTIONAL; - - PORT_Assert (!(explicit && universal)); /* bad templates */ - - may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE; - encode_kind &= ~SEC_ASN1_MAY_STREAM; - - /* Just clear this to get it out of the way; we do not need it here */ - encode_kind &= ~SEC_ASN1_DYNAMIC; - encode_kind &= ~SEC_ASN1_NO_STREAM; - - if( encode_kind & SEC_ASN1_CHOICE ) { - void *src2; - int indx = sec_asn1e_which_choice(src, theTemplate); - if( 0 == indx ) { - /* XXX set an error? "choice not found" */ - /* state->top->status = encodeError; */ - return 0; - } - - src2 = (void *)((char *)src - theTemplate->offset + theTemplate[indx].offset); - - return sec_asn1e_contents_length(&theTemplate[indx], src2, - PR_FALSE, noheaderp); - } - - if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || !universal) { - - /* XXX any bits we want to disallow (PORT_Assert against) here? */ - - theTemplate = SEC_ASN1GetSubtemplate (theTemplate, src, PR_TRUE, - NULL /* __APPLE__ */); - - if (encode_kind & SEC_ASN1_POINTER) { - /* - * XXX This used to PORT_Assert (encode_kind == SEC_ASN1_POINTER); - * but that was too restrictive. This needs to be fixed, - * probably copying what the decoder now checks for, and - * adding a big comment here to explain what the checks mean. - * Alternatively, the check here could be omitted altogether - * just letting sec_asn1e_init_state_based_on_template - * do it, since that routine can do better error handling, too. - */ - src = *(void **)src; - if (src == NULL) { - if (optional) - *noheaderp = PR_TRUE; - else - *noheaderp = PR_FALSE; - return 0; - } - } else if (encode_kind & SEC_ASN1_INLINE) { - /* check that there are no extraneous bits */ - PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional); - } - - src = (char *)src + theTemplate->offset; - - if (explicit) { - len = sec_asn1e_contents_length (theTemplate, src, PR_FALSE, - noheaderp); - if (len == 0 && optional) { - *noheaderp = PR_TRUE; - } else if (*noheaderp) { - /* Okay, *we* do not want to add in a header, but our caller still does. */ - *noheaderp = PR_FALSE; - } else { - /* if the inner content exists, our length is - * len(identifier) + len(length) + len(innercontent) - * XXX we currently assume len(identifier) == 1; - * to support a high-tag-number this would need to be smarter. - */ - len += 1 + SEC_ASN1LengthLength (len); - } - return len; - } - - underlying_kind = theTemplate->kind; - underlying_kind &= ~SEC_ASN1_MAY_STREAM; - /* XXX Should we recurse here? */ - } else { - underlying_kind = encode_kind; - } - - #ifdef __APPLE__ - signedInt = (underlying_kind & SEC_ASN1_SIGNED_INT) ? - PR_TRUE : PR_FALSE; - #endif - - /* This is only used in decoding; it plays no part in encoding. */ - if (underlying_kind & SEC_ASN1_SAVE) { - /* check that there are no extraneous bits */ - PORT_Assert (underlying_kind == SEC_ASN1_SAVE); - *noheaderp = PR_TRUE; - return 0; - } - - /* Having any of these bits is not expected here... */ - PORT_Assert ((underlying_kind & (SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL - | SEC_ASN1_INLINE | SEC_ASN1_POINTER - | SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM - | SEC_ASN1_SAVE | SEC_ASN1_SKIP)) == 0); - - if( underlying_kind & SEC_ASN1_CHOICE ) { - void *src2; - int indx = sec_asn1e_which_choice(src, theTemplate); - if( 0 == indx ) { - /* XXX set an error? "choice not found" */ - /* state->top->status = encodeError; */ - return 0; - } - - src2 = (void *)((char *)src - theTemplate->offset + theTemplate[indx].offset); - len = sec_asn1e_contents_length(&theTemplate[indx], src2, PR_FALSE, - noheaderp); - } else - - switch (underlying_kind) { - case SEC_ASN1_SEQUENCE_OF: - case SEC_ASN1_SET_OF: - { - const SecAsn1Template *tmpt; - void *sub_src; - unsigned long sub_len; - void **group; - - len = 0; - - group = *(void ***)src; - if (group == NULL) - break; - - tmpt = SEC_ASN1GetSubtemplate (theTemplate, src, PR_TRUE, - NULL /* __APPLE__ */); - - for (; *group != NULL; group++) { - sub_src = (char *)(*group) + tmpt->offset; - sub_len = sec_asn1e_contents_length (tmpt, sub_src, PR_FALSE, - noheaderp); - len += sub_len; - /* - * XXX The 1 below is the presumed length of the identifier; - * to support a high-tag-number this would need to be smarter. - */ - if (!*noheaderp) - len += 1 + SEC_ASN1LengthLength (sub_len); - } - } - break; - - case SEC_ASN1_SEQUENCE: - case SEC_ASN1_SET: - { - const SecAsn1Template *tmpt; - void *sub_src; - unsigned long sub_len; - - len = 0; - for (tmpt = theTemplate + 1; tmpt->kind; tmpt++) { - sub_src = (char *)src + tmpt->offset; - sub_len = sec_asn1e_contents_length (tmpt, sub_src, PR_FALSE, - noheaderp); - len += sub_len; - /* - * XXX The 1 below is the presumed length of the identifier; - * to support a high-tag-number this would need to be smarter. - */ - if (!*noheaderp) - len += 1 + SEC_ASN1LengthLength (sub_len); - } - } - break; - - case SEC_ASN1_BIT_STRING: - /* convert bit length to byte */ - len = (((SecAsn1Item *)src)->Length + 7) >> 3; - /* bit string contents involve an extra octet */ - if (len) - len++; - break; - - case SEC_ASN1_INTEGER: - /* ASN.1 INTEGERs are signed. - * If the source is an unsigned integer, the encoder will need - * to handle the conversion here. - */ - { - unsigned char *buf = ((SecAsn1Item *)src)->Data; - #ifndef __APPLE__ - SecAsn1ItemType integerType = ((SecAsn1Item *)src)->type; - #endif - len = ((SecAsn1Item *)src)->Length; - while (len > 0) { - if (*buf != 0) { - #ifdef __APPLE__ - if (*buf & 0x80 && !signedInt) { - #else - if (*buf & 0x80 && integerType == siUnsignedInteger) { - #endif // __APPLE__ - len++; /* leading zero needed to make number signed */ - } - break; /* reached beginning of number */ - } - if (len == 1) { - break; /* the number 0 */ - } - if (buf[1] & 0x80) { - break; /* leading zero already present */ - } - /* extraneous leading zero, keep going */ - buf++; - len--; - } - } - break; - - default: - len = ((SecAsn1Item *)src)->Length; - if (may_stream && len == 0 && !ignoresubstream) - len = 1; /* if we're streaming, we may have a secitem w/len 0 as placeholder */ - break; - } - - if ((len == 0 && optional) || underlying_kind == SEC_ASN1_ANY) - *noheaderp = PR_TRUE; - else - *noheaderp = PR_FALSE; - - return len; -} - - -static void -sec_asn1e_write_header (sec_asn1e_state *state) -{ - unsigned long contents_length; - unsigned char tag_number, tag_modifiers; - PRBool noheader; - - PORT_Assert (state->place == beforeHeader); - - tag_number = state->tag_number; - tag_modifiers = state->tag_modifiers; - - if (state->underlying_kind == SEC_ASN1_ANY) { - state->place = duringContents; - return; - } - - if( state->underlying_kind & SEC_ASN1_CHOICE ) { - int indx = sec_asn1e_which_choice(state->src, state->theTemplate); - if( 0 == indx ) { - /* XXX set an error? "choice not found" */ - state->top->status = encodeError; - return; - } - - state->place = afterChoice; - state = sec_asn1e_push_state(state->top, &state->theTemplate[indx], - (char *)state->src - state->theTemplate->offset, - PR_TRUE); - - if( (sec_asn1e_state *)NULL != state ) { - /* - * Do the "before" field notification. - */ - sec_asn1e_notify_before (state->top, state->src, state->depth); - state = sec_asn1e_init_state_based_on_template (state); - } - - (void) state; - - return; - } - - /* - * We are doing a definite-length encoding. First we have to - * walk the data structure to calculate the entire contents length. - */ - contents_length = sec_asn1e_contents_length (state->theTemplate, - state->src, - state->ignore_stream, - &noheader); - /* - * We might be told explicitly not to put out a header. - * But it can also be the case, via a pushed subtemplate, that - * sec_asn1e_contents_length could not know that this field is - * really optional. So check for that explicitly, too. - */ - if (noheader || (contents_length == 0 && state->optional)) { - state->place = afterContents; - if (state->top->streaming && state->may_stream && state->top->from_buf) - /* we did not find an optional indefinite string, so we don't encode it. - * However, if TakeFromBuf is on, we stop here anyway to give our caller - * a chance to intercept at the same point where we would stop if the - * field were present. */ - state->top->status = needBytes; - return; - } - - if (state->top->streaming && state->may_stream - && (state->top->from_buf || !state->is_string)) { - /* - * We need to put out an indefinite-length encoding. - */ - state->indefinite = PR_TRUE; - /* - * The only universal types that can be constructed are SETs, - * SEQUENCEs, and strings; so check that it is one of those, - * or that it is not universal (e.g. context-specific). - */ - PORT_Assert ((tag_number == SEC_ASN1_SET) - || (tag_number == SEC_ASN1_SEQUENCE) - || ((tag_modifiers & SEC_ASN1_CLASS_MASK) != 0) - || state->is_string); - tag_modifiers |= SEC_ASN1_CONSTRUCTED; - contents_length = 0; - } - - sec_asn1e_write_identifier_bytes (state, (unsigned char)(tag_number | tag_modifiers)); - sec_asn1e_write_length_bytes (state, contents_length, state->indefinite); - - if (contents_length == 0 && !state->indefinite) { - /* - * If no real contents to encode, then we are done with this field. - */ - state->place = afterContents; - return; - } - - /* - * An EXPLICIT is nothing but an outer header, which we have already - * written. Now we need to do the inner header and contents. - */ - if (state->explicit) { - state->place = afterContents; - state = sec_asn1e_push_state (state->top, - SEC_ASN1GetSubtemplate(state->theTemplate, - state->src, - PR_TRUE, - NULL /* __APPLE__ */), - state->src, PR_TRUE); - if (state != NULL) - state = sec_asn1e_init_state_based_on_template (state); - - (void) state; - - return; - } - - switch (state->underlying_kind) { - case SEC_ASN1_SET_OF: - case SEC_ASN1_SEQUENCE_OF: - /* - * We need to push a child to handle each member. - */ - { - void **group; - const SecAsn1Template *subt; - - group = *(void ***)state->src; - if (group == NULL || *group == NULL) { - /* - * Group is empty; we are done. - */ - state->place = afterContents; - return; - } - state->place = duringGroup; - subt = SEC_ASN1GetSubtemplate (state->theTemplate, state->src, - PR_TRUE, NULL /* __APPLE__ */); - state = sec_asn1e_push_state (state->top, subt, *group, PR_TRUE); - if (state != NULL) - state = sec_asn1e_init_state_based_on_template (state); - } - break; - - case SEC_ASN1_SEQUENCE: - case SEC_ASN1_SET: - /* - * We need to push a child to handle the individual fields. - */ - state->place = duringSequence; - state = sec_asn1e_push_state (state->top, state->theTemplate + 1, - state->src, PR_TRUE); - if (state != NULL) { - /* - * Do the "before" field notification. - */ - sec_asn1e_notify_before (state->top, state->src, state->depth); - state = sec_asn1e_init_state_based_on_template (state); - } - break; - - default: - /* - * I think we do not need to do anything else. - * XXX Correct? - */ - state->place = duringContents; - break; - } - - (void) state; -} - - -static void -sec_asn1e_write_contents (sec_asn1e_state *state, - const char *buf, unsigned long len) -{ - PORT_Assert (state->place == duringContents); - - if (state->top->from_buf) { - /* - * Probably they just turned on "take from buf", but have not - * yet given us any bytes. If there is nothing in the buffer - * then we have nothing to do but return and wait. - */ - if (buf == NULL || len == 0) { - state->top->status = needBytes; - return; - } - /* - * We are streaming, reading from a passed-in buffer. - * This means we are encoding a simple string or an ANY. - * For the former, we need to put out a substring, with its - * own identifier and length. For an ANY, we just write it - * out as is (our caller is required to ensure that it - * is a properly encoded entity). - */ - PORT_Assert (state->is_string); /* includes ANY */ - if (state->underlying_kind != SEC_ASN1_ANY) { - unsigned char identifier; - - /* - * Create the identifier based on underlying_kind. We cannot - * use tag_number and tag_modifiers because this can be an - * implicitly encoded field. In that case, the underlying - * substrings *are* encoded with their real tag. - */ - identifier = (unsigned char)state->underlying_kind & SEC_ASN1_TAG_MASK; - /* - * The underlying kind should just be a simple string; there - * should be no bits like CONTEXT_SPECIFIC or CONSTRUCTED set. - */ - PORT_Assert ((identifier & SEC_ASN1_TAGNUM_MASK) == identifier); - /* - * Write out the tag and length for the substring. - */ - sec_asn1e_write_identifier_bytes (state, identifier); - if (state->underlying_kind == SEC_ASN1_BIT_STRING) { - char byte; - /* - * Assume we have a length in bytes but we need to output - * a proper bit string. This interface only works for bit - * strings that are full multiples of 8. If support for - * real, variable length bit strings is needed then the - * caller will have to know to pass in a bit length instead - * of a byte length and then this code will have to - * perform the encoding necessary (length written is length - * in bytes plus 1, and the first octet of string is the - * number of bits remaining between the end of the bit - * string and the next byte boundary). - */ - sec_asn1e_write_length_bytes (state, len + 1, PR_FALSE); - byte = 0; - sec_asn1e_write_contents_bytes (state, &byte, 1); - } else { - sec_asn1e_write_length_bytes (state, len, PR_FALSE); - } - } - sec_asn1e_write_contents_bytes (state, buf, len); - state->top->status = needBytes; - } else { - switch (state->underlying_kind) { - case SEC_ASN1_SET: - case SEC_ASN1_SEQUENCE: - PORT_Assert (0); - break; - - case SEC_ASN1_BIT_STRING: - { - SecAsn1Item *item; - char rem; - - item = (SecAsn1Item *)state->src; - len = (item->Length + 7) >> 3; - rem = (unsigned char)((len << 3) - item->Length); /* remaining bits */ - sec_asn1e_write_contents_bytes (state, &rem, 1); - sec_asn1e_write_contents_bytes (state, (char *) item->Data, - len); - } - break; - - case SEC_ASN1_BMP_STRING: - /* The number of bytes must be divisable by 2 */ - if ((((SecAsn1Item *)state->src)->Length) % 2) { - SEC_ASN1EncoderContext *cx; - - cx = state->top; - cx->status = encodeError; - break; - } - /* otherwise, fall through to write the content */ - goto process_string; - - case SEC_ASN1_UNIVERSAL_STRING: - /* The number of bytes must be divisable by 4 */ - if ((((SecAsn1Item *)state->src)->Length) % 4) { - SEC_ASN1EncoderContext *cx; - - cx = state->top; - cx->status = encodeError; - break; - } - /* otherwise, fall through to write the content */ - goto process_string; - - case SEC_ASN1_INTEGER: - /* ASN.1 INTEGERs are signed. If the source is an unsigned - * integer, the encoder will need to handle the conversion here. - */ - { - size_t blen; - unsigned char *intbuf; - #ifdef __APPLE__ - PRBool signedInt = state->signedInt; - #else - SECItemType integerType = ((SecAsn1Item *)state->src)->type; - #endif - blen = ((SecAsn1Item *)state->src)->Length; - intbuf = ((SecAsn1Item *)state->src)->Data; - while (blen > 0) { - #ifdef __APPLE__ - if (*intbuf & 0x80 && !signedInt) { - #else - if (*intbuf & 0x80 && integerType == siUnsignedInteger) { - #endif - char zero = 0; /* write a leading 0 */ - sec_asn1e_write_contents_bytes(state, &zero, 1); - /* and then the remaining buffer */ - sec_asn1e_write_contents_bytes(state, - (char *)intbuf, blen); - break; - } - /* Check three possibilities: - * 1. No leading zeros, msb of MSB is not 1; - * 2. The number is zero itself; - * 3. Encoding a signed integer with a leading zero, - * keep the zero so that the number is positive. - */ - if (*intbuf != 0 || - blen == 1 || - #ifdef __APPLE__ - (intbuf[1] & 0x80 && signedInt) ) - #else - (intbuf[1] & 0x80 && integerType != siUnsignedInteger) ) - #endif - { - sec_asn1e_write_contents_bytes(state, - (char *)intbuf, blen); - break; - } - /* byte is 0, continue */ - intbuf++; - blen--; - } - } - /* done with this content */ - break; - -process_string: - default: - { - SecAsn1Item *item; - - item = (SecAsn1Item *)state->src; - sec_asn1e_write_contents_bytes (state, (char *) item->Data, - item->Length); - } - break; - } - state->place = afterContents; - } -} - - -/* - * We are doing a SET OF or SEQUENCE OF, and have just finished an item. - */ -static void -sec_asn1e_next_in_group (sec_asn1e_state *state) -{ - sec_asn1e_state *child; - void **group; - void *member; - - PORT_Assert (state->place == duringGroup); - PORT_Assert (state->child != NULL); - - child = state->child; - - group = *(void ***)state->src; - - /* - * Find placement of current item. - */ - member = (char *)(state->child->src) - child->theTemplate->offset; - while (*group != member) - group++; - - /* - * Move forward to next item. - */ - group++; - if (*group == NULL) { - /* - * That was our last one; we are done now. - */ - child->place = notInUse; - state->place = afterContents; - return; - } - child->src = (char *)(*group) + child->theTemplate->offset; - - /* - * Re-"push" child. - */ - sec_asn1e_scrub_state (child); - state->top->current = child; -} - - -/* - * We are moving along through a sequence; move forward by one, - * (detecting end-of-sequence when it happens). - */ -static void -sec_asn1e_next_in_sequence (sec_asn1e_state *state) -{ - sec_asn1e_state *child; - - PORT_Assert (state->place == duringSequence); - PORT_Assert (state->child != NULL); - - child = state->child; - - /* - * Do the "after" field notification. - */ - sec_asn1e_notify_after (state->top, child->src, child->depth); - - /* - * Move forward. - */ - child->theTemplate++; - if (child->theTemplate->kind == 0) { - /* - * We are done with this sequence. - */ - child->place = notInUse; - state->place = afterContents; - return; - } - - /* - * Reset state and push. - */ - - child->src = (char *)state->src + child->theTemplate->offset; - - /* - * Do the "before" field notification. - */ - sec_asn1e_notify_before (state->top, child->src, child->depth); - - state->top->current = child; - (void) sec_asn1e_init_state_based_on_template (child); -} - - -static void -sec_asn1e_after_contents (sec_asn1e_state *state) -{ - PORT_Assert (state->place == afterContents); - - if (state->indefinite) - sec_asn1e_write_end_of_contents_bytes (state); - - /* - * Just make my parent be the current state. It will then clean - * up after me and free me (or reuse me). - */ - state->top->current = state->parent; -} - - -/* - * This function is called whether or not we are streaming; if we - * *are* streaming, our caller can also instruct us to take bytes - * from the passed-in buffer (at buf, for length len, which is likely - * bytes but could even mean bits if the current field is a bit string). - * If we have been so instructed, we will gobble up bytes from there - * (rather than from our src structure) and output them, and then - * we will just return, expecting to be called again -- either with - * more bytes or after our caller has instructed us that we are done - * (for now) with the buffer. - */ -SECStatus -SEC_ASN1EncoderUpdate (SEC_ASN1EncoderContext *cx, - const char *buf, unsigned long len) -{ - sec_asn1e_state *state; - - if (cx->status == needBytes) { - PORT_Assert (buf != NULL && len != 0); - cx->status = keepGoing; - } - - while (cx->status == keepGoing) { - state = cx->current; - switch (state->place) { - case beforeHeader: - sec_asn1e_write_header (state); - break; - case duringContents: - sec_asn1e_write_contents (state, buf, len); - break; - case duringGroup: - sec_asn1e_next_in_group (state); - break; - case duringSequence: - sec_asn1e_next_in_sequence (state); - break; - case afterContents: - sec_asn1e_after_contents (state); - break; - case afterImplicit: - case afterInline: - case afterPointer: - case afterChoice: - /* - * These states are more documentation than anything. - * They just need to force a pop. - */ - PORT_Assert (!state->indefinite); - state->place = afterContents; - break; - case notInUse: - default: - /* This is not an error, but rather a plain old BUG! */ - PORT_Assert (0); - cx->status = encodeError; - break; - } - - if (cx->status == encodeError) - break; - - /* It might have changed, so we have to update our local copy. */ - state = cx->current; - - /* If it is NULL, we have popped all the way to the top. */ - if (state == NULL) { - cx->status = allDone; - break; - } - } - - if (cx->status == encodeError) { - return SECFailure; - } - - return SECSuccess; -} - - -void -SEC_ASN1EncoderFinish (SEC_ASN1EncoderContext *cx) -{ - /* - * XXX anything else that needs to be finished? - */ - - PORT_FreeArena (cx->our_pool, PR_FALSE); -} - - -SEC_ASN1EncoderContext * -SEC_ASN1EncoderStart (const void *src, const SecAsn1Template *theTemplate, - SEC_ASN1WriteProc output_proc, void *output_arg) -{ - PRArenaPool *our_pool; - SEC_ASN1EncoderContext *cx; - - our_pool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); - if (our_pool == NULL) - return NULL; - - cx = (SEC_ASN1EncoderContext*)PORT_ArenaZAlloc (our_pool, sizeof(*cx)); - if (cx == NULL) { - PORT_FreeArena (our_pool, PR_FALSE); - return NULL; - } - - cx->our_pool = our_pool; - cx->output_proc = output_proc; - cx->output_arg = output_arg; - - cx->status = keepGoing; - - if (sec_asn1e_push_state(cx, theTemplate, src, PR_FALSE) == NULL - || sec_asn1e_init_state_based_on_template (cx->current) == NULL) { - /* - * Trouble initializing (probably due to failed allocations) - * requires that we just give up. - */ - PORT_FreeArena (our_pool, PR_FALSE); - return NULL; - } - - return cx; -} - - -/* - * XXX Do we need a FilterProc, too? - */ - - -void -SEC_ASN1EncoderSetNotifyProc (SEC_ASN1EncoderContext *cx, - SEC_ASN1NotifyProc fn, void *arg) -{ - cx->notify_proc = fn; - cx->notify_arg = arg; -} - - -void -SEC_ASN1EncoderClearNotifyProc (SEC_ASN1EncoderContext *cx) -{ - cx->notify_proc = NULL; - cx->notify_arg = NULL; /* not necessary; just being clean */ -} - - -void -SEC_ASN1EncoderAbort(SEC_ASN1EncoderContext *cx, int error) -{ - PORT_Assert(cx); - PORT_SetError(error); - cx->status = encodeError; -} - - -void -SEC_ASN1EncoderSetStreaming (SEC_ASN1EncoderContext *cx) -{ - /* XXX is there a way to check that we are "between" fields here? */ - - cx->streaming = PR_TRUE; -} - - -void -SEC_ASN1EncoderClearStreaming (SEC_ASN1EncoderContext *cx) -{ - /* XXX is there a way to check that we are "between" fields here? */ - - cx->streaming = PR_FALSE; -} - - -void -SEC_ASN1EncoderSetTakeFromBuf (SEC_ASN1EncoderContext *cx) -{ - /* - * XXX is there a way to check that we are "between" fields here? this - * needs to include a check for being in between groups of items in - * a SET_OF or SEQUENCE_OF. - */ - PORT_Assert (cx->streaming); - - cx->from_buf = PR_TRUE; -} - - -void -SEC_ASN1EncoderClearTakeFromBuf (SEC_ASN1EncoderContext *cx) -{ - /* we should actually be taking from buf *now* */ - PORT_Assert (cx->from_buf); - if (! cx->from_buf) /* if not, just do nothing */ - return; - - cx->from_buf = PR_FALSE; - - if (cx->status == needBytes) { - cx->status = keepGoing; - cx->current->place = afterContents; - } -} - - -SECStatus -SEC_ASN1Encode (const void *src, const SecAsn1Template *theTemplate, - SEC_ASN1WriteProc output_proc, void *output_arg) -{ - SEC_ASN1EncoderContext *ecx; - SECStatus rv; - - ecx = SEC_ASN1EncoderStart (src, theTemplate, output_proc, output_arg); - if (ecx == NULL) - return SECFailure; - - rv = SEC_ASN1EncoderUpdate (ecx, NULL, 0); - - SEC_ASN1EncoderFinish (ecx); - return rv; -} - - -/* - * XXX depth and data_kind are unused; is there a PC way to silence warnings? - * (I mean "politically correct", not anything to do with intel/win platform) - */ -void -sec_asn1e_encode_item_count (void *arg, const char *buf, size_t len, - int depth, SEC_ASN1EncodingPart data_kind) -{ - size_t *count; - - count = (unsigned long*)arg; - PORT_Assert (count != NULL); - - *count += len; -} - - -/* XXX depth and data_kind are unused; is there a PC way to silence warnings? */ -void -sec_asn1e_encode_item_store (void *arg, const char *buf, size_t len, - int depth, SEC_ASN1EncodingPart data_kind) -{ - SecAsn1Item *dest; - - dest = (SecAsn1Item*)arg; - PORT_Assert (dest != NULL); - - PORT_Memcpy (dest->Data + dest->Length, buf, len); - dest->Length += len; -} - - -/* - * Allocate an entire SecAsn1Item, or just the data part of it, to hold - * "len" bytes of stuff. Allocate from the given pool, if specified, - * otherwise just do a vanilla PORT_Alloc. - * - * XXX This seems like a reasonable general-purpose function (for SECITEM_)? - */ -SecAsn1Item * -sec_asn1e_allocate_item (PRArenaPool *poolp, SecAsn1Item *dest, unsigned long len) -{ - if (poolp != NULL) { - void *release; - - release = PORT_ArenaMark (poolp); - if (dest == NULL) - dest = (SecAsn1Item*)PORT_ArenaAlloc (poolp, sizeof(SecAsn1Item)); - if (dest != NULL) { - dest->Data = (unsigned char*)PORT_ArenaAlloc (poolp, len); - if (dest->Data == NULL) { - dest = NULL; - } - } - if (dest == NULL) { - /* one or both allocations failed; release everything */ - PORT_ArenaRelease (poolp, release); - } else { - /* everything okay; unmark the arena */ - PORT_ArenaUnmark (poolp, release); - } - } else { - SecAsn1Item *indest; - - indest = dest; - if (dest == NULL) - dest = (SecAsn1Item*)PORT_Alloc (sizeof(SecAsn1Item)); - if (dest != NULL) { - #ifndef __APPLE__ - dest->type = siBuffer; - #endif - dest->Data = (unsigned char*)PORT_Alloc (len); - if (dest->Data == NULL) { - if (indest == NULL) - PORT_Free (dest); - dest = NULL; - } - } - } - - return dest; -} - - -SecAsn1Item * -SEC_ASN1EncodeItem (PRArenaPool *poolp, SecAsn1Item *dest, const void *src, - const SecAsn1Template *theTemplate) -{ - unsigned long encoding_length; - SECStatus rv; - - PORT_Assert (dest == NULL || dest->Data == NULL); - - encoding_length = 0; - rv = SEC_ASN1Encode (src, theTemplate, - sec_asn1e_encode_item_count, &encoding_length); - if (rv != SECSuccess) - return NULL; - - dest = sec_asn1e_allocate_item (poolp, dest, encoding_length); - if (dest == NULL) - return NULL; - - /* XXX necessary? This really just checks for a bug in the allocate fn */ - PORT_Assert (dest->Data != NULL); - if (dest->Data == NULL) - return NULL; - - dest->Length = 0; - (void) SEC_ASN1Encode (src, theTemplate, sec_asn1e_encode_item_store, dest); - - PORT_Assert (encoding_length == dest->Length); - return dest; -} - - -static SecAsn1Item * -sec_asn1e_integer(PRArenaPool *poolp, SecAsn1Item *dest, unsigned long value, - PRBool make_unsigned) -{ - unsigned long copy; - unsigned char sign; - int len = 0; - - /* - * Determine the length of the encoded value (minimum of 1). - */ - copy = value; - do { - len++; - sign = (unsigned char)(copy & 0x80); - copy >>= 8; - } while (copy); - - /* - * If this is an unsigned encoding, and the high bit of the last - * byte we counted was set, we need to add one to the length so - * we put a high-order zero byte in the encoding. - */ - if (sign && make_unsigned) - len++; - - /* - * Allocate the item (if necessary) and the data pointer within. - */ - dest = sec_asn1e_allocate_item (poolp, dest, len); - if (dest == NULL) - return NULL; - - /* - * Store the value, byte by byte, in the item. - */ - dest->Length = len; - while (len) { - dest->Data[--len] = (unsigned char)value; - value >>= 8; - } - PORT_Assert (value == 0); - - return dest; -} - - -SecAsn1Item * -SEC_ASN1EncodeInteger(PRArenaPool *poolp, SecAsn1Item *dest, long value) -{ - return sec_asn1e_integer (poolp, dest, (unsigned long) value, PR_FALSE); -} - - -extern SecAsn1Item * -SEC_ASN1EncodeUnsignedInteger(PRArenaPool *poolp, - SecAsn1Item *dest, unsigned long value) -{ - return sec_asn1e_integer (poolp, dest, value, PR_TRUE); -} diff --git a/OSX/include/security_asn1/secasn1t.h b/OSX/include/security_asn1/secasn1t.h deleted file mode 100644 index 5415f736..00000000 --- a/OSX/include/security_asn1/secasn1t.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Private (SPI) types libsecurity_asn1.h. - */ - -#ifndef _SECASN1T_H_ -#define _SECASN1T_H_ - -#include /* Boolean */ -#include -#include /* public types */ - - -/* default size used for allocation of encoding/decoding stuff */ -#define SEC_ASN1_DEFAULT_ARENA_SIZE (2048) - -/* - * Tempalte flags we don't export in the public API in SecAsn1Types.h - */ -#define SEC_ASN1_MAY_STREAM 0x40000 /* field or one of its sub-fields may - * stream in and so should encode as - * indefinite-length when streaming - * has been indicated; only for - * encoding */ -#define SEC_ASN1_NO_STREAM 0X200000 /* This entry will not stream - * even if the sub-template says - * streaming is possible. Helps - * to solve ambiguities with potential - * streaming entries that are - * optional */ - -/* Maximum depth of nested SEQUENCEs and SETs */ -#define SEC_ASN1D_MAX_DEPTH 32 - -#define SEC_ASN1_GET(x) x -#define SEC_ASN1_SUB(x) x -#define SEC_ASN1_XTRN 0 -#define SEC_ASN1_MKSUB(x) - -#define SEC_ASN1_CHOOSER_DECLARE(x) \ -extern const SecAsn1Template * NSS_Get_##x (void *arg, Boolean enc); - -#define SEC_ASN1_CHOOSER_IMPLEMENT(x) \ -const SecAsn1Template * NSS_Get_##x(void * arg, Boolean enc) \ -{ return x; } - -/* -** Opaque object used by the decoder to store state. -*/ -typedef struct sec_DecoderContext_struct SEC_ASN1DecoderContext; - -/* -** Opaque object used by the encoder to store state. -*/ -typedef struct sec_EncoderContext_struct SEC_ASN1EncoderContext; - -/* - * This is used to describe to a filter function the bytes that are - * being passed to it. This is only useful when the filter is an "outer" - * one, meaning it expects to get *all* of the bytes not just the - * contents octets. - */ -typedef enum { - SEC_ASN1_Identifier = 0, - SEC_ASN1_Length = 1, - SEC_ASN1_Contents = 2, - SEC_ASN1_EndOfContents = 3 -} SEC_ASN1EncodingPart; - -/* - * Type of the function pointer used either for decoding or encoding, - * when doing anything "funny" (e.g. manipulating the data stream) - */ -typedef void (* SEC_ASN1NotifyProc)(void *arg, Boolean before, - void *dest, int real_depth); - -/* - * Type of the function pointer used for grabbing encoded bytes. - * This can be used during either encoding or decoding, as follows... - * - * When decoding, this can be used to filter the encoded bytes as they - * are parsed. This is what you would do if you wanted to process the data - * along the way (like to decrypt it, or to perform a hash on it in order - * to do a signature check later). See SEC_ASN1DecoderSetFilterProc(). - * When processing only part of the encoded bytes is desired, you "watch" - * for the field(s) you are interested in with a "notify proc" (see - * SEC_ASN1DecoderSetNotifyProc()) and for even finer granularity (e.g. to - * ignore all by the contents bytes) you pay attention to the "data_kind" - * parameter. - * - * When encoding, this is the specification for the output function which - * will receive the bytes as they are encoded. The output function can - * perform any postprocessing necessary (like hashing (some of) the data - * to create a digest that gets included at the end) as well as shoving - * the data off wherever it needs to go. (In order to "tune" any processing, - * you can set a "notify proc" as described above in the decoding case.) - * - * The parameters: - * - "arg" is an opaque pointer that you provided at the same time you - * specified a function of this type - * - "data" is a buffer of length "len", containing the encoded bytes - * - "depth" is how deep in a nested encoding we are (it is not usually - * valuable, but can be useful sometimes so I included it) - * - "data_kind" tells you if these bytes are part of the ASN.1 encoded - * octets for identifier, length, contents, or end-of-contents - */ -typedef void (* SEC_ASN1WriteProc)(void *arg, - const char *data, size_t len, - int depth, SEC_ASN1EncodingPart data_kind); - -#endif /* _SECASN1T_H_ */ diff --git a/OSX/include/security_asn1/secasn1u.c b/OSX/include/security_asn1/secasn1u.c deleted file mode 100644 index 30e630be..00000000 --- a/OSX/include/security_asn1/secasn1u.c +++ /dev/null @@ -1,115 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Utility routines to complement the ASN.1 encoding and decoding functions. - * - * $Id: secasn1u.c,v 1.3 2004/05/13 15:29:13 dmitch Exp $ - */ - -#include "secasn1.h" - - -/* - * We have a length that needs to be encoded; how many bytes will the - * encoding take? - * - * The rules are that 0 - 0x7f takes one byte (the length itself is the - * entire encoding); everything else takes one plus the number of bytes - * in the length. - */ -int -SEC_ASN1LengthLength (unsigned long len) -{ - int lenlen = 1; - - if (len > 0x7f) { - do { - lenlen++; - len >>= 8; - } while (len); - } - - return lenlen; -} - - -/* - * XXX Move over (and rewrite as appropriate) the rest of the - * stuff in dersubr.c! - */ - - -/* - * Find the appropriate subtemplate for the given template. - * This may involve calling a "chooser" function, or it may just - * be right there. In either case, it is expected to *have* a - * subtemplate; this is asserted in debug builds (in non-debug - * builds, NULL will be returned). - * - * "thing" is a pointer to the structure being encoded/decoded - * "encoding", when true, means that we are in the process of encoding - * (as opposed to in the process of decoding) - */ -const SecAsn1Template * -SEC_ASN1GetSubtemplate ( - const SecAsn1Template *theTemplate, - void *thing, - PRBool encoding - #ifdef __APPLE__ - , - const char *buf // for decode only - #endif - ) -{ - const SecAsn1Template *subt = NULL; - - PORT_Assert (theTemplate->sub != NULL); - if (theTemplate->sub != NULL) { - if (theTemplate->kind & SEC_ASN1_DYNAMIC) { - SecAsn1TemplateChooserPtr chooserp; - - chooserp = *(SecAsn1TemplateChooserPtr *) theTemplate->sub; - if (chooserp) { - void *dest = thing; - if (thing != NULL) { - thing = (char *)thing - theTemplate->offset; - } - subt = (* chooserp)(thing, encoding, buf, dest); - } - } else { - subt = (SecAsn1Template*)theTemplate->sub; - } - } - return subt; -} diff --git a/OSX/include/security_asn1/seccomon.h b/OSX/include/security_asn1/seccomon.h deleted file mode 100644 index ef4a54aa..00000000 --- a/OSX/include/security_asn1/seccomon.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * seccomon.h - common data structures for security libraries - * - * This file should have lowest-common-denominator datastructures - * for security libraries. It should not be dependent on any other - * headers, and should not require linking with any libraries. - * - * $Id: seccomon.h,v 1.4 2004/03/23 21:31:41 mb Exp $ - */ - -#ifndef _SECCOMMON_H_ -#define _SECCOMMON_H_ - -#include - - -#ifdef __cplusplus -# define SEC_BEGIN_PROTOS extern "C" { -# define SEC_END_PROTOS } -#else -# define SEC_BEGIN_PROTOS -# define SEC_END_PROTOS -#endif - -#include - -#ifdef __APPLE__ - -#include - -/* - * Encode directly to/from SecAsn1Item. - * Avoid the need for SECItemStr.type; see SEC_ANS1_SIGNED_INT - * in secasn1t.h. - */ -typedef SecAsn1Item SECItem; -#else -/* Original NSS */ -typedef enum { - siBuffer = 0, - siClearDataBuffer = 1, - siCipherDataBuffer = 2, - siDERCertBuffer = 3, - siEncodedCertBuffer = 4, - siDERNameBuffer = 5, - siEncodedNameBuffer = 6, - siAsciiNameString = 7, - siAsciiString = 8, - siDEROID = 9, - siUnsignedInteger = 10, - siUTCTime = 11, - siGeneralizedTime = 12 -} SECItemType; - -typedef struct SECItemStr SECItem; - -struct SECItemStr { - SECItemType type; - unsigned char *data; - unsigned int len; -}; -#endif /* __APPLE__ */ - -/* -** A status code. Status's are used by procedures that return status -** values. Again the motivation is so that a compiler can generate -** warnings when return values are wrong. Correct testing of status codes: -** -** SECStatus rv; -** rv = some_function (some_argument); -** if (rv != SECSuccess) -** do_an_error_thing(); -** -*/ -typedef enum _SECStatus { - SECWouldBlock = -2, - SECFailure = -1, - SECSuccess = 0 -} SECStatus; - -/* -** A comparison code. Used for procedures that return comparision -** values. Again the motivation is so that a compiler can generate -** warnings when return values are wrong. -*/ -typedef enum _SECComparison { - SECLessThan = -1, - SECEqual = 0, - SECGreaterThan = 1 -} SECComparison; - -#endif /* _SECCOMMON_H_ */ diff --git a/OSX/include/security_asn1/secerr.h b/OSX/include/security_asn1/secerr.h deleted file mode 100644 index 21feb92f..00000000 --- a/OSX/include/security_asn1/secerr.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -#ifndef __SEC_ERR_H_ -#define __SEC_ERR_H_ - -#include - -PR_BEGIN_EXTERN_C - -#define SEC_ERROR_BASE (-0x2000) -#define SEC_ERROR_LIMIT (SEC_ERROR_BASE + 1000) - -#define IS_SEC_ERROR(code) \ - (((code) >= SEC_ERROR_BASE) && ((code) < SEC_ERROR_LIMIT)) - -#ifndef NO_SECURITY_ERROR_ENUM -typedef enum { -SEC_ERROR_IO = SEC_ERROR_BASE + 0, -SEC_ERROR_LIBRARY_FAILURE = SEC_ERROR_BASE + 1, -SEC_ERROR_BAD_DATA = SEC_ERROR_BASE + 2, -SEC_ERROR_OUTPUT_LEN = SEC_ERROR_BASE + 3, -SEC_ERROR_INPUT_LEN = SEC_ERROR_BASE + 4, -SEC_ERROR_INVALID_ARGS = SEC_ERROR_BASE + 5, -SEC_ERROR_INVALID_ALGORITHM = SEC_ERROR_BASE + 6, -SEC_ERROR_INVALID_AVA = SEC_ERROR_BASE + 7, -SEC_ERROR_INVALID_TIME = SEC_ERROR_BASE + 8, -SEC_ERROR_BAD_DER = SEC_ERROR_BASE + 9, -SEC_ERROR_BAD_SIGNATURE = SEC_ERROR_BASE + 10, -SEC_ERROR_EXPIRED_CERTIFICATE = SEC_ERROR_BASE + 11, -SEC_ERROR_REVOKED_CERTIFICATE = SEC_ERROR_BASE + 12, -SEC_ERROR_UNKNOWN_ISSUER = SEC_ERROR_BASE + 13, -SEC_ERROR_BAD_KEY = SEC_ERROR_BASE + 14, -SEC_ERROR_BAD_PASSWORD = SEC_ERROR_BASE + 15, -SEC_ERROR_RETRY_PASSWORD = SEC_ERROR_BASE + 16, -SEC_ERROR_NO_NODELOCK = SEC_ERROR_BASE + 17, -SEC_ERROR_BAD_DATABASE = SEC_ERROR_BASE + 18, -SEC_ERROR_NO_MEMORY = SEC_ERROR_BASE + 19, -SEC_ERROR_UNTRUSTED_ISSUER = SEC_ERROR_BASE + 20, -SEC_ERROR_UNTRUSTED_CERT = SEC_ERROR_BASE + 21, -SEC_ERROR_DUPLICATE_CERT = (SEC_ERROR_BASE + 22), -SEC_ERROR_DUPLICATE_CERT_NAME = (SEC_ERROR_BASE + 23), -SEC_ERROR_ADDING_CERT = (SEC_ERROR_BASE + 24), -SEC_ERROR_FILING_KEY = (SEC_ERROR_BASE + 25), -SEC_ERROR_NO_KEY = (SEC_ERROR_BASE + 26), -SEC_ERROR_CERT_VALID = (SEC_ERROR_BASE + 27), -SEC_ERROR_CERT_NOT_VALID = (SEC_ERROR_BASE + 28), -SEC_ERROR_CERT_NO_RESPONSE = (SEC_ERROR_BASE + 29), -SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE = (SEC_ERROR_BASE + 30), -SEC_ERROR_CRL_EXPIRED = (SEC_ERROR_BASE + 31), -SEC_ERROR_CRL_BAD_SIGNATURE = (SEC_ERROR_BASE + 32), -SEC_ERROR_CRL_INVALID = (SEC_ERROR_BASE + 33), -SEC_ERROR_EXTENSION_VALUE_INVALID = (SEC_ERROR_BASE + 34), -SEC_ERROR_EXTENSION_NOT_FOUND = (SEC_ERROR_BASE + 35), -SEC_ERROR_CA_CERT_INVALID = (SEC_ERROR_BASE + 36), -SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID = (SEC_ERROR_BASE + 37), -SEC_ERROR_CERT_USAGES_INVALID = (SEC_ERROR_BASE + 38), -SEC_INTERNAL_ONLY = (SEC_ERROR_BASE + 39), -SEC_ERROR_INVALID_KEY = (SEC_ERROR_BASE + 40), -SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION = (SEC_ERROR_BASE + 41), -SEC_ERROR_OLD_CRL = (SEC_ERROR_BASE + 42), -SEC_ERROR_NO_EMAIL_CERT = (SEC_ERROR_BASE + 43), -SEC_ERROR_NO_RECIPIENT_CERTS_QUERY = (SEC_ERROR_BASE + 44), -SEC_ERROR_NOT_A_RECIPIENT = (SEC_ERROR_BASE + 45), -SEC_ERROR_PKCS7_KEYALG_MISMATCH = (SEC_ERROR_BASE + 46), -SEC_ERROR_PKCS7_BAD_SIGNATURE = (SEC_ERROR_BASE + 47), -SEC_ERROR_UNSUPPORTED_KEYALG = (SEC_ERROR_BASE + 48), -SEC_ERROR_DECRYPTION_DISALLOWED = (SEC_ERROR_BASE + 49), -/* Fortezza Alerts */ -XP_SEC_FORTEZZA_BAD_CARD = (SEC_ERROR_BASE + 50), -XP_SEC_FORTEZZA_NO_CARD = (SEC_ERROR_BASE + 51), -XP_SEC_FORTEZZA_NONE_SELECTED = (SEC_ERROR_BASE + 52), -XP_SEC_FORTEZZA_MORE_INFO = (SEC_ERROR_BASE + 53), -XP_SEC_FORTEZZA_PERSON_NOT_FOUND = (SEC_ERROR_BASE + 54), -XP_SEC_FORTEZZA_NO_MORE_INFO = (SEC_ERROR_BASE + 55), -XP_SEC_FORTEZZA_BAD_PIN = (SEC_ERROR_BASE + 56), -XP_SEC_FORTEZZA_PERSON_ERROR = (SEC_ERROR_BASE + 57), -SEC_ERROR_NO_KRL = (SEC_ERROR_BASE + 58), -SEC_ERROR_KRL_EXPIRED = (SEC_ERROR_BASE + 59), -SEC_ERROR_KRL_BAD_SIGNATURE = (SEC_ERROR_BASE + 60), -SEC_ERROR_REVOKED_KEY = (SEC_ERROR_BASE + 61), -SEC_ERROR_KRL_INVALID = (SEC_ERROR_BASE + 62), -SEC_ERROR_NEED_RANDOM = (SEC_ERROR_BASE + 63), -SEC_ERROR_NO_MODULE = (SEC_ERROR_BASE + 64), -SEC_ERROR_NO_TOKEN = (SEC_ERROR_BASE + 65), -SEC_ERROR_READ_ONLY = (SEC_ERROR_BASE + 66), -SEC_ERROR_NO_SLOT_SELECTED = (SEC_ERROR_BASE + 67), -SEC_ERROR_CERT_NICKNAME_COLLISION = (SEC_ERROR_BASE + 68), -SEC_ERROR_KEY_NICKNAME_COLLISION = (SEC_ERROR_BASE + 69), -SEC_ERROR_SAFE_NOT_CREATED = (SEC_ERROR_BASE + 70), -SEC_ERROR_BAGGAGE_NOT_CREATED = (SEC_ERROR_BASE + 71), -XP_JAVA_REMOVE_PRINCIPAL_ERROR = (SEC_ERROR_BASE + 72), -XP_JAVA_DELETE_PRIVILEGE_ERROR = (SEC_ERROR_BASE + 73), -XP_JAVA_CERT_NOT_EXISTS_ERROR = (SEC_ERROR_BASE + 74), -SEC_ERROR_BAD_EXPORT_ALGORITHM = (SEC_ERROR_BASE + 75), -SEC_ERROR_EXPORTING_CERTIFICATES = (SEC_ERROR_BASE + 76), -SEC_ERROR_IMPORTING_CERTIFICATES = (SEC_ERROR_BASE + 77), -SEC_ERROR_PKCS12_DECODING_PFX = (SEC_ERROR_BASE + 78), -SEC_ERROR_PKCS12_INVALID_MAC = (SEC_ERROR_BASE + 79), -SEC_ERROR_PKCS12_UNSUPPORTED_MAC_ALGORITHM = (SEC_ERROR_BASE + 80), -SEC_ERROR_PKCS12_UNSUPPORTED_TRANSPORT_MODE = (SEC_ERROR_BASE + 81), -SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE = (SEC_ERROR_BASE + 82), -SEC_ERROR_PKCS12_UNSUPPORTED_PBE_ALGORITHM = (SEC_ERROR_BASE + 83), -SEC_ERROR_PKCS12_UNSUPPORTED_VERSION = (SEC_ERROR_BASE + 84), -SEC_ERROR_PKCS12_PRIVACY_PASSWORD_INCORRECT = (SEC_ERROR_BASE + 85), -SEC_ERROR_PKCS12_CERT_COLLISION = (SEC_ERROR_BASE + 86), -SEC_ERROR_USER_CANCELLED = (SEC_ERROR_BASE + 87), -SEC_ERROR_PKCS12_DUPLICATE_DATA = (SEC_ERROR_BASE + 88), -SEC_ERROR_MESSAGE_SEND_ABORTED = (SEC_ERROR_BASE + 89), -SEC_ERROR_INADEQUATE_KEY_USAGE = (SEC_ERROR_BASE + 90), -SEC_ERROR_INADEQUATE_CERT_TYPE = (SEC_ERROR_BASE + 91), -SEC_ERROR_CERT_ADDR_MISMATCH = (SEC_ERROR_BASE + 92), -SEC_ERROR_PKCS12_UNABLE_TO_IMPORT_KEY = (SEC_ERROR_BASE + 93), -SEC_ERROR_PKCS12_IMPORTING_CERT_CHAIN = (SEC_ERROR_BASE + 94), -SEC_ERROR_PKCS12_UNABLE_TO_LOCATE_OBJECT_BY_NAME = (SEC_ERROR_BASE + 95), -SEC_ERROR_PKCS12_UNABLE_TO_EXPORT_KEY = (SEC_ERROR_BASE + 96), -SEC_ERROR_PKCS12_UNABLE_TO_WRITE = (SEC_ERROR_BASE + 97), -SEC_ERROR_PKCS12_UNABLE_TO_READ = (SEC_ERROR_BASE + 98), -SEC_ERROR_PKCS12_KEY_DATABASE_NOT_INITIALIZED = (SEC_ERROR_BASE + 99), -SEC_ERROR_KEYGEN_FAIL = (SEC_ERROR_BASE + 100), -SEC_ERROR_INVALID_PASSWORD = (SEC_ERROR_BASE + 101), -SEC_ERROR_RETRY_OLD_PASSWORD = (SEC_ERROR_BASE + 102), -SEC_ERROR_BAD_NICKNAME = (SEC_ERROR_BASE + 103), -SEC_ERROR_NOT_FORTEZZA_ISSUER = (SEC_ERROR_BASE + 104), -SEC_ERROR_CANNOT_MOVE_SENSITIVE_KEY = (SEC_ERROR_BASE + 105), -SEC_ERROR_JS_INVALID_MODULE_NAME = (SEC_ERROR_BASE + 106), -SEC_ERROR_JS_INVALID_DLL = (SEC_ERROR_BASE + 107), -SEC_ERROR_JS_ADD_MOD_FAILURE = (SEC_ERROR_BASE + 108), -SEC_ERROR_JS_DEL_MOD_FAILURE = (SEC_ERROR_BASE + 109), -SEC_ERROR_OLD_KRL = (SEC_ERROR_BASE + 110), -SEC_ERROR_CKL_CONFLICT = (SEC_ERROR_BASE + 111), -SEC_ERROR_CERT_NOT_IN_NAME_SPACE = (SEC_ERROR_BASE + 112), -SEC_ERROR_KRL_NOT_YET_VALID = (SEC_ERROR_BASE + 113), -SEC_ERROR_CRL_NOT_YET_VALID = (SEC_ERROR_BASE + 114), -SEC_ERROR_UNKNOWN_CERT = (SEC_ERROR_BASE + 115), -SEC_ERROR_UNKNOWN_SIGNER = (SEC_ERROR_BASE + 116), -SEC_ERROR_CERT_BAD_ACCESS_LOCATION = (SEC_ERROR_BASE + 117), -SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE = (SEC_ERROR_BASE + 118), -SEC_ERROR_OCSP_BAD_HTTP_RESPONSE = (SEC_ERROR_BASE + 119), -SEC_ERROR_OCSP_MALFORMED_REQUEST = (SEC_ERROR_BASE + 120), -SEC_ERROR_OCSP_SERVER_ERROR = (SEC_ERROR_BASE + 121), -SEC_ERROR_OCSP_TRY_SERVER_LATER = (SEC_ERROR_BASE + 122), -SEC_ERROR_OCSP_REQUEST_NEEDS_SIG = (SEC_ERROR_BASE + 123), -SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST = (SEC_ERROR_BASE + 124), -SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS = (SEC_ERROR_BASE + 125), -SEC_ERROR_OCSP_UNKNOWN_CERT = (SEC_ERROR_BASE + 126), -SEC_ERROR_OCSP_NOT_ENABLED = (SEC_ERROR_BASE + 127), -SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER = (SEC_ERROR_BASE + 128), -SEC_ERROR_OCSP_MALFORMED_RESPONSE = (SEC_ERROR_BASE + 129), -SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE = (SEC_ERROR_BASE + 130), -SEC_ERROR_OCSP_FUTURE_RESPONSE = (SEC_ERROR_BASE + 131), -SEC_ERROR_OCSP_OLD_RESPONSE = (SEC_ERROR_BASE + 132), -/* smime stuff */ -SEC_ERROR_DIGEST_NOT_FOUND = (SEC_ERROR_BASE + 133), -SEC_ERROR_UNSUPPORTED_MESSAGE_TYPE = (SEC_ERROR_BASE + 134), -SEC_ERROR_MODULE_STUCK = (SEC_ERROR_BASE + 135), -SEC_ERROR_BAD_TEMPLATE = (SEC_ERROR_BASE + 136), -SEC_ERROR_CRL_NOT_FOUND = (SEC_ERROR_BASE + 137), -SEC_ERROR_REUSED_ISSUER_AND_SERIAL = (SEC_ERROR_BASE + 138), -SEC_ERROR_BUSY = (SEC_ERROR_BASE + 139), -SEC_ERROR_NO_USER_INTERACTION = (SEC_ERROR_BASE + 140) -} SECErrorCodes; -#endif /* NO_SECURITY_ERROR_ENUM */ - -#ifdef __APPLE__ -/* - * Given a PRErrorCode, obtain a const C string. Not copied, not - * to be freed by caller. - */ -const char *SECErrorString(PRErrorCode err); - -#endif /* __APPLE__ */ - -PR_END_EXTERN_C - -#endif /* __SEC_ERR_H_ */ diff --git a/OSX/include/security_asn1/secport.c b/OSX/include/security_asn1/secport.c deleted file mode 100644 index 0d19a32d..00000000 --- a/OSX/include/security_asn1/secport.c +++ /dev/null @@ -1,669 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * secport.c - portability interfaces for security libraries - * - * This file abstracts out libc functionality that libsec depends on - * - * NOTE - These are not public interfaces - * - * $Id: secport.c,v 1.5 2004/10/27 20:36:36 dmitch Exp $ - */ - -#include "seccomon.h" -#include "prmem.h" -#include "prerror.h" -#include "plarena.h" -#include "secerr.h" -#include "prmon.h" -#include "nsslocks.h" -#include "secport.h" -#include "prvrsion.h" -#include "prenv.h" - -#ifdef DEBUG -//#define THREADMARK -#endif /* DEBUG */ - -#ifdef THREADMARK -#include "prthread.h" -#endif /* THREADMARK */ - -#if defined(XP_UNIX) || defined(XP_MAC) || defined(XP_OS2) || defined(XP_BEOS) -#include -#else -#include "wtypes.h" -#endif - -#define SET_ERROR_CODE /* place holder for code to set PR error code. */ - -#ifdef THREADMARK -typedef struct threadmark_mark_str { - struct threadmark_mark_str *next; - void *mark; -} threadmark_mark; - -#endif /* THREADMARK */ - -/* The value of this magic must change each time PORTArenaPool changes. */ -#define ARENAPOOL_MAGIC 0xB8AC9BDF - -/* enable/disable mutex in PORTArenaPool */ -#define ARENA_POOL_LOCK 0 - -typedef struct PORTArenaPool_str { - PLArenaPool arena; - PRUint32 magic; - #if ARENA_POOL_LOCK - PRLock * lock; - #endif -#ifdef THREADMARK - PRThread *marking_thread; - threadmark_mark *first_mark; -#endif -} PORTArenaPool; - - -/* count of allocation failures. */ -unsigned long port_allocFailures; - -#ifndef __APPLE__ -/* locations for registering Unicode conversion functions. - * XXX is this the appropriate location? or should they be - * moved to client/server specific locations? - */ -PORTCharConversionFunc ucs4Utf8ConvertFunc; -PORTCharConversionFunc ucs2Utf8ConvertFunc; -PORTCharConversionWSwapFunc ucs2AsciiConvertFunc; -#endif /* __APPLE__ */ - -/* NSPR memory allocation functions (PR_Malloc, PR_Calloc, and PR_Realloc) - * use the PRUint32 type for the size parameter. Before we pass a size_t or - * unsigned long size to these functions, we need to ensure it is <= half of - * the maximum PRUint32 value to avoid truncation and catch a negative size. - */ -#define MAX_SIZE (PR_UINT32_MAX >> 1) - -void * -PORT_Alloc(size_t bytes) -{ - void *rv = NULL; - - if (bytes <= MAX_SIZE) { - /* Always allocate a non-zero amount of bytes */ - rv = PR_Malloc(bytes ? bytes : 1); - } - if (!rv) { - ++port_allocFailures; - PORT_SetError(SEC_ERROR_NO_MEMORY); - } - return rv; -} - -void * -PORT_Realloc(void *oldptr, size_t bytes) -{ - void *rv = NULL; - - if (bytes <= MAX_SIZE) { - rv = PR_Realloc(oldptr, bytes); - } - if (!rv) { - ++port_allocFailures; - PORT_SetError(SEC_ERROR_NO_MEMORY); - } - return rv; -} - -void * -PORT_ZAlloc(size_t bytes) -{ - void *rv = NULL; - - if (bytes <= MAX_SIZE) { - /* Always allocate a non-zero amount of bytes */ - rv = PR_Calloc(1, bytes ? bytes : 1); - } - if (!rv) { - ++port_allocFailures; - PORT_SetError(SEC_ERROR_NO_MEMORY); - } - return rv; -} - -void -PORT_Free(void *ptr) -{ - if (ptr) { - PR_Free(ptr); - } -} - -void -PORT_ZFree(void *ptr, size_t len) -{ - if (ptr) { - memset(ptr, 0, len); - PR_Free(ptr); - } -} - -char * -PORT_Strdup(const char *str) -{ - size_t len = PORT_Strlen(str)+1; - char *newstr; - - newstr = (char *)PORT_Alloc(len); - if (newstr) { - PORT_Memcpy(newstr, str, len); - } - return newstr; -} - -void -PORT_SetError(int value) -{ - PR_SetError(value, 0); - return; -} - -int -PORT_GetError(void) -{ - return(PR_GetError()); -} - -/********************* Arena code follows *****************************/ - -PLArenaPool * -PORT_NewArena(unsigned long chunksize) -{ - PORTArenaPool *pool; - - if (chunksize > MAX_SIZE) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return NULL; - } - pool = PORT_ZNew(PORTArenaPool); - if (!pool) { - return NULL; - } - pool->magic = ARENAPOOL_MAGIC; - #if ARENA_POOL_LOCK - pool->lock = PZ_NewLock(nssILockArena); - if (!pool->lock) { - ++port_allocFailures; - PORT_Free(pool); - return NULL; - } - #endif - PL_InitArenaPool(&pool->arena, "security", (PRUint32)chunksize, sizeof(double)); - return(&pool->arena); -} - -void * -PORT_ArenaAlloc(PLArenaPool *arena, size_t size) -{ - void *p = NULL; - - PORTArenaPool *pool = (PORTArenaPool *)arena; - - if (size <= 0) { - size = 1; - } - - if (size > MAX_SIZE) { - /* you lose. */ - } else - /* Is it one of ours? Assume so and check the magic */ - if (ARENAPOOL_MAGIC == pool->magic ) { - #if ARENA_POOL_LOCK - PZ_Lock(pool->lock); - #ifdef THREADMARK - /* Most likely one of ours. Is there a thread id? */ - if (pool->marking_thread && - pool->marking_thread != PR_GetCurrentThread() ) { - /* Another thread holds a mark in this arena */ - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - PORT_Assert(0); - return NULL; - } /* tid != null */ - #endif /* THREADMARK */ - #endif /* ARENA_POOL_LOCK */ - PL_ARENA_ALLOCATE(p, arena, (PRUint32)size); - #if ARENA_POOL_LOCK - PZ_Unlock(pool->lock); - #endif - } else { - PL_ARENA_ALLOCATE(p, arena, (PRUint32)size); - } - - if (!p) { - ++port_allocFailures; - PORT_SetError(SEC_ERROR_NO_MEMORY); - } - - return(p); -} - -void * -PORT_ArenaZAlloc(PLArenaPool *arena, size_t size) -{ - void *p; - - if (size <= 0) - size = 1; - - p = PORT_ArenaAlloc(arena, size); - - if (p) { - PORT_Memset(p, 0, size); - } - - return(p); -} - -/* - * If zero is true, zeroize the arena memory before freeing it. - */ -void -PORT_FreeArena(PLArenaPool *arena, PRBool zero) -{ - PORTArenaPool *pool = (PORTArenaPool *)arena; - #if ARENA_POOL_LOCK - PRLock * lock = (PRLock *)0; - #endif - size_t len = sizeof *arena; - extern const PRVersionDescription * libVersionPoint(void); - #ifndef __APPLE__ - static const PRVersionDescription * pvd; - #endif - static PRBool doFreeArenaPool = PR_FALSE; - - if (ARENAPOOL_MAGIC == pool->magic ) { - len = sizeof *pool; - #if ARENA_POOL_LOCK - lock = pool->lock; - PZ_Lock(lock); - #endif - } - #ifndef __APPLE__ - /* dmitch - not needed */ - if (!pvd) { - /* Each of NSPR's DLLs has a function libVersionPoint(). - ** We could do a lot of extra work to be sure we're calling the - ** one in the DLL that holds PR_FreeArenaPool, but instead we - ** rely on the fact that ALL NSPR DLLs in the same directory - ** must be from the same release, and we call which ever one we get. - */ - /* no need for thread protection here */ - pvd = libVersionPoint(); - if ((pvd->vMajor > 4) || - (pvd->vMajor == 4 && pvd->vMinor > 1) || - (pvd->vMajor == 4 && pvd->vMinor == 1 && pvd->vPatch >= 1)) { - const char *ev = PR_GetEnv("NSS_DISABLE_ARENA_FREE_LIST"); - if (!ev) doFreeArenaPool = PR_TRUE; - } - } - #endif - if (zero) { - PL_ClearArenaPool(arena, 0); - } - - if (doFreeArenaPool) { - PL_FreeArenaPool(arena); - } else { - PL_FinishArenaPool(arena); - } - #if ARENA_POOL_LOCK - if (lock) { - PZ_Unlock(lock); - PZ_DestroyLock(lock); - } - #endif - PORT_ZFree(arena, len); -} - -void * -PORT_ArenaGrow(PLArenaPool *arena, void *ptr, size_t oldsize, size_t newsize) -{ - PORTArenaPool *pool = (PORTArenaPool *)arena; - - if (newsize > MAX_SIZE) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return NULL; - } -#ifdef __APPLE__ - if (newsize < oldsize) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); // Not expected - return NULL; - } -#endif - if (ARENAPOOL_MAGIC == pool->magic ) { - #if ARENA_POOL_LOCK - PZ_Lock(pool->lock); - #endif - /* Do we do a THREADMARK check here? */ - PL_ARENA_GROW(ptr, arena, (PRUint32)oldsize, (PRUint32)( newsize - oldsize ) ); - #if ARENA_POOL_LOCK - PZ_Unlock(pool->lock); - #endif - } else { - PL_ARENA_GROW(ptr, arena, (PRUint32)oldsize, (PRUint32)( newsize - oldsize ) ); - } - - return(ptr); -} - -void * -PORT_ArenaMark(PLArenaPool *arena) -{ -#if ARENA_MARK_ENABLE - void * result; - - PORTArenaPool *pool = (PORTArenaPool *)arena; - if (ARENAPOOL_MAGIC == pool->magic ) { - PZ_Lock(pool->lock); -#ifdef THREADMARK - { - threadmark_mark *tm, **pw; - PRThread * currentThread = PR_GetCurrentThread(); - - if (! pool->marking_thread ) { - /* First mark */ - pool->marking_thread = currentThread; - } else if (currentThread != pool->marking_thread ) { - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - PORT_Assert(0); - return NULL; - } - - result = PL_ARENA_MARK(arena); - PL_ARENA_ALLOCATE(tm, arena, sizeof(threadmark_mark)); - if (!tm) { - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - return NULL; - } - - tm->mark = result; - tm->next = (threadmark_mark *)NULL; - - pw = &pool->first_mark; - while( *pw ) { - pw = &(*pw)->next; - } - - *pw = tm; - } -#else /* THREADMARK */ - result = PL_ARENA_MARK(arena); -#endif /* THREADMARK */ - PZ_Unlock(pool->lock); - } else { - /* a "pure" NSPR arena */ - result = PL_ARENA_MARK(arena); - } - return result; -#else - /* Some code in libsecurity_smime really checks for a nonzero - * return here, so... */ - return (void *)-1; -#endif -} - -void -PORT_ArenaRelease(PLArenaPool *arena, void *mark) -{ -#if ARENA_MARK_ENABLE - PORTArenaPool *pool = (PORTArenaPool *)arena; - if (ARENAPOOL_MAGIC == pool->magic ) { - PZ_Lock(pool->lock); -#ifdef THREADMARK - { - threadmark_mark **pw, *tm; - - if (PR_GetCurrentThread() != pool->marking_thread ) { - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - PORT_Assert(0); - return /* no error indication available */ ; - } - - pw = &pool->first_mark; - while( *pw && (mark != (*pw)->mark) ) { - pw = &(*pw)->next; - } - - if (! *pw ) { - /* bad mark */ - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - PORT_Assert(0); - return /* no error indication available */ ; - } - - tm = *pw; - *pw = (threadmark_mark *)NULL; - - PL_ARENA_RELEASE(arena, mark); - - if (! pool->first_mark ) { - pool->marking_thread = (PRThread *)NULL; - } - } -#else /* THREADMARK */ - PL_ARENA_RELEASE(arena, mark); -#endif /* THREADMARK */ - PZ_Unlock(pool->lock); - } else { - PL_ARENA_RELEASE(arena, mark); - } -#endif /* ARENA_MARK_ENABLE */ -} - -void -PORT_ArenaUnmark(PLArenaPool *arena, void *mark) -{ -#if ARENA_MARK_ENABLE -#ifdef THREADMARK - PORTArenaPool *pool = (PORTArenaPool *)arena; - if (ARENAPOOL_MAGIC == pool->magic ) { - threadmark_mark **pw, *tm; - - PZ_Lock(pool->lock); - - if (PR_GetCurrentThread() != pool->marking_thread ) { - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - PORT_Assert(0); - return /* no error indication available */ ; - } - - pw = &pool->first_mark; - while( ((threadmark_mark *)NULL != *pw) && (mark != (*pw)->mark) ) { - pw = &(*pw)->next; - } - - if ((threadmark_mark *)NULL == *pw ) { - /* bad mark */ - PZ_Unlock(pool->lock); - PORT_SetError(SEC_ERROR_NO_MEMORY); - PORT_Assert(0); - return /* no error indication available */ ; - } - - tm = *pw; - *pw = (threadmark_mark *)NULL; - - if (! pool->first_mark ) { - pool->marking_thread = (PRThread *)NULL; - } - - PZ_Unlock(pool->lock); - } -#endif /* THREADMARK */ -#endif /* ARENA_MARK_ENABLE */ -} - -char * -PORT_ArenaStrdup(PLArenaPool *arena, const char *str) { - size_t len = PORT_Strlen(str)+1; - char *newstr; - - newstr = (char*)PORT_ArenaAlloc(arena,len); - if (newstr) { - PORT_Memcpy(newstr,str,len); - } - return newstr; -} - -/********************** end of arena functions ***********************/ - -#ifndef __APPLE__ - -/****************** unicode conversion functions ***********************/ -/* - * NOTE: These conversion functions all assume that the multibyte - * characters are going to be in NETWORK BYTE ORDER, not host byte - * order. This is because the only time we deal with UCS-2 and UCS-4 - * are when the data was received from or is going to be sent out - * over the wire (in, e.g. certificates). - */ - -void -PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc) -{ - ucs4Utf8ConvertFunc = convFunc; -} - -void -PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc) -{ - ucs2AsciiConvertFunc = convFunc; -} - -void -PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc) -{ - ucs2Utf8ConvertFunc = convFunc; -} - -//#ifndef __APPLE__ -/* dmitch - not needed */ -PRBool -PORT_UCS4_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf, - unsigned int inBufLen, unsigned char *outBuf, - unsigned int maxOutBufLen, unsigned int *outBufLen) -{ - if(!ucs4Utf8ConvertFunc) { - return sec_port_ucs4_utf8_conversion_function(toUnicode, - inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen); - } - - return (*ucs4Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf, - maxOutBufLen, outBufLen); -} - -PRBool -PORT_UCS2_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf, - unsigned int inBufLen, unsigned char *outBuf, - unsigned int maxOutBufLen, unsigned int *outBufLen) -{ - if(!ucs2Utf8ConvertFunc) { - return sec_port_ucs2_utf8_conversion_function(toUnicode, - inBuf, inBufLen, outBuf, maxOutBufLen, outBufLen); - } - - return (*ucs2Utf8ConvertFunc)(toUnicode, inBuf, inBufLen, outBuf, - maxOutBufLen, outBufLen); -} -//#endif /* __APPLE__ */ - -PRBool -PORT_UCS2_ASCIIConversion(PRBool toUnicode, unsigned char *inBuf, - unsigned int inBufLen, unsigned char *outBuf, - unsigned int maxOutBufLen, unsigned int *outBufLen, - PRBool swapBytes) -{ - if(!ucs2AsciiConvertFunc) { - return PR_FALSE; - } - - return (*ucs2AsciiConvertFunc)(toUnicode, inBuf, inBufLen, outBuf, - maxOutBufLen, outBufLen, swapBytes); -} - - -/* Portable putenv. Creates/replaces an environment variable of the form - * envVarName=envValue - */ -int -NSS_PutEnv(const char * envVarName, const char * envValue) -{ -#if defined(XP_MAC) || defined(_WIN32_WCE) - return SECFailure; -#else - SECStatus result = SECSuccess; - char * encoded; - int putEnvFailed; -#ifdef _WIN32 - PRBool setOK; - - setOK = SetEnvironmentVariable(envVarName, envValue); - if (!setOK) { - SET_ERROR_CODE - return SECFailure; - } -#endif - - encoded = (char *)PORT_ZAlloc(strlen(envVarName) + 2 + strlen(envValue)); - strcpy(encoded, envVarName); - strcat(encoded, "="); - strcat(encoded, envValue); - - putEnvFailed = putenv(encoded); /* adopt. */ - if (putEnvFailed) { - SET_ERROR_CODE - result = SECFailure; - PORT_Free(encoded); - } - return result; -#endif -} -#endif /* __APPLE__ */ - diff --git a/OSX/include/security_asn1/secport.h b/OSX/include/security_asn1/secport.h deleted file mode 100644 index 373cf0b4..00000000 --- a/OSX/include/security_asn1/secport.h +++ /dev/null @@ -1,290 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * secport.h - portability interfaces for security libraries - * - * This file abstracts out libc functionality that libsec depends on - * - * NOTE - These are not public interfaces - * - * $Id: secport.h,v 1.3 2004/10/22 19:11:36 dmitch Exp $ - */ - -#ifndef _SECPORT_H_ -#define _SECPORT_H_ - -/* - * define XP_MAC, XP_WIN, XP_BEOS, or XP_UNIX, in case they are not defined - * by anyone else - */ -#ifdef macintosh -# ifndef XP_MAC -# define XP_MAC 1 -# endif -#endif - -#ifdef _WINDOWS -# ifndef XP_WIN -# define XP_WIN -# endif -#if defined(_WIN32) || defined(WIN32) -# ifndef XP_WIN32 -# define XP_WIN32 -# endif -#else -# ifndef XP_WIN16 -# define XP_WIN16 -# endif -#endif -#endif - -#ifdef __BEOS__ -# ifndef XP_BEOS -# define XP_BEOS -# endif -#endif - -#ifdef unix -# ifndef XP_UNIX -# define XP_UNIX -# endif -#endif - -#if defined(__WATCOMC__) || defined(__WATCOM_CPLUSPLUS__) -#include "watcomfx.h" -#endif - -#if defined(_WIN32_WCE) -#include -#include -#elif defined( XP_MAC ) -#include -#include /* for time_t below */ -#else -#include -#endif - -#ifdef notdef -#ifdef XP_MAC -#include "NSString.h" -#endif -#endif - -#include -#include -#if defined(_WIN32_WCE) -#include /* WinCE puts some stddef symbols here. */ -#else -#include -#endif -#include -#include "prtypes.h" -#include "prlog.h" /* for PR_ASSERT */ -#include "plarenas.h" -#include "plstr.h" - -/* - * HACK for NSS 2.8 to allow Admin to compile without source changes. - */ -#ifndef SEC_BEGIN_PROTOS -#include "seccomon.h" -#endif - -SEC_BEGIN_PROTOS - -extern void *PORT_Alloc(size_t len); -extern void *PORT_Realloc(void *old, size_t len); -extern void *PORT_AllocBlock(size_t len); -extern void *PORT_ReallocBlock(void *old, size_t len); -extern void PORT_FreeBlock(void *ptr); -extern void *PORT_ZAlloc(size_t len); -extern void PORT_Free(void *ptr); -extern void PORT_ZFree(void *ptr, size_t len); -extern time_t PORT_Time(void); -extern void PORT_SetError(int value); -extern int PORT_GetError(void); - -extern PLArenaPool *PORT_NewArena(unsigned long chunksize); -extern void *PORT_ArenaAlloc(PLArenaPool *arena, size_t size); -extern void *PORT_ArenaZAlloc(PLArenaPool *arena, size_t size); -extern void PORT_FreeArena(PLArenaPool *arena, PRBool zero); -extern void *PORT_ArenaGrow(PLArenaPool *arena, void *ptr, - size_t oldsize, size_t newsize); -extern void *PORT_ArenaMark(PLArenaPool *arena); -extern void PORT_ArenaRelease(PLArenaPool *arena, void *mark); -extern void PORT_ArenaUnmark(PLArenaPool *arena, void *mark); - -extern char *PORT_ArenaStrdup(PLArenaPool *arena, const char *str); - -#ifdef __cplusplus -} -#endif - -#define PORT_Assert PR_ASSERT -#define PORT_ZNew(type) (type*)PORT_ZAlloc(sizeof(type)) -#define PORT_New(type) (type*)PORT_Alloc(sizeof(type)) -#define PORT_ArenaNew(poolp, type) \ - (type*) PORT_ArenaAlloc(poolp, sizeof(type)) -#define PORT_ArenaZNew(poolp, type) \ - (type*) PORT_ArenaZAlloc(poolp, sizeof(type)) -#define PORT_NewArray(type, num) \ - (type*) PORT_Alloc (sizeof(type)*(num)) -#define PORT_ZNewArray(type, num) \ - (type*) PORT_ZAlloc (sizeof(type)*(num)) -#define PORT_ArenaNewArray(poolp, type, num) \ - (type*) PORT_ArenaAlloc (poolp, sizeof(type)*(num)) -#define PORT_ArenaZNewArray(poolp, type, num) \ - (type*) PORT_ArenaZAlloc (poolp, sizeof(type)*(num)) - -/* Please, keep these defines sorted alphbetically. Thanks! */ - -#ifdef XP_STRING_FUNCS - -#define PORT_Atoi XP_ATOI - -#define PORT_Memcmp XP_MEMCMP -#define PORT_Memcpy XP_MEMCPY -#define PORT_Memmove XP_MEMMOVE -#define PORT_Memset XP_MEMSET - -#define PORT_Strcasecmp XP_STRCASECMP -#define PORT_Strcat XP_STRCAT -#define PORT_Strchr XP_STRCHR -#define PORT_Strrchr XP_STRRCHR -#define PORT_Strcmp XP_STRCMP -#define PORT_Strcpy XP_STRCPY -#define PORT_Strdup XP_STRDUP -#define PORT_Strlen(s) XP_STRLEN(s) -#define PORT_Strncasecmp XP_STRNCASECMP -#define PORT_Strncat strncat -#define PORT_Strncmp XP_STRNCMP -#define PORT_Strncpy strncpy -#define PORT_Strstr XP_STRSTR -#define PORT_Strtok XP_STRTOK_R - -#define PORT_Tolower XP_TO_LOWER - -#else /* XP_STRING_FUNCS */ - -#define PORT_Atoi atoi - -#define PORT_Memcmp memcmp -#define PORT_Memcpy memcpy -#ifndef SUNOS4 -#define PORT_Memmove memmove -#else /*SUNOS4*/ -#define PORT_Memmove(s,ct,n) bcopy ((ct), (s), (n)) -#endif/*SUNOS4*/ -#define PORT_Memset memset - -#define PORT_Strcasecmp PL_strcasecmp -#define PORT_Strcat strcat -#define PORT_Strchr strchr -#define PORT_Strrchr strrchr -#define PORT_Strcmp strcmp -#define PORT_Strcpy strcpy -extern char *PORT_Strdup(const char *s); -#define PORT_Strlen(s) strlen(s) -#define PORT_Strncasecmp PL_strncasecmp -#define PORT_Strncat strncat -#define PORT_Strncmp strncmp -#define PORT_Strncpy strncpy -#define PORT_Strstr strstr -#define PORT_Strtok strtok - -#define PORT_Tolower tolower - -#endif /* XP_STRING_FUNCS */ - -#ifndef __APPLE__ - -typedef PRBool (PR_CALLBACK * PORTCharConversionWSwapFunc) (PRBool toUnicode, - unsigned char *inBuf, unsigned int inBufLen, - unsigned char *outBuf, unsigned int maxOutBufLen, - unsigned int *outBufLen, PRBool swapBytes); - -typedef PRBool (PR_CALLBACK * PORTCharConversionFunc) (PRBool toUnicode, - unsigned char *inBuf, unsigned int inBufLen, - unsigned char *outBuf, unsigned int maxOutBufLen, - unsigned int *outBufLen); - -#ifdef __cplusplus -extern "C" { -#endif - -void PORT_SetUCS4_UTF8ConversionFunction(PORTCharConversionFunc convFunc); -void PORT_SetUCS2_ASCIIConversionFunction(PORTCharConversionWSwapFunc convFunc); -PRBool PORT_UCS4_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf, - unsigned int inBufLen, unsigned char *outBuf, - unsigned int maxOutBufLen, unsigned int *outBufLen); -PRBool PORT_UCS2_ASCIIConversion(PRBool toUnicode, unsigned char *inBuf, - unsigned int inBufLen, unsigned char *outBuf, - unsigned int maxOutBufLen, unsigned int *outBufLen, - PRBool swapBytes); -void PORT_SetUCS2_UTF8ConversionFunction(PORTCharConversionFunc convFunc); -PRBool PORT_UCS2_UTF8Conversion(PRBool toUnicode, unsigned char *inBuf, - unsigned int inBufLen, unsigned char *outBuf, - unsigned int maxOutBufLen, unsigned int *outBufLen); - -PR_EXTERN(PRBool) -sec_port_ucs4_utf8_conversion_function -( - PRBool toUnicode, - unsigned char *inBuf, - unsigned int inBufLen, - unsigned char *outBuf, - unsigned int maxOutBufLen, - unsigned int *outBufLen -); - -PR_EXTERN(PRBool) -sec_port_ucs2_utf8_conversion_function -( - PRBool toUnicode, - unsigned char *inBuf, - unsigned int inBufLen, - unsigned char *outBuf, - unsigned int maxOutBufLen, - unsigned int *outBufLen -); - -extern int NSS_PutEnv(const char * envVarName, const char * envValue); - -#ifdef __cplusplus -} -#endif - -#endif /* __APPLE__ */ - -#endif /* _SECPORT_H_ */ diff --git a/OSX/include/security_asn1/security_asn1.exp b/OSX/include/security_asn1/security_asn1.exp deleted file mode 100644 index 599c680c..00000000 --- a/OSX/include/security_asn1/security_asn1.exp +++ /dev/null @@ -1,166 +0,0 @@ -_SecAsn1AllocCopy -_SecAsn1AllocCopyItem -_SecAsn1AllocItem -_SecAsn1CoderCreate -_SecAsn1CoderRelease -_SecAsn1Decode -_SecAsn1DecodeData -_SecAsn1EncodeItem -_SecAsn1Malloc -_kSecAsn1AnyTemplate -_kSecAsn1BMPStringTemplate -_kSecAsn1BitStringTemplate -_kSecAsn1BooleanTemplate -_kSecAsn1EnumeratedTemplate -_kSecAsn1GeneralizedTimeTemplate -_kSecAsn1IA5StringTemplate -_kSecAsn1IntegerTemplate -_kSecAsn1NullTemplate -_kSecAsn1ObjectIDTemplate -_kSecAsn1OctetStringTemplate -_kSecAsn1PointerToAnyTemplate -_kSecAsn1PointerToBMPStringTemplate -_kSecAsn1PointerToBitStringTemplate -_kSecAsn1PointerToBooleanTemplate -_kSecAsn1PointerToEnumeratedTemplate -_kSecAsn1PointerToGeneralizedTimeTemplate -_kSecAsn1PointerToIA5StringTemplate -_kSecAsn1PointerToIntegerTemplate -_kSecAsn1PointerToNullTemplate -_kSecAsn1PointerToObjectIDTemplate -_kSecAsn1PointerToOctetStringTemplate -_kSecAsn1PointerToPrintableStringTemplate -_kSecAsn1PointerToT61StringTemplate -_kSecAsn1PointerToTeletexStringTemplate -_kSecAsn1PointerToUTCTimeTemplate -_kSecAsn1PointerToUTF8StringTemplate -_kSecAsn1PointerToUniversalStringTemplate -_kSecAsn1PointerToVisibleStringTemplate -_kSecAsn1PrintableStringTemplate -_kSecAsn1SequenceOfAnyTemplate -_kSecAsn1SequenceOfBMPStringTemplate -_kSecAsn1SequenceOfBitStringTemplate -_kSecAsn1SequenceOfBooleanTemplate -_kSecAsn1SequenceOfEnumeratedTemplate -_kSecAsn1SequenceOfGeneralizedTimeTemplate -_kSecAsn1SequenceOfIA5StringTemplate -_kSecAsn1SequenceOfIntegerTemplate -_kSecAsn1SequenceOfNullTemplate -_kSecAsn1SequenceOfObjectIDTemplate -_kSecAsn1SequenceOfOctetStringTemplate -_kSecAsn1SequenceOfPrintableStringTemplate -_kSecAsn1SequenceOfT61StringTemplate -_kSecAsn1SequenceOfTeletexStringTemplate -_kSecAsn1SequenceOfUTCTimeTemplate -_kSecAsn1SequenceOfUTF8StringTemplate -_kSecAsn1SequenceOfUniversalStringTemplate -_kSecAsn1SequenceOfVisibleStringTemplate -_kSecAsn1SetOfAnyTemplate -_kSecAsn1SetOfBMPStringTemplate -_kSecAsn1SetOfBitStringTemplate -_kSecAsn1SetOfBooleanTemplate -_kSecAsn1SetOfEnumeratedTemplate -_kSecAsn1SetOfGeneralizedTimeTemplate -_kSecAsn1SetOfIA5StringTemplate -_kSecAsn1SetOfIntegerTemplate -_kSecAsn1SetOfNullTemplate -_kSecAsn1SetOfObjectIDTemplate -_kSecAsn1SetOfOctetStringTemplate -_kSecAsn1SetOfPrintableStringTemplate -_kSecAsn1SetOfT61StringTemplate -_kSecAsn1SetOfTeletexStringTemplate -_kSecAsn1SetOfUTCTimeTemplate -_kSecAsn1SetOfUTF8StringTemplate -_kSecAsn1SetOfUniversalStringTemplate -_kSecAsn1SetOfVisibleStringTemplate -_kSecAsn1SkipTemplate -_kSecAsn1T61StringTemplate -_kSecAsn1TeletexStringTemplate -_kSecAsn1UTCTimeTemplate -_kSecAsn1UTF8StringTemplate -_kSecAsn1UniversalStringTemplate -_kSecAsn1UnsignedIntegerTemplate -_kSecAsn1VisibleStringTemplate -_kSecAsn1CertExtensionTemplate -_kSecAsn1RevokedCertTemplate -_kSecAsn1SequenceOfCertExtensionTemplate -_kSecAsn1SequenceOfRevokedCertTemplate -_kSecAsn1SignedCertOrCRLTemplate -_kSecAsn1SignedCertTemplate -_kSecAsn1SignedCrlTemplate -_kSecAsn1TBSCertificateTemplate -_kSecAsn1TBSCrlTemplate -_kSecAsn1ValidityTemplate -_kSecAsn1AccessDescriptionTemplate -_kSecAsn1AuthorityInfoAccessTemplate -_kSecAsn1AuthorityKeyIdTemplate -_kSecAsn1BasicConstraintsTemplate -_kSecAsn1CRLDistributionPointsTemplate -_kSecAsn1CertPoliciesTemplate -_kSecAsn1DistPointFullNameTemplate -_kSecAsn1DistPointRDNTemplate -_kSecAsn1DistributionPointTemplate -_kSecAsn1IssuingDistributionPointTemplate -_kSecAsn1PolicyInformationTemplate -_kSecAsn1PolicyQualifierTemplate -_kSecAsn1CertRequestInfoTemplate -_kSecAsn1CertRequestTemplate -_kSecAsn1SignedCertRequestTemplate -_kSecAsn1AlgorithmIDTemplate -_kSecAsn1AttributeTemplate -_kSecAsn1DHAlgorithmIdentifierX942Template -_kSecAsn1DHDomainParamsX942Template -_kSecAsn1DHParameterBlockTemplate -_kSecAsn1DHParameterTemplate -_kSecAsn1DHPrivateKeyPKCS8Template -_kSecAsn1DHPrivateKeyTemplate -_kSecAsn1DHPublicKeyX509Template -_kSecAsn1DHValidationParamsTemplate -_kSecAsn1DigestInfoTemplate -_kSecAsn1EncryptedPrivateKeyInfoTemplate -_kSecAsn1PrivateKeyInfoTemplate -_kSecAsn1RSAPrivateKeyPKCS1Template -_kSecAsn1RSAPublicKeyPKCS1Template -_kSecAsn1SetOfAttributeTemplate -_kSecAsn1SubjectPublicKeyInfoTemplate -_kSecAsn1ATVTemplate -_kSecAsn1GenNameOtherNameTemplate -_kSecAsn1GeneralNameTemplate -_kSecAsn1NameTemplate -_kSecAsn1OtherNameTemplate -_kSecAsn1RDNTemplate -_SecAsn1TaggedTemplateChooser -_kSecAsn1DSAAlgParamsTemplate -_kSecAsn1DSAAlgParamsBSAFETemplate -_kSecAsn1DSAAlgorithmIdX509Template -_kSecAsn1DSAAlgorithmIdBSAFETemplate -_kSecAsn1DSAPublicKeyX509Template -_kSecAsn1DSAPublicKeyBSAFETemplate -_kSecAsn1DSAPrivateKeyOpensslTemplate -_kSecAsn1DSAPrivateKeyOctsTemplate -_kSecAsn1DSAPrivateKeyBSAFETemplate -_kSecAsn1DSAPrivateKeyPKCS8Template -_kSecAsn1DSASignatureTemplate -_kSecAsn1OCSPBasicResponseTemplate -_kSecAsn1OCSPCertIDTemplate -_kSecAsn1OCSPCertStatusGoodTemplate -_kSecAsn1OCSPCertStatusRevokedTemplate -_kSecAsn1OCSPCertStatusUnknownTemplate -_kSecAsn1OCSPRequestTemplate -_kSecAsn1OCSPResponderIDAsNameTemplate -_kSecAsn1OCSPResponderIDAsKeyTemplate -_kSecAsn1OCSPResponseBytesTemplate -_kSecAsn1OCSPResponseDataTemplate -_kSecAsn1OCSPResponseTemplate -_kSecAsn1OCSPRevokedInfoTemplate -_kSecAsn1OCSPSignatureTemplate -_kSecAsn1OCSPSignedRequestTemplate -_kSecAsn1OCSPSingleResponseTemplate -_kSecAsn1OCSPTbsRequestTemplate -_kSecAsn1OCSPDRequestTemplate -_kSecAsn1OCSPDRequestsTemplate -_kSecAsn1OCSPDReplyTemplate -_kSecAsn1OCSPDRepliesTemplate -_kSecAsn1SemanticsInformationTemplate -_kSecAsn1QC_StatementTemplate -_kSecAsn1QC_StatementsTemplate diff --git a/OSX/include/security_cdsa_client b/OSX/include/security_cdsa_client new file mode 120000 index 00000000..9737c610 --- /dev/null +++ b/OSX/include/security_cdsa_client @@ -0,0 +1 @@ +./libsecurity_cdsa_client/lib \ No newline at end of file diff --git a/OSX/include/security_cdsa_client/DLDBList.cpp b/OSX/include/security_cdsa_client/DLDBList.cpp deleted file mode 100644 index 1fede0e1..00000000 --- a/OSX/include/security_cdsa_client/DLDBList.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -/* - DLDbList.cpp -*/ - -#include "DLDBList.h" - -using namespace CssmClient; - -//---------------------------------------------------------------------- -// DLDbList implementation -//---------------------------------------------------------------------- - -void DLDbList::add(const DLDbIdentifier& dldbIdentifier) // Adds at end if not in list -{ - for (DLDbList::const_iterator ix=begin();ix!=end();ix++) - if (*ix==dldbIdentifier) // already in list - return; - push_back(dldbIdentifier); - changed(true); -} - -void DLDbList::remove(const DLDbIdentifier& dldbIdentifier) // Removes from list -{ - for (DLDbList::iterator ix=begin();ix!=end();ix++) - if (*ix==dldbIdentifier) // found in list - { - erase(ix); - changed(true); - break; - } -} - -void DLDbList::save() -{ -} diff --git a/OSX/include/security_cdsa_client/DLDBList.h b/OSX/include/security_cdsa_client/DLDBList.h deleted file mode 100644 index 3a85a3d2..00000000 --- a/OSX/include/security_cdsa_client/DLDBList.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -/* - DLDbList.h - - This implements a vector of DLDbIdentifiers. A DLDbIdentifier contains all of the - information needed to find a particular DB within a particular DL. This file - does not depend on CoreFoundation but does depend on CDSA headers. -*/ - -#ifndef _H_CDSA_CLIENT_DLDBLIST -#define _H_CDSA_CLIENT_DLDBLIST 1 - -#include -#include -#include - -namespace Security -{ - -namespace CssmClient -{ - -//------------------------------------------------------------------------------------- -// -// Lists of DL/DBs -// -//------------------------------------------------------------------------------------- - - -// -// DLDbList -// -class DLDbList : public vector -{ -public: - DLDbList() : mChanged(false) {} - virtual ~DLDbList() {} - - // API - virtual void add(const DLDbIdentifier& dldbIdentifier); // Adds at end if not in list - virtual void remove(const DLDbIdentifier& dldbIdentifier); // Removes from list - virtual void save(); - - bool hasChanged() const { return mChanged; } - -protected: - void changed(bool hasChanged) { mChanged=hasChanged; } - -private: - bool mChanged; -}; - -}; // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_DLDBLIST diff --git a/OSX/include/security_cdsa_client/aclclient.cpp b/OSX/include/security_cdsa_client/aclclient.cpp deleted file mode 100644 index 988943fd..00000000 --- a/OSX/include/security_cdsa_client/aclclient.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2000-2001,2007,2011 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// aclclient -// -#include -#include -#include -#include -#include - - -namespace Security { -namespace CssmClient { - -static inline void check(CSSM_RETURN rc) -{ - ObjectImpl::check(rc); -} - - -// -// AclBearer methods (trivial) -// -AclBearer::~AclBearer() -{ } - - -// -// Variant forms of AclBearer implemented in terms of its canonical virtual methods -// -void AclBearer::addAcl(const AclEntryInput &input, const CSSM_ACCESS_CREDENTIALS *cred) -{ - changeAcl(AclEdit(input), cred); -} - -void AclBearer::changeAcl(CSSM_ACL_HANDLE handle, const AclEntryInput &input, - const CSSM_ACCESS_CREDENTIALS *cred) -{ - changeAcl(AclEdit(handle, input), cred); -} - -void AclBearer::deleteAcl(CSSM_ACL_HANDLE handle, const CSSM_ACCESS_CREDENTIALS *cred) -{ - changeAcl(AclEdit(handle), cred); -} - -void AclBearer::deleteAcl(const char *tag, const CSSM_ACCESS_CREDENTIALS *cred) -{ - AutoAclEntryInfoList entries; - getAcl(entries, tag); - for (uint32 n = 0; n < entries.count(); n++) - deleteAcl(entries[n].handle(), cred); -} - - -// -// KeyAclBearer implementation -// -void KeyAclBearer::getAcl(AutoAclEntryInfoList &aclInfos, const char *selectionTag) const -{ - aclInfos.allocator(allocator); - check(CSSM_GetKeyAcl(csp, &key, reinterpret_cast(selectionTag), aclInfos, aclInfos)); -} - -void KeyAclBearer::changeAcl(const CSSM_ACL_EDIT &aclEdit, const CSSM_ACCESS_CREDENTIALS *cred) -{ - check(CSSM_ChangeKeyAcl(csp, AccessCredentials::needed(cred), &aclEdit, &key)); -} - -void KeyAclBearer::getOwner(AutoAclOwnerPrototype &owner) const -{ - owner.allocator(allocator); - check(CSSM_GetKeyOwner(csp, &key, owner)); -} - -void KeyAclBearer::changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *cred) -{ - check(CSSM_ChangeKeyOwner(csp, AccessCredentials::needed(cred), &key, &newOwner)); -} - - -// -// A single global structure containing pseudo-static data -// -struct Statics { - Statics(); - Allocator &alloc; - - AutoCredentials nullCred; - AutoCredentials promptCred; - AutoCredentials unlockCred; - AutoCredentials cancelCred; - AutoCredentials promptedPINCred; - AutoCredentials promptedPINItemCred; - - AclOwnerPrototype anyOwner; - AclEntryInfo anyAcl; -}; - -namespace { - ModuleNexus statics; -} - - -// -// Make pseudo-statics. -// Note: This is an eternal object. It is not currently destroyed -// if the containing code is unloaded. -// -Statics::Statics() - : alloc(Allocator::standard()), - nullCred(alloc, 1), - promptCred(alloc, 3), - unlockCred(alloc, 1), - cancelCred(alloc, 1), - promptedPINCred(alloc, 1), - promptedPINItemCred(alloc, 1), - anyOwner(TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_ANY)), - anyAcl(AclEntryPrototype(TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_ANY), 1)) -{ - // nullCred: nothing at all - // contains: - // an empty THRESHOLD sample to match threshold subjects with "free" subjects - nullCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_THRESHOLD); - - // promptCred: a credential permitting user prompt confirmations - // contains: - // a KEYCHAIN_PROMPT sample, both by itself and in a THRESHOLD - // a PROMPTED_PASSWORD sample - promptCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT); - promptCred.sample(1) = TypedList(alloc, CSSM_SAMPLE_TYPE_THRESHOLD, - new(alloc) ListElement(TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT))); - promptCred.sample(2) = TypedList(alloc, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD, - new(alloc) ListElement(alloc, CssmData())); - - // unlockCred: ??? - unlockCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, - new(alloc) ListElement(CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT)); - - cancelCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, - new(alloc) ListElement(CSSM_WORDID_CANCELED)); - - /* - We don't set this: - - promptedPINCred.tag("PIN1"); - - here to avoid triggering code in TokenDatabase::getAcl in securityd that - would always show a PIN unlock dialog. This credential is used for an - unlock of the database, i.e. a dbauthenticate call to unlock the card. - */ - promptedPINCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD, - new(alloc) ListElement(alloc, CssmData())); - - /* - This credential is used for items like non-repudiation keys that always - require an explicit entry of the PIN. We set this so that Token::authenticate - will recognize the number of the PIN we need to unlock. - */ - promptedPINItemCred.tag("PIN1"); - promptedPINItemCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_PROMPTED_PASSWORD, - new(alloc) ListElement(alloc, CssmData())); -} - - -// -// Make and break AclFactories -// -AclFactory::AclFactory() -{ } - -AclFactory::~AclFactory() -{ } - - -// -// Return basic pseudo-static values -// -const AccessCredentials *AclFactory::nullCred() const -{ return &statics().nullCred; } - -const AccessCredentials *AclFactory::promptCred() const -{ return &statics().promptCred; } - -const AccessCredentials *AclFactory::unlockCred() const -{ return &statics().unlockCred; } - - -const AccessCredentials *AclFactory::cancelCred() const -{ return &statics().cancelCred; } - -const AccessCredentials *AclFactory::promptedPINCred() const -{ return &statics().promptedPINCred; } - -const AccessCredentials *AclFactory::promptedPINItemCred() const -{ return &statics().promptedPINItemCred; } - - -// -// Manage the (pseudo) credentials used to explicitly provide a passphrase to a keychain. -// Use the eternal unlockCred() for normal (protected prompt) unlocking. -// -AclFactory::KeychainCredentials::~KeychainCredentials () -{ - DataWalkers::chunkFree(mCredentials, allocator); -} - -AclFactory::PassphraseUnlockCredentials::PassphraseUnlockCredentials (const CssmData& password, - Allocator& allocator) : KeychainCredentials(allocator) -{ - mCredentials->sample(0) = TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, - new (allocator) ListElement (CSSM_SAMPLE_TYPE_PASSWORD), - new (allocator) ListElement (CssmAutoData(allocator, password).release())); -} - - -// -// Manage the (pseudo) credentials used to explicitly change a keychain's passphrase -// -AclFactory::PasswordChangeCredentials::PasswordChangeCredentials (const CssmData& password, - Allocator& allocator) : KeychainCredentials(allocator) -{ - mCredentials->sample(0) = TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK, - new (allocator) ListElement (CSSM_SAMPLE_TYPE_PASSWORD), - new (allocator) ListElement (CssmAutoData(allocator, password).release())); -} - - -// -// Wide open ("ANY") CSSM forms for owner and ACL entry -// -const AclOwnerPrototype &AclFactory::anyOwner() const -{ return statics().anyOwner; } - -const AclEntryInfo &AclFactory::anyAcl() const -{ return statics().anyAcl; } - - -// -// Create an ANY style AclEntryInput. -// This can be used to explicitly request wide-open authorization on a new CSSM object. -// -AclFactory::AnyResourceContext::AnyResourceContext(const CSSM_ACCESS_CREDENTIALS *cred) - : mAny(CSSM_ACL_SUBJECT_TYPE_ANY), mTag(CSSM_ACL_AUTHORIZATION_ANY) -{ - // set up an ANY/EVERYTHING AclEntryInput - input().proto().subject() += &mAny; - AuthorizationGroup &authGroup = input().proto().authorization(); - authGroup.NumberOfAuthTags = 1; - authGroup.AuthTags = &mTag; - - // install the cred (not copied) - credentials(cred); -} - - -// -// CSSM ACL makers -// -AclFactory::Subject::Subject(Allocator &alloc, CSSM_ACL_SUBJECT_TYPE type) - : TypedList(alloc, type) -{ } - - -AclFactory::PWSubject::PWSubject(Allocator &alloc) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PASSWORD) -{ } - -AclFactory::PWSubject::PWSubject(Allocator &alloc, const CssmData &secret) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PASSWORD) -{ - append(new(alloc) ListElement(alloc, secret)); -} - -AclFactory::PromptPWSubject::PromptPWSubject(Allocator &alloc, const CssmData &prompt) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD) -{ - append(new(alloc) ListElement(alloc, prompt)); -} - -AclFactory::PromptPWSubject::PromptPWSubject(Allocator &alloc, const CssmData &prompt, const CssmData &secret) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD) -{ - append(new(alloc) ListElement(alloc, prompt)); - append(new(alloc) ListElement(alloc, secret)); -} - -AclFactory::ProtectedPWSubject::ProtectedPWSubject(Allocator &alloc) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PROTECTED_PASSWORD) -{ } - -AclFactory::PinSubject::PinSubject(Allocator &alloc, uint32 slot) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PREAUTH) -{ - append(new(alloc) ListElement(CSSM_ACL_AUTHORIZATION_PREAUTH(slot))); -} - -AclFactory::PinSourceSubject::PinSourceSubject(Allocator &alloc, const TypedList &form) - : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_PREAUTH_SOURCE) -{ - append(new(alloc) ListElement(form)); -} - - -} // end namespace CssmClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/aclclient.h b/OSX/include/security_cdsa_client/aclclient.h deleted file mode 100644 index 00b5b513..00000000 --- a/OSX/include/security_cdsa_client/aclclient.h +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2000-2001,2007,2011 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// aclclient -// -#ifndef _H_CDSA_CLIENT_ACLCLIENT -#define _H_CDSA_CLIENT_ACLCLIENT 1 - -#include -#include -#include -#include -#include - -namespace Security { -namespace CssmClient { - -class CSP; - - -// -// Any client-side object that has CSSM-layer ACLs shall be -// derived from AclBearer and implement its methods accordingly. -// Note the (shared/virtual) RefCount - you should handle AclBearer -// references via RefPointers. -// All the non-pure methods are implemented (in AclBearer) in terms of -// the pure virtual methods; they just restate the problem in various ways. -// -class AclBearer : public virtual RefCount { -public: - virtual ~AclBearer(); - - // Acl manipulation - virtual void getAcl(AutoAclEntryInfoList &aclInfos, - const char *selectionTag = NULL) const = 0; - virtual void changeAcl(const CSSM_ACL_EDIT &aclEdit, - const CSSM_ACCESS_CREDENTIALS *cred = NULL) = 0; - - void addAcl(const AclEntryInput &input, const CSSM_ACCESS_CREDENTIALS *cred = NULL); - void changeAcl(CSSM_ACL_HANDLE handle, const AclEntryInput &input, - const CSSM_ACCESS_CREDENTIALS *cred = NULL); - void deleteAcl(CSSM_ACL_HANDLE handle, const CSSM_ACCESS_CREDENTIALS *cred = NULL); - void deleteAcl(const char *tag = NULL, const CSSM_ACCESS_CREDENTIALS *cred = NULL); - - // Acl owner manipulation - virtual void getOwner(AutoAclOwnerPrototype &owner) const = 0; - virtual void changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *cred = NULL) = 0; -}; - - -// -// An AclBearer applied to a raw CSSM key -// -class KeyAclBearer : public AclBearer { -public: - KeyAclBearer(CSSM_CSP_HANDLE cspH, CSSM_KEY &theKey, Allocator &alloc) - : csp(cspH), key(theKey), allocator(alloc) { } - - const CSSM_CSP_HANDLE csp; - CSSM_KEY &key; - Allocator &allocator; - -protected: - void getAcl(AutoAclEntryInfoList &aclInfos, - const char *selectionTag = NULL) const; - void changeAcl(const CSSM_ACL_EDIT &aclEdit, - const CSSM_ACCESS_CREDENTIALS *cred = NULL); - void getOwner(AutoAclOwnerPrototype &owner) const; - void changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *cred = NULL); -}; - - -// -// An AclFactory helps create and maintain CSSM-layer AccessCredentials -// and matching samples. There is state in an AclFactory, though simple -// uses may not care about it. -// -class AclFactory { -public: - AclFactory(); - virtual ~AclFactory(); - - // these values are owned by the AclFactory and persist - // until it is destroyed. You don't own the memory. - const AccessCredentials *nullCred() const; // conforming empty - const AccessCredentials *promptCred() const; // enable interactive prompting - const AccessCredentials *unlockCred() const; - const AccessCredentials *cancelCred() const; - const AccessCredentials *promptedPINCred() const; - const AccessCredentials *promptedPINItemCred() const; - - const AclOwnerPrototype &anyOwner() const; // wide-open owner - const AclEntryInfo &anyAcl() const; // wide-open ACL entry (authorizes anything) - -protected: - class KeychainCredentials { - public: - KeychainCredentials(Allocator &alloc) - : allocator(alloc), mCredentials(new AutoCredentials(alloc)) { } - virtual ~KeychainCredentials(); - - Allocator &allocator; - - operator const AccessCredentials* () const { return mCredentials; } - - protected: - AutoCredentials *mCredentials; - }; - -public: - // create a self-managed AccessCredentials to explicitly provide a keychain passphrase - class PassphraseUnlockCredentials : public KeychainCredentials { - public: - PassphraseUnlockCredentials (const CssmData& password, Allocator& allocator); - }; - - // create a self-managed AccessCredentials to change a keychain passphrase - class PasswordChangeCredentials : public KeychainCredentials { - public: - PasswordChangeCredentials (const CssmData& password, Allocator& allocator); - }; - -public: - class AnyResourceContext : public ResourceControlContext { - public: - AnyResourceContext(const CSSM_ACCESS_CREDENTIALS *cred = NULL); - - private: - ListElement mAny; - CSSM_ACL_AUTHORIZATION_TAG mTag; - }; - -public: - // - // Subject makers. Contents are chunk-allocated with the Allocator given - // - struct Subject : public TypedList { - Subject(Allocator &alloc, CSSM_ACL_SUBJECT_TYPE type); - }; - - // an ANY subject, allocated dynamically for you - struct AnySubject : public Subject { - AnySubject(Allocator &alloc) : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_ANY) { } - }; - - // a "nobody" subject (something guaranteed never to match) - struct NobodySubject : public Subject { - NobodySubject(Allocator &alloc) : Subject(alloc, CSSM_ACL_SUBJECT_TYPE_COMMENT) { } - }; - - // password subjects - struct PWSubject : public Subject { - PWSubject(Allocator &alloc); // no secret - PWSubject(Allocator &alloc, const CssmData &secret); // this secret - }; - - struct PromptPWSubject : public Subject { - PromptPWSubject(Allocator &alloc, const CssmData &prompt); - PromptPWSubject(Allocator &alloc, const CssmData &prompt, const CssmData &secret); - }; - - struct ProtectedPWSubject : public Subject { - ProtectedPWSubject(Allocator &alloc); - }; - - // PIN (pre-auth) reference, origin side - struct PinSubject : public Subject { - PinSubject(Allocator &alloc, uint32 slot); - }; - - // PIN (pre-auth) source site - struct PinSourceSubject : public Subject { - PinSourceSubject(Allocator &alloc, const TypedList &form); - }; -}; - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_ACLCLIENT diff --git a/OSX/include/security_cdsa_client/clclient.cpp b/OSX/include/security_cdsa_client/clclient.cpp deleted file mode 100644 index c816acd6..00000000 --- a/OSX/include/security_cdsa_client/clclient.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2000-2002,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// clclient - client interface to CSSM CLs and their operations -// -#include - -using namespace CssmClient; - - -// -// Manage CL attachments -// -CLImpl::CLImpl(const Guid &guid) : AttachmentImpl(guid, CSSM_SERVICE_CL) -{ -} - -CLImpl::CLImpl(const Module &module) : AttachmentImpl(module, CSSM_SERVICE_CL) -{ -} - -CLImpl::~CLImpl() -{ -} - - -// -// A BuildCertGroup -// -BuildCertGroup::BuildCertGroup(CSSM_CERT_TYPE ctype, CSSM_CERT_ENCODING encoding, - CSSM_CERTGROUP_TYPE type, Allocator &alloc) - : certificates(NumCerts, GroupList.CertList) -{ - clearPod(); - CertType = ctype; - CertEncoding = encoding; - CertGroupType = type; -} diff --git a/OSX/include/security_cdsa_client/clclient.h b/OSX/include/security_cdsa_client/clclient.h deleted file mode 100644 index aa68fa81..00000000 --- a/OSX/include/security_cdsa_client/clclient.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2000-2002,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// clclient - client interface to CSSM CLs and their operations -// -#ifndef _H_CDSA_CLIENT_CLCLIENT -#define _H_CDSA_CLIENT_CLCLIENT 1 - -#include -#include - - -namespace Security { -namespace CssmClient { - - -// -// A CL attachment -// -class CLImpl : public AttachmentImpl -{ -public: - CLImpl(const Guid &guid); - CLImpl(const Module &module); - virtual ~CLImpl(); - -}; - -class CL : public Attachment -{ -public: - typedef CLImpl Impl; - - explicit CL(Impl *impl) : Attachment(impl) {} - CL(const Guid &guid) : Attachment(new Impl(guid)) {} - CL(const Module &module) : Attachment(new Impl(module)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// A self-building CertGroup. -// This is a CertGroup, but it's NOT A PODWRAPPER (it's larger). -// -class BuildCertGroup : public CertGroup { -public: - BuildCertGroup(CSSM_CERT_TYPE ctype, CSSM_CERT_ENCODING encoding, - CSSM_CERTGROUP_TYPE type, Allocator &alloc = Allocator::standard()); - - CssmVector certificates; -}; - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_CLCLIENT diff --git a/OSX/include/security_cdsa_client/cryptoclient.cpp b/OSX/include/security_cdsa_client/cryptoclient.cpp deleted file mode 100644 index 067113f7..00000000 --- a/OSX/include/security_cdsa_client/cryptoclient.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cryptoclient - client interface to CSSM CSP encryption/decryption operations -// -#include - -using namespace CssmClient; - - -Crypt::Crypt(const CSP &csp, CSSM_ALGORITHMS alg) - : Context(csp, alg), mMode(CSSM_ALGMODE_NONE), mInitVector(NULL), - mPadding(CSSM_PADDING_NONE) -{ -} - -void Crypt::key(const Key &key) -{ - mKey = key; - set(CSSM_ATTRIBUTE_KEY, static_cast(key)); -} - - -void -Crypt::activate() -{ - StLock _(mActivateMutex); - if (!mActive) - { - // Key is required unless we have a NULL algorithm (cleartext wrap/unwrap), - // in which case we'll make a symmetric context (it shouldn't matter then). - if (!mKey && mAlgorithm != CSSM_ALGID_NONE) - CssmError::throwMe(CSSMERR_CSP_MISSING_ATTR_KEY); - if (!mKey || mKey->keyClass() == CSSM_KEYCLASS_SESSION_KEY) - { // symmetric key - check(CSSM_CSP_CreateSymmetricContext(attachment()->handle(), mAlgorithm, - mMode, neededCred(), mKey, mInitVector, mPadding, NULL, - &mHandle)); - } - else - { - check(CSSM_CSP_CreateAsymmetricContext(attachment()->handle(), mAlgorithm, - neededCred(), mKey, mPadding, &mHandle)); - //@@@ stick mode and initVector explicitly into the context? - } - mActive = true; - } -} - - -// -// Manage encryption contexts -// -CSSM_SIZE -Encrypt::encrypt(const CssmData *in, uint32 inCount, - CssmData *out, uint32 outCount, CssmData &remData) -{ - unstaged(); - CSSM_SIZE total; - check(CSSM_EncryptData(handle(), in, inCount, out, outCount, &total, &remData)); - return total; -} - -void -Encrypt::init() -{ - check(CSSM_EncryptDataInit(handle())); - mStaged = true; -} - -CSSM_SIZE -Encrypt::encrypt(const CssmData *in, uint32 inCount, - CssmData *out, uint32 outCount) -{ - staged(); - CSSM_SIZE total; - check(CSSM_EncryptDataUpdate(handle(), in, inCount, out, outCount, &total)); - return total; -} - -void -Encrypt::final(CssmData &remData) -{ - staged(); - check(CSSM_EncryptDataFinal(handle(), &remData)); - mStaged = false; -} - - -// -// Manage Decryption contexts -// - -CSSM_SIZE -Decrypt::decrypt(const CssmData *in, uint32 inCount, - CssmData *out, uint32 outCount, CssmData &remData) -{ - unstaged(); - CSSM_SIZE total; - check(CSSM_DecryptData(handle(), in, inCount, out, outCount, &total, &remData)); - return total; -} - -void -Decrypt::init() -{ - check(CSSM_DecryptDataInit(handle())); - mStaged = true; -} - -CSSM_SIZE -Decrypt::decrypt(const CssmData *in, uint32 inCount, - CssmData *out, uint32 outCount) -{ - staged(); - CSSM_SIZE total; - check(CSSM_DecryptDataUpdate(handle(), in, inCount, out, outCount, &total)); - return total; -} - -void -Decrypt::final(CssmData &remData) -{ - staged(); - check(CSSM_DecryptDataFinal(handle(), &remData)); - mStaged = false; -} diff --git a/OSX/include/security_cdsa_client/cryptoclient.h b/OSX/include/security_cdsa_client/cryptoclient.h deleted file mode 100644 index d708ca16..00000000 --- a/OSX/include/security_cdsa_client/cryptoclient.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cryptoclient - client interface to CSSM CSP encryption/decryption operations -// -#ifndef _H_CDSA_CLIENT_CRYPTOCLIENT -#define _H_CDSA_CLIENT_CRYPTOCLIENT 1 - -#include -#include - -namespace Security { -namespace CssmClient { - - -// -// Common features of various cryptographic operations contexts. -// These all use symmetric or asymmetric contexts. -// -class Crypt : public Context { -public: - Crypt(const CSP &csp, CSSM_ALGORITHMS alg); - -public: - // Context attributes - CSSM_ENCRYPT_MODE mode() const { return mMode; } - void mode(CSSM_ENCRYPT_MODE m) { mMode = m; set(CSSM_ATTRIBUTE_MODE, m); } - Key key() const { return mKey; } - void key(const Key &k); - const CssmData &initVector() const { return *mInitVector; } - void initVector(const CssmData &v) { mInitVector = &v; set(CSSM_ATTRIBUTE_INIT_VECTOR, v); } - CSSM_PADDING padding() const { return mPadding; } - void padding(CSSM_PADDING p) { mPadding = p; set(CSSM_ATTRIBUTE_PADDING, p); } - -protected: - void activate(); - -protected: - CSSM_ENCRYPT_MODE mMode; - Key mKey; - const CssmData *mInitVector; - CSSM_PADDING mPadding; - RecursiveMutex mActivateMutex; -}; - - - -// -// An encryption context -// -class Encrypt : public Crypt -{ -public: - Encrypt(const CSP &csp, CSSM_ALGORITHMS alg) : Crypt(csp, alg) {}; - -public: - // integrated - CSSM_SIZE encrypt(const CssmData *in, uint32 inCount, CssmData *out, uint32 outCount, - CssmData &remData); - CSSM_SIZE encrypt(const CssmData &in, CssmData &out, CssmData &remData) - { return encrypt(&in, 1, &out, 1, remData); } - - // staged update - void init(); // Optional - CSSM_SIZE encrypt(const CssmData *in, uint32 inCount, CssmData *out, uint32 outCount); - CSSM_SIZE encrypt(const CssmData &in, CssmData &out) - { return encrypt(&in, 1, &out, 1); } - // staged final - void final(CssmData &remData); -}; - -// -// An Decryption context -// -class Decrypt : public Crypt -{ -public: - Decrypt(const CSP &csp, CSSM_ALGORITHMS alg) : Crypt(csp, alg) {}; - -public: - // integrated - CSSM_SIZE decrypt(const CssmData *in, uint32 inCount, CssmData *out, uint32 outCount, - CssmData &remData); - CSSM_SIZE decrypt(const CssmData &in, CssmData &out, CssmData &remData) - { return decrypt(&in, 1, &out, 1, remData); } - - // staged update - void init(); // Optional - CSSM_SIZE decrypt(const CssmData *in, uint32 inCount, CssmData *out, uint32 outCount); - CSSM_SIZE decrypt(const CssmData &in, CssmData &out) - { return decrypt(&in, 1, &out, 1); } - // staged final - void final(CssmData &remData); -}; - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_CRYPTOCLIENT diff --git a/OSX/include/security_cdsa_client/cspclient.cpp b/OSX/include/security_cdsa_client/cspclient.cpp deleted file mode 100644 index 186c2fa2..00000000 --- a/OSX/include/security_cdsa_client/cspclient.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (c) 2000-2002,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cspclient - client interface to CSSM CSPs and their operations -// -#include - -namespace Security { -namespace CssmClient { - - -// -// Manage CSP attachments -// -CSPImpl::CSPImpl(const Guid &guid) : AttachmentImpl(guid, CSSM_SERVICE_CSP) -{ -} - -CSPImpl::CSPImpl(const Module &module) : AttachmentImpl(module, CSSM_SERVICE_CSP) -{ -} - -CSPImpl::~CSPImpl() -{ -} - - -// -// Delete a key explicitly -// -void CSPImpl::freeKey(CssmKey &key, const AccessCredentials *cred, bool permanent) -{ - check(CSSM_FreeKey(handle(), cred, &key, permanent)); -} - - -// -// Manage generic context objects -// -Context::Context(const CSP &csp, CSSM_ALGORITHMS alg) -: ObjectImpl(csp), mAlgorithm(alg), mStaged(false), mCred(NULL) -{ -} - -Context::~Context() -{ - try - { - deactivate(); - } catch(...) {} -} - -void Context::init() -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -void Context::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - check(CSSM_DeleteContext(mHandle)); - } -} - - -void Context::algorithm(CSSM_ALGORITHMS alg) -{ - if (isActive()) - abort(); //@@@ can't (currently?) change algorithm with active context - mAlgorithm = alg; -} - - -void Context::cred(const CSSM_ACCESS_CREDENTIALS *cred) -{ - mCred = AccessCredentials::overlay(cred); - set(CSSM_ATTRIBUTE_ACCESS_CREDENTIALS, *mCred); -} - - -// -// Query context operation output sizes. -// -uint32 Context::getOutputSize(uint32 inputSize, bool encrypt /*= true*/) -{ - CSSM_QUERY_SIZE_DATA data; - data.SizeInputBlock = inputSize; - getOutputSize(data, 1, encrypt); - return data.SizeOutputBlock; -} - -void Context::getOutputSize(CSSM_QUERY_SIZE_DATA &sizes, uint32 count, bool encrypt /*= true*/) -{ - check(CSSM_QuerySize(handle(), encrypt, count, &sizes)); -} - - -// -// The override() method of Context is an expert feature. It replaces the entire -// context with a context object provided. It is up to the caller to keep this context -// consistent with the purpose of the Context subclass he is (mis)using. -// This feature is currently used by the SecurityServer. -// -void Context::override(const Security::Context &ctx) -{ - if (!isActive()) { - // make a valid context object (it doesn't matter what kind - keep it cheap) - check(CSSM_CSP_CreateDigestContext(attachment()->handle(), CSSM_ALGID_NONE, &mHandle)); - } - // now replace everything with the context data provided - check(CSSM_SetContext(mHandle, &ctx)); - mActive = true; // now active -} - - -// -// RccContexts -// -const ResourceControlContext &RccBearer::compositeRcc() const -{ - // explicitly specified RCC wins - if (mRcc) - return *mRcc; - - // cobble one up from the pieces - if (mOwner) - mWorkRcc.input() = *mOwner; - else - mWorkRcc.clearPod(); - mWorkRcc.credentials(mOpCred); - return mWorkRcc; -} - - -void RccBearer::owner(const CSSM_ACL_ENTRY_PROTOTYPE *owner) -{ - if (owner) { - mWorkInput = *owner; - this->owner(mWorkInput); - } else - this->owner((AclEntryInput*)NULL); -} - - -// -// Manage PassThrough contexts -// - -// -// Invoke passThrough -// -void -PassThrough::operator() (uint32 passThroughId, const void *inData, void **outData) -{ - check(CSSM_CSP_PassThrough(handle(), passThroughId, inData, outData)); -} - -void PassThrough::activate() -{ - StLock _(mActivateMutex); - if (!mActive) { - check(CSSM_CSP_CreatePassThroughContext(attachment()->handle(), mKey, &mHandle)); - mActive = true; - } -} - - -// -// Manage Digest contexts -// -void Digest::activate() -{ - StLock _(mActivateMutex); - if (!mActive) { - check(CSSM_CSP_CreateDigestContext(attachment()->handle(), mAlgorithm, &mHandle)); - mActive = true; - } -} - - -void Digest::digest(const CssmData *data, uint32 count, CssmData &digest) -{ - activate(); - if (mStaged) - Error::throwMe(CSSMERR_CSP_STAGED_OPERATION_IN_PROGRESS); - check(CSSM_DigestData(handle(), data, count, &digest)); -} - -void Digest::digest(const CssmData *data, uint32 count) -{ - activate(); - if (!mStaged) { - check(CSSM_DigestDataInit(handle())); - mStaged = true; - } - check(CSSM_DigestDataUpdate(handle(), data, count)); -} - -void Digest::operator () (CssmData &digest) -{ - if (!mStaged) - Error::throwMe(CSSMERR_CSP_STAGED_OPERATION_NOT_STARTED); - check(CSSM_DigestDataFinal(handle(), &digest)); - mStaged = false; -} - - -// -// Random number generation -// -void Random::seed(const CssmCryptoData &seedData) -{ - mSeed = &seedData; - set(CSSM_ATTRIBUTE_SEED, seedData); -} - -void Random::size(uint32 sz) -{ - mSize = sz; - set(CSSM_ATTRIBUTE_OUTPUT_SIZE, sz); -} - - -void Random::activate() -{ - StLock _(mActivateMutex); - if (!mActive) { - check(CSSM_CSP_CreateRandomGenContext(attachment()->handle(), mAlgorithm, - mSeed, mSize, &mHandle)); - mActive = true; - } -} - - -void Random::generate(CssmData &data, uint32 newSize) -{ - if (newSize) - size(newSize); - activate(); - assert(!mStaged); // not a stage-able operation - check(CSSM_GenerateRandom(handle(), &data)); -} - -} // end namespace CssmClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/cspclient.h b/OSX/include/security_cdsa_client/cspclient.h deleted file mode 100644 index 67c35d70..00000000 --- a/OSX/include/security_cdsa_client/cspclient.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2000-2002,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cspclient - client interface to CSSM CSPs and their operations -// -#ifndef _H_CDSA_CLIENT_CSPCLIENT -#define _H_CDSA_CLIENT_CSPCLIENT 1 - -#include -#include -#include - -namespace Security { -namespace CssmClient { - - -// -// A CSP attachment -// -class CSPImpl : public AttachmentImpl -{ -public: - CSPImpl(const Guid &guid); - CSPImpl(const Module &module); - virtual ~CSPImpl(); - - // the least inappropriate place for this one - void freeKey(CssmKey &key, const AccessCredentials *cred = NULL, bool permanent = false); -}; - -class CSP : public Attachment -{ -public: - typedef CSPImpl Impl; - - explicit CSP(Impl *impl) : Attachment(impl) {} - CSP(const Guid &guid) : Attachment(new Impl(guid)) {} - CSP(const Module &module) : Attachment(new Impl(module)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - -// -// A cryptographic context. -// Contexts always belong to CSPs (CSP attachments). -// -class Context : public ObjectImpl -{ -public: - Context(const CSP &csp, CSSM_ALGORITHMS alg = CSSM_ALGID_NONE); - ~Context(); - - CSP attachment() const { return parent(); } - Module module() const { return attachment()->module(); } - - CSSM_ALGORITHMS algorithm() const { return mAlgorithm; } - void algorithm(CSSM_ALGORITHMS alg); - - const AccessCredentials *cred() const { return mCred; } - void cred(const CSSM_ACCESS_CREDENTIALS *cred); - void cred(const CSSM_ACCESS_CREDENTIALS &cred) { this->cred(&cred); } - -public: - CSSM_CC_HANDLE handle() { activate(); return mHandle; } - - uint32 getOutputSize(uint32 inputSize, bool encrypt = true); - void getOutputSize(CSSM_QUERY_SIZE_DATA &sizes, uint32 count, bool encrypt = true); - -public: - // don't use this section unless you know what you're doing! - void override(const ::Context &ctx); - - template - void set(CSSM_ATTRIBUTE_TYPE type, const T &value) - { - if (isActive()) { - ::Context::Attr attr(type, value); - check(CSSM_UpdateContextAttributes(mHandle, 1, &attr)); - } - } - - void set(CSSM_ATTRIBUTE_TYPE type, uint32 value) - { - if (isActive()) { - ::Context::Attr attr(type, value); - check(CSSM_UpdateContextAttributes(mHandle, 1, &attr)); - } - } - - template - void add(CSSM_ATTRIBUTE_TYPE type, const T &value) - { activate(); set(type, value); } - - void add(CSSM_ATTRIBUTE_TYPE type, uint32 value) - { activate(); set(type, value); } - -protected: - void deactivate(); - - virtual void init(); // Subclasses must implement if they support staged operations. - - void unstaged() - { activate(); if (mStaged) CssmError::throwMe(CSSMERR_CSP_STAGED_OPERATION_IN_PROGRESS); } - - void staged() - { if (!mStaged) init(); } - - const AccessCredentials *neededCred() - { return AccessCredentials::needed(mCred); } - -protected: - CSSM_ALGORITHMS mAlgorithm; // intended algorithm - CSSM_CC_HANDLE mHandle; // CSSM CC handle - bool mStaged; // staged in progress - const AccessCredentials *mCred; // if explicitly set - RecursiveMutex mActivateMutex; -}; - - -// -// An RccBearer holds a ResourceControlContext. Note that this is a composite -// of an AccessCredentials and an AclEntryInput. We allow setting the whole -// thing, or its two components separately. A complete rcc set (via ::rcc) -// overrides any components. -// @@@ Perhaps we should merge components into a specified rcc? Iffy, though... -// Note: We call the credential components "opCred" to distinguish it from -// the "cred" of a CredBearer; some classes are both. As a rule, the "cred" goes -// into the context, while the "opCred" gets passed as an argument. -// -class RccBearer { -public: - RccBearer() : mOpCred(NULL), mOwner(NULL), mRcc(NULL) { } - - const AccessCredentials *opCred() const { return mOpCred; } - void opCred(const CSSM_ACCESS_CREDENTIALS *cred) { mOpCred = AccessCredentials::overlay(cred); } - void opCred(const CSSM_ACCESS_CREDENTIALS &cred) { this->opCred(&cred); } - const AclEntryInput *owner() const { return mOwner; } - void owner(const CSSM_ACL_ENTRY_INPUT *owner) { mOwner = AclEntryInput::overlay(owner); } - void owner(const CSSM_ACL_ENTRY_INPUT &owner) { this->owner(&owner); } - void owner(const CSSM_ACL_ENTRY_PROTOTYPE *owner); - void owner(const CSSM_ACL_ENTRY_PROTOTYPE &owner) { this->owner(&owner); } - const ResourceControlContext *rcc() const { return mRcc; } - void rcc(const CSSM_RESOURCE_CONTROL_CONTEXT *rcc) - { mRcc = ResourceControlContext::overlay(rcc); } - void rcc(const CSSM_RESOURCE_CONTROL_CONTEXT &rcc) { this->rcc(&rcc); } - -protected: - const ResourceControlContext &compositeRcc() const; - -private: - // an RCC contains both a cred and entryInput - // mCred/mAcl are only considered if mRcc is not set (NULL) - const AccessCredentials *mOpCred; - const AclEntryInput *mOwner; - const ResourceControlContext *mRcc; - - mutable ResourceControlContext mWorkRcc; // work area - mutable AclEntryInput mWorkInput; // work area -}; - - -// -// A PassThough context -// -class PassThrough : public Context -{ -public: - PassThrough(const CSP &csp) : Context(csp) { } - -public: - void operator () (uint32 passThroughId, const void *inData, void **outData); - - template - void operator () (uint32 passThroughId, const TIn *inData, TOut **outData) - { operator () (passThroughId, (const void *)inData, (void **)outData); } - - template - void operator () (uint32 passThroughId, const TIn *inData) - { operator () (passThroughId, (const void *)inData, NULL); } - - const CSSM_KEY *key() const { return mKey; } - void key(const CSSM_KEY *k) { mKey = k; set(CSSM_ATTRIBUTE_KEY, k); } - -protected: - void activate(); - -protected: - const CSSM_KEY *mKey; -}; - - -// -// A Digest context -// -class Digest : public Context -{ -public: - Digest(const CSP &csp, CSSM_ALGORITHMS alg) : Context(csp, alg) { } - -public: - // integrated - void digest(const CssmData &data, CssmData &digest) { this->digest(&data, 1, digest); } - void digest(const CssmData *data, uint32 count, CssmData &digest); - - // staged - void digest(const CssmData &data) { digest(&data, 1); } - void digest(const CssmData *data, uint32 count); - void operator () (CssmData &digest); - CssmData operator () () { CssmData digest; (*this)(digest); return digest; } - -protected: - void activate(); -}; - - -// -// A [P]RNG context -// -class Random : public Context -{ -public: - Random(const CSP &csp, CSSM_ALGORITHMS alg) : Context(csp, alg), mSeed(NULL), mSize(1) { } - Random(const CSP &csp, CSSM_ALGORITHMS alg, const CssmCryptoData &seed) - : Context(csp, alg), mSeed(&seed), mSize(1) { } - Random(const CSP &csp, CSSM_ALGORITHMS alg, uint32 size) - : Context(csp, alg), mSeed(NULL), mSize(size) { } - Random(const CSP &csp, CSSM_ALGORITHMS alg, const CssmCryptoData &seed, uint32 size) - : Context(csp, alg), mSeed(&seed), mSize(size) { } - - void seed(const CssmCryptoData &data); - void size(uint32 size); - -public: - void generate(CssmData &data, uint32 size = 0); - - // alternate function-call form - CssmData operator () (uint32 size = 0) - { CssmData output; generate(output, size); return output; } - -protected: - void activate(); - -private: - const CssmCryptoData *mSeed; - uint32 mSize; -}; - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_CSPCLIENT diff --git a/OSX/include/security_cdsa_client/cssmclient.cpp b/OSX/include/security_cdsa_client/cssmclient.cpp deleted file mode 100644 index 05a59c49..00000000 --- a/OSX/include/security_cdsa_client/cssmclient.cpp +++ /dev/null @@ -1,528 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cssmclient - common client interface to CSSM and MDS. -// -// Locking Strategy (preliminary): -// XXX This is obsolete update this --mb -// A CssmObject is a CountingMutex. Its count represents the number of children that have registered -// themselves (using addChild/removeChild). The lock controls the internal management fields of the -// various subclasses to protect them against corruption. It does NOT control attribute and argument -// fields and operations, not does it control object-constant fields. -// This means that if you use an object from multiple threads, you (the caller) must lock the object -// during set/get calls of attributes. Note that the CSSM operations themselves are safely multithreaded -// and thus don't need to be interlocked explicitly. -// -#include -#include - -using namespace CssmClient; - -// -// Exception model -// -const char * -Error::what () const throw() -{ - return "CSSM client library error"; -} - - -// -// General utilities -// -void -ObjectImpl::check(CSSM_RETURN status) -{ - if (status != CSSM_OK) - { - CssmError::throwMe(status); - } -} - - -// -// Common features of Objects -// -ObjectImpl::ObjectImpl() : mParent(), mChildCount(0) -{ - mActive = false; // not activated - mAllocator = NULL; // allocator to be determined -} - -ObjectImpl::ObjectImpl(const Object &mommy) : mParent(mommy.mImpl), mChildCount(0) -{ - mActive = false; // not activated - mAllocator = NULL; // allocator to be determined - if (mParent) - mParent->addChild(); -} - -ObjectImpl::~ObjectImpl() -try -{ - if (!isIdle()) - { - int i = mChildCount; - syslog(LOG_ALERT, "Object %p still has %d children at delete.\n", this, i); - } - - // release parent from her obligations (if we still have one) - if (mParent) - mParent->removeChild(); -} -catch(...) -{ - return; -} - -void -ObjectImpl::addChild() -{ - mChildCount++; // atomic -} - -void -ObjectImpl::removeChild() -{ - mChildCount--; // atomic -} - - -// -// Manage allocators in the Object tree -// -Allocator & -ObjectImpl::allocator() const -{ - if (mAllocator == NULL) - { - // fix allocator now - if (mParent) - mAllocator = &mParent->allocator(); - else - mAllocator = &Allocator::standard(); - } - - return *mAllocator; -} - -void -ObjectImpl::allocator(Allocator &alloc) -{ - assert(mAllocator == NULL); // cannot redefine allocator once set - mAllocator = &alloc; -} - -// Comparison operators use pointer comparison by default. Subclasses may override. -bool -ObjectImpl::operator <(const ObjectImpl &other) const -{ - return this < &other; -} - -bool -ObjectImpl::operator ==(const ObjectImpl &other) const -{ - return this == &other; -} - - -// -// CSSMSession objects. -// parent ::= NULL (none) -// active ::= CSSM initialized -// -ModuleNexus CssmImpl::mStandard; - -CssmImpl::CssmImpl() : ObjectImpl() -{ - setup(); - mStandard().setCssm(this); -} - -CssmImpl::CssmImpl(bool) : ObjectImpl() -{ - setup(); - // implicitly constructed - caller responsible for standard session management -} - -CssmImpl::~CssmImpl() -{ - try - { - deactivate(); - } - catch(...) {} - - // this may be the standard session... - mStandard().unsetCssm(this); -} - - -void -CssmImpl::setup() -{ - // set default configuration - mVersion.Major = 2; - mVersion.Minor = 0; - mScope = CSSM_PRIVILEGE_SCOPE_PROCESS; -} - - -Cssm -CssmImpl::standard() -{ - return Cssm(mStandard().get()); -} - - -void -CssmImpl::activate() -{ - StLock _(mActivateMutex); - if (!mActive) - { - // currently, no choices on PVC mode and key hierarchy - CSSM_PVC_MODE pvc = CSSM_PVC_NONE; - switch (CSSM_RETURN rc = CSSM_Init(&mVersion, - mScope, &mCallerGuid, - CSSM_KEY_HIERARCHY_NONE, &pvc, NULL)) { - case CSSMERR_CSSM_PVC_ALREADY_CONFIGURED: - case CSSM_OK: - break; - default: - check(rc); - } - mActive = true; - } -} - -void -CssmImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - - // clear module map (all gone now) - moduleMap.erase(moduleMap.begin(), moduleMap.end()); - - // now terminate CSSM - check(CSSM_Terminate()); - } -} - -void -CssmImpl::atExitHandler() -{ - try { - mStandard.reset(); - } catch (...) { - } -} - -void -CssmImpl::catchExit() -{ - // @@@ Even though this is the "right thing" to do. This only causes - // exceptions during exit and doesn't really help cleanup correctly. -#if 0 - if (::atexit(atExitHandler)) - UnixError::throwMe(); -#endif -} - - -// -// Manage the automatic Cssm object. -// This is a program global. -// -void CssmImpl::StandardCssm::setCssm(CssmImpl *cssm) -{ - StLock _(*this); - if (mCssm == NULL) - mCssm = cssm; -} - -void CssmImpl::StandardCssm::unsetCssm(CssmImpl *cssm) -{ - StLock _(*this); - if (mCssm == cssm) - mCssm = NULL; -} - -CssmImpl *CssmImpl::StandardCssm::get() -{ - StLock _(*this); - if (mCssm == NULL) { // make the default instance - mCssm = new CssmImpl(true); - } - return mCssm; -} - -CssmImpl::StandardCssm::~StandardCssm() -{ - if (mCssm) { - mCssm->deactivate(); - delete mCssm; - } -} - - -// -// Auto-module management -// -Module -CssmImpl::autoModule(const Guid &guid) -{ - StLock _(mapLock); - ModuleMap::iterator it = moduleMap.find(guid); - if (it == moduleMap.end()) - { - // no automodule for this guid yet, create one - Module module(guid, Cssm(this)); - moduleMap.insert(ModuleMap::value_type(guid, module)); - return module; - } - else - { - // existing automodule - use it - return it->second; - } -} - - -// -// Module objects. -// parent ::= the session object (usually Cssm::standard) -// active ::= module is loaded. -// -ModuleImpl::ModuleImpl(const Guid &guid) : ObjectImpl(Cssm::standard()), - mAppNotifyCallback(NULL), - mAppNotifyCallbackCtx(NULL) -{ - setGuid(guid); -} - -ModuleImpl::ModuleImpl(const Guid &guid, const Cssm &session) : ObjectImpl(session), - mAppNotifyCallback(NULL), - mAppNotifyCallbackCtx(NULL) -{ - setGuid(guid); -} - -ModuleImpl::~ModuleImpl() -{ - unload(); -} - - -// -// RawModuleEvent objects encapsulate CSSM module callbacks -// -RawModuleEvents::~RawModuleEvents() -{ } - -CSSM_RETURN RawModuleEvents::sendNotify(const CSSM_GUID *, void *context, - uint32 subService, CSSM_SERVICE_TYPE type, CSSM_MODULE_EVENT event) -{ - try { - reinterpret_cast(context)->notify(subService, type, event); - return CSSM_OK; - } catch (const CommonError &error) { - return CssmError::cssmError(error, CSSM_CSSM_BASE_ERROR); - } catch (...) { - return CSSMERR_CSSM_INTERNAL_ERROR; // whatever... - } -} - - -// -// ModuleEvents enhance RawModuleEvents by splitting the callback up by type -// -void ModuleEvents::notify(uint32 subService, - CSSM_SERVICE_TYPE type, CSSM_MODULE_EVENT event) -{ - switch (event) { - case CSSM_NOTIFY_INSERT: - insertion(subService, type); - break; - case CSSM_NOTIFY_REMOVE: - removal(subService, type); - break; - case CSSM_NOTIFY_FAULT: - fault(subService, type); - break; - } -} - -// default callbacks do nothing -void ModuleEvents::insertion(uint32 subService, CSSM_SERVICE_TYPE type) { } -void ModuleEvents::removal(uint32 subService, CSSM_SERVICE_TYPE type) { } -void ModuleEvents::fault(uint32 subService, CSSM_SERVICE_TYPE type) { } - - -void -ModuleImpl::appNotifyCallback(CSSM_API_ModuleEventHandler appNotifyCallback, void *appNotifyCallbackCtx) -{ - secdebug("callback","In ModuleImpl::appNotifyCallback, appNotifyCallback=%p, appNotifyCallbackCtx=%p", - appNotifyCallback, appNotifyCallbackCtx); - if (mActive) - Error::throwMe(Error::objectBusy); - - mAppNotifyCallback = appNotifyCallback; - mAppNotifyCallbackCtx = appNotifyCallbackCtx; -} - -void -ModuleImpl::appNotifyCallback(RawModuleEvents *handler) -{ - appNotifyCallback(RawModuleEvents::sendNotify, handler); -} - -void -ModuleImpl::activate() -{ - { - StLock _(mActivateMutex); - if (!mActive) - { - session()->init(); - // @@@ install handler here (use central dispatch with override) - secdebug("callback","In ModuleImpl::activate, mAppNotifyCallback=%p, mAppNotifyCallbackCtx=%p", - mAppNotifyCallback, mAppNotifyCallbackCtx); - check(CSSM_ModuleLoad(&guid(), CSSM_KEY_HIERARCHY_NONE, mAppNotifyCallback, mAppNotifyCallbackCtx)); - mActive = true; - } - } - - session()->catchExit(); -} - -void -ModuleImpl::deactivate() -{ - if (!isIdle()) - Error::throwMe(Error::objectBusy); - - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - check(CSSM_ModuleUnload(&guid(), mAppNotifyCallback, mAppNotifyCallbackCtx)); - } -} - -Cssm -ModuleImpl::session() const -{ - return parent(); -} - - -// -// CssmAttachment objects. -// parent ::= the loaded module object. -// active ::= attached. -// -AttachmentImpl::AttachmentImpl(const Guid &guid, CSSM_SERVICE_TYPE subserviceType) -: ObjectImpl(CssmImpl::standard()->autoModule(guid)) -{ - make(subserviceType); -} - -AttachmentImpl::AttachmentImpl(const Module &module, CSSM_SERVICE_TYPE subserviceType) -: ObjectImpl(module) -{ - make(subserviceType); -} - -AttachmentImpl::~AttachmentImpl() -{ - detach(); -} - -void -AttachmentImpl::make(CSSM_SERVICE_TYPE subserviceType) -{ - // default configuration - mVersion.Major = 2; - mVersion.Minor = 0; - mSubserviceType = subserviceType; - mSubserviceId = 0; - mAttachFlags = 0; -} - -void -AttachmentImpl::activate() -{ - StLock _(mActivateMutex); - if (!mActive) - { - module()->load(); - mMemoryFunctions = CssmAllocatorMemoryFunctions(allocator()); - check(CSSM_ModuleAttach(&guid(), &mVersion, - &mMemoryFunctions, - mSubserviceId, - mSubserviceType, - mAttachFlags, - CSSM_KEY_HIERARCHY_NONE, - NULL, 0, // no function pointer table return - NULL, // reserved - &mHandle)); - mActive = true; - } -} - -void -AttachmentImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - check(CSSM_ModuleDetach(mHandle)); - } -} - -CSSM_SERVICE_MASK -AttachmentImpl::subserviceMask() const -{ - return mSubserviceType; -} - -void -AttachmentImpl::subserviceId(uint32 id) -{ - mSubserviceId = id; -} - -CssmSubserviceUid -AttachmentImpl::subserviceUid() const -{ - return CssmSubserviceUid(guid(), &mVersion, mSubserviceId, subserviceMask()); -} - -Module -AttachmentImpl::module() const -{ - return parent(); -} diff --git a/OSX/include/security_cdsa_client/cssmclient.h b/OSX/include/security_cdsa_client/cssmclient.h deleted file mode 100644 index 53719b82..00000000 --- a/OSX/include/security_cdsa_client/cssmclient.h +++ /dev/null @@ -1,378 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cssmclient - common client interface to CSSM and MDS -// -#ifndef _H_CDSA_CLIENT_CSSMCLIENT -#define _H_CDSA_CLIENT_CSSMCLIENT 1 - -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace CssmClient { - - -// -// Forward declarations -// -class Cssm; -class Module; -class Attachment; - - -// -// An mixin for objects that have (store) GUIDs. -// The GUID value is meant to be set-once constant, and can be lock-handled accordingly. -// -class HasGuid { -public: - HasGuid(const Guid &guid) { mGuid = guid; } - HasGuid() { } - - const Guid &guid() const { return mGuid; } - -protected: - void setGuid(const Guid &guid) { mGuid = guid; } - -private: - Guid mGuid; -}; - - -// -// Exceptions are based on the CssmError utility class. We add our own class of client-side exceptions. -// -class Error : public CssmError { -public: - Error(CSSM_RETURN err) : CssmError(err) { } - virtual const char *what () const throw(); - - enum { - objectBusy = -1, - }; -}; - - -// -// The CssmObject abstract class models features common to different Cssm objects. -// It handles a tree hierarchy of objects (parent/children) safely. -// -class Object; - -class ObjectImpl : virtual public RefCount -{ -public: - explicit ObjectImpl(); // Constructor for Impl objects without a parent. - explicit ObjectImpl(const Object &parent); - virtual ~ObjectImpl(); - - bool isActive() const { return mActive; } - - virtual Allocator &allocator() const; - virtual void allocator(Allocator &alloc); - - // Pointer comparison by default. Subclasses may override. - virtual bool operator <(const ObjectImpl &other) const; - virtual bool operator ==(const ObjectImpl &other) const; - - static void check(CSSM_RETURN status); - bool isIdle() const { return mChildCount == 0; } - -protected: - bool mActive; // loaded, attached, etc. - RecursiveMutex mActivateMutex; - mutable Allocator *mAllocator; // allocator hierarchy (NULL => TBD) - - template Obj parent() const - { assert(mParent); return Obj(static_cast(&(*mParent))); } - - void addChild(); - void removeChild(); - - // {de,}activate() assume you have locked *this - virtual void activate() = 0; - virtual void deactivate() = 0; - -private: - RefPointer mParent; // parent object - AtomicCounter mChildCount; -}; - - -class Object -{ - friend class ObjectImpl; -public: - typedef ObjectImpl Impl; - explicit Object(Impl *impl) : mImpl(impl) {} - -protected: - // @@@ CSPDL subclass breaks if the is a static_cast - template _Impl &impl() const - { return dynamic_cast<_Impl &>(*mImpl); } - -public: - Impl *operator ->() const { return &(*mImpl); } - Impl &operator *() const { return *mImpl; } - - // @@@ Why is this needed. DbCursor which inheirits from Object wants to call this. - template _Impl &checkedImpl() const - { return dynamic_cast<_Impl &>(*mImpl); } - - bool operator !() const { return !mImpl; } - operator bool() const { return mImpl; } - - bool isActive() const { return mImpl && mImpl->isActive(); } - Allocator &allocator() const { return mImpl->allocator(); } - void release() { mImpl = NULL; } - - bool operator <(const Object &other) const - { return mImpl && other.mImpl ? *mImpl < *other.mImpl : mImpl < other.mImpl; } - bool operator ==(const Object &other) const - { return mImpl && other.mImpl ? *mImpl == *other.mImpl : mImpl == other.mImpl; } - - Impl* get() {return mImpl;} - -private: - RefPointer mImpl; -}; - - -// -// Event callback mix-in class -// -class ModuleImpl; - -class RawModuleEvents { - friend class ModuleImpl; -public: - virtual ~RawModuleEvents(); - - virtual void notify(uint32 subService, - CSSM_SERVICE_TYPE type, CSSM_MODULE_EVENT event) = 0; - -private: - static CSSM_RETURN sendNotify(const CSSM_GUID *, void *context, uint32 subService, - CSSM_SERVICE_TYPE type, CSSM_MODULE_EVENT event); -}; - -class ModuleEvents : public RawModuleEvents { -public: - virtual void insertion(uint32 subService, CSSM_SERVICE_TYPE type); - virtual void removal(uint32 subService, CSSM_SERVICE_TYPE type); - virtual void fault(uint32 subService, CSSM_SERVICE_TYPE type); - -protected: - void notify(uint32 subService, CSSM_SERVICE_TYPE type, CSSM_MODULE_EVENT event); -}; - - -// -// A CSSM loadable module. -// You rarely directly interact with these objects, but if you need to, -// here they are. -// -class ModuleImpl : public ObjectImpl, public HasGuid -{ -public: - ModuleImpl(const Guid &guid); - ModuleImpl(const Guid &guid, const Cssm &session); - virtual ~ModuleImpl(); - - void load() { activate(); } - void unload() { deactivate(); } - bool isLoaded() const { return isActive(); } - - Cssm session() const; - - void appNotifyCallback(CSSM_API_ModuleEventHandler appNotifyCallback, void *appNotifyCallbackCtx); - void appNotifyCallback(RawModuleEvents *handler); - -protected: - void activate(); - void deactivate(); - - CSSM_API_ModuleEventHandler mAppNotifyCallback; - void *mAppNotifyCallbackCtx; -}; - -class Module : public Object -{ -public: - typedef ModuleImpl Impl; - explicit Module(Impl *impl) : Object(impl) {} - Module() : Object(NULL) {} // XXX This might break operator < - Module(const Guid &guid) : Object(new Impl(guid)) {} - Module(const Guid &guid, const Cssm &session) : Object(new Impl(guid, session)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// An Attachment object. This is the base class of all typed attachment classes. -// -class AttachmentImpl : public ObjectImpl -{ -public: - AttachmentImpl(const Guid &guid, CSSM_SERVICE_TYPE subserviceType); - AttachmentImpl(const Module &module, CSSM_SERVICE_TYPE subserviceType); - //AttachmentImpl(... mds reference ...); - virtual ~AttachmentImpl(); - - // Virtual so that subclasses can return there true mask. - virtual CSSM_SERVICE_MASK subserviceMask() const; - - CSSM_SERVICE_TYPE subserviceType() const { return mSubserviceType; } - CSSM_VERSION version() const { return mVersion; } - void version(const CSSM_VERSION &v) { mVersion = v; } - uint32 subserviceId() const { return mSubserviceId; } - virtual void subserviceId(uint32 id); - CSSM_ATTACH_FLAGS flags() const { return mAttachFlags; } - void flags(CSSM_ATTACH_FLAGS f) { mAttachFlags = f; } - - void attach() { activate(); } - void detach() { deactivate(); } - bool attached() const { return isActive(); } - - Module module() const; - const Guid &guid() const { return module()->guid(); } - CSSM_MODULE_HANDLE handle() { attach(); return mHandle; } - - CssmSubserviceUid subserviceUid() const; - -protected: - void activate(); - void deactivate(); - -private: - void make(CSSM_SERVICE_TYPE subserviceType); // common constructor - - CSSM_MODULE_HANDLE mHandle; - - CSSM_SERVICE_TYPE mSubserviceType; // set by constructor - CSSM_VERSION mVersion; - uint32 mSubserviceId; - CSSM_ATTACH_FLAGS mAttachFlags; - - CssmAllocatorMemoryFunctions mMemoryFunctions; // set on attach() -}; - -class Attachment : public Object -{ -public: - typedef AttachmentImpl Impl; - explicit Attachment(Impl *impl) : Object(impl) {} - Attachment(const Guid &guid, CSSM_SERVICE_TYPE subserviceType) - : Object(new Impl(guid, subserviceType)) {} - Attachment(const Module &module, CSSM_SERVICE_TYPE subserviceType) - : Object(new Impl(module, subserviceType)) {} - //Attachment(... mds reference ...); - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// A CSSM session object. -// You usually only have one per program, or library, or what-not. -// -class Cssm; - -class CssmImpl : public ObjectImpl { - class StandardCssm; friend class StandardCssm; -public: - CssmImpl(); - virtual ~CssmImpl(); - - void init() { activate(); } - void terminate() { deactivate(); } - - CSSM_PRIVILEGE_SCOPE scope() const { return mScope; } - void scope(CSSM_PRIVILEGE_SCOPE sc) { mScope = sc; } - const Guid &callerGuid() const { return mCallerGuid; } - void callerGuid(const CSSM_GUID &guid) { mCallerGuid = Guid::overlay(guid); } - - Module autoModule(const Guid &guid); - -protected: - explicit CssmImpl(bool); // internal constructor - - void setup(); // constructor setup - - void activate(); - void deactivate(); - -private: - // CSSM global configuration -- picked up on each Init - CSSM_VERSION mVersion; - CSSM_PRIVILEGE_SCOPE mScope; - Guid mCallerGuid; - - // module repository: modules by guid (protected by self) - typedef map ModuleMap; - ModuleMap moduleMap; - Mutex mapLock; - -public: - static Cssm standard(); - static void catchExit(); - -private: - static void atExitHandler(); - - class StandardCssm : public Mutex { - public: - StandardCssm() : mCssm(NULL) { } - ~StandardCssm(); - void setCssm(CssmImpl *cssm); - void unsetCssm(CssmImpl *cssm); - CssmImpl *get(); - - private: - CssmImpl *mCssm; - }; - static ModuleNexus mStandard; -}; - -class Cssm : public Object -{ -public: - typedef CssmImpl Impl; - explicit Cssm(Impl *impl) : Object(impl) {} - explicit Cssm() : Object(new Impl()) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } - - static Cssm standard() { return CssmImpl::standard(); } -}; - -} // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_CSSMCLIENT diff --git a/OSX/include/security_cdsa_client/dl_standard.cpp b/OSX/include/security_cdsa_client/dl_standard.cpp deleted file mode 100644 index 4c11ba11..00000000 --- a/OSX/include/security_cdsa_client/dl_standard.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// mds_standard - standard-defined MDS record types -// -#include -#include - - -namespace Security { -namespace CssmClient { - - -// -// CDSA Common relation (one record per module) -// -static const char * const commonAttributes[] = { - "PrintName", - "Alias", - NULL -}; -DLCommonFields::DLCommonFields(const char * const * names) - : Record(commonAttributes) -{ - addAttributes(names); -} - -string DLCommonFields::printName() const { return mAttributes[0]; } -string DLCommonFields::alias() const - { return mAttributes[1].size() ? string(mAttributes[1]) : "(no value)"; } - - -// -// The all-record-types pseudo-record -// -AllDLRecords::AllDLRecords() - : DLCommonFields(NULL) -{ } - - -// -// CDSA Generic record attributes -// -static const char * const genericAttributes[] = { - NULL -}; -GenericRecord::GenericRecord() - : DLCommonFields(genericAttributes) -{ -} - - -// -// Apple "Generic Password" records -// -static const char * const genericPasswordAttributes[] = { - // if you find yourself here, you should add the attributes and their functions - NULL -}; -GenericPasswordRecord::GenericPasswordRecord() - : DLCommonFields(genericPasswordAttributes) -{ -} - - -// -// Common key attributes -// -static const char * const keyAttributes[] = { - "KeyClass", - "KeyType", - "KeySizeInBits", - "EffectiveKeySize", - "Label", - "ApplicationTag", - "Permanent", - "Private", - "Modifiable", - "Sensitive", - "AlwaysSensitive", - "Extractable", - "NeverExtractable", - "Encrypt", - "Decrypt", - "Derive", - "Sign", - "Verify", - "Wrap", - "Unwrap", - NULL -}; - -KeyRecord::KeyRecord() - : DLCommonFields(keyAttributes) -{ -} - -uint32 KeyRecord::keyClass() const { return mAttributes[2]; } -uint32 KeyRecord::type() const { return mAttributes[3]; } -uint32 KeyRecord::size() const { return mAttributes[4]; } -uint32 KeyRecord::effectiveSize() const { return mAttributes[5]; } -const CssmData &KeyRecord::label() const { return mAttributes[6]; } -const CssmData &KeyRecord::applicationTag() const { return mAttributes[7]; } -bool KeyRecord::isPermanent() const { return mAttributes[8]; } -bool KeyRecord::isPrivate() const { return mAttributes[9]; } -bool KeyRecord::isModifiable() const { return mAttributes[10]; } -bool KeyRecord::isSensitive() const { return mAttributes[11]; } -bool KeyRecord::wasAlwaysSensitive() const { return mAttributes[12]; } -bool KeyRecord::isExtractable() const { return mAttributes[13]; } -bool KeyRecord::wasNeverExtractable() const { return mAttributes[14]; } -bool KeyRecord::canEncrypt() const { return mAttributes[15]; } -bool KeyRecord::canDecrypt() const { return mAttributes[16]; } -bool KeyRecord::canDerive() const { return mAttributes[17]; } -bool KeyRecord::canSign() const { return mAttributes[18]; } -bool KeyRecord::canVerify() const { return mAttributes[19]; } -bool KeyRecord::canWrap() const { return mAttributes[20]; } -bool KeyRecord::canUnwrap() const { return mAttributes[21]; } - - -// -// Certificate attributes -// -static const char * const certAttributes[] = { - "CertType", - "CertEncoding", - "Subject", - "Issuer", - "SerialNumber", - "SubjectKeyIdentifier", - "PublicKeyHash", - NULL -}; - -X509CertRecord::X509CertRecord() - : DLCommonFields(certAttributes) -{ -} - -CSSM_CERT_TYPE X509CertRecord::type() const { return mAttributes[2]; } -CSSM_CERT_ENCODING X509CertRecord::encoding() const { return mAttributes[3]; } -const CssmData &X509CertRecord::subject() const { return mAttributes[4]; } -const CssmData &X509CertRecord::issuer() const { return mAttributes[5]; } -const CssmData &X509CertRecord::serial() const { return mAttributes[6]; } -const CssmData &X509CertRecord::subjectKeyIdentifier() const { return mAttributes[7]; } -const CssmData &X509CertRecord::publicKeyHash() const { return mAttributes[8]; } - - -// -// UnlockReferral attributes -// -static const char * const unlockReferralAttributes[] = { - "Type", - "DbName", - "DbNetname", - "DbGuid", - "DbSSID", - "DbSSType", - "KeyLabel", - "KeyAppTag", - NULL -}; - -UnlockReferralRecord::UnlockReferralRecord() - : DLCommonFields(unlockReferralAttributes) -{ -} - -uint32 UnlockReferralRecord::type() const { return mAttributes[2]; } -string UnlockReferralRecord::dbName() const { return mAttributes[3]; } -const CssmData &UnlockReferralRecord::dbNetname() const { return mAttributes[4]; } -const Guid &UnlockReferralRecord::dbGuid() const { return mAttributes[5]; } -uint32 UnlockReferralRecord::dbSSID() const { return mAttributes[6]; } -uint32 UnlockReferralRecord::dbSSType() const { return mAttributes[7]; } -const CssmData &UnlockReferralRecord::keyLabel() const { return mAttributes[8]; } -const CssmData &UnlockReferralRecord::keyApplicationTag() const { return mAttributes[9]; } - - -} // end namespace CssmClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/dl_standard.h b/OSX/include/security_cdsa_client/dl_standard.h deleted file mode 100644 index b39cdd90..00000000 --- a/OSX/include/security_cdsa_client/dl_standard.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dl_standard - standard-defined DL record types. -// -// These are the C++ record types corresponding to standard and Apple-defined -// DL relations. Note that not all standard fields are included; only those -// of particular interest to the implementation. Feel free to add field functions -// as needed. -// - -#ifndef _H_CDSA_CLIENT_DL_STANDARD -#define _H_CDSA_CLIENT_DL_STANDARD - -#include - - -namespace Security { -namespace CssmClient { - - -// -// All CDSA standard DL schemas contain these fields -// -class DLCommonFields : public Record { -public: - DLCommonFields(const char * const * names); - - string printName() const; - string alias() const; -}; - - -// -// A record type for all records in a DL, with PrintName (only) -// -class AllDLRecords : public DLCommonFields { -public: - AllDLRecords(); -}; - - -// -// The CDSA-standard "generic record" table -// -class GenericRecord : public DLCommonFields { -public: - GenericRecord(); - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_GENERIC; -}; - - -// -// Generic password records (Apple specific) -// -class GenericPasswordRecord : public DLCommonFields { -public: - GenericPasswordRecord(); - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_GENERIC_PASSWORD; -}; - - -// -// Key records -// -class KeyRecord : public DLCommonFields { -public: - KeyRecord(); - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_ALL_KEYS; - - uint32 keyClass() const; - uint32 type() const; - uint32 size() const; - uint32 effectiveSize() const; - const CssmData &label() const; - const CssmData &applicationTag() const; - - // boolean attributes for classification - bool isPermanent() const; - bool isPrivate() const; - bool isModifiable() const; - bool isSensitive() const; - bool wasAlwaysSensitive() const; - bool isExtractable() const; - bool wasNeverExtractable() const; - bool canEncrypt() const; - bool canDecrypt() const; - bool canDerive() const; - bool canSign() const; - bool canVerify() const; - bool canWrap() const; - bool canUnwrap() const; -}; - -class PrivateKeyRecord : public KeyRecord { -public: - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_PRIVATE_KEY; -}; - -class PublicKeyRecord : public KeyRecord { -public: - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_PUBLIC_KEY; -}; - -class SymmetricKeyRecord : public KeyRecord { -public: - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_SYMMETRIC_KEY; -}; - - -// -// X509 Certificate records -// -class X509CertRecord : public DLCommonFields { -public: - X509CertRecord(); - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_X509_CERTIFICATE; - - CSSM_CERT_TYPE type() const; - CSSM_CERT_ENCODING encoding() const; - const CssmData &subject() const; - const CssmData &issuer() const; - const CssmData &serial() const; - const CssmData &subjectKeyIdentifier() const; - const CssmData &publicKeyHash() const; -}; - - -// -// Unlock referral records -// -class UnlockReferralRecord : public DLCommonFields { -public: - UnlockReferralRecord(); - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_UNLOCK_REFERRAL; - - uint32 type() const; - string dbName() const; - const CssmData &dbNetname() const; - const Guid &dbGuid() const; - uint32 dbSSID() const; - uint32 dbSSType() const; - const CssmData &keyLabel() const; - const CssmData &keyApplicationTag() const; -}; - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_DL_STANDARD diff --git a/OSX/include/security_cdsa_client/dlclient.cpp b/OSX/include/security_cdsa_client/dlclient.cpp deleted file mode 100644 index 882fde1e..00000000 --- a/OSX/include/security_cdsa_client/dlclient.cpp +++ /dev/null @@ -1,905 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dlclient - client interface to CSSM DLs and their operations -// -#include -#include -#include -#include -#include - -using namespace CssmClient; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-const-variable" -// blob type for blobs created by these classes -- done so that we can change the formats later -const uint32 kBlobType = 0x1; -#pragma clang diagnostic pop - -// -// Abstract classes -// -DbMaker::~DbMaker() -{ /* virtual */ } - -DbCursorMaker::~DbCursorMaker() -{ /* virtual */ } - -DbUniqueRecordMaker::~DbUniqueRecordMaker() -{ /* virtual */ } - - -// -// Manage DL attachments -// -DLImpl::DLImpl(const Guid &guid) : AttachmentImpl(guid, CSSM_SERVICE_DL) -{ -} - -DLImpl::DLImpl(const Module &module) : AttachmentImpl(module, CSSM_SERVICE_DL) -{ -} - -DLImpl::~DLImpl() -{ -} - -void -DLImpl::getDbNames(char **) -{ - CssmError::throwMe(CSSMERR_DL_FUNCTION_NOT_IMPLEMENTED); -} - -void -DLImpl::freeNameList(char **) -{ - CssmError::throwMe(CSSMERR_DL_FUNCTION_NOT_IMPLEMENTED); -} - -DbImpl * -DLImpl::newDb(const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation) -{ - return new DbImpl(DL(this), inDbName, inDbLocation); -} - - -// -// Db (database) -// -DbImpl::DbImpl(const DL &dl, const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation) - : ObjectImpl(dl), mDbName(inDbName, inDbLocation), - mUseNameFromHandle(!inDbName), mNameFromHandle(NULL), - mAccessRequest(CSSM_DB_ACCESS_READ), mAccessCredentials(NULL), - mDefaultCredentials(NULL), mOpenParameters(NULL), mDbInfo(NULL), - mResourceControlContext(NULL) -{ -} - -DbImpl::~DbImpl() -{ - try - { - if (mNameFromHandle) - allocator().free(mNameFromHandle); - deactivate(); - } - catch(...) {} -} - -void -DbImpl::open() -{ - { - StLock _(mActivateMutex); - if (!mActive) - { - assert(mDbInfo == nil); - mHandle.DLHandle = dl()->handle(); - check(CSSM_DL_DbOpen(mHandle.DLHandle, mDbName.canonicalName(), dbLocation(), - mAccessRequest, mAccessCredentials, - mOpenParameters, &mHandle.DBHandle)); - - mActive = true; - } - } - - if (!mAccessCredentials && mDefaultCredentials) - if (const AccessCredentials *creds = mDefaultCredentials->makeCredentials()) - CSSM_DL_Authenticate(handle(), mAccessRequest, creds); // ignore error -} - -void -DbImpl::createWithBlob(CssmData &blob) -{ - if (mActive) - CssmError::throwMe(CSSMERR_DL_DATASTORE_ALREADY_EXISTS); - - if (mDbInfo == nil) { - // handle a missing (null) mDbInfo as an all-zero one - static const CSSM_DBINFO nullDbInfo = { }; - mDbInfo = &nullDbInfo; - } - - mHandle.DLHandle = dl()->handle(); - - // create a parameter block for our call to the passthrough - CSSM_APPLE_CSPDL_DB_CREATE_WITH_BLOB_PARAMETERS params; - - params.dbName = mDbName.canonicalName (); - params.dbLocation = dbLocation (); - params.dbInfo = mDbInfo; - params.accessRequest = mAccessRequest; - params.credAndAclEntry = NULL; - params.openParameters = mOpenParameters; - params.blob = &blob; - - check(CSSM_DL_PassThrough (mHandle, CSSM_APPLECSPDL_DB_CREATE_WITH_BLOB, ¶ms, (void**) &mHandle.DBHandle)); -} - -void -DbImpl::create() -{ - StLock _(mActivateMutex); - if (mActive) - CssmError::throwMe(CSSMERR_DL_DATASTORE_ALREADY_EXISTS); - - if (mDbInfo == nil) { - // handle a missing (null) mDbInfo as an all-zero one - static const CSSM_DBINFO nullDbInfo = { }; - mDbInfo = &nullDbInfo; - } - mHandle.DLHandle = dl()->handle(); - - if (!mResourceControlContext && mAccessCredentials) { - AclFactory::AnyResourceContext ctx(mAccessCredentials); - check(CSSM_DL_DbCreate(mHandle.DLHandle, mDbName.canonicalName(), dbLocation(), - mDbInfo, mAccessRequest, &ctx, - mOpenParameters, &mHandle.DBHandle)); - } else { - check(CSSM_DL_DbCreate(mHandle.DLHandle, mDbName.canonicalName(), dbLocation(), - mDbInfo, mAccessRequest, mResourceControlContext, - mOpenParameters, &mHandle.DBHandle)); - } - mActive = true; -} - -void -DbImpl::close() -{ - StLock _(mActivateMutex); - if (mActive) - { - check(CSSM_DL_DbClose (mHandle)); - mActive = false; - } -} - -void -DbImpl::activate() -{ - if (!mActive) - { - if (mDbInfo) - create(); - else - open(); - } -} - -void -DbImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - close(); - } -} - -void -DbImpl::deleteDb() -{ - // Deactivate so the db gets closed if it was open. - deactivate(); - // This call does not require the receiver to be active. - check(CSSM_DL_DbDelete(dl()->handle(), mDbName.canonicalName(), dbLocation(), - mAccessCredentials)); -} - -void -DbImpl::rename(const char *newName) -{ - // Deactivate so the db gets closed if it was open. - deactivate(); - if (::rename(mDbName.canonicalName(), newName)) - UnixError::throwMe(errno); - - // Change our DbName to reflect this rename. - mDbName = DbName(newName, dbLocation()); -} - -void -DbImpl::authenticate(CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_ACCESS_CREDENTIALS *inAccessCredentials) -{ - if (!mActive) - { - // XXX Could do the same for create but this would require sticking - // inAccessCredentials into mResourceControlContext. - if (!mDbInfo) - { - // We were not yet active. Just do an open. - accessRequest(inAccessRequest); - accessCredentials(inAccessCredentials); - activate(); - return; - } - } - - check(CSSM_DL_Authenticate(handle(), inAccessRequest, inAccessCredentials)); -} - -void -DbImpl::name(char *&outDbName) -{ - check(CSSM_DL_GetDbNameFromHandle(handle(), &outDbName)); -} - -const char * -DbImpl::name() -{ - if (mUseNameFromHandle) - { - if (mNameFromHandle - || !CSSM_DL_GetDbNameFromHandle(handle(), &mNameFromHandle)) - { - return mNameFromHandle; - } - - // We failed to get the name from the handle so use the passed - // in name instead - mUseNameFromHandle = false; - } - - return mDbName.canonicalName(); -} - -void -DbImpl::createRelation(CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo) -{ - check(CSSM_DL_CreateRelation(handle(), inRelationID, inRelationName, - inNumberOfAttributes, pAttributeInfo, - inNumberOfIndexes, pIndexInfo)); -} - -void -DbImpl::destroyRelation(CSSM_DB_RECORDTYPE inRelationID) -{ - check(CSSM_DL_DestroyRelation(handle(), inRelationID)); -} - -DbUniqueRecord -DbImpl::insert(CSSM_DB_RECORDTYPE recordType, const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data) -{ - DbUniqueRecord uniqueId(Db(this)); - check(CSSM_DL_DataInsert(handle(), recordType, - attributes, - data, uniqueId)); - // Activate uniqueId so CSSM_DL_FreeUniqueRecord() gets called when it goes out of scope. - uniqueId->activate(); - return uniqueId; -} - - -DbUniqueRecord -DbImpl::insertWithoutEncryption(CSSM_DB_RECORDTYPE recordType, const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - CSSM_DATA *data) -{ - DbUniqueRecord uniqueId(Db(this)); - - // fill out the parameters - CSSM_APPLECSPDL_DB_INSERT_WITHOUT_ENCRYPTION_PARAMETERS params; - params.recordType = recordType; - params.attributes = const_cast(attributes); - params.data = *data; - - // for clarity, call the overloaded operator to produce a unique record pointer - CSSM_DB_UNIQUE_RECORD_PTR *uniquePtr = uniqueId; - - // make the call - passThrough (CSSM_APPLECSPDL_DB_INSERT_WITHOUT_ENCRYPTION, ¶ms, (void**) uniquePtr); - - // Activate uniqueId so CSSM_DL_FreeUniqueRecord() gets called when it goes out of scope. - uniqueId->activate(); - return uniqueId; -} - - -// -// Generic Passthrough interface -// -void DbImpl::passThrough(uint32 passThroughId, const void *in, void **out) -{ - check(CSSM_DL_PassThrough(handle(), passThroughId, in, out)); -} - - -// -// Passthrough functions (only implemented by AppleCSPDL). -// -void -DbImpl::lock() -{ - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_LOCK, NULL, NULL)); -} - -void -DbImpl::unlock() -{ - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_UNLOCK, NULL, NULL)); -} - -void -DbImpl::unlock(const CSSM_DATA &password) -{ - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_UNLOCK, &password, NULL)); -} - -void -DbImpl::stash() -{ - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_STASH, NULL, NULL)); -} - -void -DbImpl::stashCheck() -{ - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_STASH_CHECK, NULL, NULL)); -} - -void -DbImpl::getSettings(uint32 &outIdleTimeout, bool &outLockOnSleep) -{ - CSSM_APPLECSPDL_DB_SETTINGS_PARAMETERS_PTR settings; - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_GET_SETTINGS, - NULL, reinterpret_cast(&settings))); - outIdleTimeout = settings->idleTimeout; - outLockOnSleep = settings->lockOnSleep; - allocator().free(settings); -} - -void -DbImpl::setSettings(uint32 inIdleTimeout, bool inLockOnSleep) -{ - CSSM_APPLECSPDL_DB_SETTINGS_PARAMETERS settings; - settings.idleTimeout = inIdleTimeout; - settings.lockOnSleep = inLockOnSleep; - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_SET_SETTINGS, &settings, NULL)); -} - -bool -DbImpl::isLocked() -{ - CSSM_APPLECSPDL_DB_IS_LOCKED_PARAMETERS_PTR params; - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_IS_LOCKED, - NULL, reinterpret_cast(¶ms))); - bool isLocked = params->isLocked; - allocator().free(params); - return isLocked; -} - -void -DbImpl::changePassphrase(const CSSM_ACCESS_CREDENTIALS *cred) -{ - CSSM_APPLECSPDL_DB_CHANGE_PASSWORD_PARAMETERS params; - params.accessCredentials = const_cast(cred); - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_CHANGE_PASSWORD, ¶ms, NULL)); -} - -void DbImpl::recode(const CSSM_DATA &data, const CSSM_DATA &extraData) -{ - // setup parameters for the recode call - CSSM_APPLECSPDL_RECODE_PARAMETERS params; - params.dbBlob = data; - params.extraData = extraData; - - // do the call - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_CSP_RECODE, ¶ms, NULL)); -} - -void DbImpl::copyBlob (CssmData &data) -{ - // do the call - check(CSSM_DL_PassThrough(handle(), CSSM_APPLECSPDL_DB_COPY_BLOB, NULL, (void**) (CSSM_DATA*) &data)); -} - -void DbImpl::setBatchMode(Boolean mode, Boolean rollback) -{ - // - // We need the DL_DB_Handle of the underyling DL in order to use CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT - // - CSSM_RETURN result; - CSSM_DL_DB_HANDLE dldbHandleOfUnderlyingDL; - result = CSSM_DL_PassThrough(handle(), - CSSM_APPLECSPDL_DB_GET_HANDLE, - NULL, - (void **)&dldbHandleOfUnderlyingDL); - // - // Now, toggle the autocommit... - // - if ( result == errSecSuccess ) - { - CSSM_BOOL modeToUse = !mode; - if (rollback) - { - result = (OSStatus)CSSM_DL_PassThrough(dldbHandleOfUnderlyingDL, - CSSM_APPLEFILEDL_ROLLBACK, NULL, NULL); - } - - result = CSSM_DL_PassThrough(dldbHandleOfUnderlyingDL, - CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - (void *)((size_t) modeToUse), - NULL); - if (!rollback && modeToUse) - result = CSSM_DL_PassThrough(dldbHandleOfUnderlyingDL, - CSSM_APPLEFILEDL_COMMIT, - NULL, - NULL); - } -} - -// -// DbCursorMaker -// -DbCursorImpl * -DbImpl::newDbCursor(const CSSM_QUERY &query, Allocator &allocator) -{ - return new DbDbCursorImpl(Db(this), query, allocator); -} - -DbCursorImpl * -DbImpl::newDbCursor(uint32 capacity, Allocator &allocator) -{ - return new DbDbCursorImpl(Db(this), capacity, allocator); -} - - -// -// Db adapters for AclBearer -// -void DbImpl::getAcl(AutoAclEntryInfoList &aclInfos, const char *selectionTag) const -{ - aclInfos.allocator(allocator()); - check(CSSM_DL_GetDbAcl(const_cast(this)->handle(), - reinterpret_cast(selectionTag), aclInfos, aclInfos)); -} - -void DbImpl::changeAcl(const CSSM_ACL_EDIT &aclEdit, - const CSSM_ACCESS_CREDENTIALS *accessCred) -{ - check(CSSM_DL_ChangeDbAcl(handle(), AccessCredentials::needed(accessCred), &aclEdit)); -} - -void DbImpl::getOwner(AutoAclOwnerPrototype &owner) const -{ - owner.allocator(allocator()); - check(CSSM_DL_GetDbOwner(const_cast(this)->handle(), owner)); -} - -void DbImpl::changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *accessCred) -{ - check(CSSM_DL_ChangeDbOwner(handle(), - AccessCredentials::needed(accessCred), &newOwner)); -} - -void DbImpl::defaultCredentials(DefaultCredentialsMaker *maker) -{ - mDefaultCredentials = maker; -} - - -// -// Abstract DefaultCredentialsMakers -// -DbImpl::DefaultCredentialsMaker::~DefaultCredentialsMaker() -{ /* virtual */ } - - -// -// Db adapters for DLAccess -// -CSSM_HANDLE Db::dlGetFirst(const CSSM_QUERY &query, CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, - CSSM_DATA *data, CSSM_DB_UNIQUE_RECORD *&id) -{ - CSSM_HANDLE result; - switch (CSSM_RETURN rc = CSSM_DL_DataGetFirst(handle(), &query, &result, &attributes, data, &id)) { - case CSSM_OK: - return result; - case CSSMERR_DL_ENDOFDATA: - return CSSM_INVALID_HANDLE; - default: - CssmError::throwMe(rc); - return CSSM_INVALID_HANDLE; // placebo - } -} - -bool Db::dlGetNext(CSSM_HANDLE query, CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, - CSSM_DATA *data, CSSM_DB_UNIQUE_RECORD *&id) -{ - CSSM_RETURN rc = CSSM_DL_DataGetNext(handle(), query, &attributes, data, &id); - switch (rc) { - case CSSM_OK: - return true; - case CSSMERR_DL_ENDOFDATA: - return false; - default: - CssmError::throwMe(rc); - return false; // placebo - } -} - -void Db::dlAbortQuery(CSSM_HANDLE query) -{ - CssmError::check(CSSM_DL_DataAbortQuery(handle(), query)); -} - -void Db::dlFreeUniqueId(CSSM_DB_UNIQUE_RECORD *id) -{ - CssmError::check(CSSM_DL_FreeUniqueRecord(handle(), id)); -} - -void Db::dlDeleteRecord(CSSM_DB_UNIQUE_RECORD *id) -{ - CssmError::check(CSSM_DL_DataDelete(handle(), id)); -} - -Allocator &Db::allocator() -{ - return Object::allocator(); -} - - -// -// DbUniqueRecordMaker -// -DbUniqueRecordImpl * -DbImpl::newDbUniqueRecord() -{ - return new DbUniqueRecordImpl(Db(this)); -} - - -// -// Utility methods -// -DLDbIdentifier -DbImpl::dlDbIdentifier() -{ - // Always use the same dbName and dbLocation that were passed in during - // construction - return DLDbIdentifier(dl()->subserviceUid(), mDbName.canonicalName(), dbLocation()); -} - - -// -// DbDbCursorImpl -// -DbDbCursorImpl::DbDbCursorImpl(const Db &db, const CSSM_QUERY &query, Allocator &allocator) -: DbCursorImpl(db, query, allocator), mResultsHandle(CSSM_INVALID_HANDLE) -{ -} - -DbDbCursorImpl::DbDbCursorImpl(const Db &db, uint32 capacity, Allocator &allocator) -: DbCursorImpl(db, capacity, allocator), mResultsHandle(CSSM_INVALID_HANDLE) -{ -} - -DbDbCursorImpl::~DbDbCursorImpl() -{ - try - { - deactivate(); - } - catch(...) {} -} - -bool -DbDbCursorImpl::next(DbAttributes *attributes, ::CssmDataContainer *data, DbUniqueRecord &uniqueId) -{ - if (attributes) - attributes->deleteValues(); - - if (data) - data->clear(); - - CSSM_RETURN result; - Db db(database()); - DbUniqueRecord unique(db); - if (!mActive) - { - // ask the CSP/DL if the requested record type exists - CSSM_BOOL boolResult; - CSSM_DL_PassThrough(db->handle(), CSSM_APPLECSPDL_DB_RELATION_EXISTS, &RecordType, (void**) &boolResult); - if (!boolResult) - { - if (data != NULL) - { - data->invalidate(); - } - - return false; - } - - result = CSSM_DL_DataGetFirst(db->handle(), - this, - &mResultsHandle, - attributes, - data, - unique); - - StLock _(mActivateMutex); - if (result == CSSM_OK) - mActive = true; - else if (data != NULL) - data->invalidate (); - } - else - { - result = CSSM_DL_DataGetNext(db->handle(), - mResultsHandle, - attributes, - data, - unique); - - if (result != CSSM_OK && data != NULL) - { - data->invalidate (); - } - } - - if (result != CSSM_OK && attributes != NULL) - { - attributes->invalidate(); - } - - if (result == CSSMERR_DL_ENDOFDATA) - { - StLock _(mActivateMutex); - mActive = false; - return false; - } - - check(result); - - // Activate uniqueId so CSSM_DL_FreeUniqueRecord() gets called when it goes out of scope. - unique->activate(); - uniqueId = unique; - return true; -} - -void -DbDbCursorImpl::activate() -{ -} - -void -DbDbCursorImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - check(CSSM_DL_DataAbortQuery(database()->handle(), mResultsHandle)); - } -} - - -// -// DbCursorImpl -// -DbCursorImpl::DbCursorImpl(const Object &parent, const CSSM_QUERY &query, Allocator &allocator) : -ObjectImpl(parent), CssmAutoQuery(query, allocator) -{ -} - -DbCursorImpl::DbCursorImpl(const Object &parent, uint32 capacity, Allocator &allocator) : -ObjectImpl(parent), CssmAutoQuery(capacity, allocator) -{ -} - -Allocator & -DbCursorImpl::allocator() const -{ - return ObjectImpl::allocator(); -} - -void -DbCursorImpl::allocator(Allocator &alloc) -{ - ObjectImpl::allocator(alloc); -} - - -// -// DbUniqueRecord -// -DbUniqueRecordImpl::DbUniqueRecordImpl(const Db &db) : ObjectImpl(db), mDestroyID (false) -{ -} - -DbUniqueRecordImpl::~DbUniqueRecordImpl() -{ - try - { - if (mDestroyID) - { - allocator ().free (mUniqueId); - } - - deactivate(); - } - catch(...) {} -} - -void -DbUniqueRecordImpl::deleteRecord() -{ - check(CSSM_DL_DataDelete(database()->handle(), mUniqueId)); -} - -void -DbUniqueRecordImpl::modify(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode) -{ - check(CSSM_DL_DataModify(database()->handle(), recordType, mUniqueId, - attributes, - data, modifyMode)); -} - -void -DbUniqueRecordImpl::modifyWithoutEncryption(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode) -{ - // fill out the parameters - CSSM_APPLECSPDL_DB_MODIFY_WITHOUT_ENCRYPTION_PARAMETERS params; - params.recordType = recordType; - params.uniqueID = mUniqueId; - params.attributes = const_cast(attributes); - params.data = (CSSM_DATA*) data; - params.modifyMode = modifyMode; - - // modify the data - check(CSSM_DL_PassThrough(database()->handle(), - CSSM_APPLECSPDL_DB_MODIFY_WITHOUT_ENCRYPTION, - ¶ms, - NULL)); -} - -void -DbUniqueRecordImpl::get(DbAttributes *attributes, - ::CssmDataContainer *data) -{ - if (attributes) - attributes->deleteValues(); - - if (data) - data->clear(); - - // @@@ Fix the allocators for attributes and data. - CSSM_RETURN result; - result = CSSM_DL_DataGetFromUniqueRecordId(database()->handle(), mUniqueId, - attributes, - data); - - if (result != CSSM_OK) - { - if (attributes) - attributes->invalidate(); - if (data != NULL) // the data returned is no longer valid - { - data->invalidate (); - } - } - - check(result); -} - -void -DbUniqueRecordImpl::getWithoutEncryption(DbAttributes *attributes, - ::CssmDataContainer *data) -{ - if (attributes) - attributes->deleteValues(); - - if (data) - data->clear(); - - // @@@ Fix the allocators for attributes and data. - CSSM_RETURN result; - - // make the parameter block - CSSM_APPLECSPDL_DB_GET_WITHOUT_ENCRYPTION_PARAMETERS params; - params.uniqueID = mUniqueId; - params.attributes = attributes; - - // get the data - ::CssmDataContainer recordData; - result = CSSM_DL_PassThrough(database()->handle(), CSSM_APPLECSPDL_DB_GET_WITHOUT_ENCRYPTION, ¶ms, - (void**) data); - check (result); -} - -void -DbUniqueRecordImpl::activate() -{ - StLock _(mActivateMutex); - mActive = true; -} - -void -DbUniqueRecordImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - check(CSSM_DL_FreeUniqueRecord(database()->handle(), mUniqueId)); - } -} - -void -DbUniqueRecordImpl::getRecordIdentifier(CSSM_DATA &data) -{ - check(CSSM_DL_PassThrough(database()->handle(), CSSM_APPLECSPDL_DB_GET_RECORD_IDENTIFIER, - mUniqueId, (void**) &data)); -} - -void DbUniqueRecordImpl::setUniqueRecordPtr(CSSM_DB_UNIQUE_RECORD_PTR uniquePtr) -{ - // clone the record - mUniqueId = (CSSM_DB_UNIQUE_RECORD_PTR) allocator ().malloc (sizeof (CSSM_DB_UNIQUE_RECORD)); - *mUniqueId = *uniquePtr; - mDestroyID = true; -} - -// -// DbAttributes -// -DbAttributes::DbAttributes() -: CssmAutoDbRecordAttributeData(0, Allocator::standard(), Allocator::standard()) -{ -} - -DbAttributes::DbAttributes(const Db &db, uint32 capacity, Allocator &allocator) -: CssmAutoDbRecordAttributeData(capacity, db->allocator(), allocator) -{ -} diff --git a/OSX/include/security_cdsa_client/dlclient.h b/OSX/include/security_cdsa_client/dlclient.h deleted file mode 100644 index 23c242c2..00000000 --- a/OSX/include/security_cdsa_client/dlclient.h +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dlclient - client interface to CSSM DLs and their operations -// - -#ifndef _H_CDSA_CLIENT_DLCLIENT -#define _H_CDSA_CLIENT_DLCLIENT 1 - -#include -#include -#include -#include -#include -#include -#include - - -namespace Security -{ - -namespace CssmClient -{ - -#define CSSM_DB_ATTR(ATTR) ATTR -#define CSSM_DB_ATTR_SCHEMA(ATTR) ATTR ## Schema - -#define CSSM_DB_INDEX(ATTR) ATTR ## Index -#define CSSM_DB_UNIQUE(ATTR) ATTR ## Unique - -// -// Helper macro for declaring and defining a Db index unique and non-unique attributes -// -#define CSSM_DB_INDEX_DECL(ATTR) static const CSSM_DB_INDEX_INFO CSSM_DB_INDEX(ATTR) -#define CSSM_DB_UNIQUE_DECL(ATTR) static const CSSM_DB_INDEX_INFO CSSM_DB_UNIQUE(ATTR) - - -// -// Use this macro for defining a non-unique attribute -// -#define CSSM_DB_INDEX_DEF(ATTR) \ -const CSSM_DB_INDEX_INFO CSSM_DB_INDEX(ATTR) = \ -{ \ - CSSM_DB_INDEX_NONUNIQUE, \ - CSSM_DB_INDEX_ON_ATTRIBUTE, \ - CSSM_DB_ATTR(ATTR) \ -} - -// -// Use this macro for defining a unique attribute - -// -#define CSSM_DB_UNIQUE_DEF(ATTR) \ -const CSSM_DB_INDEX_INFO CSSM_DB_UNIQUE(ATTR) = \ -{ \ - CSSM_DB_INDEX_UNIQUE, \ - CSSM_DB_INDEX_ON_ATTRIBUTE, \ - CSSM_DB_ATTR(ATTR) \ -} - - - -// -// Helper macro for declaring and defining a Db schema attributes -// Use this macro in your header to declare each attribute you require. -// -#define CSSM_DB_ATTR_DECL(ATTR) \ -static const CSSM_DB_ATTRIBUTE_INFO CSSM_DB_ATTR(ATTR); \ -static const CSSM_DB_SCHEMA_ATTRIBUTE_INFO CSSM_DB_ATTR_SCHEMA(ATTR) - -// -// Don't directly use this macro use one of the below instead. -// -#define CSSM_DB_ATTR_DEFINE_SCHEMA(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) \ -const CSSM_DB_SCHEMA_ATTRIBUTE_INFO CSSM_DB_ATTR_SCHEMA(ATTR) = \ -{ \ - INTEGER, \ - NAME, \ - { OID_LEN, OID_DATA }, \ - CSSM_DB_ATTRIBUTE_FORMAT_ ## VALUETYPE \ -} - - -// -// Use one of the following macros to defined each declared attribute required by your application. -// -// -// Use this macro to define attributes which are looked up by integer AttributeID. -// -#define CSSM_DB_INTEGER_ATTR(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) \ -const CSSM_DB_ATTRIBUTE_INFO ATTR = \ -{ \ - CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER, \ - {(char *)INTEGER}, \ - CSSM_DB_ATTRIBUTE_FORMAT_ ## VALUETYPE \ -};\ -\ -CSSM_DB_ATTR_DEFINE_SCHEMA(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) - -// -// Use this macro to define attributes which are looked up by string AttributeName. -// -#define CSSM_DB_NAME_ATTR(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) \ -const CSSM_DB_ATTRIBUTE_INFO ATTR = \ -{ \ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, \ - {NAME}, \ - CSSM_DB_ATTRIBUTE_FORMAT_ ## VALUETYPE \ -};\ -\ -CSSM_DB_ATTR_DEFINE_SCHEMA(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) - -// -// Use this macro to define attributes which are looked up by OID AttributeNameID. -// XXX This does not work yet. -// -#define CSSM_DB_OID_ATTR(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) \ -const CSSM_DB_ATTRIBUTE_INFO ATTR = \ -{ \ - CSSM_DB_ATTRIBUTE_NAME_AS_OID, \ - {{OID_LEN, OID_DATA}}, \ - CSSM_DB_ATTRIBUTE_FORMAT_ ## VALUETYPE \ -};\ -\ -CSSM_DB_ATTR_DEFINE_SCHEMA(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) - - -// -// Use this macro to define attributes which are part of the primary key. -// -#define CSSM_DB_PRIMARKEY_ATTR(ATTR, NAME) \ -const CSSM_DB_ATTRIBUTE_INFO ATTR = \ -{ \ - CSSM_DB_INDEX_UNIQUE, \ - CSSM_DB_INDEX_ON_ATTRIBUTE, \ - CSSM_DB_ATTRIBUTE_FORMAT_ ## VALUETYPE \ -};\ -\ -CSSM_DB_ATTR_DEFINE_SCHEMA(ATTR, INTEGER, NAME, OID_LEN, OID_DATA, VALUETYPE) - - - -// -// Maker interfaces used by various Impl objects -// - -// DbMaker -- someone who can create a new DbImpl. -class DbImpl; -class DbMaker -{ -public: - virtual ~DbMaker(); - virtual DbImpl *newDb(const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation) = 0; -}; - -// DbCursorMaker -- someone who can create a new DbCursorImpl. -class DbCursorImpl; -class DbCursorMaker -{ -public: - virtual ~DbCursorMaker(); - virtual DbCursorImpl *newDbCursor(const CSSM_QUERY &query, Allocator &allocator) = 0; - virtual DbCursorImpl *newDbCursor(uint32 capacity, Allocator &allocator) = 0; -}; - -// DbUniqueRecordMaker -- someone who can create a new DbUniqueRecordImpl. -class DbUniqueRecordImpl; -class DbUniqueRecordMaker -{ -public: - virtual ~DbUniqueRecordMaker(); - virtual DbUniqueRecordImpl *newDbUniqueRecord() = 0; -}; - - -// -// A DL attachment -// -class DLImpl : public AttachmentImpl, public DbMaker -{ -public: - DLImpl(const Guid &guid); - DLImpl(const Module &module); - virtual ~DLImpl(); - - virtual void getDbNames(char **); - virtual void freeNameList(char **); - - // DbMaker - virtual DbImpl *newDb(const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation); -private: -}; - -class DL : public Attachment -{ -public: - typedef DLImpl Impl; - - explicit DL(Impl *impl) : Attachment(impl) {} - DL() : Attachment(NULL) {} - DL(const Guid &guid) : Attachment(new Impl(guid)) {} - DL(const Module &module) : Attachment(new Impl(module)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } - - // Conversion to DbMaker. - operator DbMaker &() const { return impl(); } -}; - - -class DbAttributes; -class DbUniqueRecord; -class Db; - - -// -// A CSSM_DLDB handle. -// Dbs always belong to DLs (DL attachments) -// -class DbImpl : public ObjectImpl, public AclBearer, - public DbCursorMaker, public DbUniqueRecordMaker -{ -public: - DbImpl(const DL &dl, const char *inDbName = NULL, const CSSM_NET_ADDRESS *inDbLocation = NULL); - virtual ~DbImpl(); - - DL dl() const { return parent
(); } - Module module() const { return dl()->module(); } - - virtual void open(); - virtual void create(); - virtual void createWithBlob (CssmData &blob); - virtual void close(); - virtual void deleteDb(); - virtual void rename(const char *newName); - virtual void authenticate(CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_ACCESS_CREDENTIALS *inAccessCredentials); - virtual void name(char *&outName); // CSSM_DL_GetDbNameFromHandle() - - virtual void createRelation(CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo); - virtual void destroyRelation(CSSM_DB_RECORDTYPE inRelationID); - - virtual DbUniqueRecord insert(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data); - - virtual DbUniqueRecord insertWithoutEncryption(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - CSSM_DATA *data); - - const CSSM_DL_DB_HANDLE &handle() { activate(); return mHandle; } - - const DbName &dbName() { return mDbName; } - void dbName(const DbName &dbName) { mDbName = dbName; } - - // Attempt to get a (cached) name from CSSM_DL_GetDbNameFromHandle(), falls - // back to the name passed in to the constructor if this fails. - const char *name(); - - const CSSM_NET_ADDRESS *dbLocation() const { return mDbName.dbLocation(); } - - CSSM_DB_ACCESS_TYPE accessRequest() const { return mAccessRequest; } - void accessRequest(CSSM_DB_ACCESS_TYPE inAccessRequest) - { mAccessRequest = inAccessRequest; } - - const CSSM_ACCESS_CREDENTIALS *accessCredentials() const - { return mAccessCredentials; } - void accessCredentials(const CSSM_ACCESS_CREDENTIALS *inAccessCredentials) - { mAccessCredentials = inAccessCredentials; } - - const void *openParameters() const { return mOpenParameters; } - void openParameters(const void *inOpenParameters) - { mOpenParameters = inOpenParameters; } - - const CSSM_DBINFO *dbInfo() const { return mDbInfo; } - void dbInfo(const CSSM_DBINFO *inDbInfo) { mDbInfo = inDbInfo; } - - const ResourceControlContext *resourceControlContext() const - { return mResourceControlContext; } - void resourceControlContext(const CSSM_RESOURCE_CONTROL_CONTEXT *inResourceControlContext) - { mResourceControlContext = ResourceControlContext::overlay(inResourceControlContext); } - - void passThrough(uint32 passThroughId, const void *in, void **out = NULL); - - template - void passThrough(uint32 passThroughId, const TIn *in, TOut *out = NULL) - { passThrough(passThroughId, (const void *)in, (void **)out); } - - // Passthrough functions (only implemented by AppleCSPDL). - virtual void lock(); - virtual void unlock(); - virtual void unlock(const CSSM_DATA &password); - virtual void stash(); - virtual void stashCheck(); - virtual void getSettings(uint32 &outIdleTimeout, bool &outLockOnSleep); - virtual void setSettings(uint32 inIdleTimeout, bool inLockOnSleep); - virtual bool isLocked(); - virtual void changePassphrase(const CSSM_ACCESS_CREDENTIALS *cred); - virtual void recode(const CSSM_DATA &data, const CSSM_DATA &extraData); - virtual void copyBlob(CssmData &data); - virtual void setBatchMode(Boolean mode, Boolean rollback); - - // Utility methods - - // Always use the dbName and dbLocation that were passed in during - // construction. - virtual DLDbIdentifier dlDbIdentifier(); - - // DbCursorMaker - virtual DbCursorImpl *newDbCursor(const CSSM_QUERY &query, Allocator &allocator); - virtual DbCursorImpl *newDbCursor(uint32 capacity, Allocator &allocator); - - // DbUniqueRecordMaker - virtual DbUniqueRecordImpl *newDbUniqueRecord(); - - // Acl manipulation - void getAcl(AutoAclEntryInfoList &aclInfos, const char *selectionTag = NULL) const; - void changeAcl(const CSSM_ACL_EDIT &aclEdit, - const CSSM_ACCESS_CREDENTIALS *accessCred); - - // Acl owner manipulation - void getOwner(AutoAclOwnerPrototype &owner) const; - void changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *accessCred = NULL); - - // default-credential hook - class DefaultCredentialsMaker { - public: - virtual ~DefaultCredentialsMaker(); - virtual const AccessCredentials *makeCredentials() = 0; - }; - - void defaultCredentials(DefaultCredentialsMaker *maker); // NULL to turn off - - void activate(); - -protected: - void deactivate(); - -private: - CSSM_DL_DB_HANDLE mHandle; // CSSM DLDB handle - - DbName mDbName; - bool mUseNameFromHandle; // false if CSSM_DL_GetDbNameFromHandle failed - char *mNameFromHandle; // Cached CSSM_DL_GetDbNameFromHandle result. - CSSM_DB_ACCESS_TYPE mAccessRequest; - const CSSM_ACCESS_CREDENTIALS *mAccessCredentials; - DefaultCredentialsMaker *mDefaultCredentials; - const void *mOpenParameters; - - // Arguments to create - const CSSM_DBINFO *mDbInfo; - const ResourceControlContext *mResourceControlContext; -}; - - -class Db : public Object, public DLAccess -{ -public: - typedef DbImpl Impl; - typedef Impl::DefaultCredentialsMaker DefaultCredentialsMaker; - - explicit Db(Impl *impl) : Object(impl) {} - Db() : Object(NULL) {} - Db(DbMaker &maker, const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation = NULL) - : Object(maker.newDb(inDbName, inDbLocation)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } - - // Conversion to DbCursorMaker. - operator DbCursorMaker &() const { return impl(); } - // Conversion to DbUniqueRecordMaker. - operator DbUniqueRecordMaker &() const { return impl(); } - - const CSSM_DL_DB_HANDLE &handle() { return impl().handle(); } - -protected: - // DLAccess adapters - CSSM_HANDLE dlGetFirst(const CSSM_QUERY &query, - CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, CSSM_DATA *data, - CSSM_DB_UNIQUE_RECORD *&id); - bool dlGetNext(CSSM_HANDLE handle, - CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, CSSM_DATA *data, - CSSM_DB_UNIQUE_RECORD *&id); - void dlAbortQuery(CSSM_HANDLE handle); - void dlFreeUniqueId(CSSM_DB_UNIQUE_RECORD *id); - void dlDeleteRecord(CSSM_DB_UNIQUE_RECORD *id); - Allocator &allocator(); -}; - -// -// DbCursor -// - -// This class is still abstract. You must subclass it in order to be able to instantiate an instance. -class DbCursorImpl : public ObjectImpl, public CssmAutoQuery -{ -public: - DbCursorImpl(const Object &parent, const CSSM_QUERY &query, Allocator &allocator); - DbCursorImpl(const Object &parent, uint32 capacity, Allocator &allocator); - - virtual Allocator &allocator() const; - virtual void allocator(Allocator &alloc); - - virtual bool next(DbAttributes *attributes, ::CssmDataContainer *data, DbUniqueRecord &uniqueId) = 0; - void abort() { deactivate(); } -}; - -class DbCursor : public Object -{ -public: - typedef DbCursorImpl Impl; - - explicit DbCursor(Impl *impl) : Object(impl) {} - DbCursor() : Object(NULL) {} - DbCursor(DbCursorMaker &maker, const CSSM_QUERY &query, - Allocator &allocator = Allocator::standard()) - : Object(maker.newDbCursor(query, allocator)) {} - DbCursor(DbCursorMaker &maker, uint32 capacity = 0, - Allocator &allocator = Allocator::standard()) - : Object(maker.newDbCursor(capacity, allocator)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// DbUniqueRecord -// -class DbUniqueRecordImpl : public ObjectImpl -{ -public: - DbUniqueRecordImpl(const Db &db); - virtual ~DbUniqueRecordImpl(); - - virtual void deleteRecord(); - virtual void modify(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode); - - virtual void modifyWithoutEncryption (CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode); - - virtual void get(DbAttributes *attributes, ::CssmDataContainer *data); - - virtual void getWithoutEncryption(DbAttributes *attributes, ::CssmDataContainer *data); - - Db database() const { return parent(); } - - void free() { deactivate(); } - - // Client must call activate() after calling this function if mUniqueId is successfully set. - operator CSSM_DB_UNIQUE_RECORD_PTR *() { if (mActive) free(); return &mUniqueId; } - - operator CSSM_DB_UNIQUE_RECORD *() { return mUniqueId; } - operator const CSSM_DB_UNIQUE_RECORD *() const { return mUniqueId; } - - void activate(); - - void getRecordIdentifier(CSSM_DATA &data); - - void setUniqueRecordPtr (CSSM_DB_UNIQUE_RECORD_PTR uniquePtr); // because cast overloading is evil! - -protected: - void deactivate(); - - CSSM_DB_UNIQUE_RECORD_PTR mUniqueId; - bool mDestroyID; - RecursiveMutex mActivateMutex; -}; - -class DbUniqueRecord : public Object -{ -public: - typedef DbUniqueRecordImpl Impl; - - explicit DbUniqueRecord(Impl *impl) : Object(impl) {} - DbUniqueRecord() : Object(NULL) {} - DbUniqueRecord(DbUniqueRecordMaker &maker) : Object(maker.newDbUniqueRecord()) {} - - Impl *operator ->() { return &impl(); } - Impl &operator *() { return impl(); } - const Impl &operator *() const { return impl(); } - - // Conversion operators must be here. - - // Client must activate after calling this function if mUniqueId is successfully set. - operator CSSM_DB_UNIQUE_RECORD_PTR *() { return **this; } - - operator CSSM_DB_UNIQUE_RECORD *() { return **this; } - operator const CSSM_DB_UNIQUE_RECORD *() const { return **this; } -}; - - -// -// DbAttributes -// -class DbAttributes : public CssmAutoDbRecordAttributeData -{ -public: - DbAttributes(); - DbAttributes(const Db &db, uint32 capacity = 0, Allocator &allocator = Allocator::standard()); -}; - - -// -// DbDbCursor -- concrete subclass of DbCursorImpl for querying Db's -// -class DbDbCursorImpl : public DbCursorImpl -{ -public: - DbDbCursorImpl(const Db &db, const CSSM_QUERY &query, Allocator &allocator); - DbDbCursorImpl(const Db &db, uint32 capacity, Allocator &allocator); - virtual ~DbDbCursorImpl(); - - bool next(DbAttributes *attributes, ::CssmDataContainer *data, DbUniqueRecord &uniqueId); - -protected: - Db database() { return parent(); } - - void activate(); - void deactivate(); - -private: - CSSM_HANDLE mResultsHandle; - RecursiveMutex mActivateMutex; -}; - -} // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_DLCLIENT diff --git a/OSX/include/security_cdsa_client/dlclientpriv.cpp b/OSX/include/security_cdsa_client/dlclientpriv.cpp deleted file mode 100644 index 96d609bb..00000000 --- a/OSX/include/security_cdsa_client/dlclientpriv.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dlclientpriv - private client interface to CSSM DLs -// -// This file implements those (non-virtual) methods of Db/DbImpl that -// require additional libraries to function. The OS X linker is too inept -// to eliminate unused functions peacefully (as of OS X 10.3/XCode 1.5 anyway). -// -#include -#include -#include - -using namespace CssmClient; - - -// -// Currently empty. -// diff --git a/OSX/include/security_cdsa_client/dliterators.cpp b/OSX/include/security_cdsa_client/dliterators.cpp deleted file mode 100644 index 817ae646..00000000 --- a/OSX/include/security_cdsa_client/dliterators.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// mdsclient - friendly interface to CDSA MDS API -// -#include - - -namespace Security { -namespace CssmClient { - - -// -// DLAccess gets a virtual destructor just in case -// -DLAccess::~DLAccess() -{ } - - -// -// Basic Record objects (abstract) -// -Record::Record(const char * const * names) - : CssmAutoData(Allocator::standard(Allocator::sensitive)) -{ - addAttributes(names); -} - -void Record::addAttributes(const char * const * name) -{ - if (name) - while (*name) - mAttributes.add(CssmDbAttributeInfo(*name++)); -} - -Record::~Record() -{ } - - -// -// Tables and their components (non-template common features) -// -TableBase::TableBase(DLAccess &source, CSSM_DB_RECORDTYPE type, bool getData /* = true */) - : database(source), mRecordType(type), mGetData(getData) -{ -} - -TableBase::Handle::~Handle() -{ - if (query) - mAccess->dlAbortQuery(query); -} - -TableBase::Uid::~Uid() -{ - if (uid) - mAccess->dlFreeUniqueId(uid); -} - -TableBase::Iterator::Iterator(DLAccess *ac, CSSM_HANDLE query, - CSSM_DB_UNIQUE_RECORD *id, Record *record, bool getData) - : mAccess(ac), mQuery(new Handle(ac, query)), - mUid(new Uid(ac, id)), mRecord(record), mGetData(getData) -{ } - - -void TableBase::Iterator::advance(Record *fill) -{ - RefPointer newRecord = fill; // hold it safely - CSSM_DB_UNIQUE_RECORD *id; - CssmAutoData data(mAccess->allocator()); - if (mAccess->dlGetNext(mQuery->query, newRecord->attributes(), - mGetData ? &data.get() : NULL, id)) { - if (mGetData) - newRecord->recordData() = data; - mUid = new Uid(mAccess, id); - mRecord = newRecord; - } else { - mQuery->query = CSSM_INVALID_HANDLE; // was automatically aborted - // release all iterator resources and make me == end() - mQuery = NULL; - mUid = NULL; - mRecord = NULL; - } -} - - -uint32 TableBase::erase(const CSSM_QUERY &query) -{ - CSSM_DB_UNIQUE_RECORD *id; - CssmDbRecordAttributeData noAttributes; - CSSM_HANDLE handle = database.dlGetFirst(query, noAttributes, NULL, id); - if (handle == CSSM_INVALID_HANDLE) - return 0; // no match, nothing erased - uint32 count = 0; - do { - database.dlDeleteRecord(id); - count++; - database.dlFreeUniqueId(id); - } while (database.dlGetNext(handle, noAttributes, NULL, id)); - return count; -} - -uint32 TableBase::erase(const Query &query) -{ - return erase(query.cssmQuery()); -} - - -} // end namespace CssmClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/dliterators.h b/OSX/include/security_cdsa_client/dliterators.h deleted file mode 100644 index 5512c3a5..00000000 --- a/OSX/include/security_cdsa_client/dliterators.h +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dliterators - DL/MDS table access as C++ iterators -// -// This is currently an almost read-only implementation. -// (You can erase but you can't create or modify.) -// -#ifndef _H_CDSA_CLIENT_DLITERATORS -#define _H_CDSA_CLIENT_DLITERATORS - -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Security { -namespace CssmClient { - - -// -// An abstract interface to a (partial) DLDb-style object. -// This is a particular (open) database that you can perform CSSM database -// operations on. -// -class DLAccess { -public: - virtual ~DLAccess(); - - virtual CSSM_HANDLE dlGetFirst(const CSSM_QUERY &query, - CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, CSSM_DATA *data, - CSSM_DB_UNIQUE_RECORD *&id) = 0; - virtual bool dlGetNext(CSSM_HANDLE handle, - CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, CSSM_DATA *data, - CSSM_DB_UNIQUE_RECORD *&id) = 0; - virtual void dlAbortQuery(CSSM_HANDLE handle) = 0; - virtual void dlFreeUniqueId(CSSM_DB_UNIQUE_RECORD *id) = 0; - virtual void dlDeleteRecord(CSSM_DB_UNIQUE_RECORD *id) = 0; - virtual Allocator &allocator() = 0; -}; - - -// -// Abstract Database Records. -// Each database record type has a subclass of this. -// These are RefCounted; you can hang on to them as long as you like, -// stick (RefPointers to) them into maps, and so on. Just go for it. -// -class Record : public RefCount, public CssmAutoData { -public: - Record() : CssmAutoData(Allocator::standard(Allocator::sensitive)) { } - Record(const char * const * attributeNames); // sets mAttributes - virtual ~Record(); - static const CSSM_DB_RECORDTYPE recordType = CSSM_DL_DB_RECORD_ANY; - - void addAttributes(const char * const * attributeNames); // add more - - // raw attribute access - CssmDbRecordAttributeData &attributes() { return mAttributes; } - const CssmDbRecordAttributeData &attributes() const { return mAttributes; } - CSSM_DB_RECORDTYPE actualRecordType() const { return mAttributes.recordType(); } - - CssmAutoData &recordData() { return *this; } // my data nature - -protected: - CssmAutoDbRecordAttributeData mAttributes; -}; - - -// -// TableBase is an implementation class for template Table below. -// Do not use it directly (you'll be sorry). -// Continue reading at template Table below. -// -class TableBase { -public: - DLAccess &database; - - CSSM_DB_RECORDTYPE recordType() const { return mRecordType; } - void recordType(CSSM_DB_RECORDTYPE t) { mRecordType = t; } // override - - // erase all elements matching a query - uint32 erase(const CSSM_QUERY &query); - uint32 erase(const Query &query); - -protected: - TableBase(DLAccess &source, CSSM_DB_RECORDTYPE type, bool getData = true); - - class AccessRef : public RefCount { - protected: - AccessRef() : mAccess(NULL) { } - AccessRef(DLAccess *ac) : mAccess(ac) { } - DLAccess *mAccess; - }; - - struct Handle : public AccessRef { - CSSM_HANDLE query; - Handle(DLAccess *ac, CSSM_HANDLE q) : AccessRef(ac), query(q) { } - ~Handle(); - }; - - struct Uid : public AccessRef { - CSSM_DB_UNIQUE_RECORD *uid; - Uid(DLAccess *ac, CSSM_DB_UNIQUE_RECORD *id) : AccessRef(ac), uid(id) { } - ~Uid(); - }; - - class Iterator { - public: - const CSSM_DB_UNIQUE_RECORD *recordHandle() const - { assert(mUid); return mUid->uid; } - - protected: - Iterator() { } - Iterator(DLAccess *ac, CSSM_HANDLE query, CSSM_DB_UNIQUE_RECORD *id, - Record *record, bool getData); - void advance(Record *newRecord); // generic operator ++ helper - - DLAccess *mAccess; // data source - RefPointer mQuery; // DL/MDS query handle - RefPointer mUid; // record unique identifier - RefPointer mRecord; // current record value - bool mGetData; // ask for data on iteration - }; - -protected: - CSSM_DB_RECORDTYPE mRecordType; // CSSM/MDS record type - bool mGetData; // ask for record data on primary iteration -}; - - -// -// A Table represents a single relation in a database (of some kind) -// -template -class Table : private TableBase { - typedef RefPointer RecPtr; -public: - Table(DLAccess &source) : TableBase(source, RecordType::recordType) { } - Table(DLAccess &source, CSSM_DB_RECORDTYPE type) : TableBase(source, type) { } - Table(DLAccess &source, bool getData) : TableBase(source, RecordType::recordType, getData) { } - -public: - class iterator : public Iterator, - public std::iterator > { - friend class Table; - public: - iterator() { } - - bool operator == (const iterator &other) const - { return mUid.get() == other.mUid.get(); } - bool operator != (const iterator &other) const - { return mUid.get() != other.mUid.get(); } - - RecPtr operator * () const { return static_cast(mRecord.get()); } - RecordType *operator -> () const { return static_cast(mRecord.get()); } - iterator operator ++ () { advance(new RecordType); return *this; } - iterator operator ++ (int) { iterator old = *this; operator ++ (); return old; } - - void erase(); - - private: - iterator(DLAccess *ac, CSSM_HANDLE query, CSSM_DB_UNIQUE_RECORD *id, - RecordType *record, bool getData) - : Iterator(ac, query, id, record, getData) { } - }; - -public: - iterator begin(); - iterator find(const CSSM_QUERY &query); - iterator find(const Query &query); - iterator end() { return iterator(); } - RecPtr fetch(const Query &query, CSSM_RETURN err = CSSM_OK) // one-stop shopping - { return fetchFirst(find(query), err); } - RecPtr fetch(CSSM_RETURN err = CSSM_OK) // fetch first of type - { return fetchFirst(begin(), err); } - - // erase all records matching a query - void erase(const CSSM_QUERY &query); - void erase(const Query &query); - - void erase(iterator it) { it.erase(); } - -private: - iterator startQuery(const CssmQuery &query, bool getData); - RecPtr fetchFirst(iterator it, CSSM_RETURN err); -}; - - -// -// Template out-of-line functions -// -template -typename Table::iterator Table::begin() -{ - return startQuery(CssmQuery(mRecordType), mGetData); -} - -template -typename Table::iterator Table::find(const CSSM_QUERY &query) -{ - return startQuery(CssmQuery(CssmQuery::overlay(query), mRecordType), mGetData); -} - -template -typename Table::iterator Table::find(const Query &query) -{ - return startQuery(CssmQuery(query.cssmQuery(), mRecordType), mGetData); -} - -template -RefPointer Table::fetchFirst(iterator it, CSSM_RETURN err) -{ - if (it == end()) - if (err) - CssmError::throwMe(err); - else - return NULL; - else - return *it; -} - - -template -typename Table::iterator Table::startQuery(const CssmQuery &query, bool getData) -{ - RefPointer record = new RecordType; - CSSM_DB_UNIQUE_RECORD *id; - CssmAutoData data(database.allocator()); - CSSM_HANDLE queryHandle = database.dlGetFirst(query, record->attributes(), - getData ? &data.get() : NULL, id); - if (queryHandle == CSSM_INVALID_HANDLE) - return end(); // not found - if (getData) - record->recordData() = data; - return iterator(&database, queryHandle, id, record, getData); -} - - -template -void Table::iterator::erase() -{ - mAccess->dlDeleteRecord(mUid->uid); - mUid->uid = NULL; -} - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_DLITERATORS diff --git a/OSX/include/security_cdsa_client/dlquery.cpp b/OSX/include/security_cdsa_client/dlquery.cpp deleted file mode 100644 index f0d2bbac..00000000 --- a/OSX/include/security_cdsa_client/dlquery.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dlquery - search query sublanguage for DL and MDS queries -// -#include - - -namespace Security { -namespace CssmClient { - - -// -// Constructing Relations -// -Comparison::Comparison(const Comparison &r) - : mName(r.mName), mOperator(r.mOperator), mFormat(r.mFormat), - mValue(Allocator::standard()) -{ - mValue.copy(r.mValue); -} - -Comparison &Comparison::operator = (const Comparison &r) -{ - mName = r.mName; - mOperator = r.mOperator; - mFormat = r.mFormat; - mValue.copy(r.mValue); - return *this; -} - - -Comparison::Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const char *s) - : mName(attr.name()), mOperator(op), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_STRING), - mValue(Allocator::standard(), StringData(s)) -{ } - -Comparison::Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const std::string &s) - : mName(attr.name()), mOperator(op), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_STRING), - mValue(Allocator::standard(), StringData(s)) -{ } - -Comparison::Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, uint32 value) - : mName(attr.name()), mOperator(op), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_UINT32), - mValue(Allocator::standard(), CssmData::wrap(value)) -{ } - -Comparison::Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, bool value) - : mName(attr.name()), mOperator(op), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_UINT32), - mValue(Allocator::standard(), CssmData::wrap(uint32(value ? 1 : 0))) -{ } - -Comparison::Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const CssmData &data) - : mName(attr.name()), mOperator(op), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_BLOB), - mValue(Allocator::standard(), data) -{ } - -Comparison::Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const CSSM_GUID &guid) - : mName(attr.name()), mOperator(op), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_STRING), - mValue(Allocator::standard(), StringData(Guid::overlay(guid).toString())) -{ -} - - -Comparison::Comparison(const Attribute &attr) - : mName(attr.name()), mOperator(CSSM_DB_NOT_EQUAL), mFormat(CSSM_DB_ATTRIBUTE_FORMAT_UINT32), - mValue(Allocator::standard(), CssmData::wrap(uint32(CSSM_FALSE))) -{ -} - -Comparison operator ! (const Attribute &attr) -{ - return Comparison(attr, CSSM_DB_EQUAL, uint32(CSSM_FALSE)); -} - - -// -// Query methods -// -Query &Query::operator = (const Query &q) -{ - mRelations = q.mRelations; - mQueryValid = false; - return *this; -} - - -// -// Form the CssmQuery from a Query object. -// We cache this in mQuery, which we have made sure isn't copied along. -// -const CssmQuery &Query::cssmQuery() const -{ - if (!mQueryValid) { - // record type remains at ANY - mQuery.conjunctive(CSSM_DB_AND); - for (vector::const_iterator it = mRelations.begin(); it != mRelations.end(); it++) { - CssmSelectionPredicate pred; - pred.dbOperator(it->mOperator); - pred.attribute().info() = CssmDbAttributeInfo(it->mName.c_str(), it->mFormat); - pred.attribute().set(it->mValue.get()); - mPredicates.push_back(pred); - } - mQuery.set((uint32)mPredicates.size(), &mPredicates[0]); - mQueryValid = true; - } - return mQuery; -} - - -} // end namespace CssmClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/dlquery.h b/OSX/include/security_cdsa_client/dlquery.h deleted file mode 100644 index dc976b1e..00000000 --- a/OSX/include/security_cdsa_client/dlquery.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// dlquery - search query sublanguage for DL and MDS queries -// - -#ifndef _H_CDSA_CLIENT_DLQUERY -#define _H_CDSA_CLIENT_DLQUERY - -#include -#include -#include - - -namespace Security { -namespace CssmClient { - - -// -// A DL record attribute -// -class Attribute { -public: - Attribute(const std::string &name) : mName(name) { } - Attribute(const char *name) : mName(name) { } - - const std::string &name() const { return mName; } - -private: - std::string mName; -}; - - -// -// A comparison (attribute ~rel~ constant-value) -// -class Comparison { - friend class Query; -public: - Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const char *s); - Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const std::string &s); - Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, uint32 v); - Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, bool v); - Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const CSSM_GUID &guid); - Comparison(const Attribute &attr, CSSM_DB_OPERATOR op, const CssmData &data); - - Comparison(const Attribute &attr); - friend Comparison operator ! (const Attribute &attr); - - Comparison(const Comparison &r); - Comparison &operator = (const Comparison &r); - -private: - std::string mName; - CSSM_DB_OPERATOR mOperator; - CSSM_DB_ATTRIBUTE_FORMAT mFormat; - CssmAutoData mValue; -}; - -template -Comparison operator == (const Attribute &attr, const Value &value) -{ return Comparison(attr, CSSM_DB_EQUAL, value); } - -template -Comparison operator != (const Attribute &attr, const Value &value) -{ return Comparison(attr, CSSM_DB_NOT_EQUAL, value); } - -template -Comparison operator < (const Attribute &attr, const Value &value) -{ return Comparison(attr, CSSM_DB_LESS_THAN, value); } - -template -Comparison operator > (const Attribute &attr, const Value &value) -{ return Comparison(attr, CSSM_DB_GREATER_THAN, value); } - -template -Comparison operator % (const Attribute &attr, const Value &value) -{ return Comparison(attr, CSSM_DB_CONTAINS, value); } - - -// -// A Query -// -class Query { -public: - Query() : mQueryValid(false) { } - Query(const Comparison r) : mQueryValid(false) { mRelations.push_back(r); } - Query(const Attribute &attr) : mQueryValid(false) { mRelations.push_back(attr); } - - Query(const Query &q) : mRelations(q.mRelations), mQueryValid(false) { } - - Query &operator = (const Query &q); - - Query &add(const Comparison &r) - { mRelations.push_back(r); return *this; } - - const CssmQuery &cssmQuery() const; - -private: - std::vector mRelations; - - // cached CssmQuery equivalent of this object - mutable bool mQueryValid; // mQuery has been constructed - mutable vector mPredicates; // holds lifetimes for mQuery - mutable CssmQuery mQuery; -}; - -inline Query operator && (Query c, const Comparison &r) -{ return c.add(r); } - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_DLQUERY diff --git a/OSX/include/security_cdsa_client/genkey.cpp b/OSX/include/security_cdsa_client/genkey.cpp deleted file mode 100644 index ab881784..00000000 --- a/OSX/include/security_cdsa_client/genkey.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// genkey - client interface to CSSM sign/verify contexts -// -#include - -using namespace CssmClient; - - -GenerateKey::GenerateKey(const CSP &csp, CSSM_ALGORITHMS alg, uint32 size) -: Context(csp, alg), mKeySize(size), mSeed(NULL), mSalt(NULL), mParams(NULL) -{ -} - -void -GenerateKey::database(const Db &inDb) -{ - mDb = inDb; - if (mDb && isActive()) - set(CSSM_ATTRIBUTE_DL_DB_HANDLE, mDb->handle()); -} - -void GenerateKey::activate() -{ - StLock _(mActivateMutex); - if (!mActive) - { - check(CSSM_CSP_CreateKeyGenContext(attachment()->handle(), mAlgorithm, - mKeySize, mSeed, mSalt, NULL, NULL, mParams, &mHandle)); - // Must be done before calling set() since is does nothing unless we are active. - // Also we are technically active even if set() throws since we already created a context. - mActive = true; - if (mDb) - set(CSSM_ATTRIBUTE_DL_DB_HANDLE, mDb->handle()); - } -} - -Key GenerateKey::operator () (const KeySpec &spec) -{ - Key key; - - check(CSSM_GenerateKey(handle(), spec.usage, spec.attributes, spec.label, - &compositeRcc(), key.makeNewKey(attachment()))); - - key->activate(); - - return key; -} - -void GenerateKey::operator () (CssmKey &key, const KeySpec &spec) -{ - check(CSSM_GenerateKey(handle(), spec.usage, spec.attributes, spec.label, &compositeRcc(), &key)); - -} - -void GenerateKey::operator () (Key &publicKey, const KeySpec &pubSpec, - Key &privateKey, const KeySpec &privSpec) -{ - check(CSSM_GenerateKeyPair(handle(), - pubSpec.usage, pubSpec.attributes, - pubSpec.label, publicKey.makeNewKey(attachment()), - privSpec.usage, privSpec.attributes, - privSpec.label, &compositeRcc(), privateKey.makeNewKey(attachment()))); - - publicKey->activate(); - privateKey->activate(); - -} - -void GenerateKey::operator () (CssmKey &publicKey, const KeySpec &pubSpec, - CssmKey &privateKey, const KeySpec &privSpec) -{ - check(CSSM_GenerateKeyPair(handle(), - pubSpec.usage, pubSpec.attributes, pubSpec.label, &publicKey, - privSpec.usage, privSpec.attributes, privSpec.label, &compositeRcc(), &privateKey)); -} - diff --git a/OSX/include/security_cdsa_client/genkey.h b/OSX/include/security_cdsa_client/genkey.h deleted file mode 100644 index 4d112f3f..00000000 --- a/OSX/include/security_cdsa_client/genkey.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// genkey - client interface to CSSM sign/verify contexts -// -#ifndef _H_CDSA_CLIENT_GENKEY -#define _H_CDSA_CLIENT_GENKEY 1 - -#include -#include -#include -#include - - -namespace Security -{ - -namespace CssmClient -{ - -class GenerateKey : public Context, public RccBearer { -public: - GenerateKey(const CSP &csp, CSSM_ALGORITHMS alg, uint32 size = 0); - -public: - // context parameters - void size(uint32 s) { mKeySize = s; set(CSSM_ATTRIBUTE_KEY_LENGTH, s); } - void seed(const CssmCryptoData &s) { mSeed = &s; set(CSSM_ATTRIBUTE_SEED, s); } - void salt(const CssmData &s) { mSalt = &s;set(CSSM_ATTRIBUTE_SALT, s); } - void params(const CssmData &p) { mParams = &p; set(CSSM_ATTRIBUTE_ALG_PARAMS, p); } - void database(const Db &inDb); - - // symmetric key generation - Key operator () (const KeySpec &spec); - void operator () (CssmKey &key, const KeySpec &spec); - - // asymmetric key generation - void operator () (Key &publicKey, const KeySpec &publicSpec, - Key &privateKey, const KeySpec &privateSpec); - void operator () (CssmKey &publicKey, const KeySpec &publicSpec, - CssmKey &privateKey, const KeySpec &privateSpec); - - -protected: - void activate(); - -private: - // context parameters - uint32 mKeySize; - const CssmCryptoData *mSeed; - const CssmData *mSalt; - const CssmData *mParams; - Db mDb; - - // generation parameters(?) -- Unused - // const ResourceControlContext *mInitialAcl; -}; - -} // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_GENKEY diff --git a/OSX/include/security_cdsa_client/keychainacl.cpp b/OSX/include/security_cdsa_client/keychainacl.cpp deleted file mode 100644 index 271774c9..00000000 --- a/OSX/include/security_cdsa_client/keychainacl.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// keychainacl - Keychain-related ACL and credential forms -// -#ifdef __MWERKS__ -#define _CPP_KEYCHAINACL -#endif - -#include "keychainacl.h" -#include - -using namespace CssmClient; - - -// -// Construct the factory. -// @@@ Leaks. -// -KeychainAclFactory::KeychainAclFactory(Allocator &alloc) -: allocator(alloc), nullCred(alloc, 1), kcCred(alloc, 2), kcUnlockCred(alloc, 1) -{ - // the credential objects self-initialize to empty - nullCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_THRESHOLD); - - kcCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT); - kcCred.sample(1) = TypedList(alloc, CSSM_SAMPLE_TYPE_THRESHOLD, - new(alloc) ListElement(TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT))); - - // @@@ This leaks a ListElement(CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT) - kcUnlockCred.sample(0) = TypedList(alloc, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, - new(alloc) ListElement(CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT)); -} - -KeychainAclFactory::~KeychainAclFactory() -{ -} - - -// -// Produce credentials. -// These are constants that don't need to be allocated per use. -// -const AccessCredentials *KeychainAclFactory::nullCredentials() -{ - return &nullCred; -} - -const AccessCredentials *KeychainAclFactory::keychainPromptCredentials() -{ - return &kcCred; -} - -const AccessCredentials *KeychainAclFactory::keychainPromptUnlockCredentials() -{ - return &kcUnlockCred; -} - -const AutoCredentials *KeychainAclFactory::passwordChangeCredentials(const CssmData &password) -{ - AutoCredentials *cred = new AutoCredentials(allocator, 1); - // @@@ This leaks a ListElement(CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT) and ListElement(password) - cred->sample(0) = TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK, - new(allocator) ListElement(CSSM_SAMPLE_TYPE_PASSWORD), - new(allocator) ListElement(password)); - return cred; -} - -const AutoCredentials *KeychainAclFactory::passwordUnlockCredentials(const CssmData &password) -{ - AutoCredentials *cred = new AutoCredentials(allocator, 1); - // @@@ This leaks a ListElement(CSSM_SAMPLE_TYPE_KEYCHAIN_PROMPT) and ListElement(password) - cred->sample(0) = TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK, - new(allocator) ListElement(CSSM_SAMPLE_TYPE_PASSWORD), - new(allocator) ListElement(password)); - return cred; -} - - -// -// -AclEntryInput *KeychainAclFactory::keychainPromptOwner(const CssmData &description) -{ - // @@@ Make sure this works for a NULL description - AclEntryPrototype proto(TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_KEYCHAIN_PROMPT, - new(allocator) ListElement(allocator, description))); - return new(allocator) AclEntryInput(proto); -} - -AclEntryInput *KeychainAclFactory::anyOwner() -{ - AclEntryPrototype proto(TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_ANY)); - return new(allocator) AclEntryInput(proto); -} - -void KeychainAclFactory::release(AclEntryInput *input) -{ - DataWalkers::chunkFree(input, allocator); -} - - -// -// ACL editing -// -void KeychainAclFactory::comment(TypedList &subject) -{ - subject.insert(new(allocator) ListElement(CSSM_ACL_SUBJECT_TYPE_COMMENT), - subject.first()); -} - -void KeychainAclFactory::uncomment(TypedList &subject) -{ - ListElement *first = subject.first(); - assert(*first == CSSM_ACL_SUBJECT_TYPE_COMMENT); - subject -= first; - destroy(first, allocator); -} diff --git a/OSX/include/security_cdsa_client/keychainacl.h b/OSX/include/security_cdsa_client/keychainacl.h deleted file mode 100644 index 05e1354d..00000000 --- a/OSX/include/security_cdsa_client/keychainacl.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// keychainacl - Keychain-related ACL and credential forms -// -#ifndef _KEYCHAINACL -#define _KEYCHAINACL - -#include -#include -#include -#include - -#ifdef _CPP_KEYCHAINACL -# pragma export on -#endif - - -namespace Security -{ - -namespace CssmClient -{ - -class KeychainAclFactory -{ -public: - KeychainAclFactory(Allocator &alloc); - ~KeychainAclFactory(); - - Allocator &allocator; - -public: - // - // Create credentials. These functions return AccessCredentials pointers. - // - const AccessCredentials *nullCredentials(); - const AccessCredentials *keychainPromptCredentials(); - const AccessCredentials *keychainPromptUnlockCredentials(); - const AutoCredentials *passwordChangeCredentials(const CssmData &password); - const AutoCredentials *passwordUnlockCredentials(const CssmData &password); - -public: - // - // Create initial ACLs. Pass those to resource creation functions. - // - AclEntryInput *keychainPromptOwner(const CssmData &description); - AclEntryInput *anyOwner(); - void release(AclEntryInput *input); - -public: - // - // Edit ACLs (in external form, as TypedLists) - // - void comment(TypedList &subject); - void uncomment(TypedList &subject); - -private: - AutoCredentials nullCred; - AutoCredentials kcCred; - AutoCredentials kcUnlockCred; -}; - - -} // end namespace CssmClient - -} // end namespace Security - -#ifdef _CPP_KEYCHAINACL -# pragma export off -#endif - -#endif //_KEYCHAINACL diff --git a/OSX/include/security_cdsa_client/keyclient.cpp b/OSX/include/security_cdsa_client/keyclient.cpp deleted file mode 100644 index 5bf04d6e..00000000 --- a/OSX/include/security_cdsa_client/keyclient.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// keyclient -// -#include -#include - - -using namespace CssmClient; - - -KeyImpl::KeyImpl(const CSP &csp) : ObjectImpl(csp), CssmKey() -{ - mActive=false; -} - -KeyImpl::KeyImpl(const CSP &csp, const CSSM_KEY &key, bool copy) : ObjectImpl(csp), CssmKey(key) -{ - if (copy) - keyData() = CssmAutoData(csp.allocator(), keyData()).release(); - mActive=true; -} - -KeyImpl::KeyImpl(const CSP &csp, const CSSM_DATA &keyData) : ObjectImpl(csp), -CssmKey((uint32)keyData.Length, csp->allocator().alloc((UInt32)keyData.Length)) -{ - memcpy(KeyData.Data, keyData.Data, keyData.Length); - mActive=true; -} - -KeyImpl::~KeyImpl() -try -{ - deactivate(); -} -catch (...) -{ -} - -void -KeyImpl::deleteKey(const CSSM_ACCESS_CREDENTIALS *cred) -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive=false; - check(CSSM_FreeKey(csp()->handle(), cred, this, CSSM_TRUE)); - } -} - -CssmKeySize -KeyImpl::sizeInBits() const -{ - CssmKeySize size; - check(CSSM_QueryKeySizeInBits(csp()->handle(), CSSM_INVALID_HANDLE, this, &size)); - return size; -} - -void -KeyImpl::getAcl(AutoAclEntryInfoList &aclInfos, const char *selectionTag) const -{ - aclInfos.allocator(allocator()); - check(CSSM_GetKeyAcl(csp()->handle(), this, reinterpret_cast(selectionTag), aclInfos, aclInfos)); -} - -void -KeyImpl::changeAcl(const CSSM_ACL_EDIT &aclEdit, - const CSSM_ACCESS_CREDENTIALS *accessCred) -{ - check(CSSM_ChangeKeyAcl(csp()->handle(), - AccessCredentials::needed(accessCred), &aclEdit, this)); -} - -void -KeyImpl::getOwner(AutoAclOwnerPrototype &owner) const -{ - owner.allocator(allocator()); - check(CSSM_GetKeyOwner(csp()->handle(), this, owner)); -} - -void -KeyImpl::changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *accessCred) -{ - check(CSSM_ChangeKeyOwner(csp()->handle(), - AccessCredentials::needed(accessCred), this, &newOwner)); -} - -void KeyImpl::activate() -{ - StLock _(mActivateMutex); - mActive=true; -} - -void KeyImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive=false; - check(CSSM_FreeKey(csp()->handle(), NULL, this, CSSM_FALSE)); - } -} diff --git a/OSX/include/security_cdsa_client/keyclient.h b/OSX/include/security_cdsa_client/keyclient.h deleted file mode 100644 index 36e332c7..00000000 --- a/OSX/include/security_cdsa_client/keyclient.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// keyclient -// -#ifndef _H_CDSA_CLIENT_KEYCLIENT -#define _H_CDSA_CLIENT_KEYCLIENT 1 - -#include -#include - -namespace Security -{ - -namespace CssmClient -{ - -// -// Key -// -class KeyImpl : public ObjectImpl, public AclBearer, public CssmKey -{ -public: - KeyImpl(const CSP &csp); - KeyImpl(const CSP &csp, const CSSM_KEY &key, bool copy = false); - KeyImpl(const CSP &csp, const CSSM_DATA &keyData); - virtual ~KeyImpl(); - - CSP csp() const { return parent(); } - void deleteKey(const CSSM_ACCESS_CREDENTIALS *cred); - - CssmKeySize sizeInBits() const; - - // Acl manipulation - void getAcl(AutoAclEntryInfoList &aclInfos, const char *selectionTag = NULL) const; - void changeAcl(const CSSM_ACL_EDIT &aclEdit, - const CSSM_ACCESS_CREDENTIALS *accessCred); - - // Acl owner manipulation - void getOwner(AutoAclOwnerPrototype &owner) const; - void changeOwner(const CSSM_ACL_OWNER_PROTOTYPE &newOwner, - const CSSM_ACCESS_CREDENTIALS *accessCred = NULL); - - // Call this after completing the CSSM API call after having called Key::makeNewKey() - void activate(); - -protected: - void deactivate(); -}; - -class Key : public Object -{ -public: - typedef KeyImpl Impl; - explicit Key(Impl *impl) : Object(impl) {} - - Key() : Object(NULL) {} - Key(const CSP &csp, const CSSM_KEY &key, bool copy = false) : Object(new Impl(csp, key, copy)) {} - Key(const CSP &csp, const CSSM_DATA &keyData) : Object(new Impl(csp, keyData)) {} - - // Creates an inactive key, client must call activate() after this. - Key(const CSP &csp) : Object(new Impl(csp)) {} - - Impl *operator ->() const { return (*this) ? &impl() : NULL; } - Impl &operator *() const { return impl(); } - - // Conversion operators to CssmKey baseclass. - operator const CssmKey * () const { return (*this) ? &(**this) : NULL; } - operator const CssmKey & () const { return **this; } - - // a few shortcuts to make life easier - CssmKey::Header &header() const { return (*this)->header(); } - - // Creates an inactive key, client must call activate() after this. - CssmKey *makeNewKey(const CSP &csp) { (*this) = Key(csp); return &(**this); } - - // inquiries - CssmKeySize sizeInBits() const { return (*this)->sizeInBits(); } -}; - - -struct KeySpec { - CSSM_KEYUSE usage; - CSSM_KEYATTR_FLAGS attributes; - const CssmData *label; - //add rc context - - KeySpec(CSSM_KEYUSE u, CSSM_KEYATTR_FLAGS a) : usage(u), attributes(a), label(NULL) { } - KeySpec(CSSM_KEYUSE u, CSSM_KEYATTR_FLAGS a, const CssmData &l) : usage(u), attributes(a), label(&l) { } -}; - -} // end namespace CssmClient - -} // end namespace Security - - -#endif // _H_CDSA_CLIENT_KEYCLIENT diff --git a/OSX/include/security_cdsa_client/macclient.cpp b/OSX/include/security_cdsa_client/macclient.cpp deleted file mode 100644 index 63ddacc1..00000000 --- a/OSX/include/security_cdsa_client/macclient.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// macclient - client interface to CSSM sign/verify mac contexts -// -#include - -using namespace CssmClient; - - -// -// Common features of signing and verify mac contexts -// -void MacContext::activate() -{ - { - StLock _(mActivateMutex); - if (!mActive) - { - check(CSSM_CSP_CreateMacContext(attachment()->handle(), mAlgorithm, - mKey, &mHandle)); - mActive = true; - } - } - - if (cred()) - cred(cred()); // install explicitly -} - - -// -// Signing -// -void GenerateMac::sign(const CssmData *data, uint32 count, CssmData &mac) -{ - unstaged(); - check(CSSM_GenerateMac(handle(), data, count, &mac)); -} - -void GenerateMac::init() -{ - check(CSSM_GenerateMacInit(handle())); - mStaged = true; -} - -void GenerateMac::sign(const CssmData *data, uint32 count) -{ - staged(); - check(CSSM_GenerateMacUpdate(handle(), data, count)); -} - -void GenerateMac::operator () (CssmData &mac) -{ - staged(); - check(CSSM_GenerateMacFinal(handle(), &mac)); - mStaged = false; -} - - -// -// Verifying -// -void VerifyMac::verify(const CssmData *data, uint32 count, const CssmData &mac) -{ - unstaged(); - check(CSSM_VerifyMac(handle(), data, count, &mac)); -} - -void VerifyMac::init() -{ - check(CSSM_VerifyMacInit(handle())); - mStaged = true; -} - -void VerifyMac::verify(const CssmData *data, uint32 count) -{ - staged(); - check(CSSM_VerifyMacUpdate(handle(), data, count)); -} - -void VerifyMac::operator () (const CssmData &mac) -{ - staged(); - check(CSSM_VerifyMacFinal(handle(), &mac)); - mStaged = false; -} diff --git a/OSX/include/security_cdsa_client/macclient.h b/OSX/include/security_cdsa_client/macclient.h deleted file mode 100644 index 10635b15..00000000 --- a/OSX/include/security_cdsa_client/macclient.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// macclient - client interface to CSSM sign/verify mac contexts -// -#ifndef _H_CDSA_CLIENT_MACCLIENT -#define _H_CDSA_CLIENT_MACCLIENT 1 - -#include -#include - -namespace Security -{ - -namespace CssmClient -{ - -// -// A signing/verifying mac context -// -class MacContext : public Context -{ -public: - MacContext(const CSP &csp, CSSM_ALGORITHMS alg) - : Context(csp, alg) { } - - // preliminary interface - Key key() const { assert(mKey); return mKey; } - void key(const Key &k) { mKey = k; set(CSSM_ATTRIBUTE_KEY, mKey); } - -protected: - void activate(); - Key mKey; -}; - - -class GenerateMac : public MacContext -{ -public: - GenerateMac(const CSP &csp, CSSM_ALGORITHMS alg) : MacContext(csp, alg) { } - - // integrated - void sign(const CssmData &data, CssmData &mac) { sign(&data, 1, mac); } - void sign(const CssmData *data, uint32 count, CssmData &mac); - - // staged - void init(); // Optional - void sign(const CssmData &data) { sign(&data, 1); } - void sign(const CssmData *data, uint32 count); - void operator () (CssmData &mac); - CssmData operator () () { CssmData mac; (*this)(mac); return mac; } -}; - -class VerifyMac : public MacContext -{ -public: - VerifyMac(const CSP &csp, CSSM_ALGORITHMS alg) : MacContext(csp, alg) { } - - // integrated - void verify(const CssmData &data, const CssmData &mac) { verify(&data, 1, mac); } - void verify(const CssmData *data, uint32 count, const CssmData &mac); - - // staged - void init(); // Optional - void verify(const CssmData &data) { verify(&data, 1); } - void verify(const CssmData *data, uint32 count); - void operator () (const CssmData &mac); -}; - -} // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_MACCLIENT diff --git a/OSX/include/security_cdsa_client/mds_standard.cpp b/OSX/include/security_cdsa_client/mds_standard.cpp deleted file mode 100644 index 8d709150..00000000 --- a/OSX/include/security_cdsa_client/mds_standard.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// mds_standard - standard-defined MDS record types -// -#include -#include - - -namespace Security { -namespace MDSClient { - - -// -// CDSA Common relation (one record per module) -// -static const char * const commonAttributes[] = { - "ModuleID", - "ModuleName", - "Path", - "Desc", - "DynamicFlag", - "MultiThreadFlag", - "ServiceMask", - NULL -}; -Common::Common() : Record(commonAttributes) { } - -string Common::moduleID() const { return mAttributes[0]; } -string Common::moduleName() const { return mAttributes[1]; } -string Common::path() const { return mAttributes[2]; } -string Common::description() const { return mAttributes[3]; } -bool Common::dynamic() const { return mAttributes[4]; } -bool Common::singleThreaded() const { return !mAttributes[5]; } -CSSM_SERVICE_MASK Common::serviceMask() const { return mAttributes[6]; } - - -// -// Common::Carrier draws in the Common fields for anything with -// a ModuleID attribute (which must be the first attribute listed) -// -Common::Carrier::~Carrier() { } - -Common &Common::Carrier::common() const -{ - if (!mCommon) { - const CssmDbRecordAttributeData &attrs - = dynamic_cast(this)->attributes(); - RefPointer rpc; - rpc = Table(mds()).fetch( - Attribute("ModuleID") == string(attrs[0]), - CSSMERR_DL_ENDOFDATA); - mCommon = rpc; - } - return *mCommon; -} - - -// -// Attributes that are common to all primary relations -// -static const char * const primaryAttributes[] = { - "ModuleID", - "SSID", - "ModuleName", - "ProductVersion", - "Vendor", - NULL -}; -PrimaryRecord::PrimaryRecord(const char * const * names) - : Record(primaryAttributes) -{ - addAttributes(names); -} - -string PrimaryRecord::moduleID() const { return mAttributes[0]; } -uint32 PrimaryRecord::subserviceID() const { return mAttributes[1]; } -string PrimaryRecord::moduleName() const { return mAttributes[2]; } -string PrimaryRecord::productVersion() const { return mAttributes[3]; } -string PrimaryRecord::vendor() const { return mAttributes[4]; } - - -// -// CSP Primary relation (one record per CSP SSID) -// -static const char * const cspAttributes[] = { - // up to Vendor is handled by PrimaryRecord - "CspType", - "CspFlags", - NULL -}; -CSP::CSP() : PrimaryRecord(cspAttributes) { } - -uint32 CSP::cspType() const { return mAttributes[5]; } -CSSM_CSP_FLAGS CSP::cspFlags() const { return mAttributes[6]; } - - -// -// CSP capabilities relation -// -static const char * const capAttributes[] = { - "ModuleID", - "SSID", - "ContextType", - "AlgType", - "GroupId", - "AttributeType", - "Description", - NULL -}; -CSPCapabilities::CSPCapabilities() : Record(capAttributes) { } - -string CSPCapabilities::moduleID() const { return mAttributes[0]; } -uint32 CSPCapabilities::subserviceID() const { return mAttributes[1]; } -uint32 CSPCapabilities::contextType() const { return mAttributes[2]; } -uint32 CSPCapabilities::algorithm() const { return mAttributes[3]; } -uint32 CSPCapabilities::group() const { return mAttributes[4]; } -uint32 CSPCapabilities::attribute() const { return mAttributes[5]; } -string CSPCapabilities::description() const { return mAttributes[6]; } - - -// -// CSP SmartcardInfo relation (one record per smartcard token present) -// -static const char * const scAttributes[] = { - "ModuleID", - "SSID", - "ScDesc", - "ScVendor", - "ScVersion", - "ScFirmwareVersion", - "ScFlags", - "ScCustomFlags", - "ScSerialNumber", - NULL -}; -SmartcardInfo::SmartcardInfo() : Record(scAttributes) { } - -string SmartcardInfo::moduleID() const { return mAttributes[0]; } -uint32 SmartcardInfo::subserviceID() const { return mAttributes[1]; } -string SmartcardInfo::description() const { return mAttributes[2]; } -string SmartcardInfo::vendor() const { return mAttributes[3]; } -string SmartcardInfo::version() const { return mAttributes[4]; } -string SmartcardInfo::firmware() const { return mAttributes[5]; } -CSSM_SC_FLAGS SmartcardInfo::flags() const { return mAttributes[6]; } -CSSM_SC_FLAGS SmartcardInfo::customFlags() const { return mAttributes[7]; } -string SmartcardInfo::serial() const { return mAttributes[8]; } - - -// -// DL Primary relation (one record per DL SSID) -// -static const char * const dlAttributes[] = { - // up to Vendor is handled by PrimaryRecord - "DLType", - "QueryLimitsFlag", - NULL -}; -DL::DL() : PrimaryRecord(dlAttributes) { } - -uint32 DL::dlType() const { return mAttributes[5]; } -uint32 DL::queryLimits() const { return mAttributes[6]; } - - -// -// CL Primary relation (one record per CL SSID) -// -static const char * const clAttributes[] = { - // up to Vendor is handled by PrimaryRecord - "CertTypeFormat", - "CrlTypeFormat", - NULL -}; -CL::CL() : PrimaryRecord(clAttributes) { } - -uint32 CL::certTypeFormat() const { return mAttributes[5]; } -uint32 CL::crlTypeFormat() const { return mAttributes[6]; } - - -// -// TP Primary relation (one record per TP SSID) -// -static const char * const tpAttributes[] = { - // up to Vendor is handled by PrimaryRecord - "CertTypeFormat", - NULL -}; -TP::TP() : PrimaryRecord(tpAttributes) { } - -uint32 TP::certTypeFormat() const { return mAttributes[5]; } - - -// -// TP Policy-OIDS relation (one record per supported policy and TP) -// -static const char * const policyAttributes[] = { - "ModuleID", - "SSID", - "OID", - "Value", - NULL -}; -PolicyOids::PolicyOids() : Record(policyAttributes) { } - -string PolicyOids::moduleID() const { return mAttributes[0]; } -uint32 PolicyOids::subserviceID() const { return mAttributes[1]; } -CssmData PolicyOids::oid() const { return mAttributes[2]; } -CssmData PolicyOids::value() const { return mAttributes[3]; } - - -} // end namespace MDSClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/mds_standard.h b/OSX/include/security_cdsa_client/mds_standard.h deleted file mode 100644 index 0f5bd344..00000000 --- a/OSX/include/security_cdsa_client/mds_standard.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// mds_standard - standard-defined MDS record types. -// -// These are the C++ record types corresponding to standard and Apple-defined -// MDS relations. Note that not all standard fields are included; only those -// of particular interest to the implementation. Feel free to add field functions -// as needed. -// - -#ifndef _H_CDSA_CLIENT_MDS_STANDARD -#define _H_CDSA_CLIENT_MDS_STANDARD - -#include - - -namespace Security { -namespace MDSClient { - - -// -// The CDSA Common table (one record per module) -// -class Common : public Record { -public: - Common(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_COMMON_RECORDTYPE; - - string moduleID() const; - string moduleName() const; - string path() const; - string description() const; - bool dynamic() const; - bool singleThreaded() const; - CSSM_SERVICE_MASK serviceMask() const; - -public: - // - // "Link in" a Common into another record, whose attributes()[0] is the ModuleID - // - class Carrier { - public: - virtual ~Carrier(); - - string moduleName() const { return common().moduleName(); } - string path() const { return common().path(); } - string description() const { return common().description(); } - bool dynamic() const { return common().dynamic(); } - bool singleThreaded() const { return common().singleThreaded(); } - CSSM_SERVICE_MASK serviceMask() const { return common().serviceMask(); } - - private: - mutable RefPointer mCommon; - - Common &common() const; - }; -}; - - -// -// PrimaryRecord shapes the "common head" of all MDS primary relations -// -class PrimaryRecord : public Record, public Common::Carrier { -public: - PrimaryRecord(const char * const * names); - - string moduleID() const; - uint32 subserviceID() const; - string moduleName() const; - string productVersion() const; - string vendor() const; -}; - - -// -// The CSP Primary relation -// -class CSP : public PrimaryRecord { -public: - CSP(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_CSP_PRIMARY_RECORDTYPE; - - uint32 cspType() const; - CSSM_CSP_FLAGS cspFlags() const; -}; - - -// -// The CSP Capabilities relation -// -class CSPCapabilities : public Record, public Common::Carrier { -public: - CSPCapabilities(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_CSP_CAPABILITY_RECORDTYPE; - - string moduleID() const; - uint32 subserviceID() const; - uint32 contextType() const; - uint32 algorithm() const; - uint32 group() const; - uint32 attribute() const; - string description() const; -}; - - -// -// The CSP "smartcard token" relation -// -class SmartcardInfo : public Record, public Common::Carrier { -public: - SmartcardInfo(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_CSP_SC_INFO_RECORDTYPE; - - string moduleID() const; - uint32 subserviceID() const; - string description() const; - string vendor() const; - string version() const; - string firmware() const; - CSSM_SC_FLAGS flags() const; - CSSM_SC_FLAGS customFlags() const; - string serial() const; -}; - - -// -// The DL Primary relation -// -class DL : public PrimaryRecord { -public: - DL(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_DL_PRIMARY_RECORDTYPE; - - uint32 dlType() const; - uint32 queryLimits() const; -}; - - -// -// The CL Primary relation -// -class CL : public PrimaryRecord { -public: - CL(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_CL_PRIMARY_RECORDTYPE; - - uint32 certTypeFormat() const; - uint32 certType() const { return certTypeFormat() >> 16; } - uint32 certEncoding() const { return certTypeFormat() & 0xFFFF; } - uint32 crlTypeFormat() const; - uint32 crlType() const { return crlTypeFormat() >> 16; } - uint32 crlEncoding() const { return crlTypeFormat() & 0xFFFF; } -}; - - -// -// The TP Primary relation -// -class TP : public PrimaryRecord { -public: - TP(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_TP_PRIMARY_RECORDTYPE; - - uint32 certTypeFormat() const; - uint32 certType() const { return certTypeFormat() >> 16; } - uint32 certEncoding() const { return certTypeFormat() & 0xFFFF; } -}; - - -// -// The TP Policy-OIDS relation -// -class PolicyOids : public Record { -public: - PolicyOids(); - static const CSSM_DB_RECORDTYPE recordType = MDS_CDSADIR_TP_OIDS_RECORDTYPE; - - string moduleID() const; - uint32 subserviceID() const; - CssmData oid() const; - CssmData value() const; -}; - - -} // end namespace MDSClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_MDS_STANDARD diff --git a/OSX/include/security_cdsa_client/mdsclient.cpp b/OSX/include/security_cdsa_client/mdsclient.cpp deleted file mode 100644 index 15e8ae32..00000000 --- a/OSX/include/security_cdsa_client/mdsclient.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// mdsclient - friendly interface to CDSA MDS API -// -#include -#include - - -namespace Security { -namespace MDSClient { - - -// -// The MDS access object singleton -// -ModuleNexus mds; - - -// -// Directory construction initializes MDS and opens the "CDSA" database -// -Directory::Directory() - : mMemoryFunctions(Allocator::standard()) -{ - StLock _(mInitLock); - CssmError::check(MDS_Initialize(&mCallerGuid, &mMemoryFunctions, - this, &mCDSA.DLHandle)); - mCDSA.DBHandle = CSSM_INVALID_HANDLE; -} - - -// -// Cleanup (only called if the ModuleNexus is explicitly reset) -// -Directory::~Directory() -{ - if (mCDSA.DBHandle) - CssmError::check(DbClose(mCDSA)); - CssmError::check(MDS_Terminate(mds())); -} - - -// -// Open MDS database if needed -// -const MDS_DB_HANDLE &Directory::cdsa() const -{ - if (mCDSA.DBHandle == CSSM_INVALID_HANDLE) { - StLock _(mInitLock); - if (mCDSA.DBHandle == CSSM_INVALID_HANDLE) - CssmError::check(DbOpen(mCDSA.DLHandle, MDS_CDSA_DIRECTORY_NAME, NULL, - CSSM_DB_ACCESS_READ, // access mode - NULL, // credentials - NULL, // OpenParameters - &mCDSA.DBHandle)); - } - return mCDSA; -} - - -// -// The DLAccess implementation for MDS. -// We don't ever return record data, of course; we just zero it out. -// -CSSM_HANDLE Directory::dlGetFirst(const CSSM_QUERY &query, CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, - CSSM_DATA *data, CSSM_DB_UNIQUE_RECORD *&id) -{ - CSSM_HANDLE result; - switch (CSSM_RETURN rc = DataGetFirst(cdsa(), &query, &result, &attributes, NULL, &id)) { - case CSSM_OK: - if (data) - *data = CssmData(); - return result; - case CSSMERR_DL_ENDOFDATA: - return CSSM_INVALID_HANDLE; - default: - CssmError::throwMe(rc); - return CSSM_INVALID_HANDLE; // placebo - } -} - -bool Directory::dlGetNext(CSSM_HANDLE handle, CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, - CSSM_DATA *data, CSSM_DB_UNIQUE_RECORD *&id) -{ - CSSM_RETURN rc = DataGetNext(cdsa(), handle, &attributes, NULL, &id); - switch (rc) { - case CSSM_OK: - if (data) - *data = CssmData(); - return true; - case CSSMERR_DL_ENDOFDATA: - return false; - default: - CssmError::throwMe(rc); - return false; // placebo - } -} - -void Directory::dlAbortQuery(CSSM_HANDLE handle) -{ - CssmError::check(DataAbortQuery(cdsa(), handle)); -} - -void Directory::dlFreeUniqueId(CSSM_DB_UNIQUE_RECORD *id) -{ - CssmError::check(FreeUniqueRecord(cdsa(), id)); -} - -void Directory::dlDeleteRecord(CSSM_DB_UNIQUE_RECORD *id) -{ - CssmError::check(DataDelete(cdsa(), id)); -} - -Allocator &Directory::allocator() -{ - return Allocator::standard(); -} - - -// -// Public MDS operations -// -void Directory::install() -{ - CssmError::check(MDS_Install(this->mds())); -} - -void Directory::install(const MDS_InstallDefaults *defaults, - const char *path, const char *subdir, const char *file) -{ - CssmError::check(MDS_InstallFile(this->mds(), defaults, path, subdir, file)); -} - -void Directory::uninstall(const char *guid, uint32 ssid) -{ - CssmError::check(MDS_RemoveSubservice(this->mds(), guid, ssid)); -} - - -} // end namespace MDSClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/mdsclient.h b/OSX/include/security_cdsa_client/mdsclient.h deleted file mode 100644 index 96a381ed..00000000 --- a/OSX/include/security_cdsa_client/mdsclient.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// mdsclient - friendly interface to CDSA MDS API -// -// It is useful to think of the mdsclient interface as "slightly below" the -// rest of the cdsa_client layer. It does not actually call into CSSM (we -// consider MDS as a separate facility, "slightly lower" than CSSM as well). -// This means that you can use mdsclient without creating a binary dependency -// on CSSM, and thus Security.framework. -// - -#ifndef _H_CDSA_CLIENT_MDSCLIENT -#define _H_CDSA_CLIENT_MDSCLIENT - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Security { -namespace MDSClient { - -// import query sublanguage classes into MDSClient namespace -using CssmClient::Attribute; -using CssmClient::Query; -using CssmClient::Record; -using CssmClient::Table; - - -// -// A singleton for the MDS itself. -// This is automatically created as a ModuleNexus when needed. -// You can reset() it to release resources. -// Don't make your own. -// -class Directory : public MDS_FUNCS, public CssmClient::DLAccess { -public: - Directory(); - virtual ~Directory(); - - MDS_HANDLE mds() const { return mCDSA.DLHandle; } - const MDS_DB_HANDLE &cdsa() const; - -public: - CSSM_HANDLE dlGetFirst(const CSSM_QUERY &query, - CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, CSSM_DATA *data, - CSSM_DB_UNIQUE_RECORD *&id); - bool dlGetNext(CSSM_HANDLE handle, - CSSM_DB_RECORD_ATTRIBUTE_DATA &attributes, CSSM_DATA *data, - CSSM_DB_UNIQUE_RECORD *&id); - void dlAbortQuery(CSSM_HANDLE handle); - void dlFreeUniqueId(CSSM_DB_UNIQUE_RECORD *id); - void dlDeleteRecord(CSSM_DB_UNIQUE_RECORD *id); - Allocator &allocator(); - -public: - // not for ordinary use - system administration only - void install(); // system default install/regenerate - void install(const MDS_InstallDefaults *defaults, // defaults - const char *path, // path to bundle (NULL -> main) - const char *subdir = NULL, // subdirectory in Resources (NULL -> all) - const char *file = NULL); // individual file (NULL -> all) - void uninstall(const char *guid, uint32 ssid); - -private: - mutable MDS_DB_HANDLE mCDSA; // CDSA database handle - mutable Mutex mInitLock; // interlock for lazy DB open - CssmAllocatorMemoryFunctions mMemoryFunctions; - Guid mCallerGuid; //@@@ fake/unused -}; - -extern ModuleNexus mds; - - -} // end namespace MDSClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_MDSCLIENT diff --git a/OSX/include/security_cdsa_client/multidldb.cpp b/OSX/include/security_cdsa_client/multidldb.cpp deleted file mode 100644 index 596d01c7..00000000 --- a/OSX/include/security_cdsa_client/multidldb.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// MultiDLDb implementation. -// - -#include -#include - - - -namespace Security -{ - -using namespace CssmClient; - -namespace CssmClient -{ - -// -// MultiDLDbDbCursorImpl declaration -// -class MultiDLDbDbCursorImpl : public DbCursorImpl -{ -public: - MultiDLDbDbCursorImpl(const MultiDLDb &parent, const CSSM_QUERY &query, Allocator &allocator); - MultiDLDbDbCursorImpl(const MultiDLDb &parent, uint32 capacity, Allocator &allocator); - virtual ~MultiDLDbDbCursorImpl(); - - bool next(DbAttributes *attributes, ::CssmDataContainer *data, DbUniqueRecord &uniqueId); -private: - MultiDLDb multiDLDb() { return parent(); } - void activate(); - void deactivate(); - - MultiDLDbImpl::ListRef mListRef; - MultiDLDbImpl::List::const_iterator mNext; - MultiDLDbImpl::List::const_iterator mEnd; - DbCursor mCursor; -}; - -} // end namespace CssmClient - -} // end namespace Security - -// -// MultiDLDbImpl -// -MultiDLDbImpl::MultiDLDbImpl(const vector &list, bool useSecureStorage, const Cssm &cssm) -: ObjectImpl(cssm), mListRef(list), mUseSecureStorage(useSecureStorage) -{ -} - -MultiDLDbImpl::MultiDLDbImpl(const vector &list, bool useSecureStorage) -: ObjectImpl(Cssm::standard()), mListRef(list), mUseSecureStorage(useSecureStorage) -{ -} - -MultiDLDbImpl::~MultiDLDbImpl() -{ - deactivate(); -} - -Db -MultiDLDbImpl::database(const DLDbIdentifier &dlDbIdentifier) -{ - StLock _(mLock); - DbMap::const_iterator it = mDbMap.find(dlDbIdentifier); - if (it != mDbMap.end()) - return it->second; - - Module module(dlDbIdentifier.ssuid().guid(), cssm()); - DL dl; - if (dlDbIdentifier.ssuid().subserviceType() & CSSM_SERVICE_CSP) - { - if (mUseSecureStorage) - dl = SSCSPDL(module); - else - dl = CSPDL(module); - } - else - dl = DL(module); - - dl->subserviceId(dlDbIdentifier.ssuid().subserviceId()); - dl->version(dlDbIdentifier.ssuid().version()); - Db db(dl, dlDbIdentifier.dbName()); - if (find(mListRef->begin(), mListRef->end(), dlDbIdentifier) != mListRef->end()) - mDbMap.insert(DbMap::value_type(dlDbIdentifier, db)); - - return db; -} - -void -MultiDLDbImpl::list(const vector &list) -{ - StLock _(mLock); - set oldList(mListRef->begin(), mListRef->end()); - mListRef = ListRef(list); - set newList(mListRef->begin(), mListRef->end()); - vector obsolete; - back_insert_iterator > ii(obsolete); - // Remove all db's from the map that were in oldList but are not in mListRef. - set_difference(oldList.begin(), oldList.end(), newList.begin(), newList.end(), ii); - for (vector::const_iterator it = obsolete.begin(); it != obsolete.end(); ++it) - mDbMap.erase(*it); -} - -DbCursorImpl * -MultiDLDbImpl::newDbCursor(const CSSM_QUERY &query, Allocator &allocator) -{ - return new MultiDLDbDbCursorImpl(MultiDLDb(this), query, allocator); -} - -DbCursorImpl * -MultiDLDbImpl::newDbCursor(uint32 capacity, Allocator &allocator) -{ - return new MultiDLDbDbCursorImpl(MultiDLDb(this), capacity, allocator); -} - -void -MultiDLDbImpl::activate() -{ -} - -void -MultiDLDbImpl::deactivate() -{ - StLock _(mLock); - mDbMap.erase(mDbMap.begin(), mDbMap.end()); -} - - -// -// MultiDLDbDbCursorImpl -// -MultiDLDbDbCursorImpl::MultiDLDbDbCursorImpl(const MultiDLDb &parent, - const CSSM_QUERY &query, Allocator &allocator) -: DbCursorImpl(parent, query, allocator) -{ -} - -MultiDLDbDbCursorImpl::MultiDLDbDbCursorImpl(const MultiDLDb &parent, - uint32 capacity, Allocator &allocator) -: DbCursorImpl(parent, capacity, allocator) -{ -} - -MultiDLDbDbCursorImpl::~MultiDLDbDbCursorImpl() -{ - try - { - deactivate(); - } - catch(...) {} -} - -bool -MultiDLDbDbCursorImpl::next(DbAttributes *attributes, ::CssmDataContainer *data, DbUniqueRecord &uniqueId) -{ - activate(); - for (;;) - { - if (!mCursor) - { - if (mNext == mEnd) - { - // This is how it ends. - deactivate(); - return false; - } - - mCursor = DbCursor(multiDLDb()->database(*mNext++), *this); - } - - try - { - if (mCursor->next(attributes, data, uniqueId)) - return true; - } - - catch(const CommonError &err) - { - OSStatus status = err.osStatus(); - if(status != CSSMERR_DL_DATASTORE_DOESNOT_EXIST) - throw; - } - - - - mCursor = DbCursor(); - } -} - -void -MultiDLDbDbCursorImpl::activate() -{ - StLock _(mActivateMutex); - if (!mActive) - { - mListRef = multiDLDb()->listRef(); - mNext = mListRef->begin(); - mEnd = mListRef->end(); - mActive = true; - } -} - -void -MultiDLDbDbCursorImpl::deactivate() -{ - StLock _(mActivateMutex); - if (mActive) - { - mActive = false; - mListRef = MultiDLDbImpl::ListRef(); - mNext = mEnd; - mCursor = DbCursor(); - } -} - diff --git a/OSX/include/security_cdsa_client/multidldb.h b/OSX/include/security_cdsa_client/multidldb.h deleted file mode 100644 index fb5fd909..00000000 --- a/OSX/include/security_cdsa_client/multidldb.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// multidldb interfaces for searching multiple dls or db with a single cursor. -// -#ifndef _H_CDSA_CLIENT_MULTIDLDB -#define _H_CDSA_CLIENT_MULTIDLDB 1 - -#include -#include - -namespace Security -{ - -namespace CssmClient -{ - -// -// The MultiDLDb class. -// -class MultiDLDbImpl : public ObjectImpl, public DbCursorMaker -{ -public: - struct List : public vector, public RefCount - { - List(const vector &list) : vector(list) {} - }; - - struct ListRef : public RefPointer - { - ListRef() {} - ListRef(const vector &list) : RefPointer(new List(list)) {} - }; - - MultiDLDbImpl(const vector &list, bool useSecureStorage, const Cssm &cssm); - MultiDLDbImpl(const vector &list, bool useSecureStorage); - virtual ~MultiDLDbImpl(); - - Cssm cssm() const { return parent(); } - Db database(const DLDbIdentifier &dlDbIdentifier); - ListRef listRef() { return mListRef; } - void list(const vector &list); - const vector &list() { return *mListRef; } - - // DbCursorMaker - virtual DbCursorImpl *newDbCursor(const CSSM_QUERY &query, Allocator &allocator); - virtual DbCursorImpl *newDbCursor(uint32 capacity, Allocator &allocator); - -protected: - void activate(); - void deactivate(); - -private: - typedef map DbMap; - - // Lock protecting this object during changes. - Mutex mLock; - ListRef mListRef; - DbMap mDbMap; - bool mUseSecureStorage; -}; - -class MultiDLDb : public Object -{ -public: - typedef MultiDLDbImpl Impl; - - explicit MultiDLDb(Impl *impl) : Object(impl) {} - MultiDLDb(const vector &list, bool useSecureStorage, const Cssm &cssm) - : Object(new Impl(list, useSecureStorage, cssm)) {} - MultiDLDb(const vector &list, bool useSecureStorage) - : Object(new Impl(list, useSecureStorage)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } - - // Conversion to DbCursorMaker - operator DbCursorMaker &() { return impl(); } -}; - -}; // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_MULTIDLDB diff --git a/OSX/include/security_cdsa_client/securestorage.cpp b/OSX/include/security_cdsa_client/securestorage.cpp deleted file mode 100644 index 6fb56f0d..00000000 --- a/OSX/include/security_cdsa_client/securestorage.cpp +++ /dev/null @@ -1,650 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#include "securestorage.h" -#include -//#include //@@@CONV -#include -#include - -using namespace CssmClient; -//using namespace KeychainCore; - -// -// Manage CSPDL attachments -// -CSPDLImpl::CSPDLImpl(const Guid &guid) -: CSPImpl(Cssm::standard()->autoModule(guid)), -DLImpl(CSPImpl::module()) -{ -} - -CSPDLImpl::CSPDLImpl(const Module &module) -: CSPImpl(module), -DLImpl(module) -{ -} - -CSPDLImpl::~CSPDLImpl() -try -{ -} -catch (...) -{ -} - -Allocator &CSPDLImpl::allocator() const -{ - DLImpl::allocator(); return CSPImpl::allocator(); -} - -void CSPDLImpl::allocator(Allocator &alloc) -{ - CSPImpl::allocator(alloc); DLImpl::allocator(alloc); -} - -bool CSPDLImpl::operator <(const CSPDLImpl &other) const -{ - return (static_cast(*this) < static_cast(other) || - (!(static_cast(other) < static_cast(*this)) - && static_cast(*this) < static_cast(other))); -} - -bool CSPDLImpl::operator ==(const CSPDLImpl &other) const -{ - return (static_cast(*this) == static_cast(other) - && static_cast(*this) == static_cast(other)); -} - -CSSM_SERVICE_MASK CSPDLImpl::subserviceMask() const -{ - return CSPImpl::subserviceType() | DLImpl::subserviceType(); -} - -void CSPDLImpl::subserviceId(uint32 id) -{ - CSPImpl::subserviceId(id); DLImpl::subserviceId(id); -} - - -// -// Secure storage -// -SSCSPDLImpl::SSCSPDLImpl(const Guid &guid) : CSPDLImpl::CSPDLImpl(guid) -{ -} - -SSCSPDLImpl::SSCSPDLImpl(const Module &module) : CSPDLImpl::CSPDLImpl(module) -{ -} - -SSCSPDLImpl::~SSCSPDLImpl() -{ -} - -DbImpl * -SSCSPDLImpl::newDb(const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation) -{ - return new SSDbImpl(SSCSPDL(this), inDbName, inDbLocation); -} - - -// -// SSDbImpl -- Secure Storage Database Implementation -// -SSDbImpl::SSDbImpl(const SSCSPDL &cspdl, const char *inDbName, - const CSSM_NET_ADDRESS *inDbLocation) -: DbImpl(cspdl, inDbName, inDbLocation) -{ -} - -SSDbImpl::~SSDbImpl() -{ -} - -void -SSDbImpl::create() -{ - DbImpl::create(); -} - -void -SSDbImpl::open() -{ - DbImpl::open(); -} - -SSDbUniqueRecord -SSDbImpl::insert(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - const CSSM_RESOURCE_CONTROL_CONTEXT *rc) -{ - // Get the handle of the DL underlying this CSPDL. - CSSM_DL_DB_HANDLE dldbh; - passThrough(CSSM_APPLECSPDL_DB_GET_HANDLE, NULL, - reinterpret_cast(&dldbh)); - - // Turn off autocommit on the underlying DL and remember the old state. - CSSM_BOOL autoCommit = CSSM_TRUE; - check(CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - 0, reinterpret_cast(&autoCommit))); - SSGroup group(SSDb(this), rc); - const CSSM_ACCESS_CREDENTIALS *cred = rc ? rc->AccessCred : NULL; - try - { - return insert(recordType, attributes, data, group, cred); - if (autoCommit) - { - // autoCommit was on so commit now that we are done and turn - // it back on. - check(CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_COMMIT, NULL, NULL)); - CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - reinterpret_cast(autoCommit), NULL); - } - } - catch(...) - { - try { group->deleteKey(cred); } catch (...) {} - if (autoCommit) - { - // autoCommit was off so rollback since we failed and turn - // autoCommit back on. - CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_ROLLBACK, NULL, NULL); - CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - reinterpret_cast(autoCommit), NULL); - } - throw; - } - - // keep the compiler happy -- this path is NEVER taken - CssmError::throwMe(0); -} - -SSDbUniqueRecord -SSDbImpl::insert(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, const SSGroup &group, - const CSSM_ACCESS_CREDENTIALS *cred) -{ - // Create an encoded dataBlob for this item. - CssmDataContainer dataBlob(allocator()); - group->encodeDataBlob(data, cred, dataBlob); - - // Insert the record with the new juicy dataBlob. - return SSDbUniqueRecord(safe_cast - (&(*DbImpl::insert(recordType, attributes, &dataBlob)))); -} - - -// DbCursorMaker -DbCursorImpl * -SSDbImpl::newDbCursor(const CSSM_QUERY &query, Allocator &allocator) -{ - return new SSDbCursorImpl(Db(this), query, allocator); -} - -DbCursorImpl * -SSDbImpl::newDbCursor(uint32 capacity, Allocator &allocator) -{ - return new SSDbCursorImpl(Db(this), capacity, allocator); -} - - -// SSDbUniqueRecordMaker -DbUniqueRecordImpl * -SSDbImpl::newDbUniqueRecord() -{ - return new SSDbUniqueRecordImpl(Db(this)); -} - - -// -// SSGroup -- Group key with acl, used to protect a group of items. -// -// @@@ Get this from a shared spot. -CSSM_DB_NAME_ATTR(SSGroupImpl::kLabel, 6, (char*) "Label", 0, NULL, BLOB); - -// Create a new group. -SSGroupImpl::SSGroupImpl(const SSDb &ssDb, - const CSSM_RESOURCE_CONTROL_CONTEXT *credAndAclEntry) -: KeyImpl(ssDb->csp()), mLabel(ssDb->allocator()) -{ - mLabel.Length = kLabelSize; - mLabel.Data = reinterpret_cast - (mLabel.mAllocator.malloc(mLabel.Length)); - - // Get our csp and set up a random number generation context. - CSP csp(this->csp()); - Random random(csp, CSSM_ALGID_APPLE_YARROW); - - // Generate a kLabelSize byte random number that will be the label of - // the key which we store in the dataBlob. - random.generate(mLabel, (uint32)mLabel.Length); - - // Overwrite the first 4 bytes with the magic cookie for a group. - reinterpret_cast(mLabel.Data)[0] = h2n(uint32(kGroupMagic)); - - // @@@ Ensure that the label is unique (Chance of collision is 2^80 -- - // birthday paradox). - - // Generate a permanent 3DES key that we will use to encrypt the data. - GenerateKey genKey(csp, CSSM_ALGID_3DES_3KEY, 192); - genKey.database(ssDb); - - // Set the acl of the key correctly here - genKey.rcc(credAndAclEntry); - - // Generate the key - genKey(*this, KeySpec(CSSM_KEYUSE_ENCRYPT|CSSM_KEYUSE_DECRYPT, - CSSM_KEYATTR_PERMANENT|CSSM_KEYATTR_SENSITIVE, - mLabel)); - - // Activate ourself so CSSM_FreeKey will get called when we go out of - // scope. - activate(); -} - -// Lookup an existing group based on a dataBlob. -SSGroupImpl::SSGroupImpl(const SSDb &ssDb, const CSSM_DATA &dataBlob) -: KeyImpl(ssDb->csp()), mLabel(ssDb->allocator()) -{ - if (dataBlob.Length < kLabelSize + kIVSize) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); // Not a SS record - - mLabel = CssmData(dataBlob.Data, kLabelSize); - if (*reinterpret_cast(mLabel.Data) != h2n (uint32(kGroupMagic))) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); // Not a SS record - - // Look up the symmetric key with that label. - DbCursor cursor(new DbDbCursorImpl(ssDb, 0, Allocator::standard())); - cursor->recordType(CSSM_DL_DB_RECORD_SYMMETRIC_KEY); - cursor->add(CSSM_DB_EQUAL, kLabel, mLabel); - - DbUniqueRecord keyId; - CssmDataContainer keyData(ssDb->allocator()); - if (!cursor->next(NULL, &keyData, keyId)) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); // The key can't be found - - // Set the key part of ourself. - static_cast(*this) = - *reinterpret_cast(keyData.Data); - - // Activate ourself so CSSM_FreeKey will get called when we go out of - // scope. - activate(); -} - -bool -SSGroupImpl::isGroup(const CSSM_DATA &dataBlob) -{ - return dataBlob.Length >= kLabelSize + kIVSize - && *reinterpret_cast(dataBlob.Data) == h2n(uint32(kGroupMagic)); -} - -const CssmData -SSGroupImpl::label() const -{ - return mLabel; -} - -void -SSGroupImpl::decodeDataBlob(const CSSM_DATA &dataBlob, - const CSSM_ACCESS_CREDENTIALS *cred, - Allocator &allocator, CSSM_DATA &data) -{ - // First get the IV and the cipherText from the blob. - CssmData iv(&dataBlob.Data[kLabelSize], kIVSize); - CssmData cipherText(&dataBlob.Data[kLabelSize + kIVSize], - dataBlob.Length - (kLabelSize + kIVSize)); - - CssmDataContainer plainText1(allocator); - CssmDataContainer plainText2(allocator); - // Decrypt the data - // @@@ Don't use staged decrypt once the AppleCSPDL can do combo - // encryption. - // Setup decryption context - Decrypt decrypt(csp(), algorithm()); - decrypt.mode(CSSM_ALGMODE_CBCPadIV8); - decrypt.padding(CSSM_PADDING_PKCS1); - decrypt.initVector(iv); - decrypt.key(Key(this)); - decrypt.cred(AccessCredentials::overlay(cred)); - decrypt.decrypt(&cipherText, 1, &plainText1, 1); - decrypt.final(plainText2); - - // Use DL allocator for allocating memory for data. - CSSM_SIZE length = plainText1.Length + plainText2.Length; - data.Data = allocator.alloc((UInt32)length); - data.Length = length; - memcpy(data.Data, plainText1.Data, plainText1.Length); - memcpy(&data.Data[plainText1.Length], plainText2.Data, plainText2.Length); -} - -void -SSGroupImpl::encodeDataBlob(const CSSM_DATA *data, - const CSSM_ACCESS_CREDENTIALS *cred, - CssmDataContainer &dataBlob) -{ - // Get our csp and set up a random number generation context. - CSP csp(this->csp()); - Random random(csp, CSSM_ALGID_APPLE_YARROW); - - // Encrypt data using key and encode it in a dataBlob. - - // First calculate a random IV. - uint8 ivBuf[kIVSize]; - CssmData iv(ivBuf, kIVSize); - random.generate(iv, kIVSize); - - // Setup encryption context - Encrypt encrypt(csp, algorithm()); - encrypt.mode(CSSM_ALGMODE_CBCPadIV8); - encrypt.padding(CSSM_PADDING_PKCS1); - encrypt.initVector(iv); - encrypt.key(Key(this)); - encrypt.cred(AccessCredentials::overlay(cred)); - - // Encrypt the data - const CssmData nothing; - const CssmData *plainText = data ? CssmData::overlay(data) : ¬hing; - // @@@ Don't use staged encrypt once the AppleCSPDL can do combo - // encryption. - CssmDataContainer cipherText1, cipherText2; - encrypt.encrypt(plainText, 1, &cipherText1, 1); - encrypt.final(cipherText2); - - // Create a dataBlob containing the label followed by the IV followed - // by the cipherText. - CSSM_SIZE length = (kLabelSize + kIVSize - + cipherText1.Length + cipherText2.Length); - dataBlob.Data = dataBlob.mAllocator.alloc((UInt32)length); - dataBlob.Length = length; - memcpy(dataBlob.Data, mLabel.Data, kLabelSize); - memcpy(&dataBlob.Data[kLabelSize], iv.Data, kIVSize); - memcpy(&dataBlob.Data[kLabelSize + kIVSize], - cipherText1.Data, cipherText1.Length); - memcpy(&dataBlob.Data[kLabelSize + kIVSize + cipherText1.Length], - cipherText2.Data, cipherText2.Length); -} - - -// -// SSDbCursorImpl -- Secure Storage Database Cursor Implementation. -// -SSDbCursorImpl::SSDbCursorImpl(const Db &db, const CSSM_QUERY &query, - Allocator &allocator) -: DbDbCursorImpl(db, query, allocator) -{ -} - -SSDbCursorImpl::SSDbCursorImpl(const Db &db, uint32 capacity, - Allocator &allocator) -: DbDbCursorImpl(db, capacity, allocator) -{ -} - -bool -SSDbCursorImpl::next(DbAttributes *attributes, ::CssmDataContainer *data, - DbUniqueRecord &uniqueId) -{ - return next(attributes, data, uniqueId, NULL); -} - -bool -SSDbCursorImpl::next(DbAttributes *attributes, ::CssmDataContainer *data, - DbUniqueRecord &uniqueId, - const CSSM_ACCESS_CREDENTIALS *cred) -{ - if (!data) - return DbDbCursorImpl::next(attributes, data, uniqueId); - - DbAttributes noAttrs, *attrs; - attrs = attributes ? attributes : &noAttrs; - - // Get the datablob for this record - CssmDataContainer dataBlob(allocator()); - for (;;) - { - if (!DbDbCursorImpl::next(attrs, &dataBlob, uniqueId)) - return false; - - // Keep going until we find a non key type record. - CSSM_DB_RECORDTYPE rt = attrs->recordType(); - if (rt != CSSM_DL_DB_RECORD_SYMMETRIC_KEY - && rt != CSSM_DL_DB_RECORD_PRIVATE_KEY - && rt != CSSM_DL_DB_RECORD_PUBLIC_KEY) - { - // @@@ Check the label and if it doesn't start with the magic for a SSKey return the key. - break; - } - else - { - // Free the key we just retrieved - database()->csp()->freeKey(*reinterpret_cast(dataBlob.Data)); - } - } - - if (!SSGroupImpl::isGroup(dataBlob)) - { - data->Data = dataBlob.Data; - data->Length = dataBlob.Length; - dataBlob.Data = NULL; - dataBlob.Length = 0; - return true; - } - - // Get the group for dataBlob - SSGroup group(database(), dataBlob); - - // Decode the dataBlob, pass in the DL allocator. - group->decodeDataBlob(dataBlob, cred, database()->allocator(), *data); - return true; -} - -bool -SSDbCursorImpl::nextKey(DbAttributes *attributes, Key &key, - DbUniqueRecord &uniqueId) -{ - DbAttributes noAttrs, *attrs; - attrs = attributes ? attributes : &noAttrs; - CssmDataContainer keyData(database()->allocator()); - for (;;) - { - if (!DbDbCursorImpl::next(attrs, &keyData, uniqueId)) - return false; - // Keep going until we find a key type record. - CSSM_DB_RECORDTYPE rt = attrs->recordType(); - if (rt == CSSM_DL_DB_RECORD_SYMMETRIC_KEY - || rt == CSSM_DL_DB_RECORD_PRIVATE_KEY - || rt == CSSM_DL_DB_RECORD_PUBLIC_KEY) - break; - } - - key = Key(database()->csp(), *reinterpret_cast(keyData.Data)); - return true; -} - -void -SSDbCursorImpl::activate() -{ - return DbDbCursorImpl::activate(); -} - -void -SSDbCursorImpl::deactivate() -{ - return DbDbCursorImpl::deactivate(); -} - - -// -// SSDbUniqueRecordImpl -- Secure Storage UniqueRecord Implementation. -// -SSDbUniqueRecordImpl::SSDbUniqueRecordImpl(const Db &db) -: DbUniqueRecordImpl(db) -{ -} - -SSDbUniqueRecordImpl::~SSDbUniqueRecordImpl() -{ -} - -void -SSDbUniqueRecordImpl::deleteRecord() -{ - deleteRecord(NULL); -} - -void -SSDbUniqueRecordImpl::deleteRecord(const CSSM_ACCESS_CREDENTIALS *cred) -{ - // Get the datablob for this record - // @@@ Fixme so we don't need to call DbUniqueRecordImpl::get - CssmDataContainer dataBlob(allocator()); - DbAttributes attributes; - - DbUniqueRecordImpl::get(&attributes, &dataBlob); - CSSM_KEY_PTR keyPtr = (CSSM_KEY_PTR) dataBlob.data(); - - // delete data part first: - // (1) don't leave data without keys around - // (2) delete orphaned data anyway - DbUniqueRecordImpl::deleteRecord(); - - // @@@ Use transactions? - if (SSGroupImpl::isGroup(dataBlob)) - try { - // Get the group for dataBlob - SSGroup group(database(), dataBlob); - // Delete the group (key) - group->deleteKey(cred); - } catch (const CssmError &err) { - switch (err.error) { - case CSSMERR_DL_RECORD_NOT_FOUND: - // Zombie item (no group key). Finally at peace! No error - break; - default: - - if (attributes.recordType() == CSSM_DL_DB_RECORD_PUBLIC_KEY || - attributes.recordType() == CSSM_DL_DB_RECORD_PRIVATE_KEY || - attributes.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - { - allocator().free(keyPtr->KeyData.Data); - } - - throw; - } - } - - if (attributes.recordType() == CSSM_DL_DB_RECORD_PUBLIC_KEY || - attributes.recordType() == CSSM_DL_DB_RECORD_PRIVATE_KEY || - attributes.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - { - allocator().free(keyPtr->KeyData.Data); - } -} - -void -SSDbUniqueRecordImpl::modify(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode) -{ - modify(recordType, attributes, data, modifyMode, NULL); -} - -void -SSDbUniqueRecordImpl::modify(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode, - const CSSM_ACCESS_CREDENTIALS *cred) -{ - if (!data) - { - DbUniqueRecordImpl::modify(recordType, attributes, NULL, modifyMode); - return; - } - - // Get the datablob for this record - // @@@ Fixme so we don't need to call DbUniqueRecordImpl::get - CssmDataContainer oldDataBlob(allocator()); - DbUniqueRecordImpl::get(NULL, &oldDataBlob); - - if (!SSGroupImpl::isGroup(oldDataBlob)) - { - DbUniqueRecordImpl::modify(recordType, attributes, data, modifyMode); - return; - } - - // Get the group for oldDataBlob - SSGroup group(database(), oldDataBlob); - - // Create a new dataBlob. - CssmDataContainer dataBlob(allocator()); - group->encodeDataBlob(data, cred, dataBlob); - DbUniqueRecordImpl::modify(recordType, attributes, &dataBlob, modifyMode); -} - -void -SSDbUniqueRecordImpl::get(DbAttributes *attributes, ::CssmDataContainer *data) -{ - get(attributes, data, NULL); -} - -void -SSDbUniqueRecordImpl::get(DbAttributes *attributes, ::CssmDataContainer *data, - const CSSM_ACCESS_CREDENTIALS *cred) -{ - if (!data) - { - DbUniqueRecordImpl::get(attributes, NULL); - return; - } - - // Get the datablob for this record - // @@@ Fixme so we don't need to call DbUniqueRecordImpl::get - CssmDataContainer dataBlob(allocator()); - DbUniqueRecordImpl::get(attributes, &dataBlob); - - if (!SSGroupImpl::isGroup(dataBlob)) - { - data->Data = dataBlob.Data; - data->Length = dataBlob.Length; - dataBlob.Data = NULL; - dataBlob.Length = 0; - return; - } - - // Get the group for dataBlob - SSGroup group(database(), dataBlob); - - // Decode the dataBlob, pass in the DL allocator. - group->decodeDataBlob(dataBlob, cred, allocator(), *data); -} - -SSGroup -SSDbUniqueRecordImpl::group() -{ - // Get the datablob for this record - // @@@ Fixme so we don't need to call DbUniqueRecordImpl::get - CssmDataContainer dataBlob(allocator()); - DbUniqueRecordImpl::get(NULL, &dataBlob); - return SSGroup(database(), dataBlob); -} diff --git a/OSX/include/security_cdsa_client/securestorage.h b/OSX/include/security_cdsa_client/securestorage.h deleted file mode 100644 index 7474fbfd..00000000 --- a/OSX/include/security_cdsa_client/securestorage.h +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// securestorage - client interface to CSP DLs and their operations -// -#ifndef _H_CDSA_CLIENT_SECURESTORAGE -#define _H_CDSA_CLIENT_SECURESTORAGE 1 - -#include -#include -#include - -namespace Security -{ - -namespace CssmClient -{ - -// -// A CSP and a DL attachment of the same subservice -// -// This gives us 2 Object instances, but we make sure that have the same -// mImpl. Currently this class has no behaviour, but it will get some in -// the future. -// -class CSPDLImpl : public CSPImpl, public DLImpl -{ -public: - CSPDLImpl(const Guid &guid); - CSPDLImpl(const Module &module); - virtual ~CSPDLImpl(); - - // Object methods. - bool isActive() const { return CSPImpl::isActive() || DLImpl::isActive(); } - - virtual Allocator &allocator() const; - virtual void allocator(Allocator &alloc); - - virtual bool operator <(const CSPDLImpl &other) const; - virtual bool operator ==(const CSPDLImpl &other) const; - - // Attachment methods. - virtual CSSM_SERVICE_MASK subserviceMask() const; - virtual void subserviceId(uint32 id); - - uint32 subserviceId() const { return CSPImpl::subserviceId(); } - CSSM_ATTACH_FLAGS cspFlags() const { return CSPImpl::flags(); } - void cspFlags(CSSM_ATTACH_FLAGS f) { CSPImpl::flags(f); } - CSSM_ATTACH_FLAGS dlFlags() const { return DLImpl::flags(); } - void dlFlags(CSSM_ATTACH_FLAGS f) { DLImpl::flags(f); } - - void attach() { CSPImpl::attach(); DLImpl::attach(); } - void detach() { CSPImpl::detach(); DLImpl::detach(); } - bool attached() const { return CSPImpl::attached() || DLImpl::attached(); } - - Module module() const { return CSPImpl::module(); } - const Guid &guid() const { return CSPImpl::guid(); } - CSSM_MODULE_HANDLE cspHandle() { return CSPImpl::handle(); } - CSSM_MODULE_HANDLE dlHandle() { return DLImpl::handle(); } - - CssmSubserviceUid subserviceUid() const - { return CSPImpl::subserviceUid(); } - -private: -}; - - -class CSPDL : public CSP, public DL -{ -public: - typedef CSPDLImpl Impl; - - explicit CSPDL(Impl *impl) : CSP(impl), DL(impl) {} - CSPDL(const Guid &guid) : CSP(new Impl(guid)), DL(&CSP::impl()) {} - CSPDL(const Module &module) - : CSP(new Impl(module)), DL(&CSP::impl()) {} - - //template _Impl &impl() const - //{ return CSP::impl<_Impl>(); } - - Impl *get() const { return &CSP::impl(); } - Impl *operator ->() const { return &CSP::impl(); } - Impl &operator *() const { return CSP::impl(); } - - // Conversion operators must be here - bool operator !() const { return !get(); } - operator bool() const { return get(); } - - bool operator <(const CSPDL &other) const - { return *this && other ? **this < *other : get() < other.get(); } - bool operator ==(const CSPDL &other) const - { return *this && other ? **this == *other : get() == other.get(); } -}; - - -// -// SSCSPDL -- Secure storage class -// -class SSCSPDLImpl : public CSPDLImpl -{ -public: - SSCSPDLImpl(const Guid &guid); - SSCSPDLImpl(const Module &module); - virtual ~SSCSPDLImpl(); - - // DbMaker - DbImpl *newDb(const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation); -private: -}; - -class SSCSPDL : public CSPDL -{ -public: - typedef SSCSPDLImpl Impl; - - explicit SSCSPDL(Impl *impl) : CSPDL(impl) {} - SSCSPDL(const Guid &guid) : CSPDL(new Impl(guid)) {} - SSCSPDL(const Module &module) : CSPDL(new Impl(module)) {} - - Impl *operator ->() const { return &CSP::impl(); } - Impl &operator *() const { return CSP::impl(); } -}; - - -// -// SSDbImpl -- A Security Storage Db object. -// -class SSGroup; -class SSDbUniqueRecord; - -class SSDbImpl : public DbImpl -{ -public: - SSDbImpl(const SSCSPDL &cspdl, - const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation); - virtual ~SSDbImpl(); - - void create(); - void open(); - - SSDbUniqueRecord insert(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - const CSSM_RESOURCE_CONTROL_CONTEXT *rc = NULL); - - SSDbUniqueRecord insert(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, const SSGroup &group, - const CSSM_ACCESS_CREDENTIALS *cred); - - // DbCursorMaker - DbCursorImpl *newDbCursor(const CSSM_QUERY &query, - Allocator &allocator); - DbCursorImpl *newDbCursor(uint32 capacity, Allocator &allocator); - - // SSDbUniqueRecordMaker - DbUniqueRecordImpl *newDbUniqueRecord(); - - CSP csp() { return parent(); } -}; - -class SSDb : public Db -{ -public: - typedef SSDbImpl Impl; - - explicit SSDb(Impl *impl) : Db(impl) {} - SSDb(const SSCSPDL &cspdl, const char *inDbName, - const CSSM_NET_ADDRESS *inDbLocation = NULL) - : Db(cspdl->newDb(inDbName, inDbLocation)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// SSGroup -- Group key with acl, used to protect a group of items. -// -class SSGroupImpl : public KeyImpl -{ -public: - SSGroupImpl(const SSDb &ssDb, const CSSM_DATA &dataBlob); - SSGroupImpl(const SSDb &ssDb, - const CSSM_RESOURCE_CONTROL_CONTEXT *credAndAclEntry); - - static bool isGroup(const CSSM_DATA &dataBlob); - - const CssmData label() const; - void decodeDataBlob(const CSSM_DATA &dataBlob, - const CSSM_ACCESS_CREDENTIALS *cred, - Allocator &allocator, CSSM_DATA &data); - void encodeDataBlob(const CSSM_DATA *data, - const CSSM_ACCESS_CREDENTIALS *cred, - CssmDataContainer &dataBlob); - -private: - // Constants - enum - { - // Label prefix for a secure storage group - kGroupMagic = FOUR_CHAR_CODE('ssgp'), - - // Size of label (including prefix) - kLabelSize = 20, - - // Size of IV - kIVSize = 8 - }; - - CSSM_DB_ATTR_DECL(kLabel); - - CssmDataContainer mLabel; -}; - -class SSGroup : public Key -{ -public: - typedef SSGroupImpl Impl; - explicit SSGroup(Impl *impl) : Key(impl) {} - - SSGroup() : Key(NULL) {} - - // Create a new group. - SSGroup(const SSDb &ssDb, - const CSSM_RESOURCE_CONTROL_CONTEXT *credAndAclEntry) - : Key(new Impl(ssDb, credAndAclEntry)) {} - - // Lookup an existing group based on a dataBlob. - SSGroup(const SSDb &ssDb, const CSSM_DATA &dataBlob) - : Key(new Impl(ssDb, dataBlob)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// SSDbCursor -- Cursor for iterating over Securely Stored records (or keys) -// -class SSDbCursorImpl : public DbDbCursorImpl -{ -public: - SSDbCursorImpl(const Db &db, const CSSM_QUERY &query, - Allocator &allocator); - SSDbCursorImpl(const Db &db, uint32 capacity, - Allocator &allocator); - - bool next(DbAttributes *attributes, ::CssmDataContainer *data, - DbUniqueRecord &uniqueId); - bool next(DbAttributes *attributes, ::CssmDataContainer *data, - DbUniqueRecord &uniqueId, const CSSM_ACCESS_CREDENTIALS *cred); - bool nextKey(DbAttributes *attributes, Key &key, DbUniqueRecord &uniqueId); - //bool nextGroup(DbAttributes *attributes, SSGroup &group, DbUniqueRecord &uniqueId); - - SSDb database() { return parent(); } -protected: - void activate(); - void deactivate(); -}; - -class SSDbCursor : public DbCursor -{ -public: - typedef SSDbCursorImpl Impl; - - explicit SSDbCursor(Impl *impl) : DbCursor(impl) {} - SSDbCursor(const SSDb &ssDb, const CSSM_QUERY &query, - Allocator &allocator = Allocator::standard()) - : DbCursor(ssDb->newDbCursor(query, allocator)) {} - SSDbCursor(const SSDb &ssDb, const uint32 capacity = 0, - Allocator &allocator = Allocator::standard()) - : DbCursor(ssDb->newDbCursor(capacity, allocator)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// SSDbUniqueRecord -// -class SSDbUniqueRecordImpl : public DbUniqueRecordImpl -{ -public: - SSDbUniqueRecordImpl(const Db &db); - virtual ~SSDbUniqueRecordImpl(); - - void deleteRecord(); - void deleteRecord(const CSSM_ACCESS_CREDENTIALS *cred); - void modify(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode); - void modify(CSSM_DB_RECORDTYPE recordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *attributes, - const CSSM_DATA *data, - CSSM_DB_MODIFY_MODE modifyMode, - const CSSM_ACCESS_CREDENTIALS *cred); - void get(DbAttributes *attributes, ::CssmDataContainer *data); - void get(DbAttributes *attributes, ::CssmDataContainer *data, - const CSSM_ACCESS_CREDENTIALS *cred); - - SSDb database() { return parent(); } - - // Return the group that this record is in. - SSGroup group(); -}; - -class SSDbUniqueRecord : public DbUniqueRecord -{ -public: - typedef SSDbUniqueRecordImpl Impl; - - explicit SSDbUniqueRecord(Impl *impl) : DbUniqueRecord(impl) {} - SSDbUniqueRecord(const SSDb &ssDb) - : DbUniqueRecord(ssDb->newDbUniqueRecord()) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - -}; // end namespace CssmClient - -} // end namespace Security - -#endif //_H_CDSA_CLIENT_SECURESTORAGE diff --git a/OSX/include/security_cdsa_client/signclient.cpp b/OSX/include/security_cdsa_client/signclient.cpp deleted file mode 100644 index d7744a65..00000000 --- a/OSX/include/security_cdsa_client/signclient.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// signclient - client interface to CSSM sign/verify contexts -// -#include - -using namespace CssmClient; - - -// -// Common features of signing and verify contexts -// -void SigningContext::activate() -{ - StLock _(mActivateMutex); - if (!mActive) - { - check(CSSM_CSP_CreateSignatureContext(attachment()->handle(), mAlgorithm, - cred(), mKey, &mHandle)); - mActive = true; - } -} - - -// -// Signing -// -void Sign::sign(const CssmData *data, uint32 count, CssmData &signature) -{ - unstaged(); - check(CSSM_SignData(handle(), data, count, mSignOnly, &signature)); -} - -void Sign::init() -{ - check(CSSM_SignDataInit(handle())); - mStaged = true; -} - -void Sign::sign(const CssmData *data, uint32 count) -{ - staged(); - check(CSSM_SignDataUpdate(handle(), data, count)); -} - -void Sign::operator () (CssmData &signature) -{ - staged(); - check(CSSM_SignDataFinal(handle(), &signature)); - mStaged = false; -} - - -// -// Verifying -// -void Verify::verify(const CssmData *data, uint32 count, const CssmData &signature) -{ - unstaged(); - check(CSSM_VerifyData(handle(), data, count, mSignOnly, &signature)); -} - -void Verify::init() -{ - check(CSSM_VerifyDataInit(handle())); - mStaged = true; -} - -void Verify::verify(const CssmData *data, uint32 count) -{ - staged(); - check(CSSM_VerifyDataUpdate(handle(), data, count)); -} - -void Verify::operator () (const CssmData &signature) -{ - staged(); - check(CSSM_VerifyDataFinal(handle(), &signature)); - mStaged = false; -} diff --git a/OSX/include/security_cdsa_client/signclient.h b/OSX/include/security_cdsa_client/signclient.h deleted file mode 100644 index 81c90dbb..00000000 --- a/OSX/include/security_cdsa_client/signclient.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// signclient - client interface to CSSM sign/verify contexts -// -#ifndef _H_CDSA_CLIENT_SIGNCLIENT -#define _H_CDSA_CLIENT_SIGNCLIENT 1 - -#include -#include - -namespace Security { -namespace CssmClient { - - -// -// A signing/verifying context -// -class SigningContext : public Context -{ -public: - SigningContext(const CSP &csp, CSSM_ALGORITHMS alg, CSSM_ALGORITHMS signOnly = CSSM_ALGID_NONE) - : Context(csp, alg), mSignOnly(signOnly) { } - - Key key() const { assert(mKey); return mKey; } - void key(const Key &k) { mKey = k; set(CSSM_ATTRIBUTE_KEY, mKey); } - - CSSM_ALGORITHMS signOnlyAlgorithm() const { return mSignOnly; } - void signOnlyAlgorithm(CSSM_ALGORITHMS alg) { mSignOnly = alg; } - -protected: - void activate(); - CSSM_ALGORITHMS mSignOnly; - Key mKey; -}; - - -class Sign : public SigningContext -{ -public: - Sign(const CSP &csp, CSSM_ALGORITHMS alg, CSSM_ALGORITHMS signOnly = CSSM_ALGID_NONE) - : SigningContext(csp, alg, signOnly) { } - - // integrated - void sign(const CssmData &data, CssmData &signature) { sign(&data, 1, signature); } - void sign(const CssmData *data, uint32 count, CssmData &signature); - - // staged - void init(); // Optional - void sign(const CssmData &data) { sign(&data, 1); } - void sign(const CssmData *data, uint32 count); - void operator () (CssmData &signature); - CssmData operator () () { CssmData signature; (*this)(signature); return signature; } -}; - -class Verify : public SigningContext -{ -public: - Verify(const CSP &csp, CSSM_ALGORITHMS alg, CSSM_ALGORITHMS verifyOnly = CSSM_ALGID_NONE) - : SigningContext(csp, alg, verifyOnly) { } - - // integrated - void verify(const CssmData &data, const CssmData &signature) { verify(&data, 1, signature); } - void verify(const CssmData *data, uint32 count, const CssmData &signature); - - // staged - void init(); // Optional - void verify(const CssmData &data) { verify(&data, 1); } - void verify(const CssmData *data, uint32 count); - void operator () (const CssmData &signature); -}; - -} // end namespace CssmClient - -} // end namespace Security - -#endif // _H_CDSA_CLIENT_SIGNCLIENT diff --git a/OSX/include/security_cdsa_client/tpclient.cpp b/OSX/include/security_cdsa_client/tpclient.cpp deleted file mode 100644 index f64fef31..00000000 --- a/OSX/include/security_cdsa_client/tpclient.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2000-2002,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// tpclient - client interface to CSSM TPs and their operations -// -#include - -namespace Security { -namespace CssmClient { - - -// -// Manage TP attachments -// -TPImpl::TPImpl(const Guid &guid) - : AttachmentImpl(guid, CSSM_SERVICE_TP), mUseCL(NULL), mUseCSP(NULL), - mOwnCL(false), mOwnCSP(false) -{ -} - -TPImpl::TPImpl(const Module &module) - : AttachmentImpl(module, CSSM_SERVICE_TP), mUseCL(NULL), mUseCSP(NULL), - mOwnCL(false), mOwnCSP(false) -{ -} - -TPImpl::~TPImpl() -{ - if (mOwnCL) - delete mUseCL; - if (mOwnCSP) - delete mUseCSP; -} - - -// -// Verify a CertGroup -// -void TPImpl::certGroupVerify(const CertGroup &certGroup, - const TPVerifyContext &context, - TPVerifyResult *result) -{ - setupCL(); - setupCSP(); - check(CSSM_TP_CertGroupVerify(handle(), (*mUseCL)->handle(), (*mUseCSP)->handle(), - &certGroup, &context, result)); -} - - -// -// Initialize auxiliary modules for operation -// -void TPImpl::setupCL() -{ - if (mUseCL == NULL) { - secdebug("tpclient", "TP is auto-attaching supporting CL"); - mUseCL = new CL(gGuidAppleX509CL); - mOwnCL = true; - } -} - -void TPImpl::setupCSP() -{ - if (mUseCSP == NULL) { - secdebug("tpclient", "TP is auto-attaching supporting CSP"); - mUseCSP = new CSP(gGuidAppleCSP); - mOwnCSP = true; - } -} - -void TPImpl::use(CL &cl) -{ - if (mOwnCL) - delete mUseCL; - mUseCL = &cl; - mOwnCL = false; -} - -void TPImpl::use(CSP &csp) -{ - if (mOwnCSP) - delete mUseCSP; - mUseCSP = &csp; - mOwnCSP = false; -} - -CL &TPImpl::usedCL() -{ - setupCL(); - return *mUseCL; -} - -CSP &TPImpl::usedCSP() -{ - setupCSP(); - return *mUseCSP; -} - - -// -// A TPBuildVerifyContext -// -TPBuildVerifyContext::TPBuildVerifyContext(CSSM_TP_ACTION action, Allocator &alloc) - : allocator(alloc) -{ - // clear out the PODs - clearPod(); - mCallerAuth.clearPod(); - mDlDbList.clearPod(); - - // set initial elements - Action = action; - callerAuthPtr(&mCallerAuth); - mCallerAuth.dlDbList() = &mDlDbList; -} - - -} // end namespace CssmClient -} // end namespace Security - diff --git a/OSX/include/security_cdsa_client/tpclient.h b/OSX/include/security_cdsa_client/tpclient.h deleted file mode 100644 index ca28f2a4..00000000 --- a/OSX/include/security_cdsa_client/tpclient.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2000-2002,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// tpclient - client interface to CSSM TPs and their operations -// -#ifndef _H_CDSA_CLIENT_TPCLIENT -#define _H_CDSA_CLIENT_TPCLIENT 1 - -#include -#include -#include -#include -#include -#include - - -namespace Security { -namespace CssmClient { - - -// -// A TP attachment -// -class TPImpl : public AttachmentImpl -{ -public: - TPImpl(const Guid &guid); - TPImpl(const Module &module); - virtual ~TPImpl(); - -public: - // the CL and CSP used with many TP operations is usually - // pretty stable. The system may even figure them out - // automatically in the future. - void use(CL &cl); - void use(CSP &csp); - CL &usedCL(); - CSP &usedCSP(); - -public: - void certGroupVerify(const CertGroup &certGroup, const TPVerifyContext &context, - TPVerifyResult *result); - -private: - void setupCL(); // setup mUseCL - void setupCSP(); // setup mUseCSP - -private: - CL *mUseCL; // use this CL for TP operation - CSP *mUseCSP; // use this CSP for TP operation - bool mOwnCL, mOwnCSP; // whether we've made our own -}; - - -class TP : public Attachment -{ -public: - typedef TPImpl Impl; - - explicit TP(Impl *impl) : Attachment(impl) {} - TP(const Guid &guid) : Attachment(new Impl(guid)) {} - TP(const Module &module) : Attachment(new Impl(module)) {} - - Impl *operator ->() const { return &impl(); } - Impl &operator *() const { return impl(); } -}; - - -// -// A self-building TPVerifyContext. -// This is a TPVerifyContext, but it's NOT A PODWRAPPER (it's larger). -// -// NOTE: This is not a client-side object. -// -class TPBuildVerifyContext : public TPVerifyContext { -public: - TPBuildVerifyContext(CSSM_TP_ACTION action = CSSM_TP_ACTION_DEFAULT, - Allocator &alloc = Allocator::standard()); - - Allocator &allocator; - -private: - TPCallerAuth mCallerAuth; - // PolicyInfo mPolicyInfo; // -- unused - CssmDlDbList mDlDbList; -}; - - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_CLCLIENT diff --git a/OSX/include/security_cdsa_client/wrapkey.cpp b/OSX/include/security_cdsa_client/wrapkey.cpp deleted file mode 100644 index 541b7748..00000000 --- a/OSX/include/security_cdsa_client/wrapkey.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// wrapkey - client interface for wrapping and unwrapping keys -// -#include - -namespace Security { -namespace CssmClient { - - -Key -WrapKey::operator () (Key &keyToBeWrapped, const CssmData *descriptiveData) -{ - Key wrappedKey; - - check(CSSM_WrapKey(handle(), neededCred(), keyToBeWrapped, descriptiveData, - wrappedKey.makeNewKey(attachment()))); - wrappedKey->activate(); - - return wrappedKey; -} - -void -WrapKey::operator () (const CssmKey &keyToBeWrapped, CssmKey &wrappedKey, - const CssmData *descriptiveData) -{ - check(CSSM_WrapKey(handle(), neededCred(), &keyToBeWrapped, - descriptiveData, &wrappedKey)); -} - -void -WrapKey::activate() -{ - if (!mActive) - { - Crypt::activate(); - if (mWrappedKeyFormat != CSSM_KEYBLOB_WRAPPED_FORMAT_NONE) - set(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT, mWrappedKeyFormat); - } -} - -Key -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec) -{ - CssmData data(reinterpret_cast(1), 0); - Key unwrappedKey; - check(CSSM_UnwrapKey(handle(), NULL, - &keyToBeUnwrapped, spec.usage, spec.attributes, - spec.label, &compositeRcc(), - unwrappedKey.makeNewKey(attachment()), &data)); - unwrappedKey->activate(); - - return unwrappedKey; -} - -void -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey) -{ - CssmData data(reinterpret_cast(1), 0); - check(CSSM_UnwrapKey(handle(), NULL, &keyToBeUnwrapped, spec.usage, - spec.attributes, spec.label, &compositeRcc(), - &unwrappedKey, &data)); -} - -Key -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - Key &optionalPublicKey) -{ - CssmData data(reinterpret_cast(1), 0); - Key unwrappedKey; - check(CSSM_UnwrapKey(handle(), optionalPublicKey, - &keyToBeUnwrapped, spec.usage, spec.attributes, - spec.label, &compositeRcc(), - unwrappedKey.makeNewKey(attachment()), &data)); - - unwrappedKey->activate(); - - return unwrappedKey; -} - -void -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey, - const CssmKey *optionalPublicKey) -{ - CssmData data(reinterpret_cast(1), 0); - check(CSSM_UnwrapKey(handle(), optionalPublicKey, &keyToBeUnwrapped, - spec.usage, spec.attributes, spec.label, - &compositeRcc(), &unwrappedKey, &data)); -} - - -Key -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmData *descriptiveData) -{ - Key unwrappedKey; - check(CSSM_UnwrapKey(handle(), NULL, &keyToBeUnwrapped, spec.usage, - spec.attributes, spec.label, &compositeRcc(), - unwrappedKey.makeNewKey(attachment()), - descriptiveData)); - unwrappedKey->activate(); - - return unwrappedKey; -} - -void -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey, CssmData *descriptiveData) -{ - check(CSSM_UnwrapKey(handle(), NULL, &keyToBeUnwrapped, spec.usage, - spec.attributes, spec.label, &compositeRcc(), - &unwrappedKey, descriptiveData)); -} - -Key -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - const Key &optionalPublicKey, CssmData *descriptiveData) -{ - Key unwrappedKey; - check(CSSM_UnwrapKey(handle(), optionalPublicKey, &keyToBeUnwrapped, - spec.usage, spec.attributes, spec.label, - &compositeRcc(), - unwrappedKey.makeNewKey(attachment()), - descriptiveData)); - unwrappedKey->activate(); - - return unwrappedKey; -} - -void -UnwrapKey::operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey, CssmData *descriptiveData, - const CssmKey *optionalPublicKey) -{ - check(CSSM_UnwrapKey(handle(), optionalPublicKey, &keyToBeUnwrapped, - spec.usage, spec.attributes, spec.label, - &compositeRcc(), &unwrappedKey, - descriptiveData)); -} - - -void DeriveKey::activate() -{ - if (!mActive) - { - check(CSSM_CSP_CreateDeriveKeyContext(attachment()->handle(), mAlgorithm, - mTargetType, mKeySize, mCred, mKey, mIterationCount, mSalt, mSeed, &mHandle)); - mActive = true; - } -} - - -Key -DeriveKey::operator () (CssmData *param, const KeySpec &spec) -{ - Key derivedKey; - check(CSSM_DeriveKey(handle(), param, spec.usage, spec.attributes, - spec.label, &compositeRcc(), - derivedKey.makeNewKey(attachment()))); - derivedKey->activate(); - - return derivedKey; -} - -void -DeriveKey::operator () (CssmData *param, const KeySpec &spec, - CssmKey &derivedKey) -{ - check(CSSM_DeriveKey(handle(), param, spec.usage, spec.attributes, - spec.label, &compositeRcc(), &derivedKey)); -} - -} // end namespace CssmClient -} // end namespace Security diff --git a/OSX/include/security_cdsa_client/wrapkey.h b/OSX/include/security_cdsa_client/wrapkey.h deleted file mode 100644 index 41d7c752..00000000 --- a/OSX/include/security_cdsa_client/wrapkey.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// wrapkey - client interface for wrapping and unwrapping keys -// -#ifndef _H_CDSA_CLIENT_WRAPKEY -#define _H_CDSA_CLIENT_WRAPKEY 1 - -#include -#include -#include - - -namespace Security { -namespace CssmClient { - - -// -// Wrap a key -// -class WrapKey : public Crypt { -public: - WrapKey(const CSP &csp, CSSM_ALGORITHMS alg) : - Crypt(csp, alg), mWrappedKeyFormat(CSSM_KEYBLOB_WRAPPED_FORMAT_NONE) {} - -public: - CSSM_KEYBLOB_FORMAT wrappedKeyFormat() const { return mWrappedKeyFormat; } - void wrappedKeyFormat(CSSM_KEYBLOB_FORMAT wrappedKeyFormat) - { mWrappedKeyFormat = wrappedKeyFormat; set(CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT, wrappedKeyFormat); } - - // wrap the key - Key operator () (Key &keyToBeWrapped, const CssmData *descriptiveData = NULL); - void operator () (const CssmKey &keyToBeWrapped, CssmKey &wrappedKey, - const CssmData *descriptiveData = NULL); - -protected: - void activate(); - -private: - CSSM_KEYBLOB_FORMAT mWrappedKeyFormat; -}; - - -// -// Unwrap a key. This creates a new key object -// -class UnwrapKey : public Crypt, public RccBearer { -public: - UnwrapKey(const CSP &csp, CSSM_ALGORITHMS alg) : Crypt(csp, alg) {} - -public: - // wrap the key - Key operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec); - void operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey); - - Key operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - Key &optionalPublicKey); - void operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey, const CssmKey *optionalPublicKey); - - Key operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmData *descriptiveData); - void operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey, CssmData *descriptiveData); - - Key operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - const Key &optionalPublicKey, CssmData *descriptiveData); - void operator () (const CssmKey &keyToBeUnwrapped, const KeySpec &spec, - CssmKey &unwrappedKey, CssmData *descriptiveData, - const CssmKey *optionalPublicKey); -}; - - -// -// Derive a key in various and wonderous ways. Creates a new key object. -// -class DeriveKey : public Crypt, public RccBearer { -public: - DeriveKey(const CSP &csp, CSSM_ALGORITHMS alg, CSSM_ALGORITHMS target, uint32 size = 0) - : Crypt(csp, alg), mKeySize(size), mTargetType(target), mIterationCount(0), - mSeed(NULL), mSalt(NULL) { } - -public: - CSSM_ALGORITHMS targetType() const { return mTargetType; } - void targetType(CSSM_ALGORITHMS alg) { mTargetType = alg; } - uint32 iterationCount() const { return mIterationCount; } - void iterationCount(uint32 c) { mIterationCount = c; } - const CssmCryptoData seed() const { return *mSeed; } - void seed(const CssmCryptoData &data) { mSeed = &data; } - const CssmData salt() const { return *mSalt; } - void salt(const CssmData &data) { mSalt = &data; } - - Key operator () (CssmData *param, const KeySpec &spec); - void operator () (CssmData *param, const KeySpec &spec, - CssmKey &derivedKey); - - void activate(); - -private: - uint32 mKeySize; - CSSM_ALGORITHMS mTargetType; - uint32 mIterationCount; - const CssmCryptoData *mSeed; - const CssmData *mSalt; -}; - -} // end namespace CssmClient -} // end namespace Security - -#endif // _H_CDSA_CLIENT_WRAPKEY diff --git a/OSX/include/security_cdsa_plugin b/OSX/include/security_cdsa_plugin new file mode 120000 index 00000000..2be156f8 --- /dev/null +++ b/OSX/include/security_cdsa_plugin @@ -0,0 +1 @@ +./libsecurity_cdsa_plugin/lib \ No newline at end of file diff --git a/OSX/include/security_cdsa_plugin/ACsession.h b/OSX/include/security_cdsa_plugin/ACsession.h deleted file mode 100644 index bf2c4fca..00000000 --- a/OSX/include/security_cdsa_plugin/ACsession.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// ACsession.h - Framework for AC plugin modules -// -#ifndef _H_ACSESSION -#define _H_ACSESSION - -#include - -namespace Security -{ - -// -// The abstract ACPluginSession class is the common ancestor of your implementation -// object for an AC type plugin attachment session. Inherit from this and implement -// the abstract methods to define a plugin session. -// -class ACPluginSession : public PluginSession, public ACAbstractPluginSession { -public: - ACPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls) - : PluginSession(theHandle, plug, version, subserviceId, subserviceType, attachFlags, upcalls) { } - -protected: - CSSM_MODULE_FUNCS_PTR construct(); -}; - -} // end namespace Security - -#endif //_H_ACSESSION diff --git a/OSX/include/security_cdsa_plugin/CLsession.h b/OSX/include/security_cdsa_plugin/CLsession.h deleted file mode 100644 index d53c53fa..00000000 --- a/OSX/include/security_cdsa_plugin/CLsession.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// CLsession.h - Framework for CL plugin modules -// -#ifndef _H_CLSESSION -#define _H_CLSESSION - -#include - -namespace Security { - -// -// The abstract CLPluginSession class is the common ancestor of your implementation -// object for an CL type plugin attachment session. Inherit from this and implement -// the abstract methods to define a plugin session. -// -class CLPluginSession : public PluginSession, public CLAbstractPluginSession { -public: - CLPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls) - : PluginSession(theHandle, plug, version, subserviceId, subserviceType, attachFlags, upcalls) { } - -protected: - CSSM_MODULE_FUNCS_PTR construct(); -}; - -} // end namespace Security - -#endif //_H_CLSESSION diff --git a/OSX/include/security_cdsa_plugin/CSPsession.cpp b/OSX/include/security_cdsa_plugin/CSPsession.cpp deleted file mode 100644 index 41f4ee85..00000000 --- a/OSX/include/security_cdsa_plugin/CSPsession.cpp +++ /dev/null @@ -1,1156 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// CSPsession - Plugin framework for CSP plugin modules -// -#include -#include -#include - - -typedef CSPFullPluginSession::CSPContext CSPContext; - - -// -// PluginContext construction -// -CSPPluginSession::PluginContext::~PluginContext() -{ /* virtual */ } - -CSPFullPluginSession::AlgorithmFactory::~AlgorithmFactory() -{ /* virtual */ } - - -// -// Internal utilities -// -CssmData CSPFullPluginSession::makeBuffer(size_t size, Allocator &alloc) -{ - return CssmData(alloc.malloc(size), size); -} - -inline size_t CSPFullPluginSession::totalBufferSize(const CssmData *data, uint32 count) -{ - size_t size = 0; - for (uint32 n = 0; n < count; n++) - size += data[n].length(); - return size; -} - - -// -// Notify a context that its underlying CSSM context has (well, may have) changed. -// The default reaction is to ask the frame to delete the context and start over. -// -bool CSPPluginSession::PluginContext::changed(const Context &context) -{ - return false; // delete me, please -} - - -// -// The Session's init() function calls your setupContext() method to prepare -// it for action, then calls the context's init() method. -// -CSPContext *CSPFullPluginSession::init(CSSM_CC_HANDLE ccHandle, - CSSM_CONTEXT_TYPE type, - const Context &context, bool encoding) -{ - CSPContext *ctx = getContext(ccHandle); - checkOperation(context.type(), type); - - // ask the implementation to set up an internal context - setupContext(ctx, context, encoding); - assert(ctx != NULL); // must have context now (@@@ throw INTERNAL_ERROR instead?) - ctx->mType = context.type(); - ctx->mDirection = encoding; - setContext(ccHandle, ctx); - - // initialize the context and return it - ctx->init(context, encoding); - return ctx; -} - - -// -// Retrieve a context for a staged operation in progress. -// -CSPContext *CSPFullPluginSession::getStagedContext(CSSM_CC_HANDLE ccHandle, - CSSM_CONTEXT_TYPE type, bool encoding) -{ - CSPContext *ctx = getContext(ccHandle); - if (ctx == NULL) - CssmError::throwMe(CSSMERR_CSP_INVALID_CONTEXT); //@@@ better diagnostic? - checkOperation(ctx->type(), type); - if (ctx->encoding() != encoding) - CssmError::throwMe(CSSMERR_CSP_INVALID_CONTEXT); - return ctx; -} - - -// -// The Session's checkState() function is called for subsequent staged operations -// (update/final) to verify that the user didn't screw up the sequencing. -// -void CSPFullPluginSession::checkOperation(CSSM_CONTEXT_TYPE ctxType, CSSM_CONTEXT_TYPE opType) -{ - switch (opType) { - case CSSM_ALGCLASS_NONE: // no check - return; - case CSSM_ALGCLASS_CRYPT: // symmetric or asymmetric encryption - if (ctxType == CSSM_ALGCLASS_SYMMETRIC || - ctxType == CSSM_ALGCLASS_ASYMMETRIC) - return; - default: // plain match - if (ctxType == opType) - return; - } - CssmError::throwMe(CSSMERR_CSP_INVALID_CONTEXT); -} - - -// -// The default implementations of the primary context operations throw internal -// errors. You must implement any of these that are actually called by the -// operations involved. The others, of course, can be left alone. -// -void CSPContext::init(const Context &context, bool encoding) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::update(const CssmData &data) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::update(void *inp, size_t &inSize, void *outp, size_t &outSize) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::final(CssmData &out) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::final(const CssmData &in) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::generate(const Context &, CssmKey &pubKey, CssmKey &privKey) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::generate(const Context &, uint32, CssmData ¶ms, - uint32 &attrCount, Context::Attr * &attrs) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -size_t CSPContext::inputSize(size_t outSize) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -size_t CSPContext::outputSize(bool final, size_t inSize) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -void CSPContext::minimumProgress(size_t &in, size_t &out) -{ CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); } - -CSPFullPluginSession::CSPContext *CSPContext::clone(Allocator &) -{ CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); } - -void CSPContext::setDigestAlgorithm(CSSM_ALGORITHMS digestAlg) -{ CssmError::throwMe(CSSMERR_CSP_INVALID_ALGORITHM); } - -void CSPContext::update(const CssmData *in, - uint32 inCount, Writer &writer) -{ - const CssmData *lastIn = in + inCount; - CssmData current; - for (;;) { - if (current.length() == 0) { - if (in == lastIn) - return; // all done - current = *in++; - continue; // Just in case next block is zero length too. - } - // match up current input and output buffers - void *outP; size_t outSize; - writer.nextBlock(outP, outSize); - size_t inSize = inputSize(outSize); - if (inSize > current.length()) - inSize = current.length(); // cap to remaining input buffer - if (inSize > 0) { - // we can stuff into the current output buffer - do it - update(current.data(), inSize, outP, outSize); - current.use(inSize); - writer.use(outSize); - } else { - // We have remaining output buffer space, but not enough - // for the algorithm to make progress with it. We must proceed with - // a bounce buffer and split it manually into this and the next buffer(s). - size_t minOutput; - minimumProgress(inSize, minOutput); - assert(minOutput > outSize); // PluginContext consistency (not fatal) - char splitBuffer[128]; - assert(minOutput <= sizeof(splitBuffer)); // @@@ static buffer for now - outSize = sizeof(splitBuffer); - if (current.length() < inSize) - inSize = current.length(); // cap to data remaining in input buffer - update(current.data(), inSize, splitBuffer, outSize); - assert(inSize > 0); // progress made - writer.put(splitBuffer, outSize); // stuff into buffer, the hard way - current.use(inSize); - } - } -} - -void CSPContext::final(CssmData &out, Allocator &alloc) -{ - size_t needed = outputSize(true, 0); - if (out) { - if (out.length() < needed) - CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR); - } else { - out = makeBuffer(needed, alloc); - } - final(out); -} - -void CSPContext::final(Writer &writer, Allocator &alloc) -{ - if (size_t needed = outputSize(true, 0)) { - // need to generate additional output - writer.allocate(needed, alloc); // belt + suspender - - void *addr; size_t size; - writer.nextBlock(addr, size); // next single block available - if (needed <= size) { // rest fits into one block - CssmData chunk(addr, size); - final(chunk); - writer.use(chunk.length()); - } else { // need to split it up - char splitBuffer[128]; - assert(needed <= sizeof(splitBuffer)); - CssmData chunk(splitBuffer, sizeof(splitBuffer)); - final(chunk); - writer.put(chunk.data(), chunk.length()); - } - } -} - - -// -// Default context response functions -// -CSPPluginSession::PluginContext * -CSPPluginSession::contextCreate(CSSM_CC_HANDLE, const Context &) -{ - return NULL; // request no local context -} - -void CSPPluginSession::contextUpdate(CSSM_CC_HANDLE ccHandle, - const Context &context, PluginContext * &ctx) -{ - // call update notifier in context object - if (ctx && !ctx->changed(context)) { - // context requested that it be removed - delete ctx; - ctx = NULL; - } -} - -void CSPPluginSession::contextDelete(CSSM_CC_HANDLE, const Context &, PluginContext *) -{ - // do nothing (you can't prohibit deletion here) -} - - -// -// Default event notification handler. -// This default handler calls the virtual context* methods to dispose of context actions. -// -void CSPPluginSession::EventNotify(CSSM_CONTEXT_EVENT event, - CSSM_CC_HANDLE ccHandle, const Context &context) -{ - switch (event) { - case CSSM_CONTEXT_EVENT_CREATE: - if (PluginContext *ctx = contextCreate(ccHandle, context)) { - StLock _(contextMapLock); - assert(contextMap[ccHandle] == NULL); // check context re-creation - contextMap[ccHandle] = ctx; - } - break; - case CSSM_CONTEXT_EVENT_UPDATE: - // note that the handler can change the map entry (even to NULL, if desired) - { - StLock _(contextMapLock); - contextUpdate(ccHandle, context, contextMap[ccHandle]); - } - break; - case CSSM_CONTEXT_EVENT_DELETE: - { - StLock _(contextMapLock); - if (PluginContext *ctx = contextMap[ccHandle]) { - contextDelete(ccHandle, context, ctx); - delete ctx; - } - contextMap.erase(ccHandle); - } - break; - default: - CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); // unexpected event code - } -} - - -// -// Defaults for methods you *should* implement. -// If you don't, they'll throw UNIMPLEMENTED. -// -void CSPFullPluginSession::getKeySize(const CssmKey &key, CSSM_KEY_SIZE &size) -{ unimplemented(); } - - -// -// Encryption and decryption -// -void CSPFullPluginSession::EncryptData(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData clearBufs[], - uint32 clearBufCount, - CssmData cipherBufs[], - uint32 cipherBufCount, - CSSM_SIZE &bytesEncrypted, - CssmData &remData, - CSSM_PRIVILEGE privilege) -{ - Writer writer(cipherBufs, cipherBufCount, &remData); - CSPContext *ctx = init(ccHandle, CSSM_ALGCLASS_CRYPT, context, true); - size_t outNeeded = ctx->outputSize(true, totalBufferSize(clearBufs, clearBufCount)); - writer.allocate(outNeeded, *this); - ctx->update(clearBufs, clearBufCount, writer); - ctx->final(writer, *this); - bytesEncrypted = writer.close(); -} - -void CSPFullPluginSession::EncryptDataInit(CSSM_CC_HANDLE ccHandle, - const Context &context, - CSSM_PRIVILEGE Privilege) -{ - init(ccHandle, CSSM_ALGCLASS_CRYPT, context, true); -} - -void CSPFullPluginSession::EncryptDataUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData clearBufs[], - uint32 clearBufCount, - CssmData cipherBufs[], - uint32 cipherBufCount, - CSSM_SIZE &bytesEncrypted) -{ - CSPContext *alg = getStagedContext(ccHandle, CSSM_ALGCLASS_CRYPT, true); - Writer writer(cipherBufs, cipherBufCount); - size_t outNeeded = alg->outputSize(false, totalBufferSize(clearBufs, clearBufCount)); - writer.allocate(outNeeded, *this); - alg->update(clearBufs, clearBufCount, writer); - bytesEncrypted = writer.close(); -} - -void CSPFullPluginSession::EncryptDataFinal(CSSM_CC_HANDLE ccHandle, - CssmData &remData) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_CRYPT, true)->final(remData, *this); -} - - -void CSPFullPluginSession::DecryptData(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData cipherBufs[], - uint32 cipherBufCount, - CssmData clearBufs[], - uint32 clearBufCount, - CSSM_SIZE &bytesDecrypted, - CssmData &remData, - CSSM_PRIVILEGE privilege) -{ - Writer writer(clearBufs, clearBufCount, &remData); - CSPContext *ctx = init(ccHandle, CSSM_ALGCLASS_CRYPT, context, false); - size_t outNeeded = ctx->outputSize(true, totalBufferSize(cipherBufs, cipherBufCount)); - writer.allocate(outNeeded, *this); - ctx->update(cipherBufs, cipherBufCount, writer); - ctx->final(writer, *this); - bytesDecrypted = writer.close(); -} - -void CSPFullPluginSession::DecryptDataInit(CSSM_CC_HANDLE ccHandle, - const Context &context, - CSSM_PRIVILEGE Privilege) -{ - init(ccHandle, CSSM_ALGCLASS_CRYPT, context, false); -} - -void CSPFullPluginSession::DecryptDataUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData cipherBufs[], - uint32 cipherBufCount, - CssmData clearBufs[], - uint32 clearBufCount, - CSSM_SIZE &bytesDecrypted) -{ - CSPContext *ctx = getStagedContext(ccHandle, CSSM_ALGCLASS_CRYPT, false); - Writer writer(clearBufs, clearBufCount); - size_t outNeeded = ctx->outputSize(false, totalBufferSize(cipherBufs, cipherBufCount)); - writer.allocate(outNeeded, *this); - ctx->update(cipherBufs, cipherBufCount, writer); - bytesDecrypted = writer.close(); -} - -void CSPFullPluginSession::DecryptDataFinal(CSSM_CC_HANDLE ccHandle, - CssmData &remData) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_CRYPT, false)->final(remData, *this); -} - -void CSPFullPluginSession::QuerySize(CSSM_CC_HANDLE ccHandle, - const Context &context, - CSSM_BOOL encrypt, - uint32 querySizeCount, - QuerySizeData *dataBlock) -{ - if (querySizeCount == 0) - return; // nothing ventured, nothing gained - CSPContext *ctx = getContext(ccHandle); // existing context? - if (ctx == NULL) // force internal context creation (as best we can) - ctx = init(ccHandle, context.type(), context, encrypt); - // If QuerySizeCount > 1, we assume this inquires about a staged - // operation, and the LAST item gets the 'final' treatment. - //@@@ Intel revised algspec says "use the staged flag" -- TBD - for (uint32 n = 0; n < querySizeCount; n++) { - // the outputSize() call might throw CSSMERR_CSP_QUERY_SIZE_UNKNOWN - dataBlock[n].SizeOutputBlock = - (uint32)ctx->outputSize(n == querySizeCount-1, dataBlock[n].inputSize()); - } - //@@@ if we forced a context creation, should we discard it now? -} - - -// -// Key wrapping and unwrapping. -// -void CSPFullPluginSession::WrapKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const AccessCredentials &AccessCred, - const CssmKey &Key, - const CssmData *DescriptiveData, - CssmKey &WrappedKey, - CSSM_PRIVILEGE Privilege) -{ - unimplemented(); -} - -void CSPFullPluginSession::UnwrapKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmKey *PublicKey, - const CssmKey &WrappedKey, - uint32 KeyUsage, - uint32 KeyAttr, - const CssmData *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CssmKey &UnwrappedKey, - CssmData &DescriptiveData, - CSSM_PRIVILEGE Privilege) -{ - unimplemented(); -} - -void CSPFullPluginSession::DeriveKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - CssmData &Param, - uint32 KeyUsage, - uint32 KeyAttr, - const CssmData *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CssmKey &DerivedKey) -{ - unimplemented(); -} - - -// -// Message Authentication Codes. -// Almost like signatures (signatures with symmetric keys), though the -// underlying implementation may be somewhat different. -// -void CSPFullPluginSession::GenerateMac(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData dataBufs[], - uint32 dataBufCount, - CssmData &mac) -{ - GenerateMacInit(ccHandle, context); - GenerateMacUpdate(ccHandle, dataBufs, dataBufCount); - GenerateMacFinal(ccHandle, mac); -} - -void CSPFullPluginSession::GenerateMacInit(CSSM_CC_HANDLE ccHandle, - const Context &context) -{ - init(ccHandle, CSSM_ALGCLASS_MAC, context, true); -} - -void CSPFullPluginSession::GenerateMacUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData dataBufs[], - uint32 dataBufCount) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_MAC, true)->update(dataBufs, dataBufCount); -} - -void CSPFullPluginSession::GenerateMacFinal(CSSM_CC_HANDLE ccHandle, - CssmData &mac) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_MAC, true)->final(mac, *this); -} - -void CSPFullPluginSession::VerifyMac(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData dataBufs[], - uint32 dataBufCount, - const CssmData &mac) -{ - VerifyMacInit(ccHandle, context); - VerifyMacUpdate(ccHandle, dataBufs, dataBufCount); - VerifyMacFinal(ccHandle, mac); -} - -void CSPFullPluginSession::VerifyMacInit(CSSM_CC_HANDLE ccHandle, - const Context &context) -{ - init(ccHandle, CSSM_ALGCLASS_MAC, context, false); -} - -void CSPFullPluginSession::VerifyMacUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData dataBufs[], - uint32 dataBufCount) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_MAC, false)->update(dataBufs, dataBufCount); -} - -void CSPFullPluginSession::VerifyMacFinal(CSSM_CC_HANDLE ccHandle, - const CssmData &mac) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_MAC, false)->final(mac); -} - - -// -// Signatures -// -void CSPFullPluginSession::SignData(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData dataBufs[], - uint32 dataBufCount, - CSSM_ALGORITHMS digestAlgorithm, - CssmData &Signature) -{ - SignDataInit(ccHandle, context); - if(digestAlgorithm != CSSM_ALGID_NONE) { - getStagedContext(ccHandle, CSSM_ALGCLASS_SIGNATURE, - true)->setDigestAlgorithm(digestAlgorithm); - } - SignDataUpdate(ccHandle, dataBufs, dataBufCount); - SignDataFinal(ccHandle, Signature); -} - -void CSPFullPluginSession::SignDataInit(CSSM_CC_HANDLE ccHandle, - const Context &context) -{ - init(ccHandle, CSSM_ALGCLASS_SIGNATURE, context, true); -} - -void CSPFullPluginSession::SignDataUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData dataBufs[], - uint32 dataBufCount) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_SIGNATURE, true)->update(dataBufs, dataBufCount); -} - -void CSPFullPluginSession::SignDataFinal(CSSM_CC_HANDLE ccHandle, - CssmData &signature) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_SIGNATURE, true)->final(signature, *this); -} - - -void CSPFullPluginSession::VerifyData(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData dataBufs[], - uint32 dataBufCount, - CSSM_ALGORITHMS digestAlgorithm, - const CssmData &Signature) -{ - VerifyDataInit(ccHandle, context); - if(digestAlgorithm != CSSM_ALGID_NONE) { - getStagedContext(ccHandle, CSSM_ALGCLASS_SIGNATURE, - false)->setDigestAlgorithm(digestAlgorithm); - } - VerifyDataUpdate(ccHandle, dataBufs, dataBufCount); - VerifyDataFinal(ccHandle, Signature); -} - -void CSPFullPluginSession::VerifyDataInit(CSSM_CC_HANDLE ccHandle, const Context &context) -{ - init(ccHandle, CSSM_ALGCLASS_SIGNATURE, context, false); -} - -void CSPFullPluginSession::VerifyDataUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData dataBufs[], - uint32 dataBufCount) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_SIGNATURE, false)->update(dataBufs, dataBufCount); -} - -void CSPFullPluginSession::VerifyDataFinal(CSSM_CC_HANDLE ccHandle, - const CssmData &signature) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_SIGNATURE, false)->final(signature); -} - - -// -// Digesting -// -void CSPFullPluginSession::DigestData(CSSM_CC_HANDLE ccHandle, - const Context &context, - const CssmData dataBufs[], - uint32 DataBufCount, - CssmData &Digest) -{ - DigestDataInit(ccHandle, context); - DigestDataUpdate(ccHandle, dataBufs, DataBufCount); - DigestDataFinal(ccHandle, Digest); -} - -void CSPFullPluginSession::DigestDataInit(CSSM_CC_HANDLE ccHandle, const Context &context) -{ - init(ccHandle, CSSM_ALGCLASS_DIGEST, context); -} - -void CSPFullPluginSession::DigestDataUpdate(CSSM_CC_HANDLE ccHandle, - const CssmData dataBufs[], - uint32 dataBufCount) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_DIGEST)->update(dataBufs, dataBufCount); -} - -void CSPFullPluginSession::DigestDataFinal(CSSM_CC_HANDLE ccHandle, - CssmData &digest) -{ - getStagedContext(ccHandle, CSSM_ALGCLASS_DIGEST)->final(digest, *this); -} - -void CSPFullPluginSession::DigestDataClone(CSSM_CC_HANDLE ccHandle, - CSSM_CC_HANDLE clonedCCHandle) -{ - CSPContext *cloned = getStagedContext(ccHandle, CSSM_ALGCLASS_DIGEST)->clone(*this); - cloned->mDirection = true; - cloned->mType = CSSM_ALGCLASS_DIGEST; - setContext(clonedCCHandle, cloned); -} - - -// -// Key generation, Derivation, and inquiry -// -void CSPFullPluginSession::GenerateKey(CSSM_CC_HANDLE ccHandle, - const Context &context, - uint32 keyUsage, - uint32 keyAttr, - const CssmData *keyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *credAndAclEntry, - CssmKey &key, - CSSM_PRIVILEGE privilege) -{ - CSPContext *alg = init(ccHandle, CSSM_ALGCLASS_KEYGEN, context); - setKey(key, context, CSSM_KEYCLASS_SESSION_KEY, keyAttr, keyUsage); - CssmKey blank; // dummy 2nd key (not used) - alg->generate(context, key, blank); -} - -class ContextMinder -{ -private: - CSSM_CC_HANDLE mHandle; - -public: - ContextMinder(CSSM_CC_HANDLE ccHandle) : mHandle(ccHandle) {} - ~ContextMinder() {CSSM_DeleteContext(mHandle);} -}; - - - -void CSPFullPluginSession::GenerateKeyPair(CSSM_CC_HANDLE ccHandle, - const Context &context, - uint32 publicKeyUsage, - uint32 publicKeyAttr, - const CssmData *publicKeyLabel, - CssmKey &publicKey, - uint32 privateKeyUsage, - uint32 privateKeyAttr, - const CssmData *privateKeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *credAndAclEntry, - CssmKey &privateKey, - CSSM_PRIVILEGE privilege) -{ - CSPContext *alg = init(ccHandle, CSSM_ALGCLASS_KEYGEN, context); - - setKey(publicKey, context, CSSM_KEYCLASS_PUBLIC_KEY, publicKeyAttr, publicKeyUsage); - setKey(privateKey, context, CSSM_KEYCLASS_PRIVATE_KEY, privateKeyAttr, privateKeyUsage); - alg->generate(context, publicKey, privateKey); - - //@@@ handle labels - //@@@ handle reference keys - - bool encryptPublic = publicKeyUsage & CSSM_KEYUSE_ENCRYPT; - bool encryptPrivate = privateKeyUsage & CSSM_KEYUSE_ENCRYPT; - - if (!(encryptPublic || encryptPrivate)) - { - return ; - } - - // time to do the FIPS required test! - CSSM_CSP_HANDLE moduleHandle = handle(); - CSSM_CC_HANDLE encryptHandle; - CSSM_ACCESS_CREDENTIALS nullCreds; - memset(&nullCreds, 0, sizeof(nullCreds)); - - CSSM_KEY_PTR encryptingKey, decryptingKey; - if (encryptPublic) - { - encryptingKey = &publicKey; - decryptingKey = &privateKey; - } - else - { - encryptingKey = &privateKey; - decryptingKey = &publicKey; - } - - // make data to be encrypted - unsigned bytesInKey = encryptingKey->KeyHeader.LogicalKeySizeInBits / 8; - u_int8_t buffer[bytesInKey]; - unsigned i; - - for (i = 0; i < bytesInKey; ++i) - { - buffer[i] = i; - } - - CSSM_DATA clearBuf = {bytesInKey, buffer}; - CSSM_DATA cipherBuf; // have the CSP allocate the resulting memory - CSSM_SIZE bytesEncrypted; - CSSM_DATA remData = {0, NULL}; - CSSM_DATA decryptedBuf = {bytesInKey, buffer}; - - CSSM_RETURN result = CSSM_CSP_CreateAsymmetricContext(moduleHandle, encryptingKey->KeyHeader.AlgorithmId, &nullCreds, encryptingKey, CSSM_PADDING_NONE, &encryptHandle); - if (result != CSSM_OK) - { - CssmError::throwMe(result); - } - - ContextMinder encryptMinder(encryptHandle); // auto throw away if we error out - - CSSM_QUERY_SIZE_DATA qsData; - qsData.SizeInputBlock = bytesInKey; - result = CSSM_QuerySize(encryptHandle, CSSM_TRUE, 1, &qsData); - if (result == CSSMERR_CSP_INVALID_ALGORITHM) - { - return; - } - - uint8 cipherBuffer[qsData.SizeOutputBlock]; - cipherBuf.Length = qsData.SizeOutputBlock; - cipherBuf.Data = cipherBuffer; - - // do the encryption - result = CSSM_EncryptData(encryptHandle, &clearBuf, 1, &cipherBuf, 1, &bytesEncrypted, &remData); - if (result != CSSM_OK) - { - CssmError::throwMe(result); - } - - // check the result - if (memcmp(cipherBuf.Data, clearBuf.Data, clearBuf.Length) == 0) - { - // we have a match, that's not good news... - abort(); - } - - // clean up - if (remData.Data != NULL) - { - free(remData.Data); - } - - // make a context to perform the decryption - CSSM_CC_HANDLE decryptHandle; - result = CSSM_CSP_CreateAsymmetricContext(moduleHandle, encryptingKey->KeyHeader.AlgorithmId, &nullCreds, decryptingKey, CSSM_PADDING_NONE, &decryptHandle); - ContextMinder decryptMinder(decryptHandle); - - if (result != CSSM_OK) - { - CssmError::throwMe(result); - } - - result = CSSM_DecryptData(decryptHandle, &cipherBuf, 1, &decryptedBuf, 1, &bytesEncrypted, &remData); - if (result != CSSM_OK) - { - CssmError::throwMe(result); - } - - // check the results - for (i = 0; i < bytesInKey; ++i) - { - if (decryptedBuf.Data[i] != (i & 0xFF)) - { - // bad news - abort(); - } - } - - if (remData.Data != NULL) - { - free(remData.Data); - } -} - -void CSPFullPluginSession::ObtainPrivateKeyFromPublicKey(const CssmKey &PublicKey, - CssmKey &PrivateKey) -{ - unimplemented(); -} - -void CSPFullPluginSession::QueryKeySizeInBits(CSSM_CC_HANDLE ccHandle, - const Context *context, - const CssmKey *key, - CSSM_KEY_SIZE &keySize) -{ - if (context) { - getKeySize(context->get(CSSM_ATTRIBUTE_KEY, CSSMERR_CSP_MISSING_ATTR_KEY), - keySize); - } else { - getKeySize(CssmKey::required(key), keySize); - } -} - - -// -// Free a key object. -// -void CSPFullPluginSession::FreeKey(const AccessCredentials *AccessCred, - CssmKey &key, - CSSM_BOOL Delete) -{ - free(key.data()); -} - - -// -// Random number and parameter generation -// -void CSPFullPluginSession::GenerateRandom(CSSM_CC_HANDLE ccHandle, - const Context &context, - CssmData &randomNumber) -{ - init(ccHandle, CSSM_ALGCLASS_RANDOMGEN, context)->final(randomNumber, *this); -} - -void CSPFullPluginSession::GenerateAlgorithmParams(CSSM_CC_HANDLE ccHandle, - const Context &context, - uint32 paramBits, - CssmData ¶m, - uint32 &attrCount, - CSSM_CONTEXT_ATTRIBUTE_PTR &attrs) -{ - Context::Attr *attrList; - init(ccHandle, CSSM_ALGCLASS_NONE, context)->generate(context, paramBits, - param, attrCount, attrList); - attrs = attrList; -} - - -// -// Login/Logout and token operational maintainance. -// These mean little without support by the actual implementation, but we can help... -// @@@ Should this be in CSP[non-Full]PluginSession? -// -void CSPFullPluginSession::Login(const AccessCredentials &AccessCred, - const CssmData *LoginName, - const void *Reserved) -{ - if (Reserved != NULL) - CssmError::throwMe(CSSM_ERRCODE_INVALID_POINTER); - - // default implementation refuses to log in - //@@@ should hand it to implementation virtual defaulting to this - CssmError::throwMe(CSSMERR_CSP_INVALID_LOGIN_NAME); -} - -void CSPFullPluginSession::Logout() -{ - if (!loggedIn(false)) - CssmError::throwMe(CSSMERR_CSP_NOT_LOGGED_IN); -} - -void CSPFullPluginSession::VerifyDevice(const CssmData &DeviceCert) -{ - CssmError::throwMe(CSSMERR_CSP_DEVICE_VERIFY_FAILED); -} - -void CSPFullPluginSession::GetOperationalStatistics(CSPOperationalStatistics &statistics) -{ - memset(&statistics, 0, sizeof(statistics)); - statistics.UserAuthenticated = loggedIn(); - //@@@ collect device flags - capability matrix setup? - //@@@ collect token limitation parameters (static) - capability matrix setup? - //@@@ collect token statistics (dynamic) - dynamic accounting call-downs? -} - - -// -// Utterly miscellaneous, rarely used, strange functions -// -void CSPFullPluginSession::RetrieveCounter(CssmData &Counter) -{ - unimplemented(); -} - -void CSPFullPluginSession::RetrieveUniqueId(CssmData &UniqueID) -{ - unimplemented(); -} - -void CSPFullPluginSession::GetTimeValue(CSSM_ALGORITHMS TimeAlgorithm, CssmData &TimeData) -{ - unimplemented(); -} - - -// -// ACL retrieval and change operations -// -void CSPFullPluginSession::GetKeyOwner(const CssmKey &Key, - CSSM_ACL_OWNER_PROTOTYPE &Owner) -{ - unimplemented(); -} - -void CSPFullPluginSession::ChangeKeyOwner(const AccessCredentials &AccessCred, - const CssmKey &Key, - const CSSM_ACL_OWNER_PROTOTYPE &NewOwner) -{ - unimplemented(); -} - -void CSPFullPluginSession::GetKeyAcl(const CssmKey &Key, - const CSSM_STRING *SelectionTag, - uint32 &NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &AclInfos) -{ - unimplemented(); -} - -void CSPFullPluginSession::ChangeKeyAcl(const AccessCredentials &AccessCred, - const CSSM_ACL_EDIT &AclEdit, - const CssmKey &Key) -{ - unimplemented(); -} - -void CSPFullPluginSession::GetLoginOwner(CSSM_ACL_OWNER_PROTOTYPE &Owner) -{ - unimplemented(); -} - -void CSPFullPluginSession::ChangeLoginOwner(const AccessCredentials &AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &NewOwner) -{ - unimplemented(); -} - -void CSPFullPluginSession::GetLoginAcl(const CSSM_STRING *SelectionTag, - uint32 &NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &AclInfos) -{ - unimplemented(); -} - -void CSPFullPluginSession::ChangeLoginAcl(const AccessCredentials &AccessCred, - const CSSM_ACL_EDIT &AclEdit) -{ - unimplemented(); -} - - - -// -// Passthroughs (by default, unimplemented) -// -void CSPFullPluginSession::PassThrough(CSSM_CC_HANDLE CCHandle, - const Context &Context, - uint32 PassThroughId, - const void *InData, - void **OutData) -{ - unimplemented(); -} - - -// -// KeyPool -- ReferencedKey management functionality -// -KeyPool::KeyPool() -{ -} - -KeyPool::~KeyPool() -{ - StLock _(mKeyMapLock); - // Delete every ReferencedKey in the pool, but be careful to deactivate them first - // to keep them from calling erase (which would cause deadlock since we already hold mKeyMapLock). - KeyMap::iterator end = mKeyMap.end(); - for (KeyMap::iterator it = mKeyMap.begin(); it != end; ++it) - { - try - { - it->second->deactivate(); - } - catch(...) {} - delete it->second; - } - mKeyMap.clear(); -} - -void -KeyPool::add(ReferencedKey &referencedKey) -{ - StLock _(mKeyMapLock); - bool inserted; - inserted = mKeyMap.insert(KeyMap::value_type(referencedKey.keyReference(), &referencedKey)).second; - // Since add is only called from the constructor of ReferencedKey we should - // never add a key that is already in mKeyMap - assert(inserted); -} - -ReferencedKey & -KeyPool::findKey(const CSSM_KEY &key) const -{ - return findKeyReference(ReferencedKey::keyReference(key)); -} - -ReferencedKey & -KeyPool::findKeyReference(ReferencedKey::KeyReference keyReference) const -{ - StLock _(mKeyMapLock); - KeyMap::const_iterator it = mKeyMap.find(keyReference); - if (it == mKeyMap.end()) - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE); - - return *it->second; -} - -void -KeyPool::erase(ReferencedKey &referencedKey) -{ - erase(referencedKey.keyReference()); -} - -ReferencedKey & -KeyPool::erase(ReferencedKey::KeyReference keyReference) -{ - StLock _(mKeyMapLock); - KeyMap::iterator it = mKeyMap.find(keyReference); - if (it == mKeyMap.end()) - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE); - - ReferencedKey &referencedKey = *it->second; - mKeyMap.erase(it); - return referencedKey; -} - -// Erase keyReference from mKeyMap, free the ioKey, and delete the ReferencedKey -void -KeyPool::freeKey(Allocator &allocator, CSSM_KEY &ioKey) -{ - delete &erase(ReferencedKey::freeReferenceKey(allocator, ioKey)); -} - -// -// ReferencedKey class -// -ReferencedKey::ReferencedKey(KeyPool &keyPool) : mKeyPool(&keyPool) -{ - mKeyPool->add(*this); -} - -ReferencedKey::~ReferencedKey() -{ - if (isActive()) - mKeyPool->erase(*this); -} - -ReferencedKey::KeyReference -ReferencedKey::keyReference() -{ - // @@@ Possibly check isActive() and return an invalid reference if it is not set. - return reinterpret_cast(this); -} - -// -// Making, retrieving and freeing Key references of CssmKeys -// -void -ReferencedKey::makeReferenceKey(Allocator &allocator, KeyReference keyReference, CSSM_KEY &key) -{ - key.KeyHeader.BlobType = CSSM_KEYBLOB_REFERENCE; - key.KeyHeader.Format = CSSM_KEYBLOB_REF_FORMAT_INTEGER; - key.KeyData.Length = sizeof(KeyReference); - key.KeyData.Data = allocator.alloc(sizeof(KeyReference)); - uint8 *cp = key.KeyData.Data; - for (int i = sizeof(KeyReference); --i >= 0;) - { - cp[i] = keyReference & 0xff; - keyReference = keyReference >> 8; - } -} - -ReferencedKey::KeyReference -ReferencedKey::keyReference(const CSSM_KEY &key) -{ - if (key.KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE - || key.KeyHeader.Format != CSSM_KEYBLOB_REF_FORMAT_INTEGER - || key.KeyData.Length != sizeof(KeyReference) - || key.KeyData.Data == NULL) - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE); - - const uint8 *cp = key.KeyData.Data; - KeyReference keyReference = 0; - for (uint32 i = 0; i < sizeof(KeyReference); ++i) - keyReference = (keyReference << 8) + cp[i]; - - return keyReference; -} - -ReferencedKey::KeyReference -ReferencedKey::freeReferenceKey(Allocator &allocator, CSSM_KEY &key) -{ - KeyReference aKeyReference = keyReference(key); - allocator.free(key.KeyData.Data); - key.KeyData.Data = NULL; - key.KeyData.Length = 0; - return aKeyReference; -} diff --git a/OSX/include/security_cdsa_plugin/CSPsession.h b/OSX/include/security_cdsa_plugin/CSPsession.h deleted file mode 100644 index b755bf77..00000000 --- a/OSX/include/security_cdsa_plugin/CSPsession.h +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// CSPsession.h - Framework for CSP plugin modules -// -#ifndef _H_CSPSESSION -#define _H_CSPSESSION - -#include -#include - - -namespace Security { - -// -// The CSPPluginSession provides a general bed for CSP plugin session objects. -// Derive from this if you want to write your CSP, effectively, from scratch. -// We still provide a framework for managing local cryptographic contexts and -// (module) logins. -// -class CSPPluginSession : public PluginSession, public CSPAbstractPluginSession { -public: - CSPPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls) - : PluginSession(theHandle, plug, version, subserviceId, subserviceType, attachFlags, upcalls) { } - - // methods implemented here that you should not override in a subclass - void EventNotify(CSSM_CONTEXT_EVENT e, - CSSM_CC_HANDLE ccHandle, const Context &context); - CSSM_MODULE_FUNCS_PTR construct(); - -public: - class PluginContext { - public: - virtual bool changed(const Context &context); - virtual ~PluginContext(); - }; - -public: - bool loggedIn() const { return mLoggedIn; } - bool loggedIn(bool li) { bool old = mLoggedIn; mLoggedIn = li; return old; } - - template Ctx *getContext(CSSM_CC_HANDLE handle) - { StLock _(contextMapLock); return safe_cast(contextMap[handle]); } - - void setContext(CSSM_CC_HANDLE handle, PluginContext *ctx) - { StLock _(contextMapLock); contextMap[handle] = ctx; } - -public: - // context management methods - override as needed - virtual PluginContext *contextCreate(CSSM_CC_HANDLE handle, const Context &context); - virtual void contextUpdate(CSSM_CC_HANDLE handle, - const Context &context, PluginContext * &ctx); - virtual void contextDelete(CSSM_CC_HANDLE handle, const Context &context, PluginContext *ctx); - -private: - bool mLoggedIn; - - map contextMap; - Mutex contextMapLock; -}; - - -// -// On the other hand, for most CSP modules, this subclass of CSPPluginSession provides -// much more convenient embedding facilities. The theory of operation is too complicated -// to explain here; refer to the accompanying documentation. -// -class CSPFullPluginSession : public CSPPluginSession { -public: - class CSPContext; - class AlgorithmFactory; - - CSPFullPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls) - : CSPPluginSession(theHandle, plug, version, - subserviceId, subserviceType, attachFlags, upcalls) { } - - // final context preparation (called by secondary transition layer) - CSPContext *init(CSSM_CC_HANDLE ccHandle, CSSM_CONTEXT_TYPE type, - const Context &context, bool encoding = true); - - // verify proper state on continuation (update/final) calls - CSPContext *getStagedContext(CSSM_CC_HANDLE ccHandle, - CSSM_CONTEXT_TYPE type, bool encoding = true); - - static const uint32 CSSM_ALGCLASS_CRYPT = 1001; // internally added to CONTEXT_TYPE - -protected: - // validate operation type against context class - void checkOperation(CSSM_CONTEXT_TYPE ctxType, CSSM_CONTEXT_TYPE opType); - -protected: - // - // The Writer class encapsulates staged-output destinations with optional overflow - // - class Writer { - public: - Writer(CssmData *v, uint32 n, CssmData *rem = NULL); - - // can this buffer be extended? - bool isExtensible() const - { return !*vec || (remData && !*remData); } - - // increase size if necessary (and possible) - void allocate(size_t needed, Allocator &alloc); - - // straight-forward buffer writing - void put(void *addr, size_t size); - - // locate-mode output (deliver buffer mode) - void nextBlock(void * &p, size_t &sz); - void use(size_t sz); - - // wrap up and return total number of bytes written - size_t close(); - - private: - CssmData *vec; // current buffer descriptor (the one in use) - CssmData *firstVec; // first buffer descriptor - CssmData *lastVec; // last buffer descriptor (NOT one past it) - CssmData *remData; // overflow buffer, if any - - void *currentBuffer; // next free byte in vec - size_t currentSize; // free bytes in vec - - size_t written; // bytes written - - void useData(CssmData *data) - { currentBuffer = data->data(); currentSize = data->length(); } - }; - -public: - // internal utilities (used by our own subclasses) - static CssmData makeBuffer(size_t size, Allocator &alloc); - static size_t totalBufferSize(const CssmData *data, uint32 count); - void setKey(CssmKey &key, - const Context &context, CSSM_KEYCLASS keyClass, - CSSM_KEYATTR_FLAGS attrs, CSSM_KEYUSE use); - -public: - // - // All contexts from CSPFullPluginSession's subclasses must derive from CSPContext. - // CSPFullPluginSession reformulates CSSM operations in terms of virtual methods of - // the context class. - // - class CSPContext : public PluginContext { - friend class CSPFullPluginSession; - public: - CSSM_CONTEXT_TYPE type() const { return mType; } - bool encoding() const { return mDirection; } - - // init() is called for all algorithms - virtual void init(const Context &context, bool encoding = true); - - // the following methods will be called for some but not all algorithms - virtual void update(const CssmData &data); // all block-input algorithms - virtual void update(void *inp, size_t &inSize, void *outp, size_t &outSize); // cryption algs - virtual void final(CssmData &out); // output-data producing algorithms - virtual void final(const CssmData &in); // verifying algorithms - virtual void generate(const Context &context, CssmKey &pubKey, CssmKey &privKey); - virtual void generate(const Context &context, uint32, - CssmData ¶ms, uint32 &attrCount, Context::Attr * &attrs); - virtual CSPContext *clone(Allocator &); // clone internal state - virtual void setDigestAlgorithm(CSSM_ALGORITHMS digestAlg); - - virtual size_t inputSize(size_t outSize); // input for given output size - virtual size_t outputSize(bool final = false, size_t inSize = 0); // output for given input size - virtual void minimumProgress(size_t &in, size_t &out); // minimum progress chunks - - protected: - // convenience forms of the above - void update(const CssmData *in, uint32 inCount, Writer &writer); - void final(CssmData &out, Allocator &alloc); - void final(Writer &writer, Allocator &alloc); - - void update(const CssmData *in, uint32 inCount) - { for (uint32 n = 0; n < inCount; n++) update(in[n]); } - - void checkOperation(CSSM_CONTEXT_TYPE type); - void checkOperation(CSSM_CONTEXT_TYPE type, bool encode); - - CSSM_CONTEXT_TYPE mType; // CSSM context type - bool mDirection; // operation direction (true if irrelevant) - }; - -protected: - virtual void setupContext(CSPContext * &ctx, const Context &context, bool encoding) = 0; - - virtual void getKeySize(const CssmKey &key, CSSM_KEY_SIZE &size); - -public: - // an algorithm factory. This is an optional feature - class AlgorithmFactory { - public: - virtual ~AlgorithmFactory(); - - // set ctx and return true if you can handle this - virtual bool setup(CSPContext * &ctx, const Context &context) = 0; - }; - -public: - void EncryptData(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData ClearBufs[], - uint32 ClearBufCount, - CssmData CipherBufs[], - uint32 CipherBufCount, - CSSM_SIZE &bytesEncrypted, - CssmData &RemData, - CSSM_PRIVILEGE Privilege); - void EncryptDataInit(CSSM_CC_HANDLE CCHandle, - const Context &Context, - CSSM_PRIVILEGE Privilege); - void EncryptDataUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData ClearBufs[], - uint32 ClearBufCount, - CssmData CipherBufs[], - uint32 CipherBufCount, - CSSM_SIZE &bytesEncrypted); - void EncryptDataFinal(CSSM_CC_HANDLE CCHandle, - CssmData &RemData); - - void DecryptData(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData CipherBufs[], - uint32 CipherBufCount, - CssmData ClearBufs[], - uint32 ClearBufCount, - CSSM_SIZE &bytesDecrypted, - CssmData &RemData, - CSSM_PRIVILEGE Privilege); - void DecryptDataInit(CSSM_CC_HANDLE CCHandle, - const Context &Context, - CSSM_PRIVILEGE Privilege); - void DecryptDataUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData CipherBufs[], - uint32 CipherBufCount, - CssmData ClearBufs[], - uint32 ClearBufCount, - CSSM_SIZE &bytesDecrypted); - void DecryptDataFinal(CSSM_CC_HANDLE CCHandle, - CssmData &RemData); - - void QuerySize(CSSM_CC_HANDLE CCHandle, - const Context &Context, - CSSM_BOOL Encrypt, - uint32 QuerySizeCount, - QuerySizeData *DataBlock); - - void WrapKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const AccessCredentials &AccessCred, - const CssmKey &Key, - const CssmData *DescriptiveData, - CssmKey &WrappedKey, - CSSM_PRIVILEGE Privilege); - void UnwrapKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmKey *PublicKey, - const CssmKey &WrappedKey, - uint32 KeyUsage, - uint32 KeyAttr, - const CssmData *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CssmKey &UnwrappedKey, - CssmData &DescriptiveData, - CSSM_PRIVILEGE Privilege); - void DeriveKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - CssmData &Param, - uint32 KeyUsage, - uint32 KeyAttr, - const CssmData *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CssmKey &DerivedKey); - - void GenerateMac(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData DataBufs[], - uint32 DataBufCount, - CssmData &Mac); - void GenerateMacInit(CSSM_CC_HANDLE CCHandle, - const Context &Context); - void GenerateMacUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData DataBufs[], - uint32 DataBufCount); - void GenerateMacFinal(CSSM_CC_HANDLE CCHandle, - CssmData &Mac); - - void VerifyMac(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData DataBufs[], - uint32 DataBufCount, - const CssmData &Mac); - virtual void VerifyMacInit(CSSM_CC_HANDLE CCHandle, - const Context &Context); - virtual void VerifyMacUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData DataBufs[], - uint32 DataBufCount); - virtual void VerifyMacFinal(CSSM_CC_HANDLE CCHandle, - const CssmData &Mac); - - void SignData(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData DataBufs[], - uint32 DataBufCount, - CSSM_ALGORITHMS DigestAlgorithm, - CssmData &Signature); - void SignDataInit(CSSM_CC_HANDLE CCHandle, - const Context &Context); - void SignDataUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData DataBufs[], - uint32 DataBufCount); - void SignDataFinal(CSSM_CC_HANDLE CCHandle, - CssmData &Signature); - - void VerifyData(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData DataBufs[], - uint32 DataBufCount, - CSSM_ALGORITHMS DigestAlgorithm, - const CssmData &Signature); - virtual void VerifyDataInit(CSSM_CC_HANDLE CCHandle, - const Context &Context); - virtual void VerifyDataUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData DataBufs[], - uint32 DataBufCount); - virtual void VerifyDataFinal(CSSM_CC_HANDLE CCHandle, - const CssmData &Signature); - - void DigestData(CSSM_CC_HANDLE CCHandle, - const Context &Context, - const CssmData DataBufs[], - uint32 DataBufCount, - CssmData &Digest); - void DigestDataInit(CSSM_CC_HANDLE CCHandle, - const Context &Context); - void DigestDataUpdate(CSSM_CC_HANDLE CCHandle, - const CssmData DataBufs[], - uint32 DataBufCount); - void DigestDataFinal(CSSM_CC_HANDLE CCHandle, - CssmData &Digest); - void DigestDataClone(CSSM_CC_HANDLE CCHandle, - CSSM_CC_HANDLE ClonedCCHandle); - - void GenerateKey(CSSM_CC_HANDLE CCHandle, - const Context &Context, - uint32 KeyUsage, - uint32 KeyAttr, - const CssmData *KeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CssmKey &Key, - CSSM_PRIVILEGE Privilege); - void GenerateKeyPair(CSSM_CC_HANDLE CCHandle, - const Context &Context, - uint32 PublicKeyUsage, - uint32 PublicKeyAttr, - const CssmData *PublicKeyLabel, - CssmKey &PublicKey, - uint32 PrivateKeyUsage, - uint32 PrivateKeyAttr, - const CssmData *PrivateKeyLabel, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - CssmKey &PrivateKey, - CSSM_PRIVILEGE Privilege); - - void ObtainPrivateKeyFromPublicKey(const CssmKey &PublicKey, - CssmKey &PrivateKey); - void QueryKeySizeInBits(CSSM_CC_HANDLE CCHandle, - const Context *Context, - const CssmKey *Key, - CSSM_KEY_SIZE &KeySize); - - void FreeKey(const AccessCredentials *AccessCred, - CssmKey &KeyPtr, - CSSM_BOOL Delete); - - void GenerateRandom(CSSM_CC_HANDLE CCHandle, - const Context &Context, - CssmData &RandomNumber); - void GenerateAlgorithmParams(CSSM_CC_HANDLE CCHandle, - const Context &Context, - uint32 ParamBits, - CssmData &Param, - uint32 &NumberOfUpdatedAttibutes, - CSSM_CONTEXT_ATTRIBUTE_PTR &UpdatedAttributes); - - void Login(const AccessCredentials &AccessCred, - const CssmData *LoginName, - const void *Reserved); - void Logout(); - void VerifyDevice(const CssmData &DeviceCert); - void GetOperationalStatistics(CSPOperationalStatistics &Statistics); - - void RetrieveCounter(CssmData &Counter); - void RetrieveUniqueId(CssmData &UniqueID); - void GetTimeValue(CSSM_ALGORITHMS TimeAlgorithm, CssmData &TimeData); - - void GetKeyOwner(const CssmKey &Key, - CSSM_ACL_OWNER_PROTOTYPE &Owner); - void ChangeKeyOwner(const AccessCredentials &AccessCred, - const CssmKey &Key, - const CSSM_ACL_OWNER_PROTOTYPE &NewOwner); - void GetKeyAcl(const CssmKey &Key, - const CSSM_STRING *SelectionTag, - uint32 &NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &AclInfos); - void ChangeKeyAcl(const AccessCredentials &AccessCred, - const CSSM_ACL_EDIT &AclEdit, - const CssmKey &Key); - - void GetLoginOwner(CSSM_ACL_OWNER_PROTOTYPE &Owner); - void ChangeLoginOwner(const AccessCredentials &AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &NewOwner); - void GetLoginAcl(const CSSM_STRING *SelectionTag, - uint32 &NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &AclInfos); - void ChangeLoginAcl(const AccessCredentials &AccessCred, - const CSSM_ACL_EDIT &AclEdit); - - void PassThrough(CSSM_CC_HANDLE CCHandle, - const Context &Context, - uint32 PassThroughId, - const void *InData, - void **OutData); -}; - - -// -// Classes for dealing with reference keys. -// - -// Forward declaration. -class KeyPool; - -// -// A ReferencedKey -- The private (to the CSP) part of a Reference Key. -// -class ReferencedKey -{ - friend class KeyPool; // So it can call deactivate() -public: - // What we use to reference a ReferencedKey. - typedef CSSM_INTPTR KeyReference; - ReferencedKey(KeyPool &session); // Calls KeyPool::add() - virtual ~ReferencedKey(); // Calls KeyPool::erase() - - KeyReference keyReference(); - bool isActive() { return mKeyPool != NULL; } - - template - SubPool &keyPool() { assert(mKeyPool); return safer_cast(*mKeyPool); } -public: - // Making, retrieving and freeing CSSM_KEYBLOB_REF_FORMAT_INTEGER CSSM_KEY type reference keys - // NOTE: that none of these functions affect mKeyMap. - static void makeReferenceKey(Allocator &allocator, KeyReference keyReference, CSSM_KEY &ioKey); - static KeyReference keyReference(const CSSM_KEY &key); - static KeyReference freeReferenceKey(Allocator &allocator, CSSM_KEY &ioKey); - -private: - void deactivate() { mKeyPool = NULL; } - - // Will be NULL iff this key is not active - KeyPool *mKeyPool; -}; - - -// -// KeyPool -- a mixin class to manage a pool of ReferencedKeys -// -class KeyPool -{ -public: - friend class ReferencedKey; // So it can call add() and erase() -public: - KeyPool(); - virtual ~KeyPool(); - - // Type safe ReferencedKey subclass lookup - template - Subclass &find(const CSSM_KEY &key) const; - - // Free the ioKey, erase keyReference from mKeyMap, and delete the ReferencedKey - void freeKey(Allocator &allocator, CSSM_KEY &key); - -protected: - // Called by the constructor of ReferencedKey -- add referencedKey to mKeyMap - void add(ReferencedKey &referencedKey); - - ReferencedKey &findKey(const CSSM_KEY &key) const; - ReferencedKey &findKeyReference(ReferencedKey::KeyReference keyReference) const; - - // Called by the destructor of ReferencedKey -- erase keyReference from mKeyMap - void erase(ReferencedKey &referencedKey); - - // Erase keyReference from mKeyMap, and return it (for deletion) - ReferencedKey &erase(ReferencedKey::KeyReference keyReference); - -protected: - typedef map KeyMap; - KeyMap mKeyMap; - mutable Mutex mKeyMapLock; -}; - -// Implementation of type safe ReferencedKey subclass lookup. -template -Subclass & -KeyPool::find(const CSSM_KEY &key) const -{ - Subclass *sub; - if (!(sub = dynamic_cast(&findKey(key)))) - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE); - return *sub; -} - -} // end namespace Security - -#endif //_H_CSPSESSION diff --git a/OSX/include/security_cdsa_plugin/DLsession.cpp b/OSX/include/security_cdsa_plugin/DLsession.cpp deleted file mode 100644 index 89a88690..00000000 --- a/OSX/include/security_cdsa_plugin/DLsession.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DLsession - Plugin framework for CSP plugin modules -// -#ifdef __MWERKS__ -#define _CPP_DLSESSION -#endif - -#include -#include - - -// -// Construct a DLPluginSession -// -DLPluginSession::DLPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls, - DatabaseManager &databaseManager) - : PluginSession(theHandle, plug, version, subserviceId, subserviceType, attachFlags, upcalls), - DatabaseSession (databaseManager) -{ -} - - -// -// Implement Allocator methods from the PluginSession side -// -void *DLPluginSession::malloc(size_t size) throw(std::bad_alloc) -{ return PluginSession::malloc(size); } - -void DLPluginSession::free(void *addr) throw() -{ return PluginSession::free(addr); } - -void *DLPluginSession::realloc(void *addr, size_t size) throw(std::bad_alloc) -{ return PluginSession::realloc(addr, size); } diff --git a/OSX/include/security_cdsa_plugin/DLsession.h b/OSX/include/security_cdsa_plugin/DLsession.h deleted file mode 100644 index 67c35ecb..00000000 --- a/OSX/include/security_cdsa_plugin/DLsession.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DLsession.h - Framework for DL plugin modules -// -#ifndef _H_DLSESSION -#define _H_DLSESSION - -#include -#include - -namespace Security { - -// -// The abstract DLPluginSession class is the common ancestor of your implementation -// object for an DL type plugin attachment session. Inherit from this and implement -// the abstract methods to define a plugin session. -// -class DLPluginSession : public PluginSession, public DatabaseSession { - NOCOPY(DLPluginSession) -public: - DLPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls, - DatabaseManager &databaseManager); - - void *malloc(size_t size) throw(std::bad_alloc); - void free(void *addr) throw(); - void *realloc(void *addr, size_t size) throw(std::bad_alloc); - -protected: - CSSM_MODULE_FUNCS_PTR construct(); -}; - -} // end namespace Security - -#endif //_H_DLSESSION diff --git a/OSX/include/security_cdsa_plugin/Database.cpp b/OSX/include/security_cdsa_plugin/Database.cpp deleted file mode 100644 index ef7da434..00000000 --- a/OSX/include/security_cdsa_plugin/Database.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#ifdef __MWERKS__ -#define _CPP_DATABASE -#endif -#include -#include -#include -#include - -DatabaseManager::DatabaseManager () -{ -} - -DatabaseManager::~DatabaseManager () -{ -} - -Database * -DatabaseManager::get (const DbName &inDbName) -{ - StLock _(mDatabaseMapLock); - DatabaseMap::iterator anIterator = mDatabaseMap.find (inDbName); - if (anIterator == mDatabaseMap.end()) - { - auto_ptr aDatabase(make(inDbName)); - mDatabaseMap.insert(DatabaseMap::value_type(aDatabase->mDbName, aDatabase.get())); - return aDatabase.release(); - } - - return anIterator->second; -} - -void -DatabaseManager::removeIfUnused(Database &inDatabase) -{ - StLock _(mDatabaseMapLock); - if (!inDatabase.hasDbContexts()) { - mDatabaseMap.erase(inDatabase.mDbName); - delete &inDatabase; - } -} - -DbContext & -DatabaseManager::dbOpen(DatabaseSession &inDatabaseSession, - const DbName &inDbName, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters) -{ - Database &aDatabase = *get(inDbName); - try - { - return aDatabase._dbOpen(inDatabaseSession, inAccessRequest, inAccessCred, inOpenParameters); - } - catch (...) - { - removeIfUnused(aDatabase); - throw; - } -} - -DbContext & -DatabaseManager::dbCreate(DatabaseSession &inDatabaseSession, - const DbName &inDbName, - const CSSM_DBINFO &inDBInfo, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *inCredAndAclEntry, - const void *inOpenParameters) -{ - Database &aDatabase = *get(inDbName); - try - { - return aDatabase._dbCreate(inDatabaseSession, inDBInfo, inAccessRequest, - inCredAndAclEntry, inOpenParameters); - } - catch (...) - { - removeIfUnused(aDatabase); - throw; - } -} - -// Delete a DbContext instance created by calling dbOpen or dbCreate. -void -DatabaseManager::dbClose(DbContext &inDbContext) -{ - Database &aDatabase = inDbContext.mDatabase; - aDatabase._dbClose(inDbContext); - removeIfUnused(aDatabase); -} - -// Delete a database. -void -DatabaseManager::dbDelete(DatabaseSession &inDatabaseSession, - const DbName &inDbName, - const AccessCredentials *inAccessCred) -{ - Database &aDatabase = *get(inDbName); - try - { - aDatabase.dbDelete(inDatabaseSession, inAccessCred); - } - catch (...) - { - removeIfUnused(aDatabase); - throw; - } - - removeIfUnused(aDatabase); -} - -// List all available databases. -CSSM_NAME_LIST_PTR -DatabaseManager::getDbNames(DatabaseSession &inDatabaseSession) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -void -DatabaseManager::freeNameList(DatabaseSession &inDatabaseSession, - CSSM_NAME_LIST &inNameList) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -// Start of Database implementation. - -Database::Database (const DbName &inDbName) -: mDbName(inDbName) -{ -} - -Database::~Database () -{ -} - -bool -Database::hasDbContexts() -{ - StLock _(mDbContextSetLock); - return !mDbContextSet.empty(); -} - -DbContext & -Database::_dbOpen(DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters) -{ - auto_ptraDbContext(makeDbContext(inDatabaseSession, - inAccessRequest, - inAccessCred, - inOpenParameters)); - { - StLock _(mDbContextSetLock); - mDbContextSet.insert(aDbContext.get()); - // Release the mDbContextSetLock - } - - try - { - dbOpen(*aDbContext); - } - catch (...) - { - StLock _(mDbContextSetLock); - mDbContextSet.erase(aDbContext.get()); - throw; - } - - return *aDbContext.release(); -} - -DbContext & -Database::_dbCreate(DatabaseSession &inDatabaseSession, - const CSSM_DBINFO &inDBInfo, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *inCredAndAclEntry, - const void *inOpenParameters) -{ - auto_ptraDbContext(makeDbContext(inDatabaseSession, - inAccessRequest, - (inCredAndAclEntry - ? AccessCredentials::optional(inCredAndAclEntry->AccessCred) - : NULL), - inOpenParameters)); - { - StLock _(mDbContextSetLock); - mDbContextSet.insert(aDbContext.get()); - // Release the mDbContextSetLock - } - - try - { - dbCreate(*aDbContext, inDBInfo, - inCredAndAclEntry ? &inCredAndAclEntry->InitialAclEntry : NULL); - } - catch (...) - { - StLock _(mDbContextSetLock); - mDbContextSet.erase(aDbContext.get()); - throw; - } - - return *aDbContext.release(); -} - -void -Database::_dbClose(DbContext &dbContext) -{ - StLock _(mDbContextSetLock); - mDbContextSet.erase(&dbContext); - if (mDbContextSet.empty()) - dbClose(); -} diff --git a/OSX/include/security_cdsa_plugin/Database.h b/OSX/include/security_cdsa_plugin/Database.h deleted file mode 100644 index a674243d..00000000 --- a/OSX/include/security_cdsa_plugin/Database.h +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#ifndef _DATABASE_H_ -#define _DATABASE_H_ 1 - -#include -#include -#include -#include -#include -#include - - -// @@@ Should not use using in headers. -using namespace std; - -namespace Security -{ - -class Database; -class DatabaseFactory; -class DatabaseSession; -class DbContext; - -/* DatabaseManager class. */ -class DatabaseManager -{ - NOCOPY(DatabaseManager) -public: - DatabaseManager (); - virtual ~DatabaseManager (); - - // Create and return a new DbContext instance which is owned by us and must be discared by calling dbClose. - virtual DbContext &dbOpen(DatabaseSession &inDatabaseSession, - const DbName &inDbName, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters); - virtual DbContext &dbCreate(DatabaseSession &inDatabaseSession, - const DbName &inDbName, - const CSSM_DBINFO &inDBInfo, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *inCredAndAclEntry, - const void *inOpenParameters); - - // Delete a DbContext instance created by calling dbOpen or dbCreate. - virtual void dbClose(DbContext &inDbContext); - - // Delete a database. - virtual void dbDelete(DatabaseSession &inDatabaseSession, - const DbName &inDbName, - const AccessCredentials *inAccessCred); - - // List all available databases. - virtual CSSM_NAME_LIST_PTR getDbNames(DatabaseSession &inDatabaseSession); - virtual void freeNameList(DatabaseSession &inDatabaseSession, - CSSM_NAME_LIST &inNameList); -protected: - virtual void removeIfUnused(Database &inDatabase); - virtual Database *get (const DbName &inDbName); // Get existing instance or make a new one. - virtual Database *make (const DbName &inDbName) = 0; // Create a new database instance subclass must implement. -private: - typedef map DatabaseMap; - DatabaseMap mDatabaseMap; - Mutex mDatabaseMapLock; -}; - - -/* Database is an abstract class. Each Database subclass should implement all the - pure virtual methods listed below. The constructor for a particular Database - subclass should create the Database object. A subsequent call to dBOpen or - dBCreate should be is made. This returns a DbContext. All other methods take - a DbContext as an argument. - */ -class Database -{ -public: - virtual void - dbCreate (DbContext &inDbContext, const CSSM_DBINFO &inDBInfo, - const CSSM_ACL_ENTRY_INPUT *inInitialAclEntry) = 0; - - // Don't override this method in subclasses. - virtual DbContext & - _dbCreate(DatabaseSession &inDatabaseSession, - const CSSM_DBINFO &inDBInfo, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *inCredAndAclEntry, - const void *inOpenParameters); - - virtual void - dbOpen (DbContext &inDbContext) = 0; - - // Don't override this method in subclasses. - virtual DbContext & - _dbOpen (DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters); - - virtual void - dbClose () = 0; - - // Don't override this method in subclasses. - virtual void - _dbClose (DbContext &dbContext); - - virtual void - dbDelete(DatabaseSession &inDatabaseSession, - const AccessCredentials *inAccessCred) = 0; - - virtual void - createRelation (DbContext &dbContext, - CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO &inIndexInfo) = 0; - - virtual void - destroyRelation (DbContext &dbContext, - CSSM_DB_RECORDTYPE inRelationID) = 0; - - virtual void - authenticate(DbContext &dbContext, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials &inAccessCred) = 0; - - virtual void - getDbAcl(DbContext &dbContext, - const CSSM_STRING *inSelectionTag, - uint32 &outNumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &outAclInfos) = 0; - - virtual void - changeDbAcl(DbContext &dbContext, - const AccessCredentials &inAccessCred, - const CSSM_ACL_EDIT &inAclEdit) = 0; - - virtual void - getDbOwner(DbContext &dbContext, CSSM_ACL_OWNER_PROTOTYPE &outOwner) = 0; - - virtual void - changeDbOwner(DbContext &dbContext, - const AccessCredentials &inAccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &inNewOwner) = 0; - - virtual char * - getDbNameFromHandle (const DbContext &dbContext) const = 0; - - virtual CSSM_DB_UNIQUE_RECORD_PTR - dataInsert (DbContext &dbContext, - CSSM_DB_RECORDTYPE RecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData) = 0; - - virtual void - dataDelete (DbContext &dbContext, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecordIdentifier) = 0; - - virtual void - dataModify (DbContext &dbContext, - CSSM_DB_RECORDTYPE RecordType, - CSSM_DB_UNIQUE_RECORD &inoutUniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributesToBeModified, - const CssmData *inDataToBeModified, - CSSM_DB_MODIFY_MODE ModifyMode) = 0; - - virtual CSSM_HANDLE - dataGetFirst (DbContext &dbContext, - const CssmQuery *inQuery, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord) = 0; - - virtual bool - dataGetNext (DbContext &dbContext, - CSSM_HANDLE inResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord) = 0; - - virtual void - dataAbortQuery (DbContext &dbContext, - CSSM_HANDLE inResultsHandle) = 0; - - virtual void - dataGetFromUniqueRecordId (DbContext &dbContext, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData) = 0; - - virtual void - freeUniqueRecord (DbContext &dbContext, - CSSM_DB_UNIQUE_RECORD &inUniqueRecord) = 0; - - virtual void - passThrough(DbContext &dbContext, - uint32 passThroughId, - const void *inputParams, - void **outputParams) = 0; - - Database (const DbName &inDbName); - virtual ~Database (); - - virtual bool hasDbContexts(); - - // XXX @@@ Think about consequences of race conditions between DbOpen/DbCreate/DbDelete/DbClose - // on databases with the same name at the same time. - //virtual DbContext &insertDbContext(); - //virtual void removeDbContext(DbContext &inDbContext); - - const DbName mDbName; -protected: - // Subclasses must implement this method. - virtual DbContext *makeDbContext(DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters) = 0; -private: - typedef set DbContextSet; - DbContextSet mDbContextSet; - Mutex mDbContextSetLock; -}; - -} // end namespace Security - -#ifdef _CPP_DATABASE -# pragma export off -#endif - -#endif //_DATABASE_H_ diff --git a/OSX/include/security_cdsa_plugin/DatabaseSession.cpp b/OSX/include/security_cdsa_plugin/DatabaseSession.cpp deleted file mode 100644 index 637806ba..00000000 --- a/OSX/include/security_cdsa_plugin/DatabaseSession.cpp +++ /dev/null @@ -1,692 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DatabaseSession.cpp - DL Session. -// -#include - -#include -#include -#include -#include -#include - -/* log open/close events */ -#define DOCDebug(args...) secdebug("DBOpen", ## args) - - -using namespace std; - -extern "C" char* cssmErrorString(CSSM_RETURN errCode); - -// -// Session constructor -// -DatabaseSession::DatabaseSession(DatabaseManager &inDatabaseManager) -: mDatabaseManager(inDatabaseManager) -{ -} - -DatabaseSession::~DatabaseSession() -{ -} - - -// Utility functions -void -DatabaseSession::GetDbNames(CSSM_NAME_LIST_PTR &outNameList) -{ - secdebug("dbsession", "GetDbNames"); - outNameList = mDatabaseManager.getDbNames (*this); - -#ifndef NDEBUG - // dump the returned names - uint32 n; - secdebug("dbsession", "GetDbNames returned %d names", outNameList->NumStrings); - for (n = 0; n < outNameList->NumStrings; ++n) - { - secdebug("dbsession", "%d: %s", n, outNameList->String[n]); - } -#endif - - secdebug("dbsession", "********************"); -} - - -void -DatabaseSession::FreeNameList(CSSM_NAME_LIST &inNameList) -{ - secdebug("dbsession", "FreeNameList"); - mDatabaseManager.freeNameList (*this, inNameList); - secdebug("dbsession", "********************"); -} - - -void -DatabaseSession::DbDelete(const char *inDbName, - const CSSM_NET_ADDRESS *inDbLocation, - const AccessCredentials *inAccessCred) -{ - // The databaseManager will notify all its DbContext instances - // that the database is question is being deleted. - secdebug("dbsession", "DbDelete of %s", inDbName); - mDatabaseManager.dbDelete(*this, DbName(inDbName, CssmNetAddress::optional(inDbLocation)), inAccessCred); - secdebug("dbsession", "********************"); -} - -// DbContext creation and destruction. -void -DatabaseSession::DbCreate(const char *inDbName, - const CSSM_NET_ADDRESS *inDbLocation, - const CSSM_DBINFO &inDBInfo, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *inCredAndAclEntry, - const void *inOpenParameters, - CSSM_DB_HANDLE &outDbHandle) -{ - outDbHandle = CSSM_INVALID_HANDLE; // CDSA 2.0 says to set this if we fail - secdebug("dbsession", "DbCreate of %s", inDbName); - - outDbHandle = insertDbContext(mDatabaseManager.dbCreate(*this, - DbName(inDbName, CssmNetAddress::optional(inDbLocation)), - inDBInfo, - inAccessRequest, - inCredAndAclEntry, - inOpenParameters)); - secdebug("dbsession", "DbCreate returned handle %#lx", outDbHandle); - - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::DbOpen(const char *inDbName, - const CSSM_NET_ADDRESS *inDbLocation, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters, - CSSM_DB_HANDLE &outDbHandle) -{ - DOCDebug("DatabaseSession::DbOpen: dbName %s", inDbName); - secdebug("dbsession", "DbOpen of %s", inDbName); - outDbHandle = CSSM_INVALID_HANDLE; // CDSA 2.0 says to set this if we fail - outDbHandle = insertDbContext(mDatabaseManager.dbOpen(*this, - DbName(inDbName, CssmNetAddress::optional(inDbLocation)), - inAccessRequest, - inAccessCred, - inOpenParameters)); - secdebug("dbsession", "DbOpen returned handle %#lx", outDbHandle); - secdebug("dbsession", "********************"); -} - -CSSM_DB_HANDLE -DatabaseSession::insertDbContext(DbContext &inDbContext) -{ - CSSM_DB_HANDLE aDbHandle; - try - { - aDbHandle = inDbContext.handle (); - StLock _(mDbContextMapLock); - mDbContextMap.insert(DbContextMap::value_type(aDbHandle, &inDbContext)); - } - catch (...) - { - // Close the context - mDatabaseManager.dbClose(inDbContext); - throw; - } - - return aDbHandle; -} - -DbContext & -DatabaseSession::findDbContext(CSSM_DB_HANDLE inDbHandle) -{ - StLock _(mDbContextMapLock); - DbContextMap::iterator it = mDbContextMap.find(inDbHandle); - if (it == mDbContextMap.end()) - CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE); - return *it->second; -} - -void -DatabaseSession::closeAll() -{ - StLock _(mDbContextMapLock); - for (DbContextMap::iterator it = mDbContextMap.begin(); - it != mDbContextMap.end(); - it++) - { - DbContext *aDbContext = it->second; - try - { - mDatabaseManager.dbClose(*aDbContext); - // This is done by the database itself which owns the context. - //delete aDbContext; - } - catch (...) - { - // Ignore exceptions since we want to close as many DBs as possible. - // XXX @@@ log an error or something. - } - } - - mDbContextMap.clear(); - secdebug("dbsession", "********************"); -} - -// Operations using DbContext instances. -void -DatabaseSession::DbClose(CSSM_DB_HANDLE inDbHandle) -{ - StLock _(mDbContextMapLock); - DOCDebug("DatabaseSession::Close"); - secdebug("dbsession", "DbClose of handle %ld", inDbHandle); - DbContextMap::iterator it = mDbContextMap.find(inDbHandle); - if (it == mDbContextMap.end()) - CssmError::throwMe(CSSM_ERRCODE_INVALID_DB_HANDLE); - auto_ptr aDbContext(it->second); - mDbContextMap.erase(it); - mDatabaseManager.dbClose(*aDbContext); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::CreateRelation(CSSM_DB_HANDLE inDbHandle, - CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO &inIndexInfo) -{ - secdebug("dbsession", "CreateRelation from handle %ld of record type %X with relation name %s", inDbHandle, inRelationID, inRelationName); - secdebug("dbsession", "number of attributes = %d", inNumberOfAttributes); -#ifndef NDEBUG - unsigned n; - for (n = 0; n < inNumberOfAttributes; ++n) - { - secdebug("dbsession", "%d: id %d name %s, data type %d", n, inAttributeInfo[n].AttributeId, - inAttributeInfo[n].AttributeName, - inAttributeInfo[n].DataType); - } -#endif - - secdebug("dbsession", "number of indexes: %d", inNumberOfIndexes); -#ifndef NDEBUG - for (n = 0; n < inNumberOfIndexes; ++n) - { - secdebug("dbsession", "%d: id %d indexid %d indextype %d location %d", n, inIndexInfo.AttributeId, - inIndexInfo.IndexedDataLocation, - inIndexInfo.IndexId, - inIndexInfo.IndexType); - } -#endif - - DbContext &aDbContext = findDbContext(inDbHandle); - return aDbContext.mDatabase.createRelation(aDbContext, inRelationID, inRelationName, - inNumberOfAttributes, inAttributeInfo, - inNumberOfIndexes, inIndexInfo); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::DestroyRelation(CSSM_DB_HANDLE inDbHandle, - CSSM_DB_RECORDTYPE inRelationID) -{ - secdebug("dbsession", "DestroyRelation (handle %ld) %d", inDbHandle, inRelationID); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.destroyRelation(aDbContext, inRelationID); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::Authenticate(CSSM_DB_HANDLE inDbHandle, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials &inAccessCred) -{ - secdebug("dbsession", "Authenticate (handle %ld) inAccessRequest %d", inDbHandle, inAccessRequest); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.authenticate(aDbContext, inAccessRequest, inAccessCred); - secdebug("dbsession", "********************"); -} - - -void -DatabaseSession::GetDbAcl(CSSM_DB_HANDLE inDbHandle, - const CSSM_STRING *inSelectionTag, - uint32 &outNumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &outAclInfos) -{ - secdebug("dbsession", "GetDbAcl (handle %ld)", inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.getDbAcl(aDbContext, inSelectionTag, outNumberOfAclInfos, outAclInfos); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::ChangeDbAcl(CSSM_DB_HANDLE inDbHandle, - const AccessCredentials &inAccessCred, - const CSSM_ACL_EDIT &inAclEdit) -{ - secdebug("dbsession", "ChangeDbAcl (handle %ld)", inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.changeDbAcl(aDbContext, inAccessCred, inAclEdit); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::GetDbOwner(CSSM_DB_HANDLE inDbHandle, - CSSM_ACL_OWNER_PROTOTYPE &outOwner) -{ - secdebug("dbsession", "GetDbOwner (handle %ld)", inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.getDbOwner(aDbContext, outOwner); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::ChangeDbOwner(CSSM_DB_HANDLE inDbHandle, - const AccessCredentials &inAccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &inNewOwner) -{ - secdebug("dbsession", "ChangeDbOwner (handle %ld)", inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.changeDbOwner(aDbContext, inAccessCred, inNewOwner); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::GetDbNameFromHandle(CSSM_DB_HANDLE inDbHandle, - char **outDbName) -{ - secdebug("dbsession", "GetDbNameFromHandle (handle %ld)", inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - Required(outDbName) = aDbContext.mDatabase.getDbNameFromHandle(aDbContext); - secdebug("dbsession", "name: %s", *outDbName); - secdebug("dbsession", "********************"); -} - - -#ifndef NDEBUG - -#if 0 /* unusued functions */ - -static -void DumpAttributeInfo(const CSSM_DB_ATTRIBUTE_INFO &info) -{ - const char* attrNameType; - switch (info.AttributeFormat) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - attrNameType = "CSSM_DB_ATTRIBUTE_NAME_AS_STRING"; - break; - - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - attrNameType = "CSSM_DB_ATTRIBUTE_NAME_AS_OID"; - break; - - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - attrNameType = "CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER"; - break; - } - - secdebug("dbsession", " Attribute name type: %s", attrNameType); - switch (info.AttributeFormat) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - secdebug("dbsession", " name: %s", info.Label.AttributeName); - break; - - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - secdebug("dbsession", " name: %d", info.Label.AttributeID); - break; - - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - secdebug("dbsession", " name is oid"); - break; - } - - const char* s; - switch (info.AttributeFormat) - { - case CSSM_DB_ATTRIBUTE_FORMAT_STRING: - s = "CSSM_DB_ATTRIBUTE_FORMAT_STRING"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_SINT32: - s = "CSSM_DB_ATTRIBUTE_FORMAT_SINT32"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_UINT32: - s = "CSSM_DB_ATTRIBUTE_FORMAT_UINT32"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM: - s = "CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_REAL: - s = "CSSM_DB_ATTRIBUTE_FORMAT_REAL"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE: - s = "CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_BLOB: - s = "CSSM_DB_ATTRIBUTE_FORMAT_BLOB"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32: - s = "CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32"; - break; - case CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX: - s = "CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX"; - break; - } - - secdebug("dbsession", " attribute format: %s", s); -} - - -static -void DumpAttributes(const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes) -{ - if (!inAttributes) - { - secdebug("dbsession", "No attributes defined."); - return; - } - - secdebug("dbsession", "insert into %d", inAttributes->DataRecordType); - secdebug("dbsession", "Semantic information %d", inAttributes->SemanticInformation); - secdebug("dbsession", "Number of attributes: %d", inAttributes->NumberOfAttributes); - - unsigned n; - for (n = 0; n < inAttributes->NumberOfAttributes; ++n) - { - DumpAttributeInfo(inAttributes->AttributeData[n].Info); - secdebug("dbsession", "Attribute %d\n", n); - secdebug("dbsession", " number of values: %d", inAttributes->AttributeData[n].NumberOfValues); - unsigned i; - for (i = 0; i < inAttributes->AttributeData[n].NumberOfValues; ++i) - { - switch (inAttributes->AttributeData[n].Info.AttributeFormat) - { - case CSSM_DB_ATTRIBUTE_FORMAT_STRING: - { - std::string ss((char*) inAttributes->AttributeData[n].Value[i].Data, inAttributes->AttributeData[n].Value[i].Length); - secdebug("dbsession", " Value %d: %s", i, ss.c_str()); - break; - } - case CSSM_DB_ATTRIBUTE_FORMAT_SINT32: - secdebug("dbsession", " Value %d: %d", i, *(sint32*)inAttributes->AttributeData[n].Value[i].Data); - break; - case CSSM_DB_ATTRIBUTE_FORMAT_UINT32: - secdebug("dbsession", " Value %d: %u", i, *(uint32*)inAttributes->AttributeData[n].Value[i].Data); - break; - case CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM: - secdebug("dbsession", " Value %d: (bignum)", i); - break; - case CSSM_DB_ATTRIBUTE_FORMAT_REAL: - secdebug("dbsession", " Value %d: %f", i, *(double*)inAttributes->AttributeData[n].Value[i].Data); - break; - case CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE: - secdebug("dbsession", " Value %d: %s", i, (char*)inAttributes->AttributeData[n].Value[i].Data); - break; - case CSSM_DB_ATTRIBUTE_FORMAT_BLOB: - secdebug("dbsession", " Value %d: (blob)", i); - break; - case CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32: - { - unsigned long j; - unsigned long numInts = inAttributes->AttributeData[n].Value[i].Length / sizeof(UInt32); - for (j = 0; j < numInts; ++j) - { - uint32* nums = (uint32*) inAttributes->AttributeData[n].Value[i].Data; - secdebug("dbsession", " %d", nums[j]); - } - - break; - } - - case CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX: - secdebug("dbsession", " Value %d: (complex)", i); - break; - } - } - } -} -#endif - - -static void -DumpUniqueRecord(const CSSM_DB_UNIQUE_RECORD &record) -{ -/* - const char* s; - - switch (record.RecordLocator.IndexType) - { - case CSSM_DB_INDEX_UNIQUE: - { - s = "CSSM_DB_INDEX_UNIQUE"; - break; - } - - case CSSM_DB_INDEX_NONUNIQUE: - { - s = "CSSM_DB_INDEX_NONUNIQUE"; - break; - } - } - - secdebug("dbsession", "RecordLocator.IndexType: %s", s); - - switch (record.RecordLocator.IndexedDataLocation) - { - case CSSM_DB_INDEX_ON_UNKNOWN: - { - s = "CSSM_DB_INDEX_ON_UNKNOWN"; - break; - } - - case CSSM_DB_INDEX_ON_ATTRIBUTE: - { - s = "CSSM_DB_INDEX_ON_ATTRIBUTE"; - break; - } - - case CSSM_DB_INDEX_ON_RECORD: - { - s = "CSSM_DB_INDEX_ON_RECORD"; - break; - } - } - - secdebug("dbsession", "RecordLocator.IndexedDataLocation: %s", s); - - secdebug("dbsession", "Attribute info:"); - - DumpAttributeInfo(record.RecordLocator.Info); -*/ - - // put the record ID into hex - std::string output; - char hexBuffer[4]; - unsigned i; - for (i = 0; i < record.RecordIdentifier.Length; ++i) - { - sprintf(hexBuffer, "%02X", record.RecordIdentifier.Data[i]); - output += hexBuffer; - } - - secdebug("dbsession", " RecordIdentifier.Data: %s", output.c_str()); -} -#endif /* NDEBUG */ - -void -DatabaseSession::DataInsert(CSSM_DB_HANDLE inDbHandle, - CSSM_DB_RECORDTYPE inRecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueId) -{ - secdebug("dbsession", "%p DataInsert(%lx,%x)", this, inDbHandle, inRecordType); - DbContext &aDbContext = findDbContext(inDbHandle); - outUniqueId = aDbContext.mDatabase.dataInsert(aDbContext, inRecordType, inAttributes, inData); - -#ifndef NDEBUG - secdebug("dbsession", "Returned unique id:"); - DumpUniqueRecord(*outUniqueId); -#endif - - secdebug("dbsession", "********************"); -} - - -void -DatabaseSession::DataDelete(CSSM_DB_HANDLE inDbHandle, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecordIdentifier) -{ - secdebug("dbsession", "%p DataDelete(%lx)", this, inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.dataDelete(aDbContext, inUniqueRecordIdentifier); - -#ifndef NDEBUG - secdebug("dbsession", "Record identifier:"); - DumpUniqueRecord(inUniqueRecordIdentifier); -#endif - secdebug("dbsession", "********************"); -} - - -void -DatabaseSession::DataModify(CSSM_DB_HANDLE inDbHandle, - CSSM_DB_RECORDTYPE inRecordType, - CSSM_DB_UNIQUE_RECORD &inoutUniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributesToBeModified, - const CssmData *inDataToBeModified, - CSSM_DB_MODIFY_MODE inModifyMode) -{ - secdebug("dbsession", "%p DataModify(%lx,%x)", this, inDbHandle, inRecordType); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.dataModify(aDbContext, inRecordType, inoutUniqueRecordIdentifier, - inAttributesToBeModified, inDataToBeModified, inModifyMode); -#ifndef NDEBUG - secdebug("dbsession", "Out record identifier:"); - DumpUniqueRecord(inoutUniqueRecordIdentifier); -#endif - secdebug("dbsession", "********************"); -} - -CSSM_HANDLE -DatabaseSession::DataGetFirst(CSSM_DB_HANDLE inDbHandle, - const CssmQuery *inQuery, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueId) -{ - secdebug("dbsession", "%p DataGetFirst(%lx)", this, inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - - CSSM_HANDLE result = aDbContext.mDatabase.dataGetFirst(aDbContext, inQuery, - inoutAttributes, inoutData, outUniqueId); -#ifndef NDEBUG - secdebug("dbsession", "result handle: %lx", result); - if (result != 0) - { - secdebug("dbsession", "Returned ID:"); - DumpUniqueRecord(*outUniqueId); - } -#endif - - secdebug("dbsession", "********************"); - return result; -} - -bool -DatabaseSession::DataGetNext(CSSM_DB_HANDLE inDbHandle, - CSSM_HANDLE inResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord) -{ - secdebug("dbsession", "DataGetNext(%lx)", inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - - bool result = aDbContext.mDatabase.dataGetNext(aDbContext, inResultsHandle, inoutAttributes, - inoutData, outUniqueRecord); - -#ifndef NDEBUG - if (result) - { - secdebug("dbsession", "Returned ID:"); - DumpUniqueRecord(*outUniqueRecord); - } -#endif - - secdebug("dbsession", "********************"); - return result; -} - -void -DatabaseSession::DataAbortQuery(CSSM_DB_HANDLE inDbHandle, - CSSM_HANDLE inResultsHandle) -{ - secdebug("dbsession", "%p DataAbortQuery(%lx)", this, inDbHandle); - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.dataAbortQuery(aDbContext, inResultsHandle); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::DataGetFromUniqueRecordId(CSSM_DB_HANDLE inDbHandle, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData) -{ - secdebug("dbsession", "%p DataGetFromUniqueId(%lx)", this, inDbHandle); -#ifndef NDEBUG - secdebug("dbsession", "inUniqueRecord:"); - DumpUniqueRecord(inUniqueRecord); -#endif - - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.dataGetFromUniqueRecordId(aDbContext, inUniqueRecord, - inoutAttributes, inoutData); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::FreeUniqueRecord(CSSM_DB_HANDLE inDbHandle, - CSSM_DB_UNIQUE_RECORD &inUniqueRecordIdentifier) -{ - secdebug("dbsession", "FreeUniqueRecord: %lx", inDbHandle); -#ifndef NDEBUG - secdebug("dbsession", "inUniqueRecordIdentifier follows:"); - DumpUniqueRecord(inUniqueRecordIdentifier); -#endif - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.freeUniqueRecord(aDbContext, inUniqueRecordIdentifier); - secdebug("dbsession", "********************"); -} - -void -DatabaseSession::PassThrough(CSSM_DB_HANDLE inDbHandle, - uint32 passThroughId, - const void *inputParams, - void **outputParams) -{ - DbContext &aDbContext = findDbContext(inDbHandle); - aDbContext.mDatabase.passThrough(aDbContext, passThroughId, inputParams, outputParams); -} diff --git a/OSX/include/security_cdsa_plugin/DatabaseSession.h b/OSX/include/security_cdsa_plugin/DatabaseSession.h deleted file mode 100644 index 46d22535..00000000 --- a/OSX/include/security_cdsa_plugin/DatabaseSession.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DatabaseSession.h - Framework for DL plugin modules -// -#ifndef _H_DATABASESESSION -#define _H_DATABASESESSION - -#include - -#include -#include -#include -#include - -namespace Security { - -class DatabaseManager; -class DbContext; - -// A class providing some of the base Database (DL and MDS) functionality. -class DatabaseSession: public DLAbstractPluginSession, public Allocator -{ -public: - DatabaseSession(DatabaseManager &inDatabaseManager); - virtual ~DatabaseSession(); - - virtual void GetDbNames(CSSM_NAME_LIST_PTR &NameList); - virtual void FreeNameList(CSSM_NAME_LIST &NameList); - void DbDelete(const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - const AccessCredentials *AccessCred); - void DbCreate(const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - const CSSM_DBINFO &DBInfo, - CSSM_DB_ACCESS_TYPE AccessRequest, - const CSSM_RESOURCE_CONTROL_CONTEXT *CredAndAclEntry, - const void *OpenParameters, - CSSM_DB_HANDLE &DbHandle); - virtual void DbOpen(const char *DbName, - const CSSM_NET_ADDRESS *DbLocation, - CSSM_DB_ACCESS_TYPE AccessRequest, - const AccessCredentials *AccessCred, - const void *OpenParameters, - CSSM_DB_HANDLE &DbHandle); - void DbClose(CSSM_DB_HANDLE DBHandle); - void CreateRelation(CSSM_DB_HANDLE DBHandle, - CSSM_DB_RECORDTYPE RelationID, - const char *RelationName, - uint32 NumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 NumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO &pIndexInfo); - void DestroyRelation(CSSM_DB_HANDLE DBHandle, - CSSM_DB_RECORDTYPE RelationID); - - void Authenticate(CSSM_DB_HANDLE DBHandle, - CSSM_DB_ACCESS_TYPE AccessRequest, - const AccessCredentials &AccessCred); - void GetDbAcl(CSSM_DB_HANDLE DBHandle, - const CSSM_STRING *SelectionTag, - uint32 &NumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &AclInfos); - void ChangeDbAcl(CSSM_DB_HANDLE DBHandle, - const AccessCredentials &AccessCred, - const CSSM_ACL_EDIT &AclEdit); - void GetDbOwner(CSSM_DB_HANDLE DBHandle, - CSSM_ACL_OWNER_PROTOTYPE &Owner); - void ChangeDbOwner(CSSM_DB_HANDLE DBHandle, - const AccessCredentials &AccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &NewOwner); - void GetDbNameFromHandle(CSSM_DB_HANDLE DBHandle, - char **DbName); - void DataInsert(CSSM_DB_HANDLE DBHandle, - CSSM_DB_RECORDTYPE RecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *Attributes, - const CssmData *Data, - CSSM_DB_UNIQUE_RECORD_PTR &UniqueId); - void DataDelete(CSSM_DB_HANDLE DBHandle, - const CSSM_DB_UNIQUE_RECORD &UniqueRecordIdentifier); - void DataModify(CSSM_DB_HANDLE DBHandle, - CSSM_DB_RECORDTYPE RecordType, - CSSM_DB_UNIQUE_RECORD &UniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *AttributesToBeModified, - const CssmData *DataToBeModified, - CSSM_DB_MODIFY_MODE ModifyMode); - CSSM_HANDLE DataGetFirst(CSSM_DB_HANDLE DBHandle, - const CssmQuery *Query, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CssmData *Data, - CSSM_DB_UNIQUE_RECORD_PTR &UniqueId); - bool DataGetNext(CSSM_DB_HANDLE DBHandle, - CSSM_HANDLE ResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CssmData *Data, - CSSM_DB_UNIQUE_RECORD_PTR &UniqueId); - void DataAbortQuery(CSSM_DB_HANDLE DBHandle, - CSSM_HANDLE ResultsHandle); - void DataGetFromUniqueRecordId(CSSM_DB_HANDLE DBHandle, - const CSSM_DB_UNIQUE_RECORD &UniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR Attributes, - CssmData *Data); - void FreeUniqueRecord(CSSM_DB_HANDLE DBHandle, - CSSM_DB_UNIQUE_RECORD &UniqueRecord); - void PassThrough(CSSM_DB_HANDLE DBHandle, - uint32 PassThroughId, - const void *InputParams, - void **OutputParams); - - DatabaseManager &mDatabaseManager; -protected: - void closeAll(); -private: - CSSM_DB_HANDLE insertDbContext(DbContext &dbContext); - DbContext &findDbContext(CSSM_DB_HANDLE inDbHandle); - - typedef std::map DbContextMap; - DbContextMap mDbContextMap; - Mutex mDbContextMapLock; -}; - -} // end namespace Security - -#endif //_H_DATABASESESSION diff --git a/OSX/include/security_cdsa_plugin/DbContext.cpp b/OSX/include/security_cdsa_plugin/DbContext.cpp deleted file mode 100644 index 51810fae..00000000 --- a/OSX/include/security_cdsa_plugin/DbContext.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#ifdef __MWERKS__ -#define _CPP_DBCONTEXT -#endif -#include - -#include - -#include - -DbContext::DbContext (Database &inDatabase, - DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_ACCESS_CREDENTIALS *inAccessCred) : - mDatabase (inDatabase), - mDatabaseSession (inDatabaseSession), - mAccessRequest (inAccessRequest) -{ - // XXX Copy the ACL. - //mAccessCred = inAccessCred; -} - -DbContext::~DbContext () -{ - //delete mAccessCred; - // XXX How do we delete these? -} diff --git a/OSX/include/security_cdsa_plugin/DbContext.h b/OSX/include/security_cdsa_plugin/DbContext.h deleted file mode 100644 index e3df05c4..00000000 --- a/OSX/include/security_cdsa_plugin/DbContext.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#ifndef _DBCONTEXT_H_ -#define _DBCONTEXT_H_ 1 - -#include -#include - -#ifdef _CPP_DBCONTEXT -# pragma export on -#endif - -namespace Security -{ - -class DatabaseSession; - -class DbContext : public HandleObject -{ - NOCOPY(DbContext) -public: - Database &mDatabase; - DatabaseSession &mDatabaseSession; - - DbContext(Database &inDatabase, - DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const CSSM_ACCESS_CREDENTIALS *inAccessCred); - - virtual ~DbContext(); - - CSSM_HANDLE - dataGetFirst(const CssmQuery *inQuery, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord); - - void - dataGetNext(CSSM_HANDLE inResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord); - - void - dataAbortQuery(CSSM_HANDLE inResultsHandle); -private: - CSSM_DB_ACCESS_TYPE mAccessRequest; - CSSM_ACCESS_CREDENTIALS *mAccessCred; - //typedef set DbQuerySet; - //DbQuerySet mDbQuerySet; - //Mutex mDbQuerySetLock; -}; - -} // end namespace Security - -#ifdef _CPP_DBCONTEXT -# pragma export off -#endif - -#endif //_DBCONTEXT_H_ diff --git a/OSX/include/security_cdsa_plugin/TPsession.h b/OSX/include/security_cdsa_plugin/TPsession.h deleted file mode 100644 index e95a869e..00000000 --- a/OSX/include/security_cdsa_plugin/TPsession.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// TPsession.h - Framework for TP plugin modules -// -#ifndef _H_TPSESSION -#define _H_TPSESSION - -#include - -#if defined(_CPP_TPSESSION) -# pragma export on -#endif - -namespace Security { - -// -// The abstract TPPluginSession class is the common ancestor of your implementation -// object for an TP type plugin attachment session. Inherit from this and implement -// the abstract methods to define a plugin session. -// -class TPPluginSession : public PluginSession, public TPAbstractPluginSession { -public: - TPPluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &plug, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls) - : PluginSession(theHandle, plug, version, subserviceId, subserviceType, attachFlags, upcalls) { } - -protected: - CSSM_MODULE_FUNCS_PTR construct(); -}; - -} // end namespace Security - - -#endif //_H_TPSESSION diff --git a/OSX/include/security_cdsa_plugin/c++plugin.h b/OSX/include/security_cdsa_plugin/c++plugin.h deleted file mode 100644 index d59e41d5..00000000 --- a/OSX/include/security_cdsa_plugin/c++plugin.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// spilayer - "roof" interface layer for CDSA SPI plugins -// -#ifndef _H_SPILAYER -#define _H_SPILAYER - -#include -#include -#include -#include - - -namespace Security -{ - -// -// Forward/common - separate file (which?) @@@ -// -class CssmPlugin; -class PluginSession; - -} // end namespace Security - -#endif //_H_SPILAYER diff --git a/OSX/include/security_cdsa_plugin/csputilities.cpp b/OSX/include/security_cdsa_plugin/csputilities.cpp deleted file mode 100644 index e0d78ff1..00000000 --- a/OSX/include/security_cdsa_plugin/csputilities.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// csputilities - utility classes for CSP implementation -// -#include -#include -#include -#include - -using LowLevelMemoryUtilities::increment; - - -// -// Writer objects -// -CSPFullPluginSession::Writer::Writer(CssmData *v, uint32 n, CssmData *rem) -: vec(v), firstVec(v), lastVec(v + n - 1), remData(rem) -{ - if (vec == NULL || n == 0) - CssmError::throwMe(CSSMERR_CSP_INVALID_OUTPUT_VECTOR); // CDSA p.253, amended - useData(vec); - written = 0; -} - -void CSPFullPluginSession::Writer::allocate(size_t needed, Allocator &alloc) -{ - if (!needed) - return; // No output buffer space needed so we're done. - else if (vec == firstVec && !*vec) { // initial null vector element, wants allocation there - *vec = makeBuffer(needed, alloc); - lastVec = vec; // ignore all subsequent buffers in vector - useData(vec); - } else { - // how much output space do we have left? - size_t size = currentSize; - for (CssmData *v = vec + 1; v <= lastVec; v++) - size += v->length(); - if (size >= needed) - return; // we're fine - if (remData) { - if (!*remData) { // have overflow, can allocate - *remData = makeBuffer(needed - size, alloc); - return; // got it - } - if (size + remData->length() >= needed) - return; // will fit into overflow - } - // not enough buffer space, and can't allocate - CssmError::throwMe(CSSMERR_CSP_OUTPUT_LENGTH_ERROR); - } -} - -void CSPFullPluginSession::Writer::nextBlock(void * &ptr, size_t &size) -{ - ptr = currentBuffer; - size = currentSize; -} - -void CSPFullPluginSession::Writer::use(size_t used) -{ - assert(used <= currentSize); - written += used; - if (used < currentSize) { - currentBuffer = increment(currentBuffer, used); - currentSize -= used; - } else { - if (vec < lastVec) { - useData(vec++); // use next vector buffer - } else if (vec == lastVec && remData) { - useData(remData); // use remainder buffer - vec++; // mark used -#if !defined(NDEBUG) && 0 - } else if (vec == lastVec) { - vec++; - } else if (vec > lastVec) { - assert(false); // 2nd try to overflow end -#endif /* !NDEBUG */ - } else { - currentBuffer = NULL; // no more output buffer - currentSize = 0; - } - } -} - -void CSPFullPluginSession::Writer::put(void *addr, size_t size) -{ - while (size > 0) { - void *p; size_t sz; - nextBlock(p, sz); - if (size < sz) - sz = size; // cap transfer - memcpy(p, addr, sz); - use(sz); - addr = increment(addr, sz); - size -= sz; - } -} - -size_t CSPFullPluginSession::Writer::close() -{ - return written; -} - - -// -// Common algorithm utilities -// -void CSPFullPluginSession::setKey(CssmKey &key, - const Context &context, CSSM_KEYCLASS keyClass, - CSSM_KEYATTR_FLAGS attrs, CSSM_KEYUSE use) -{ - // general setup - memset(&key.KeyHeader, 0, sizeof(key.KeyHeader)); - key.KeyHeader.HeaderVersion = CSSM_KEYHEADER_VERSION; - key.KeyHeader.CspId = plugin.myGuid(); - key.KeyHeader.AlgorithmId = context.algorithm(); - key.KeyHeader.KeyClass = keyClass; - key.KeyHeader.KeyUsage = use; - key.KeyHeader.KeyAttr = attrs; - - CssmDate *theDate = context.get(CSSM_ATTRIBUTE_START_DATE); - if(theDate) { - key.KeyHeader.StartDate = *theDate; - } - theDate = context.get(CSSM_ATTRIBUTE_END_DATE); - if(theDate) { - key.KeyHeader.EndDate = *theDate; - } - - // defaults (change as needed) - key.KeyHeader.WrapAlgorithmId = CSSM_ALGID_NONE; - - // clear key data (standard says, "Always allocate this, ignore prior contents.") - key = CssmData(); -} diff --git a/OSX/include/security_cdsa_plugin/cssmplugin.cpp b/OSX/include/security_cdsa_plugin/cssmplugin.cpp deleted file mode 100644 index c8680c4b..00000000 --- a/OSX/include/security_cdsa_plugin/cssmplugin.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cssmplugin - adapter framework for C++-based CDSA plugin modules -// -// A note on locking: Attachments are effectively reference counted in CSSM. -// CSSM will not let a client detach an attachment that has a(nother) thread -// active in its code. Thus, our locks merely protect global maps; they do not -// need (or try) to close the classic use-and-delete window. -// -#include -#include -#include - - -ModuleNexus CssmPlugin::sessionMap; - - -CssmPlugin::CssmPlugin() - : mLoaded(false) -{ -} - -CssmPlugin::~CssmPlugin() -{ - // Note: if mLoaded, we're being unloaded forcibly. - // (CSSM wouldn't do this to us in normal operation.) -} - - -// -// Load processing. -// CSSM only calls this once for a module, and multiplexes any additional -// CSSM_ModuleLoad calls internally. So this is only called when we have just -// been loaded (and not yet attached). -// -void CssmPlugin::moduleLoad(const Guid &cssmGuid, - const Guid &moduleGuid, - const ModuleCallback &newCallback) -{ - if (mLoaded) - CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); - - mMyGuid = moduleGuid; - - // let the implementation know that we're loading - this->load(); - - // commit - mCallback = newCallback; - mLoaded = true; -} - - -// -// Unload processing. -// The callback passed here will be the same passed to load. -// CSSM only calls this on a "final" CSSM_ModuleUnload, after all attachments -// are destroyed and (just) before we are physically unloaded. -// -void CssmPlugin::moduleUnload(const Guid &cssmGuid, - const Guid &moduleGuid, - const ModuleCallback &oldCallback) -{ - // check the callback vector - if (!mLoaded || oldCallback != mCallback) - CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); - - // tell our subclass that we're closing down - this->unload(); - - // commit closure - mLoaded = false; -} - - -// -// Create one attachment session. This is what CSSM calls to process -// a CSSM_ModuleAttach call. moduleLoad() has already been called and has -// returned successfully. -// -void CssmPlugin::moduleAttach(CSSM_MODULE_HANDLE theHandle, - const Guid &newCssmGuid, - const Guid &moduleGuid, - const Guid &moduleManagerGuid, - const Guid &callerGuid, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - CSSM_KEY_HIERARCHY keyHierarchy, - const CSSM_UPCALLS &upcalls, - CSSM_MODULE_FUNCS_PTR &funcTbl) -{ - // basic (in)sanity checks - if (moduleGuid != mMyGuid) - CssmError::throwMe(CSSM_ERRCODE_INVALID_GUID); - - // make the new session object, hanging in thin air - auto_ptr session(this->makeSession(theHandle, - version, - subserviceId, subserviceType, - attachFlags, - upcalls)); - - // haggle with the implementor - funcTbl = session->construct(); - - // commit this session creation - StLock _(sessionMap()); - sessionMap()[theHandle] = session.release(); -} - - -// -// Undo a (single) module attachment. This calls the detach() method on -// the Session object representing the attachment. This is only called -// if session->construct() has succeeded previously. -// If session->detach() fails, we do not destroy the session and it continues -// to live, though its handle may have (briefly) been invalid. This is for -// desperate "mustn't go right now" situations and should not be abused. -// CSSM always has the ability to ditch you without your consent if you are -// obstreporous. -// -void CssmPlugin::moduleDetach(CSSM_MODULE_HANDLE handle) -{ - // locate the plugin and hold the sessionMapLock - PluginSession *session; - { - StLock _(sessionMap()); - SessionMap::iterator it = sessionMap().find(handle); - if (it == sessionMap().end()) - CssmError::throwMe(CSSMERR_CSSM_INVALID_ADDIN_HANDLE); - session = it->second; - sessionMap().erase(it); - } - - // let the session know it is going away - try { - session->detach(); - delete session; - } catch (...) { - // session detach failed - put the plugin back and fail - StLock _(sessionMap()); - sessionMap()[handle] = session; - throw; - } -} - - -// -// Send an official CSSM module callback message upstream -// -void CssmPlugin::sendCallback(CSSM_MODULE_EVENT event, uint32 ssid, - CSSM_SERVICE_TYPE serviceType) const -{ - assert(mLoaded); - mCallback(event, mMyGuid, ssid, serviceType); -} - - -// -// Default subclass hooks. -// The default implementations succeed without doing anything. -// -void CssmPlugin::load() { } - -void CssmPlugin::unload() { } diff --git a/OSX/include/security_cdsa_plugin/cssmplugin.h b/OSX/include/security_cdsa_plugin/cssmplugin.h deleted file mode 100644 index 7059849b..00000000 --- a/OSX/include/security_cdsa_plugin/cssmplugin.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// cssmplugin - common header for CSSM plugin modules -// -#ifndef _H_CSSMPLUGIN -#define _H_CSSMPLUGIN - -#include -#include -#include -#include - -#include - -namespace Security { - - -// -// Inherit from this (abstract) class to implement your plugin -// -class CssmPlugin { - NOCOPY(CssmPlugin) -public: - CssmPlugin(); - virtual ~CssmPlugin(); - - void moduleLoad(const Guid &cssmGuid, - const Guid &moduleGuid, - const ModuleCallback &callback); - void moduleUnload(const Guid &cssmGuid, - const Guid &moduleGuid, - const ModuleCallback &callback); - - void moduleAttach(CSSM_MODULE_HANDLE theHandle, - const Guid &cssmGuid, - const Guid &moduleGuid, - const Guid &moduleManagerGuid, - const Guid &callerGuid, - const CSSM_VERSION &Version, - uint32 SubserviceID, - CSSM_SERVICE_TYPE SubServiceType, - CSSM_ATTACH_FLAGS AttachFlags, - CSSM_KEY_HIERARCHY KeyHierarchy, - const CSSM_UPCALLS &Upcalls, - CSSM_MODULE_FUNCS_PTR &FuncTbl); - void moduleDetach(CSSM_MODULE_HANDLE handle); - - const Guid &myGuid() const { return mMyGuid; } - - void sendCallback(CSSM_MODULE_EVENT event, - uint32 ssid, - CSSM_SERVICE_TYPE serviceType) const; - - void sendInsertion(uint32 subId, CSSM_SERVICE_TYPE serviceType) const - { sendCallback(CSSM_NOTIFY_INSERT, subId, serviceType); } - - void sendRemoval(uint32 subId, CSSM_SERVICE_TYPE serviceType) const - { sendCallback(CSSM_NOTIFY_REMOVE, subId, serviceType); } - - void sendFault(uint32 subId, CSSM_SERVICE_TYPE serviceType) const - { sendCallback(CSSM_NOTIFY_FAULT, subId, serviceType); } - -protected: - // subclass-defined methods - virtual void load(); - virtual void unload(); - - // make a session object for your plugin - virtual PluginSession *makeSession(CSSM_MODULE_HANDLE handle, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &upcalls) = 0; - -private: - // map of (CSSM) handles to attachment objects - struct SessionMap : - public std::unordered_map, - public Mutex { }; - - static ModuleNexus sessionMap; - - Guid mMyGuid; - - // the registered callback. Set during load processing, unset during unload - ModuleCallback mCallback; - bool mLoaded; - -public: - static PluginSession *find(CSSM_MODULE_HANDLE h) - { - StLock _(sessionMap()); - SessionMap::iterator it = sessionMap().find(h); - if (it == sessionMap().end()) - CssmError::throwMe(CSSMERR_CSSM_INVALID_ADDIN_HANDLE); - return it->second; - } -}; - -template -inline SessionClass &findSession(CSSM_MODULE_HANDLE h) -{ - SessionClass *session = dynamic_cast(CssmPlugin::find(h)); - if (session == NULL) - CssmError::throwMe(CSSMERR_CSSM_INVALID_ADDIN_HANDLE); - assert(session->handle() == h); - return *session; -} - -} // end namespace Security - -#endif //_H_CSSMPLUGIN diff --git a/OSX/include/security_cdsa_plugin/generator.cfg b/OSX/include/security_cdsa_plugin/generator.cfg deleted file mode 100644 index 6a585002..00000000 --- a/OSX/include/security_cdsa_plugin/generator.cfg +++ /dev/null @@ -1,59 +0,0 @@ -# -# transition.cfg -# -# Configuration file for generating the CSSM plugin framework transition layer. -# - - -# -# Specify optional arguments -# - -# CSP -optional CSP:Login LoginName -optional CSP:GetLoginAcl SelectionTag -optional CSP:GetKeyAcl SelectionTag -optional DL:GetDbAcl SelectionTag -optional CSP:GenerateKey KeyLabel CredAndAclEntry -optional CSP:GenerateKeyPair PrivateKeyLabel PublicKeyLabel CredAndAclEntry -optional CSP:WrapKey DescriptiveData -optional CSP:UnwrapKey PublicKey KeyLabel CredAndAclEntry -optional CSP:DeriveKey KeyLabel CredAndAclEntry -optional CSP:FreeKey AccessCred -optional CSP:QuerySize DataBlock -optional CSP:QueryKeySizeInBits Context Key - -# CL/TP -optional TP:SubmitCredRequest PreferredAuthority CallerAuthContext -optional TP:RetrieveCredResult CallerAuthCredentials -optional TP:ConfirmCredResult CallerAuthCredentials PreferredAuthority -optional TP:CertReclaimKey CredAndAclEntry -optional TP:FormRequest PreferredAuthority -optional TP:FormSubmit ClearanceAuthority RepresentedAuthority Credentials -optional TP:CertGroupVerify VerifyContext VerifyContextResult -optional TP:CertSign SignerVerifyContext SignerVerifyResult -optional TP:CrlVerify VerifyContext RevokerVerifyResult -optional TP:CertRevoke OldCrlTemplate -optional TP:CertRemoveFromCrlTemplate OldCrlTemplate -optional TP:CrlSign SignerVerifyContext SignerVerifyResult -optional TP:ApplyCrlToDb ApplyCrlVerifyContext -optional TP:PassThrough DBList -optional AC:AuthCompute Credentials RequestedAuthorizationPeriod -optional CL:CertSign SignScope -optional CL:CertVerify SignerCert VerifyScope -optional CL:CertGroupToSignedBundle SignerCert BundleInfo -optional CL:CertGroupFromVerifiedBundle SignerCert -optional CL:CrlSign SignScope -optional CL:CrlVerify SignerCert VerifyScope -optional CL:CrlGetFirstCachedFieldValue CrlRecordIndex - -# DL -optional DL:DbOpen DbLocation AccessCred -optional DL:DbCreate DbLocation CredAndAclEntry -optional DL:DbDelete DbLocation AccessCred -optional DL:DataInsert Attributes Data -optional DL:DataModify AttributesToBeModified DataToBeModified -optional DL:DataGetFirst Query Attributes Data -optional DL:DataGetNext Query Attributes Data -optional DL:DataGetFromUniqueRecordId Attributes Data -optional DL:CreateRelation pAttributeInfo diff --git a/OSX/include/security_cdsa_plugin/generator.mk b/OSX/include/security_cdsa_plugin/generator.mk deleted file mode 100644 index 0451e8c4..00000000 --- a/OSX/include/security_cdsa_plugin/generator.mk +++ /dev/null @@ -1,29 +0,0 @@ -# Makefile for generated files. - -SOURCES = $(BUILT_PRODUCTS_DIR)/derived_src/security_cdsa_plugin -HEADERS = $(SOURCES) - -HFILES = $(HEADERS)/ACabstractsession.h -CPPFILES = $(SOURCES)/ACabstractsession.cpp - -build: $(HFILES) $(CPPFILES) - -install: build - -installhdrs: $(HFILES) - -installsrc: - -clean: - rm -f $(SPIGLUE_GEN) - -debug: build - -profile: build - -.PHONY: build clean debug profile - -# partial dependencies only -$(HFILES) $(CPPFILES) : $(PROJECT_DIR)/lib/generator.pl $(PROJECT_DIR)/lib/generator.cfg - mkdir -p $(SOURCES) - perl $(PROJECT_DIR)/lib/generator.pl $(CSSM_HEADERS) $(PROJECT_DIR)/lib/generator.cfg $(HEADERS) $(SOURCES) diff --git a/OSX/include/security_cdsa_plugin/generator.pl b/OSX/include/security_cdsa_plugin/generator.pl deleted file mode 100644 index 585186b0..00000000 --- a/OSX/include/security_cdsa_plugin/generator.pl +++ /dev/null @@ -1,247 +0,0 @@ -#!/usr/bin/perl -# -# generator.pl - auto-generate code for the CSSM plugin interfaces -# -# Usage: -# perl generator.pl input-directory h-output-dir c-output-dir -# -# Perry The Cynic, Fall 1999. -# -@API_H=("cssmapi.h"); -%SPI_H=("AC" => "cssmaci.h", "CSP" => "cssmcspi.h", "DL" => "cssmdli.h", - "CL" => "cssmcli.h", "TP" => "cssmtpi.h"); - -$SOURCEPATH=$ARGV[0]; # where all the input files are -$APICFG=$ARGV[1]; # configuration file -$HTARGETDIR=$ARGV[2]; # where the generated headers go -$CTARGETDIR=$ARGV[3]; # where the generated sources go - - -$tabs = "\t\t\t"; # argument indentation (noncritical) -$warning = "This file was automatically generated. Do not edit on penalty of futility!"; - - -# -# Open and read the configuration file -# -$/=undef; # gulp file -open(APICFG, $APICFG) or die "Cannot open $APICFG: $^E"; -$_=; -close(APICFG); -%optionals = /^\s*optional\s+(\w+:\w+)\s+(.*)$/gm; - - -# -# Pre-arranged arrays for processing below -# -%noDataReturnError = ( CL => "CSSMERR_CL_NO_FIELD_VALUES", - DL => "CSSMERR_DL_ENDOFDATA" ); - - -# -# process one SPI at a time -# -while (($type, $header) = each %SPI_H) { - my(%functions, %methods, %actuals); - ($typelower = $type) =~ tr/A-Z/a-z/; # lowercase version of type - - # start in on the $type header file - for my $sourcedir (split (/:/, $SOURCEPATH)) { - open(SPI, "$sourcedir/$header") and last; - } - SPI or die "cannot find $header in $SOURCEPATH: $^E"; - $/=undef; # big gulp mode - $_ = ; # aaaaah... - close(SPI); # done - # throw away leading and trailing crud (only interested in SPI structure) - s/^.*struct cssm_spi.*{(.*)} CSSM_SPI.*$/$1/s - or die "bad format in $SPI_H{$name}"; - - # break up into functions (you'd do that HOW in YOUR language? :-) - @functions = /CSSM_RETURN \(CSSM${type}I \*([A-Za-z_]+)\)\s+\(([^)]+)\);/g; - %functions = @functions; - - $MOREHEADERS=""; - $MOREHEADERS .= "#include \n" if /CSSM_CONTEXT/; - $MOREHEADERS .= "#include \n" if /CSSM_(ACL|ACCESS)/; - $MOREHEADERS .= "#include \n" if /CSSM_QUERY/; - - # break function arguments into many forms: - # functions => formal SPI arguments - # methods => formal C++ method arguments - # actuals => actual expression forms for transition layer use - # and (by the way) massage them into a more palatable form... - $nFunctions = 0; - while (($function, $_) = each %functions) { - # - # Turn CSSM SPI formal into method formal - # - $returntype{$function} = "void"; - $prefix{$function} = ""; - $postfix{$function} = ";"; - # reshape initial argument (the module handle, more or less) - s/^CSSM_${type}_HANDLE ${type}Handle(,\s*\n\s*|$)//s; # remove own handle (-> this) - s/^CSSM_DL_DB_HANDLE DLDBHandle/CSSM_DB_HANDLE DBHandle/s; # DL_DB handle -> DB handle - s/CSSM_HANDLE_PTR ResultsHandle(,?)\n//m # turn ptr-to-resultshandle into fn result - and do { - $returntype{$function} = "CSSM_HANDLE"; - $prefix{$function} = "if ((Required(ResultsHandle) = "; - $postfix{$function} = ") == CSSM_INVALID_HANDLE)\n return $noDataReturnError{$type};"; - }; - if ($function =~ /GetNext/) { # *GetNext* returns a bool - $returntype{$function} = "bool"; - $prefix{$function} = "if (!"; - $postfix{$function} = ")\n return $noDataReturnError{$type};"; - } - # reshape subsequent arguments - s/([su]int32) \*(\w+,?)/$1 \&$2/gm; # int * -> int & (output integer) - s/(CSSM_\w+_PTR) \*(\w+,?)/$1 \&$2/gm; # _PTR * -> _PTR & - s/(CSSM_\w+)_PTR (\w+)/$1 \*$2/gm; # XYZ_PTR -> XYZ * (explicit) - s/(const )?CSSM_DATA \*(\w+)Bufs/$1CssmData $2Bufs\[\]/gm; # c DATA *Bufs (plural) - s/(const )?CSSM_(DATA|OID) \*/$1CssmData \&/gm; # c DATA * -> c Data & - s/(const )?CSSM_FIELD \*(\w+)Fields/$1CSSM_FIELD $2Fields\[\]/gm; # c FIELD *Fields (plural) - s/(const )?CSSM_FIELD \*CrlTemplate/$1CSSM_FIELD CrlTemplate\[\]/gm; # c FIELD *CrlTemplate - s/const CSSM_CONTEXT \*/const Context \&/gm; # c CSSM_CONTEXT * -> c Context & - s/(const )?CSSM_ACCESS_CREDENTIALS \*/$1AccessCredentials \&/gm; # ditto - s/(const )?CSSM_QUERY_SIZE_DATA \*/$1QuerySizeData \&/gm; # ditto - s/(const )?CSSM_CSP_OPERATIONAL_STATISTICS \*/$1CSPOperationalStatistics \&/gm; # ditto - s/(const )?CSSM_(WRAP_)?KEY \*/$1CssmKey \&/gm; # CSSM[WRAP]KEY * -> CssmKey & - s/const CSSM_QUERY \*/const CssmQuery \&/gm; # c QUERY * -> c Query & - s/(const )?(CSSM_[A-Z_]+) \*/$1$2 \&/gm; # c CSSM_ANY * -> c CSSM_ANY & - $methods{$function} = $_; - - # - # Now turn the method formal into the transition invocation actuals - # - s/^CSSM_DB_HANDLE \w+(,?)/DLDBHandle.DBHandle$1/s; # matching change to DL_DB handles - s/(const )?([A-Z][a-z]\w+) &(\w+)(,?)/$2::required($3)$4/gm; # BIG_ * -> Small_ & - s/(const )?CssmData (\w+)Bufs\[\](,?)/\&\&CssmData::required($2Bufs)$3/gm; # c DATA *DataBufs - s/(const )?CSSM_FIELD (\w+)Fields\[\](,?)/$2Fields$3/gm; # c CSSM_FIELD *Fields - s/(const )?CSSM_FIELD CrlTemplate\[\](,?)/CrlTemplate$2/gm; # c CSSM_FIELD *CrlTemplate - # now remove formal arguments and clean up - s/^.* \&\&(\w+,?)/$tabs\&$1/gm; # && escape (to keep real &) - s/^.* \&(\w+)(,?)/${tabs}Required($1)$2/gm; # dereference for ref transition - s/^.* \**(\w+,?)/$tabs$1/gm; # otherwise, plain actual argument - s/^$tabs//; - $actuals{$function} = $_; - - # - # Fix optional arguments - # - foreach $opt (split " ", $optionals{"$type:$function"}) { - $methods{$function} =~ s/\&$opt\b/\*$opt/; # turn refs back into pointers - $actuals{$function} =~ s/::required\($opt\)/::optional($opt)/; # optional specific - $actuals{$function} =~ s/Required\($opt\)/$opt/; # optional generic - }; - $nFunctions++; - }; - - # - # Prepare to write header and source files - # - open(H, ">$HTARGETDIR/${type}abstractsession.h") or die "cannot write ${type}abstractsession.h: $^E"; - open(C, ">$CTARGETDIR/${type}abstractsession.cpp") or die "cannot write ${type}abstractsession.cpp: $^E"; - - # - # Create header file - # - print H < -#include -$MOREHEADERS - -namespace Security { - - -// -// A pure abstract class to define the ${type} module interface -// -class ${type}AbstractPluginSession { -public: - virtual ~${type}AbstractPluginSession(); -HDRHEAD - - $functionCount = 0; - while (($function, $arglist) = each %methods) { - # generate method declaration - print H " virtual $returntype{$function} $function($arglist) = 0;\n"; - $functionCount++; - }; - print H < -#include -#include -#include - - -${type}AbstractPluginSession::~${type}AbstractPluginSession() -{ /* virtual */ } - -BODY - - # write transition layer functions - while (($function, $arglist) = each %functions) { - $lookupHandle = "${type}Handle"; - $lookupHandle = "DLDBHandle.DLHandle" if $arglist =~ /DL_DB_HANDLE/; - print C <($lookupHandle).$function($actuals{$function})${postfix{$function}} - END_API($type) -} - -SHIM - }; - - # generate dispatch table - in the right order, please - print C "\nstatic const CSSM_SPI_${type}_FUNCS ${type}FunctionStruct = {\n"; - while ($function = shift @functions) { - print C " cssm_$function,\n"; - shift @functions; # skip over arglist part - }; - print C "};\n\n"; - - print C < -#include -#include - - -// -// Construct a PluginSession -// -PluginSession::PluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &myPlugin, - const CSSM_VERSION &version, - uint32 subserviceId, - CSSM_SERVICE_TYPE subserviceType, - CSSM_ATTACH_FLAGS attachFlags, - const CSSM_UPCALLS &inUpcalls) - : HandledObject(theHandle), plugin(myPlugin), - mVersion(version), mSubserviceId(subserviceId), - mSubserviceType(subserviceType), mAttachFlags(attachFlags), - upcalls(inUpcalls) -{ -} - - -// -// Destruction -// -PluginSession::~PluginSession() -{ -} - - -// -// The default implementation of detach() does nothing -// -void PluginSession::detach() -{ -} - - -// -// Allocation management -// -void *PluginSession::malloc(size_t size) throw(std::bad_alloc) -{ - if (void *addr = upcalls.malloc_func(handle(), size)) - return addr; - throw std::bad_alloc(); -} - -void *PluginSession::realloc(void *oldAddr, size_t size) throw(std::bad_alloc) -{ - if (void *addr = upcalls.realloc_func(handle(), oldAddr, size)) - return addr; - throw std::bad_alloc(); -} - - -// -// Dispatch callback events through the plugin object. -// Subsystem ID and subservice type default to our own. -// - -void PluginSession::sendCallback(CSSM_MODULE_EVENT event, - uint32 ssid, - CSSM_SERVICE_TYPE serviceType) const -{ - plugin.sendCallback(event, - (ssid == uint32(-1)) ? mSubserviceId : ssid, - serviceType ? serviceType : mSubserviceType); -} diff --git a/OSX/include/security_cdsa_plugin/pluginsession.h b/OSX/include/security_cdsa_plugin/pluginsession.h deleted file mode 100644 index d58ba5ea..00000000 --- a/OSX/include/security_cdsa_plugin/pluginsession.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// pluginsession - an attachment session for a CSSM plugin -// -#ifndef _H_PLUGINSESSION -#define _H_PLUGINSESSION - -#include -#include -#include - - -namespace Security { - - -// -// A PluginSession object describes an ongoing connection between a particular -// CSSM client and our plugin. Every time CSSM_SPI_ModuleAttach is called -// (due to the client calling CSSM_ModuleAttach), a new PluginSession object -// is created as a result. Sessions and CSSM_MODULE_HANDLES correspond one-to-one. -// Note that CSSM makes up our module handle; we just record it. -// -// A PluginSession *is* an Allocator, whose implementation is to call the -// "application allocator" functions provided by CSSM's caller for the attachment. -// Use the session object as the Allocator for anything you return to your caller. -// -class PluginSession : public Allocator, public HandledObject { - NOCOPY(PluginSession) - friend class CssmPlugin; -public: - PluginSession(CSSM_MODULE_HANDLE theHandle, - CssmPlugin &myPlugin, - const CSSM_VERSION &Version, - uint32 SubserviceID, - CSSM_SERVICE_TYPE SubServiceType, - CSSM_ATTACH_FLAGS AttachFlags, - const CSSM_UPCALLS &upcalls); - virtual ~PluginSession(); - virtual void detach(); - - CssmPlugin &plugin; - - void sendCallback(CSSM_MODULE_EVENT event, - uint32 ssid = uint32(-1), - CSSM_SERVICE_TYPE serviceType = 0) const; - - static void unimplemented() { CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); } - -protected: - virtual CSSM_MODULE_FUNCS_PTR construct() = 0; - -public: - // implement Allocator - void *malloc(size_t size) throw(std::bad_alloc); - void *realloc(void *addr, size_t size) throw(std::bad_alloc); - void free(void *addr) throw() { upcalls.free_func(handle(), addr); } - - // about ourselves - const CSSM_VERSION &version() const { return mVersion; } - uint32 subserviceId() const { return mSubserviceId; } - CSSM_SERVICE_TYPE subserviceType() const { return mSubserviceType; } - CSSM_ATTACH_FLAGS attachFlags() const { return mAttachFlags; } - -private: - CSSM_VERSION mVersion; - uint32 mSubserviceId; - CSSM_SERVICE_TYPE mSubserviceType; - CSSM_ATTACH_FLAGS mAttachFlags; - const CSSM_UPCALLS &upcalls; -}; - -} // end namespace Security - - -#endif //_H_PLUGINSESSION diff --git a/OSX/include/security_cdsa_plugin/pluginspi.h b/OSX/include/security_cdsa_plugin/pluginspi.h deleted file mode 100644 index f5d8d491..00000000 --- a/OSX/include/security_cdsa_plugin/pluginspi.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// pluginspi - "roof" level entry points into a CSSM plugin. -// -// This file is meant to be included into the top-level source file -// for a CSSM plugin written to the C++ alternate interface. -// It contains actual code that defines the four required entry points. -// -#include - - -// -// Provide some flexibility for the includer -// -#if !defined(SPIPREFIX) -# define SPIPREFIX extern "C" CSSMSPI -#endif - -#if !defined(SPINAME) -# define SPINAME(s) s -#endif - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleLoad) (const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleGuid, - CSSM_SPI_ModuleEventHandler CssmNotifyCallback, - void *CssmNotifyCallbackCtx); - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleLoad) (const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleGuid, - CSSM_SPI_ModuleEventHandler CssmNotifyCallback, - void *CssmNotifyCallbackCtx) -{ - BEGIN_API - plugin().moduleLoad(Guid::required(CssmGuid), - Guid::required(ModuleGuid), - ModuleCallback(CssmNotifyCallback, CssmNotifyCallbackCtx)); - END_API(CSSM) -} - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleUnload) (const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleGuid, - CSSM_SPI_ModuleEventHandler CssmNotifyCallback, - void *CssmNotifyCallbackCtx); - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleUnload) (const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleGuid, - CSSM_SPI_ModuleEventHandler CssmNotifyCallback, - void *CssmNotifyCallbackCtx) -{ - BEGIN_API - plugin().moduleUnload(Guid::required(CssmGuid), - Guid::required(ModuleGuid), - ModuleCallback(CssmNotifyCallback, CssmNotifyCallbackCtx)); - END_API(CSSM) -} - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleAttach) (const CSSM_GUID *ModuleGuid, - const CSSM_VERSION *Version, - uint32 SubserviceID, - CSSM_SERVICE_TYPE SubServiceType, - CSSM_ATTACH_FLAGS AttachFlags, - CSSM_MODULE_HANDLE ModuleHandle, - CSSM_KEY_HIERARCHY KeyHierarchy, - const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleManagerGuid, - const CSSM_GUID *CallerGuid, - const CSSM_UPCALLS *Upcalls, - CSSM_MODULE_FUNCS_PTR *FuncTbl); - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleAttach) (const CSSM_GUID *ModuleGuid, - const CSSM_VERSION *Version, - uint32 SubserviceID, - CSSM_SERVICE_TYPE SubServiceType, - CSSM_ATTACH_FLAGS AttachFlags, - CSSM_MODULE_HANDLE ModuleHandle, - CSSM_KEY_HIERARCHY KeyHierarchy, - const CSSM_GUID *CssmGuid, - const CSSM_GUID *ModuleManagerGuid, - const CSSM_GUID *CallerGuid, - const CSSM_UPCALLS *Upcalls, - CSSM_MODULE_FUNCS_PTR *FuncTbl) -{ - BEGIN_API - plugin().moduleAttach(ModuleHandle, - Guid::required(CssmGuid), - Guid::required(ModuleGuid), - Guid::required(ModuleManagerGuid), - Guid::required(CallerGuid), - *Version, - SubserviceID, - SubServiceType, - AttachFlags, - KeyHierarchy, - Required(Upcalls), - Required(FuncTbl)); - END_API(CSSM) -} - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleDetach) (CSSM_MODULE_HANDLE ModuleHandle); - -SPIPREFIX CSSM_RETURN SPINAME(CSSM_SPI_ModuleDetach) (CSSM_MODULE_HANDLE ModuleHandle) -{ - BEGIN_API - plugin().moduleDetach(ModuleHandle); - END_API(CSSM) -} diff --git a/OSX/include/security_cdsa_utilities b/OSX/include/security_cdsa_utilities new file mode 120000 index 00000000..2634481d --- /dev/null +++ b/OSX/include/security_cdsa_utilities @@ -0,0 +1 @@ +./libsecurity_cdsa_utilities/lib \ No newline at end of file diff --git a/OSX/include/security_cdsa_utilities/AuthorizationData.cpp b/OSX/include/security_cdsa_utilities/AuthorizationData.cpp deleted file mode 100644 index 26ccdea1..00000000 --- a/OSX/include/security_cdsa_utilities/AuthorizationData.cpp +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include -#include -#include - - -// checkpw() that uses provided struct passwd -extern "C" -{ -int checkpw_internal( const struct passwd *pw, const char* password ); -} - - -namespace Authorization { - - -AuthValueRef::AuthValueRef(const AuthValue &value) : - RefPointer(new AuthValue(value)) {} - -AuthValueRef::AuthValueRef(const AuthorizationValue &value) : - RefPointer(new AuthValue(value)) {} - -AuthValue::AuthValue(const AuthorizationValue &value) : - mOwnsValue(false) -{ - mValue.length = value.length; - mValue.data = value.data; -} - -AuthValueRef::AuthValueRef(UInt32 length, void *data) : - RefPointer(new AuthValue(length, data)) {} - -AuthValue::AuthValue(UInt32 length, void *data) : - mOwnsValue(true) -{ - mValue.length = length; - mValue.data = new uint8_t[length]; - if (length) - memcpy(mValue.data, data, length); -} - -AuthValue::~AuthValue() -{ - if (mOwnsValue) - { - memset(mValue.data, 0, mValue.length); - delete[] reinterpret_cast(mValue.data); - } -} - -AuthValue & -AuthValue::operator = (const AuthValue &other) -{ - if (mOwnsValue) - { - memset(mValue.data, 0 , mValue.length); - delete[] reinterpret_cast(mValue.data); - } - - mValue = other.mValue; - mOwnsValue = other.mOwnsValue; - other.mOwnsValue = false; - return *this; -} - -void -AuthValue::fillInAuthorizationValue(AuthorizationValue &value) -{ - value.length = mValue.length; - value.data = mValue.data; -} - -AuthValueVector & -AuthValueVector::operator = (const AuthorizationValueVector& valueVector) -{ - clear(); - for (unsigned int i=0; i < valueVector.count; i++) - push_back(AuthValueRef(valueVector.values[i])); - return *this; -} - -void -AuthValueVector::copy(AuthorizationValueVector **data, size_t *length) const -{ - AuthorizationValueVector valueVector; - valueVector.count = (UInt32)size(); - valueVector.values = new AuthorizationValue[valueVector.count]; - int i = 0; - for (const_iterator it = begin(); it != end(); ++it, ++i) - { - (*it)->fillInAuthorizationValue(valueVector.values[i]); - } - - DataWalkers::Copier flatValueVector(&valueVector); - *length = flatValueVector.length(); - *data = flatValueVector.keep(); - - delete[] valueVector.values; -} - -AuthItem::AuthItem(const AuthorizationItem &item) : - mFlags(item.flags), - mOwnsName(true), - mOwnsValue(true) -{ - if (!item.name) - MacOSError::throwMe(errAuthorizationInternal); - size_t nameLen = strlen(item.name) + 1; - mName = new char[nameLen]; - memcpy(const_cast(mName), item.name, nameLen); - - mValue.length = item.valueLength; - mValue.data = new uint8_t[item.valueLength]; - if (mValue.length) - memcpy(mValue.data, item.value, item.valueLength); -} - - -AuthItem::AuthItem(AuthorizationString name) : - mName(name), - mFlags(0), - mOwnsName(false), - mOwnsValue(false) -{ - mValue.length = 0; - mValue.data = NULL; -} - -AuthItem::AuthItem(AuthorizationString name, AuthorizationValue value, AuthorizationFlags flags) : - mFlags(flags), - mOwnsName(true), - mOwnsValue(true) -{ - if (!name) - MacOSError::throwMe(errAuthorizationInternal); - size_t nameLen = strlen(name) + 1; - mName = new char[nameLen]; - memcpy(const_cast(mName), name, nameLen); - - mValue.length = value.length; - mValue.data = new uint8_t[value.length]; - if (mValue.length) - memcpy(mValue.data, value.data, value.length); -} - -AuthItem::~AuthItem() -{ - if (mOwnsName) - delete[] mName; - if (mOwnsValue) - { - memset(mValue.data, 0, mValue.length); - delete[] reinterpret_cast(mValue.data); - } -} - -bool -AuthItem::operator < (const AuthItem &other) const -{ - return strcmp(mName, other.mName) < 0; -} - -AuthItem & -AuthItem::operator = (const AuthItem &other) -{ - if (mOwnsName) - delete[] mName; - if (mOwnsValue) - { - memset(mValue.data, 0, mValue.length); - delete[] reinterpret_cast(mValue.data); - } - - mName = other.mName; - mValue = other.mValue; - mFlags = other.mFlags; - mOwnsName = other.mOwnsName; - other.mOwnsName = false; - mOwnsValue = other.mOwnsValue; - other.mOwnsValue = false; - return *this; -} - -void -AuthItem::fillInAuthorizationItem(AuthorizationItem &item) -{ - item.name = mName; - item.valueLength = mValue.length; - item.value = mValue.data; - item.flags = mFlags; -} - -bool -AuthItem::getBool(bool &value) -{ - if (mValue.length == sizeof(bool)) - { - bool *tmpValue = (bool *)mValue.data; - - if (tmpValue) - { - value = *tmpValue; - return true; - } - } - - return false; -} - -bool -AuthItem::getString(string &value) -{ - value = string(static_cast(mValue.data), mValue.length); - return true; -} - -bool -AuthItem::getCssmData(CssmAutoData &value) -{ - value = CssmData(static_cast(mValue.data), mValue.length); - return true; -} - - -AuthItemRef::AuthItemRef(const AuthorizationItem &item) : RefPointer(new AuthItem(item)) {} - -AuthItemRef::AuthItemRef(AuthorizationString name) : RefPointer(new AuthItem(name)) {} - -AuthItemRef::AuthItemRef(AuthorizationString name, AuthorizationValue value, AuthorizationFlags flags) : RefPointer(new AuthItem(name, value, flags)) {} - - -// -// AuthItemSet -// -AuthItemSet::AuthItemSet() -: firstItemName(NULL) -{ -} - -AuthItemSet::~AuthItemSet() -{ - if (NULL != firstItemName) - free(firstItemName); -} - -AuthItemSet & -AuthItemSet::operator = (const AuthorizationItemSet& itemSet) -{ - clear(); - - for (unsigned int i=0; i < itemSet.count; i++) - insert(AuthItemRef(itemSet.items[i])); - - return *this; -} - -AuthItemSet& -AuthItemSet::operator=(const AuthItemSet& itemSet) -{ - std::set::operator=(itemSet); - - if (this != &itemSet) { - duplicate(itemSet); - } - - return *this; -} - -AuthItemSet::AuthItemSet(const AuthorizationItemSet *itemSet) -: firstItemName(NULL) -{ - if (NULL != itemSet && NULL != itemSet->items) - { - if (0 < itemSet->count && NULL != itemSet->items[0].name) - firstItemName = strdup(itemSet->items[0].name); - - for (unsigned int i=0; i < itemSet->count; i++) - insert(AuthItemRef(itemSet->items[i])); - } -} - -AuthItemSet::AuthItemSet(const AuthItemSet& itemSet) -: std::set(itemSet) -{ - duplicate(itemSet); -} - -void -AuthItemSet::duplicate(const AuthItemSet& itemSet) -{ - if (itemSet.firstItemName != NULL) - firstItemName = strdup(itemSet.firstItemName); - else - firstItemName = NULL; -} - -void -AuthItemSet::copy(AuthorizationItemSet *&data, size_t &length, Allocator &alloc) const -{ - AuthorizationItemSet itemSet; - itemSet.count = (UInt32)size(); - itemSet.items = new AuthorizationItem[itemSet.count]; - int i = 0; - for (const_iterator it = begin(); it != end(); ++it, ++i) - { - (*it)->fillInAuthorizationItem(itemSet.items[i]); - } - - DataWalkers::Copier flatItemSet(&itemSet, alloc); - length = flatItemSet.length(); - - data = flatItemSet.keep(); - // else flatItemSet disappears again - - delete[] itemSet.items; -} - -AuthorizationItemSet * -AuthItemSet::copy() const -{ - AuthorizationItemSet *aCopy; - size_t aLength; - copy(aCopy, aLength); - return aCopy; -} - -AuthItem * -AuthItemSet::find(const char *name) -{ - AuthItemSet::const_iterator found = find_if(this->begin(), this->end(), FindAuthItemByRightName(name) ); - if (found != this->end()) - return *found; - - return NULL; -} - -} // end namespace Authorization diff --git a/OSX/include/security_cdsa_utilities/AuthorizationData.h b/OSX/include/security_cdsa_utilities/AuthorizationData.h deleted file mode 100644 index 3b2c24fa..00000000 --- a/OSX/include/security_cdsa_utilities/AuthorizationData.h +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2000,2002-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * AuthorizationData.h - * Authorization - */ - -#ifndef _H_AUTHORIZATIONDATA -#define _H_AUTHORIZATIONDATA 1 - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -// ptrdiff_t needed, so including STL type closest -#include - -// @@@ Should consider making the various types better citizens by taking an Allocator, for now values are wiped. - -namespace Authorization -{ - -class AuthValueOverlay : public AuthorizationValue -{ -public: - AuthValueOverlay(const string& stringValue) { length = stringValue.length(); data = const_cast(stringValue.c_str()); } - AuthValueOverlay(UInt32 inLength, void *inData) { length = inLength; data = inData; } -}; - -class AuthValueRef; - -class AuthValue : public RefCount -{ - friend class AuthValueRef; -private: - AuthValue(const AuthValue& value) {} -protected: - AuthValue(const AuthorizationValue &value); - AuthValue(UInt32 length, void *data); -public: - AuthValue &operator = (const AuthValue &other); - ~AuthValue(); - void fillInAuthorizationValue(AuthorizationValue &value); - const AuthorizationValue& value() const { return mValue; } -private: - AuthorizationValue mValue; - mutable bool mOwnsValue; -}; - -// AuthValueRef impl -class AuthValueRef : public RefPointer -{ -public: - AuthValueRef(const AuthValue &value); - AuthValueRef(const AuthorizationValue &value); - AuthValueRef(UInt32 length, void *data); -}; - - -// vector should become a member with accessors -class AuthValueVector : public vector -{ -public: - AuthValueVector() {} - ~AuthValueVector() {} - - AuthValueVector &operator = (const AuthorizationValueVector& valueVector); - - void copy(AuthorizationValueVector **data, size_t *length) const; -}; - - - -class AuthItemRef; - -class AuthItem : public RefCount -{ - friend class AuthItemRef; -private: - AuthItem(const AuthItem& item); -protected: - AuthItem(const AuthorizationItem &item); - AuthItem(AuthorizationString name); - AuthItem(AuthorizationString name, AuthorizationValue value); - AuthItem(AuthorizationString name, AuthorizationValue value, AuthorizationFlags flags); - - bool operator < (const AuthItem &other) const; - -public: - AuthItem &operator = (const AuthItem &other); - ~AuthItem(); - - void fillInAuthorizationItem(AuthorizationItem &item); - - AuthorizationString name() const { return mName; } - const AuthorizationValue& value() const { return mValue; } - string stringValue() const { return string(static_cast(mValue.data), mValue.length); } - AuthorizationFlags flags() const { return mFlags; } - void setFlags(AuthorizationFlags inFlags) { mFlags = inFlags; }; - -private: - AuthorizationString mName; - AuthorizationValue mValue; - AuthorizationFlags mFlags; - mutable bool mOwnsName; - mutable bool mOwnsValue; - -public: - bool getBool(bool &value); - bool getString(string &value); - bool getCssmData(CssmAutoData &value); -}; - -class AuthItemRef : public RefPointer -{ -public: - AuthItemRef(const AuthorizationItem &item); - AuthItemRef(AuthorizationString name); - AuthItemRef(AuthorizationString name, AuthorizationValue value, AuthorizationFlags flags = 0); - - bool operator < (const AuthItemRef &other) const - { - return **this < *other; - } -}; - -// set should become a member with accessors -class AuthItemSet : public set -{ -public: - AuthItemSet(); - ~AuthItemSet(); - AuthItemSet(const AuthorizationItemSet *item); - AuthItemSet(const AuthItemSet& itemSet); - - AuthItemSet &operator = (const AuthorizationItemSet& itemSet); - AuthItemSet &operator = (const AuthItemSet& itemSet); - - void copy(AuthorizationItemSet *&data, size_t &length, Allocator &alloc = Allocator::standard()) const; - AuthorizationItemSet *copy() const; - - char *firstItemName; - -public: - AuthItem *find(const char *name); - -private: - void duplicate(const AuthItemSet& itemSet); -}; - -class FindAuthItemByRightName -{ -public: - FindAuthItemByRightName(const char *find_name) : name(find_name) { } - - bool operator()( const AuthItemRef& authitem ) - { - return (!strcmp(name, authitem->name())); - } - bool operator()( const AuthorizationItem* authitem ) - { - return (!strcmp(name, authitem->name)); - } - -private: - const char *name; -}; - -}; // namespace Authorization - -#endif /* ! _H_AUTHORIZATIONDATA */ diff --git a/OSX/include/security_cdsa_utilities/AuthorizationWalkers.h b/OSX/include/security_cdsa_utilities/AuthorizationWalkers.h deleted file mode 100644 index 2ef7dd0f..00000000 --- a/OSX/include/security_cdsa_utilities/AuthorizationWalkers.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * AuthorizationWalkers.h - * SecurityCore - */ - -#if !defined(__AuthorizationWalkers__) -#define __AuthorizationWalkers__ 1 - -#include -#include -#include -#include // char * walker - -namespace Security { -namespace DataWalkers { - - -template -void walk(Action &operate, AuthorizationItem &item) -{ - operate(item); - walk(operate, const_cast(item.name)); - operate.blob(item.value, item.valueLength); - // Ignore reserved -} - -template -AuthorizationItemSet *walk(Action &operate, AuthorizationItemSet * &itemSet) -{ - operate(itemSet); - operate.blob(itemSet->items, itemSet->count * sizeof(itemSet->items[0])); - for (uint32 n = 0; n < itemSet->count; n++) - walk(operate, itemSet->items[n]); - return itemSet; -} - -template -void walk(Action &operate, AuthorizationValue &authvalue) -{ - operate.blob(authvalue.data, authvalue.length); -} - -template -AuthorizationValueVector *walk(Action &operate, AuthorizationValueVector * &valueVector) -{ - operate(valueVector); - operate.blob(valueVector->values, valueVector->count * sizeof(valueVector->values[0])); - for (uint32 n = 0; n < valueVector->count; n++) - walk(operate, valueVector->values[n]); - return valueVector; -} - - - -} // end namespace DataWalkers -} // end namespace Security - -#endif /* ! __AuthorizationWalkers__ */ diff --git a/OSX/include/security_cdsa_utilities/KeySchema.h b/OSX/include/security_cdsa_utilities/KeySchema.h deleted file mode 100644 index 000d63b7..00000000 --- a/OSX/include/security_cdsa_utilities/KeySchema.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// KeySchema.h -// -#ifndef _H_KEYSCHEMA -#define _H_KEYSCHEMA - -#include - -namespace KeySchema -{ - extern const CSSM_DB_ATTRIBUTE_INFO KeyClass; - extern const CSSM_DB_ATTRIBUTE_INFO PrintName; - extern const CSSM_DB_ATTRIBUTE_INFO Alias; - extern const CSSM_DB_ATTRIBUTE_INFO Permanent; - extern const CSSM_DB_ATTRIBUTE_INFO Private; - extern const CSSM_DB_ATTRIBUTE_INFO Modifiable; - extern const CSSM_DB_ATTRIBUTE_INFO Label; - extern const CSSM_DB_ATTRIBUTE_INFO ApplicationTag; - extern const CSSM_DB_ATTRIBUTE_INFO KeyCreator; - extern const CSSM_DB_ATTRIBUTE_INFO KeyType; - extern const CSSM_DB_ATTRIBUTE_INFO KeySizeInBits; - extern const CSSM_DB_ATTRIBUTE_INFO EffectiveKeySize; - extern const CSSM_DB_ATTRIBUTE_INFO StartDate; - extern const CSSM_DB_ATTRIBUTE_INFO EndDate; - extern const CSSM_DB_ATTRIBUTE_INFO Sensitive; - extern const CSSM_DB_ATTRIBUTE_INFO AlwaysSensitive; - extern const CSSM_DB_ATTRIBUTE_INFO Extractable; - extern const CSSM_DB_ATTRIBUTE_INFO NeverExtractable; - extern const CSSM_DB_ATTRIBUTE_INFO Encrypt; - extern const CSSM_DB_ATTRIBUTE_INFO Decrypt; - extern const CSSM_DB_ATTRIBUTE_INFO Derive; - extern const CSSM_DB_ATTRIBUTE_INFO Sign; - extern const CSSM_DB_ATTRIBUTE_INFO Verify; - extern const CSSM_DB_ATTRIBUTE_INFO SignRecover; - extern const CSSM_DB_ATTRIBUTE_INFO VerifyRecover; - extern const CSSM_DB_ATTRIBUTE_INFO Wrap; - extern const CSSM_DB_ATTRIBUTE_INFO Unwrap; - - extern const CSSM_DB_SCHEMA_ATTRIBUTE_INFO KeySchemaAttributeList[]; - extern const CSSM_DB_SCHEMA_INDEX_INFO KeySchemaIndexList[]; - extern const uint32 KeySchemaAttributeCount; - extern const uint32 KeySchemaIndexCount; -}; - - -#endif // _H_KEYSCHEMA diff --git a/OSX/include/security_cdsa_utilities/KeySchema.m4 b/OSX/include/security_cdsa_utilities/KeySchema.m4 deleted file mode 100644 index cbbe75ea..00000000 --- a/OSX/include/security_cdsa_utilities/KeySchema.m4 +++ /dev/null @@ -1,129 +0,0 @@ -divert(-1) -changecom(/*, */) -/* - * Copyright (c) 2000-2002 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - -define(`startClass', -`define(`indexIndex', 0)dnl -define(`class', $1)dnl -divert(2)dnl -// $1 attributes -const CSSM_DB_SCHEMA_ATTRIBUTE_INFO $1SchemaAttributeList[] = -{ -divert(3)dnl -// $1 indices -const CSSM_DB_SCHEMA_INDEX_INFO $1SchemaIndexList[] = -{') - -define(`endClass', -`divert(2)dnl -}; - -const uint32 class()SchemaAttributeCount = sizeof(class()SchemaAttributeList) / sizeof(CSSM_DB_SCHEMA_ATTRIBUTE_INFO); - -divert(3)dnl -` // Unique (primary) index' -undivert(5) -` // Secondary indices' -undivert(6)dnl -}; - -const uint32 class()SchemaIndexCount = sizeof(class()SchemaIndexList) / sizeof(CSSM_DB_SCHEMA_INDEX_INFO); - -undivert(4)dnl -divert(0)dnl -undivert(1)dnl -undivert(2)dnl -undivert(3)dnl') - -define(`attributeBody', -`{ -ifelse(index(`$1',`s'),-1, -` CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER, - {(char *)((uint64_t)$3<<32|$3)},', -` CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {$4},') - CSSM_DB_ATTRIBUTE_FORMAT_$7 -}') - -define(`simpleAttribute', -`const CSSM_DB_ATTRIBUTE_INFO $2 = -attributeBody($*); -') - -define(`attribute', -`divert(2)dnl - { $3, (char*) $4, { $5, $6 }, CSSM_DB_ATTRIBUTE_FORMAT_$7 }, -divert(-1) -ifelse(index(`$1',`S'),-1,`', -`divert(4)dnl -simpleAttribute($*) -divert(-1)')dnl - -ifelse(index(`$1',`U'),-1,`', -`divert(5)dnl - { $3, 0, CSSM_DB_INDEX_UNIQUE, CSSM_DB_INDEX_ON_ATTRIBUTE }, -divert(-1)')dnl -ifelse(index(`$1',`I'),-1,`', -`define(`indexIndex', incr(indexIndex))dnl -divert(6)dnl - { $3, indexIndex(), CSSM_DB_INDEX_NONUNIQUE, CSSM_DB_INDEX_ON_ATTRIBUTE }, -divert(-1)')') - -/* Start of actual output */ -divert(0)dnl -/* - * Generated by m4 from KeySchema.m4 please do not edit this file. - */ - -`#include ' -#include - -namespace KeySchema { - -divert(-1) -startClass(Key) -attribute(` Ss', KeyClass, kSecKeyKeyClass, (char*) "KeyClass", 0, NULL, UINT32) -attribute(` Ss', PrintName, kSecKeyPrintName, (char*) "PrintName", 0, NULL, BLOB) -attribute(` Ss', Alias, kSecKeyAlias, (char*) "Alias", 0, NULL, BLOB) -attribute(` Ss', Permanent, kSecKeyPermanent, (char*) "Permanent", 0, NULL, UINT32) -attribute(` Ss', Private, kSecKeyPrivate, (char*) "Private", 0, NULL, UINT32) -attribute(` Ss', Modifiable, kSecKeyModifiable, (char*) "Modifiable", 0, NULL, UINT32) -attribute(`UISs', Label, kSecKeyLabel, (char*) "Label", 0, NULL, BLOB) -attribute(`U Ss', ApplicationTag, kSecKeyApplicationTag, (char*) "ApplicationTag", 0, NULL, BLOB) -attribute(`U Ss', KeyCreator, kSecKeyKeyCreator, (char*) "KeyCreator", 0, NULL, BLOB) -attribute(`U Ss', KeyType, kSecKeyKeyType, (char*) "KeyType", 0, NULL, UINT32) -attribute(`U Ss', KeySizeInBits, kSecKeyKeySizeInBits, (char*) "KeySizeInBits", 0, NULL, UINT32) -attribute(`U Ss', EffectiveKeySize, kSecKeyEffectiveKeySize, (char*) "EffectiveKeySize", 0, NULL, UINT32) -attribute(`U Ss', StartDate, kSecKeyStartDate, (char*) "StartDate", 0, NULL, BLOB) -attribute(`U Ss', EndDate, kSecKeyEndDate, (char*) "EndDate", 0, NULL, BLOB) -attribute(` Ss', Sensitive, kSecKeySensitive, (char*) "Sensitive", 0, NULL, UINT32) -attribute(` Ss', AlwaysSensitive, kSecKeyAlwaysSensitive, (char*) "AlwaysSensitive", 0, NULL, UINT32) -attribute(` Ss', Extractable, kSecKeyExtractable, (char*) "Extractable", 0, NULL, UINT32) -attribute(` Ss', NeverExtractable, kSecKeyNeverExtractable, (char*) "NeverExtractable", 0, NULL, UINT32) -attribute(` ISs', Encrypt, kSecKeyEncrypt, (char*) "Encrypt", 0, NULL, UINT32) -attribute(` ISs', Decrypt, kSecKeyDecrypt, (char*) "Decrypt", 0, NULL, UINT32) -attribute(` ISs', Derive, kSecKeyDerive, (char*) "Derive", 0, NULL, UINT32) -attribute(` ISs', Sign, kSecKeySign, (char*) "Sign", 0, NULL, UINT32) -attribute(` ISs', Verify, kSecKeyVerify, (char*) "Verify", 0, NULL, UINT32) -attribute(` ISs', SignRecover, kSecKeySignRecover, (char*) "SignRecover", 0, NULL, UINT32) -attribute(` ISs', VerifyRecover, kSecKeyVerifyRecover, (char*) "VerifyRecover", 0, NULL, UINT32) -attribute(` ISs', Wrap, kSecKeyWrap, (char*) "Wrap", 0, NULL, UINT32) -attribute(` ISs', Unwrap, kSecKeyUnwrap, (char*) "Unwrap", 0, NULL, UINT32) -endClass() - -} // end namespace KeySchema diff --git a/OSX/include/security_cdsa_utilities/Schema.h b/OSX/include/security_cdsa_utilities/Schema.h deleted file mode 100644 index 69fd626f..00000000 --- a/OSX/include/security_cdsa_utilities/Schema.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Schema.h -// -#ifndef _SECURITY_SCHEMA_H_ -#define _SECURITY_SCHEMA_H_ - -#include - -namespace Security { - -namespace KeychainCore { - -namespace Schema { - -CSSM_DB_RECORDTYPE recordTypeFor(SecItemClass itemClass); -SecItemClass itemClassFor(CSSM_DB_RECORDTYPE recordType); -const CSSM_DB_ATTRIBUTE_INFO &attributeInfo(SecKeychainAttrType attrType); - -extern const CSSM_DB_ATTRIBUTE_INFO RelationID; -extern const CSSM_DB_ATTRIBUTE_INFO RelationName; -extern const CSSM_DB_ATTRIBUTE_INFO AttributeID; -extern const CSSM_DB_ATTRIBUTE_INFO AttributeNameFormat; -extern const CSSM_DB_ATTRIBUTE_INFO AttributeName; -extern const CSSM_DB_ATTRIBUTE_INFO AttributeNameID; -extern const CSSM_DB_ATTRIBUTE_INFO AttributeFormat; -extern const CSSM_DB_ATTRIBUTE_INFO IndexType; - -extern const CSSM_DBINFO DBInfo; - -// Certificate attributes and schema -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateCertType; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateCertEncoding; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificatePrintName; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateAlias; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateSubject; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateIssuer; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateSerialNumber; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificateSubjectKeyIdentifier; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CertificatePublicKeyHash; - -extern const CSSM_DB_SCHEMA_ATTRIBUTE_INFO X509CertificateSchemaAttributeList[]; -extern const CSSM_DB_SCHEMA_INDEX_INFO X509CertificateSchemaIndexList[]; -extern const uint32 X509CertificateSchemaAttributeCount; -extern const uint32 X509CertificateSchemaIndexCount; - -// CRL attributes and schema -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlCrlType; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlCrlEncoding; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlPrintName; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlAlias; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlIssuer; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlSerialNumber; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlThisUpdate; -extern const CSSM_DB_ATTRIBUTE_INFO kX509CrlNextUpdate; - -extern const CSSM_DB_SCHEMA_ATTRIBUTE_INFO X509CrlSchemaAttributeList[]; -extern const CSSM_DB_SCHEMA_INDEX_INFO X509CrlSchemaIndexList[]; -extern const uint32 X509CrlSchemaAttributeCount; -extern const uint32 X509CrlSchemaIndexCount; - -// UserTrust records attributes and schema -extern const CSSM_DB_ATTRIBUTE_INFO kUserTrustTrustedCertificate; -extern const CSSM_DB_ATTRIBUTE_INFO kUserTrustTrustedPolicy; - -extern const CSSM_DB_SCHEMA_ATTRIBUTE_INFO UserTrustSchemaAttributeList[]; -extern const CSSM_DB_SCHEMA_INDEX_INFO UserTrustSchemaIndexList[]; -extern const uint32 UserTrustSchemaAttributeCount; -extern const uint32 UserTrustSchemaIndexCount; - -// UnlockReferral records attributes and schema -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralType; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralDbName; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralDbGuid; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralDbSSID; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralDbSSType; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralDbNetname; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralKeyLabel; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralKeyAppTag; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralPrintName; -extern const CSSM_DB_ATTRIBUTE_INFO kUnlockReferralAlias; - -extern const CSSM_DB_SCHEMA_ATTRIBUTE_INFO UnlockReferralSchemaAttributeList[]; -extern const CSSM_DB_SCHEMA_INDEX_INFO UnlockReferralSchemaIndexList[]; -extern const uint32 UnlockReferralSchemaAttributeCount; -extern const uint32 UnlockReferralSchemaIndexCount; - -// Extended Attribute record attributes and schema -extern const CSSM_DB_ATTRIBUTE_INFO kExtendedAttributeRecordType; -extern const CSSM_DB_ATTRIBUTE_INFO kExtendedAttributeItemID; -extern const CSSM_DB_ATTRIBUTE_INFO kExtendedAttributeAttributeName; -extern const CSSM_DB_ATTRIBUTE_INFO kExtendedAttributeModDate; -extern const CSSM_DB_ATTRIBUTE_INFO kExtendedAttributeAttributeValue; - -extern const CSSM_DB_SCHEMA_ATTRIBUTE_INFO ExtendedAttributeSchemaAttributeList[]; -extern const CSSM_DB_SCHEMA_INDEX_INFO ExtendedAttributeSchemaIndexList[]; -extern const uint32 ExtendedAttributeSchemaAttributeCount; -extern const uint32 ExtendedAttributeSchemaIndexCount; - -} // end namespace Schema - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_SCHEMA_H_ diff --git a/OSX/include/security_cdsa_utilities/Schema.m4 b/OSX/include/security_cdsa_utilities/Schema.m4 deleted file mode 100644 index 5bc9248f..00000000 --- a/OSX/include/security_cdsa_utilities/Schema.m4 +++ /dev/null @@ -1,471 +0,0 @@ -divert(-1) -changecom(/*, */) -/* - * Copyright (c) 2000-2002 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - -define(`startClass', -`define(`arrayIndex', 0)dnl -define(`class', $1)dnl -divert(0)dnl -// $1 password attributes -static const CSSM_DB_ATTRIBUTE_INFO $1Attributes[] = -{ -divert(1)dnl -// $1 password indices -static const CSSM_DB_INDEX_INFO $1Indices[] = -{') - -define(`endClass', -`divert(0)dnl -}; - -divert(1)dnl -` // Unique (primary) index' -undivert(3) -` // Secondary indices' -undivert(4)dnl -}; - -divert(-1)') - -define(`attributeBody', -` { -ifelse(index(`$1',`s'),-1, -` CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER, - {(char *)((uint64_t)$3<<32|$3)},', -` CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {$4},') - CSSM_DB_ATTRIBUTE_FORMAT_$7 - }') - -define(`simpleAttribute', -`const CSSM_DB_ATTRIBUTE_INFO $2 = -attributeBody($*); -') - -define(`attribute', -`ifelse(index(`$1',`U'),-1,`', -`divert(3)dnl - { - CSSM_DB_INDEX_UNIQUE, - CSSM_DB_INDEX_ON_ATTRIBUTE, -attributeBody($*) - }, -')dnl -ifelse(index(`$1',`I'),-1,`', -`divert(4)dnl - { - CSSM_DB_INDEX_NONUNIQUE, - CSSM_DB_INDEX_ON_ATTRIBUTE, -attributeBody($*) - }, -')dnl -divert(2)dnl -dnl const CSSM_DB_ATTRIBUTE_INFO &`k'class()$2 = class()Attributes[arrayIndex()]; -`#define k'class()$2 class()Attributes[arrayIndex()]; -divert(0)dnl -attributeBody($*),dnl -define(`arrayIndex', incr(arrayIndex))dnl -') - -define(`attrInfo', -`{ - $1, - sizeof($2Attributes) / sizeof(CSSM_DB_ATTRIBUTE_INFO), - const_cast($2Attributes) - }') - -define(`indexInfo', -`{ - $1, - sizeof($2Indices) / sizeof(CSSM_DB_INDEX_INFO), - const_cast($2Indices) - }') - -define(`parseInfo', -`{ - CSSM_DB_RECORDTYPE_APP_DEFINED_START, - { - {0,0,0,{0}}, - {0,0}, - 0, - 0 - } - }') - -define(`startNewClass', -`define(`indexIndex', 0)dnl -define(`class', $1)dnl -divert(2)dnl -// $1 attributes -const CSSM_DB_SCHEMA_ATTRIBUTE_INFO $1SchemaAttributeList[] = -{ -divert(3)dnl -// $1 indices -const CSSM_DB_SCHEMA_INDEX_INFO $1SchemaIndexList[] = -{') - -define(`endNewClass', -`divert(2)dnl -}; - -const uint32 class()SchemaAttributeCount = sizeof(class()SchemaAttributeList) / sizeof(CSSM_DB_SCHEMA_ATTRIBUTE_INFO); - -divert(3)dnl -` // Unique (primary) index' -undivert(5) -` // Secondary indices' -undivert(6)dnl -}; - -const uint32 class()SchemaIndexCount = sizeof(class()SchemaIndexList) / sizeof(CSSM_DB_SCHEMA_INDEX_INFO); - -undivert(4)dnl -divert(0)dnl -undivert(2)dnl -undivert(3)dnl') - -define(`newAttributeBody', -`{ -ifelse(index(`$1',`s'),-1, -` CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER, - {(char *)((uint64_t)$3<<32|$3)},', -` CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {$4},') - CSSM_DB_ATTRIBUTE_FORMAT_$7 -}') - -define(`simpleNewAttribute', -`const CSSM_DB_ATTRIBUTE_INFO `k'class()$2 = -newAttributeBody($*); -') - -define(`newAttribute', -`divert(2)dnl - { $3, $4, { $5, $6 }, CSSM_DB_ATTRIBUTE_FORMAT_$7 }, -divert(-1) -ifelse(index(`$1',`S'),-1,`', -`divert(4)dnl -simpleNewAttribute($*) -divert(-1)')dnl - -ifelse(index(`$1',`U'),-1,`', -`divert(5)dnl - { $3, 0, CSSM_DB_INDEX_UNIQUE, CSSM_DB_INDEX_ON_ATTRIBUTE }, -divert(-1)')dnl -ifelse(index(`$1',`I'),-1,`', -`define(`indexIndex', incr(indexIndex))dnl -divert(6)dnl - { $3, indexIndex(), CSSM_DB_INDEX_NONUNIQUE, CSSM_DB_INDEX_ON_ATTRIBUTE }, -divert(-1)')') - -/* Start of actual output */ -divert(0)dnl -/* - * Generated by m4 from Schema.m4 please do not edit this file. - */ - -`#include ' - -`#include ' -`#include ' -`#include ' -`#include ' -`#include ' - -`#pragma clang diagnostic push' -`#pragma clang diagnostic ignored "-Wunused-const-variable"' - -namespace Security { - -namespace KeychainCore { - -namespace Schema { - -// Meta attributes -simpleAttribute(` s', RelationID, 0, (char*) "RelationID", 0, NULL, UINT32) -simpleAttribute(` s', RelationName, 1, (char*) "RelationName", 0, NULL, STRING) -simpleAttribute(` s', AttributeID, 1, (char*) "AttributeID", 0, NULL, UINT32) -simpleAttribute(` s', AttributeNameFormat, 2, (char*) "AttributeNameFormat", 0, NULL, UINT32) -simpleAttribute(` s', AttributeName, 3, (char*) "AttributeName", 0, NULL, STRING) -simpleAttribute(` s', AttributeNameID, 4, (char*) "AttributeNameID", 0, NULL, BLOB) -simpleAttribute(` s', AttributeFormat, 5, (char*) "AttributeFormat", 0, NULL, UINT32) -simpleAttribute(` s', IndexType, 3, (char*) "IndexType", 0, NULL, UINT32) - -divert(-1) -startClass(Generic) -attribute(` i', CreationDate, kSecCreationDateItemAttr, (char*) "CreationDate", 0, NULL, TIME_DATE) -attribute(` i', ModDate, kSecModDateItemAttr, (char*) "ModDate", 0, NULL, TIME_DATE) -attribute(` i', Description, kSecDescriptionItemAttr, (char*) "Description", 0, NULL, BLOB) -attribute(` i', Comment, kSecCommentItemAttr, (char*) "Comment", 0, NULL, BLOB) -attribute(` i', Creator, kSecCreatorItemAttr, (char*) "Creator", 0, NULL, UINT32) -attribute(` i', Type, kSecTypeItemAttr, (char*) "Type", 0, NULL, UINT32) -attribute(` i', ScriptCode, kSecScriptCodeItemAttr, (char*) "ScriptCode", 0, NULL, SINT32) -attribute(` s', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -attribute(` s', Alias, kSecAlias, (char*) "Alias", 0, NULL, BLOB) -attribute(` i', Invisible, kSecInvisibleItemAttr, (char*) "Invisible", 0, NULL, SINT32) -attribute(` i', Negative, kSecNegativeItemAttr, (char*) "Negative", 0, NULL, SINT32) -attribute(` i', CustomIcon, kSecCustomIconItemAttr, (char*) "CustomIcon", 0, NULL, SINT32) -attribute(` i', Protected, kSecProtectedDataItemAttr, (char*) "Protected", 0, NULL, BLOB) -attribute(`UIi', Account, kSecAccountItemAttr, (char*) "Account", 0, NULL, BLOB) -attribute(`UIi', Service, kSecServiceItemAttr, (char*) "Service", 0, NULL, BLOB) -attribute(` i', Generic, kSecGenericItemAttr, (char*) "Generic", 0, NULL, BLOB) -endClass() - -startClass(Appleshare) -attribute(` i', CreationDate, kSecCreationDateItemAttr, (char*) "CreationDate", 0, NULL, TIME_DATE) -attribute(` i', ModDate, kSecModDateItemAttr, (char*) "ModDate", 0, NULL, TIME_DATE) -attribute(` i', Description, kSecDescriptionItemAttr, (char*) "Description", 0, NULL, BLOB) -attribute(` i', Comment, kSecCommentItemAttr, (char*) "Comment", 0, NULL, BLOB) -attribute(` i', Creator, kSecCreatorItemAttr, (char*) "Creator", 0, NULL, UINT32) -attribute(` i', Type, kSecTypeItemAttr, (char*) "Type", 0, NULL, UINT32) -attribute(` i', ScriptCode, kSecScriptCodeItemAttr, (char*) "ScriptCode", 0, NULL, SINT32) -attribute(` s', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -attribute(` s', Alias, kSecAlias, (char*) "Alias", 0, NULL, BLOB) -attribute(` i', Invisible, kSecInvisibleItemAttr, (char*) "Invisible", 0, NULL, SINT32) -attribute(` i', Negative, kSecNegativeItemAttr, (char*) "Negative", 0, NULL, SINT32) -attribute(` i', CustomIcon, kSecCustomIconItemAttr, (char*) "CustomIcon", 0, NULL, SINT32) -attribute(` i', Protected, kSecProtectedDataItemAttr, (char*) "Protected", 0, NULL, BLOB) -attribute(`UIi', Account, kSecAccountItemAttr, (char*) "Account", 0, NULL, BLOB) -attribute(`UIi', Volume, kSecVolumeItemAttr, (char*) "Volume", 0, NULL, BLOB) -attribute(` i', Server, kSecServerItemAttr, (char*) "Server", 0, NULL, BLOB) -attribute(` i', Protocol, kSecProtocolItemAttr, (char*) "Protocol", 0, NULL, UINT32) -attribute(`UIi', Address, kSecAddressItemAttr, (char*) "Address", 0, NULL, BLOB) -attribute(`UIi', Signature, kSecSignatureItemAttr, (char*) "Signature", 0, NULL, BLOB) -endClass() - -startClass(Internet) -attribute(` i', CreationDate, kSecCreationDateItemAttr, (char*) "CreationDate", 0, NULL, TIME_DATE) -attribute(` i', ModDate, kSecModDateItemAttr, (char*) "ModDate", 0, NULL, TIME_DATE) -attribute(` i', Description, kSecDescriptionItemAttr, (char*) "Description", 0, NULL, BLOB) -attribute(` i', Comment, kSecCommentItemAttr, (char*) "Comment", 0, NULL, BLOB) -attribute(` i', Creator, kSecCreatorItemAttr, (char*) "Creator", 0, NULL, UINT32) -attribute(` i', Type, kSecTypeItemAttr, (char*) "Type", 0, NULL, UINT32) -attribute(` i', ScriptCode, kSecScriptCodeItemAttr, (char*) "ScriptCode", 0, NULL, SINT32) -attribute(` s', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -attribute(` s', Alias, kSecAlias, (char*) "Alias", 0, NULL, BLOB) -attribute(` i', Invisible, kSecInvisibleItemAttr, (char*) "Invisible", 0, NULL, SINT32) -attribute(` i', Negative, kSecNegativeItemAttr, (char*) "Negative", 0, NULL, SINT32) -attribute(` i', CustomIcon, kSecCustomIconItemAttr, (char*) "CustomIcon", 0, NULL, SINT32) -attribute(` i', Protected, kSecProtectedDataItemAttr, (char*) "Protected", 0, NULL, BLOB) -attribute(`UIi', Account, kSecAccountItemAttr, (char*) "Account", 0, NULL, BLOB) -attribute(`UIi', SecurityDomain, kSecSecurityDomainItemAttr, (char*) "SecurityDomain", 0, NULL, BLOB) -attribute(`UIi', Server, kSecServerItemAttr, (char*) "Server", 0, NULL, BLOB) -attribute(`UIi', Protocol, kSecProtocolItemAttr, (char*) "Protocol", 0, NULL, UINT32) -attribute(`UIi', AuthType, kSecAuthenticationTypeItemAttr, (char*) "AuthType", 0, NULL, BLOB) -attribute(`UIi', Port, kSecPortItemAttr, (char*) "Port", 0, NULL, UINT32) -attribute(`UIi', Path, kSecPathItemAttr, (char*) "Path", 0, NULL, BLOB) -endClass() - -startNewClass(X509Certificate) -newAttribute(`UISs', CertType, kSecCertTypeItemAttr, (char*) "CertType", 0, NULL, UINT32) -newAttribute(` Ss', CertEncoding, kSecCertEncodingItemAttr, (char*) "CertEncoding", 0, NULL, UINT32) -newAttribute(` Ss', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -newAttribute(` ISs', Alias, kSecAlias, (char*) "Alias", 0, NULL, BLOB) -newAttribute(` ISs', Subject, kSecSubjectItemAttr, (char*) "Subject", 0, NULL, BLOB) -newAttribute(`UISs', Issuer, kSecIssuerItemAttr, (char*) "Issuer", 0, NULL, BLOB) -newAttribute(`UISs', SerialNumber, kSecSerialNumberItemAttr, (char*) "SerialNumber", 0, NULL, BLOB) -newAttribute(` ISs', SubjectKeyIdentifier, kSecSubjectKeyIdentifierItemAttr, (char*) "SubjectKeyIdentifier", 0, NULL, BLOB) -newAttribute(` ISs', PublicKeyHash, kSecPublicKeyHashItemAttr, (char*) "PublicKeyHash", 0, NULL, BLOB) -endNewClass() - -startNewClass(X509Crl) -newAttribute(`UISs', CrlType, kSecCrlType, (char*) "CrlType", 0, NULL, UINT32) -newAttribute(` Ss', CrlEncoding, kSecCrlEncodingItemAttr, (char*) "CrlEncoding", 0, NULL, UINT32) -newAttribute(` Ss', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -newAttribute(` Ss', Alias, kSecAlias, (char*) "Alias", 0, NULL, BLOB) -newAttribute(`UISs', Issuer, kSecIssuerItemAttr, (char*) "Issuer", 0, NULL, BLOB) -newAttribute(`UISs', ThisUpdate, kSecThisUpdateItemAttr, (char*) "ThisUpdate", 0, NULL, BLOB) -newAttribute(`UISs', NextUpdate, kSecNextUpdateItemAttr, (char*) "NextUpdate", 0, NULL, BLOB) -newAttribute(` Ss', URI, kSecUriItemAttr, (char*) "URI", 0, NULL, BLOB) -newAttribute(` ISs', CrlNumber, kSecCrlNumberItemAttr, (char*) "CrlNumber", 0, NULL, UINT32) -newAttribute(` ISs', DeltaCrlNumber, kSecDeltaCrlNumberItemAttr, (char*) "DeltaCrlNumber", 0, NULL, UINT32) -endNewClass() - -startNewClass(UserTrust) -newAttribute(`UISs', TrustedCertificate, kSecTrustCertAttr, (char*) "TrustedCertificate", 0, NULL, BLOB) -newAttribute(`UISs', TrustedPolicy, kSecTrustPolicyAttr, (char*) "TrustedPolicy", 0, NULL, BLOB) -newAttribute(` Ss', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -endNewClass() - -startNewClass(UnlockReferral) -newAttribute(`UISs', Type, kSecReferralTypeAttr, (char*) "Type", 0, NULL, UINT32) -newAttribute(`UISs', DbName, kSecReferralDbNameAttr, (char*) "DbName", 0, NULL, STRING) -newAttribute(`UISs', DbNetname, kSecReferralDbNetnameAttr, (char*) "DbNetname", 0, NULL, BLOB) -newAttribute(`UISs', DbGuid, kSecReferralDbGuidAttr, (char*) "DbGuid", 0, NULL, BLOB) -newAttribute(`UISs', DbSSID, kSecReferralDbSSIDAttr, (char*) "DbSSID", 0, NULL, UINT32) -newAttribute(`UISs', DbSSType, kSecReferralDbSSTypeAttr, (char*) "DbSSType", 0, NULL, UINT32) -newAttribute(` ISs', KeyLabel, kSecReferralKeyLabelAttr, (char*) "KeyLabel", 0, NULL, BLOB) -newAttribute(` ISs', KeyAppTag, kSecReferralKeyAppTagAttr, (char*) "KeyAppTag", 0, NULL, BLOB) -newAttribute(` Ss', PrintName, kSecLabelItemAttr, (char*) "PrintName", 0, NULL, BLOB) -newAttribute(` Ss', Alias, kSecAlias, (char*) "Alias", 0, NULL, BLOB) -endNewClass() - -// Extended Attribute -startNewClass(ExtendedAttribute) -newAttribute(`UISs', RecordType, kExtendedAttrRecordTypeAttr, (char*) "RecordType", 0, NULL, UINT32) -newAttribute(`UISs', ItemID, kExtendedAttrItemIDAttr, (char*) "ItemID", 0, NULL, BLOB) -newAttribute(`UISs', AttributeName, kExtendedAttrAttributeNameAttr, (char*) "AttributeName", 0, NULL, BLOB) -newAttribute(` Ss', ModDate, kSecModDateItemAttr, (char*) "ModDate", 0, NULL, TIME_DATE) -newAttribute(` Ss', AttributeValue, kExtendedAttrAttributeValueAttr, (char*) "AttributeValue", 0, NULL, BLOB) -endNewClass() - -divert(3) -static const CSSM_DB_RECORD_ATTRIBUTE_INFO Attributes[] = -{ - attrInfo(CSSM_DL_DB_RECORD_GENERIC_PASSWORD, Generic), - attrInfo(CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD, Appleshare), - attrInfo(CSSM_DL_DB_RECORD_INTERNET_PASSWORD, Internet) -}; - -static const CSSM_DB_RECORD_INDEX_INFO Indices[] = -{ - indexInfo(CSSM_DL_DB_RECORD_GENERIC_PASSWORD, Generic), - indexInfo(CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD, Appleshare), - indexInfo(CSSM_DL_DB_RECORD_INTERNET_PASSWORD, Internet) -}; - -static const CSSM_DB_PARSING_MODULE_INFO ParseInfos[] = -{ - parseInfo(), - parseInfo(), - parseInfo() -}; - -// -// Public stuff -// -const CSSM_DBINFO DBInfo = -{ - sizeof(Attributes) / sizeof(CSSM_DB_RECORD_ATTRIBUTE_INFO), - const_cast(ParseInfos), - const_cast(Attributes), - const_cast(Indices), - CSSM_TRUE, - NULL, - NULL -}; - -// -// Schema methods -// -CSSM_DB_RECORDTYPE -recordTypeFor(SecItemClass itemClass) -{ - switch (itemClass) - { - case kSecGenericPasswordItemClass: return CSSM_DL_DB_RECORD_GENERIC_PASSWORD; - case kSecInternetPasswordItemClass: return CSSM_DL_DB_RECORD_INTERNET_PASSWORD; - case 'ashp': return CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD; - default: return CSSM_DB_RECORDTYPE(itemClass); - } -} - -SecItemClass -itemClassFor(CSSM_DB_RECORDTYPE recordType) -{ - switch (recordType) - { - case CSSM_DL_DB_RECORD_GENERIC_PASSWORD: return kSecGenericPasswordItemClass; - case CSSM_DL_DB_RECORD_INTERNET_PASSWORD: return kSecInternetPasswordItemClass; - case CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD: return 'ashp'; - default: return SecItemClass(recordType); - } -} - -const CSSM_DB_ATTRIBUTE_INFO & -attributeInfo(SecKeychainAttrType attrType) -{ - switch (attrType) - { - case kSecCreationDateItemAttr: return kGenericCreationDate; - case kSecModDateItemAttr: return kGenericModDate; - case kSecDescriptionItemAttr: return kGenericDescription; - case kSecCommentItemAttr: return kGenericComment; - case kSecCreatorItemAttr: return kGenericCreator; - case kSecTypeItemAttr: return kGenericType; - case kSecScriptCodeItemAttr: return kGenericScriptCode; - case kSecLabelItemAttr: return kGenericPrintName; - case kSecAlias: return kGenericAlias; - case kSecInvisibleItemAttr: return kGenericInvisible; - case kSecNegativeItemAttr: return kGenericNegative; - case kSecCustomIconItemAttr: return kGenericCustomIcon; - /* Unique Generic password attributes */ - case kSecAccountItemAttr: return kGenericAccount; - case kSecServiceItemAttr: return kGenericService; - case kSecGenericItemAttr: return kGenericGeneric; - /* Unique Appleshare password attributes */ - case kSecVolumeItemAttr: return kAppleshareVolume; - case kSecAddressItemAttr: return kAppleshareAddress; - case kSecSignatureItemAttr: return kAppleshareSignature; - /* Unique AppleShare and Internet attributes */ - case kSecServerItemAttr: return kAppleshareServer; - case kSecProtocolItemAttr: return kAppleshareProtocol; - /* Unique Internet password attributes */ - case kSecSecurityDomainItemAttr: return kInternetSecurityDomain; - case kSecAuthenticationTypeItemAttr: return kInternetAuthType; - case kSecPortItemAttr: return kInternetPort; - case kSecPathItemAttr: return kInternetPath; - /* Unique Certificate attributes */ - case kSecCertTypeItemAttr: return kX509CertificateCertType; - case kSecCertEncodingItemAttr: return kX509CertificateCertEncoding; - case kSecSubjectItemAttr: return kX509CertificateSubject; - case kSecIssuerItemAttr: return kX509CertificateIssuer; - case kSecSerialNumberItemAttr: return kX509CertificateSerialNumber; - case kSecSubjectKeyIdentifierItemAttr: return kX509CertificateSubjectKeyIdentifier; - case kSecPublicKeyHashItemAttr: return kX509CertificatePublicKeyHash; - /* Unique UserTrust attributes */ - case kSecTrustCertAttr: return kUserTrustTrustedCertificate; - case kSecTrustPolicyAttr: return kUserTrustTrustedPolicy; - /* Unique UnlockReferral attributes */ - case kSecReferralTypeAttr: return kUnlockReferralType; - case kSecReferralDbNameAttr: return kUnlockReferralDbName; - case kSecReferralDbGuidAttr: return kUnlockReferralDbGuid; - case kSecReferralDbSSIDAttr: return kUnlockReferralDbSSID; - case kSecReferralDbSSTypeAttr: return kUnlockReferralDbSSType; - case kSecReferralDbNetnameAttr: return kUnlockReferralDbNetname; - case kSecReferralKeyLabelAttr: return kUnlockReferralKeyLabel; - case kSecReferralKeyAppTagAttr: return kUnlockReferralKeyAppTag; - /* Unique ExtendedAttribute attributes */ - case kExtendedAttrRecordTypeAttr: return kExtendedAttributeRecordType; - case kExtendedAttrItemIDAttr: return kExtendedAttributeItemID; - case kExtendedAttrAttributeNameAttr: return kExtendedAttributeAttributeName; - case kExtendedAttrAttributeValueAttr: return kExtendedAttributeAttributeValue; - /* ??? */ - case kSecProtectedDataItemAttr: return kGenericProtected; - default: - { - if (attrType == 7) - { - return kGenericPrintName; - } - else if (attrType == 8) - { - return kGenericAlias; - } - MacOSError::throwMe(errSecNoSuchAttr); - } - } -} - -} // end namespace Schema - -} // end namespace KeychainCore - -} // end namespace Security - -`#pragma clang diagnostic pop' diff --git a/OSX/include/security_cdsa_utilities/acl_any.cpp b/OSX/include/security_cdsa_utilities/acl_any.cpp deleted file mode 100644 index 25f6a0e5..00000000 --- a/OSX/include/security_cdsa_utilities/acl_any.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_any - "anyone" ACL subject type. -// -#include -#include - - -// -// The ANY subject matches all credentials, including none at all. -// -bool AnyAclSubject::validate(const AclValidationContext &) const -{ - return true; -} - - -// -// The CSSM_LIST version is trivial. It has no private part to omit. -// -CssmList AnyAclSubject::toList(Allocator &alloc) const -{ - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_ANY); -} - - -// -// The subject form takes no arguments. -// -AnyAclSubject *AnyAclSubject::Maker::make(const TypedList &list) const -{ - crack(list, 0); // no arguments in input list - return new AnyAclSubject(); -} - -AnyAclSubject *AnyAclSubject::Maker::make(Version, Reader &, Reader &) const -{ - return new AnyAclSubject(); -} - diff --git a/OSX/include/security_cdsa_utilities/acl_any.h b/OSX/include/security_cdsa_utilities/acl_any.h deleted file mode 100644 index b985c872..00000000 --- a/OSX/include/security_cdsa_utilities/acl_any.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_any - "anyone" ACL subject type. -// -// This subject will categorically match everything and anything, even no -// credentials at all (a NULL AccessCredentials pointer). -// -#ifndef _ACL_ANY -#define _ACL_ANY - -#include -#include - -namespace Security { - - -// -// The ANY subject simply matches everything. No sweat. -// -class AnyAclSubject : public AclSubject { -public: - AnyAclSubject() : AclSubject(CSSM_ACL_SUBJECT_TYPE_ANY) { } - bool validate(const AclValidationContext &ctx) const; - CssmList toList(Allocator &alloc) const; - - class Maker : public AclSubject::Maker { - public: - Maker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_ANY) { } - AnyAclSubject *make(const TypedList &list) const; - AnyAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; -}; - -} // end namespace Security - - -#endif //_ACL_ANY diff --git a/OSX/include/security_cdsa_utilities/acl_codesigning.cpp b/OSX/include/security_cdsa_utilities/acl_codesigning.cpp deleted file mode 100644 index a848449f..00000000 --- a/OSX/include/security_cdsa_utilities/acl_codesigning.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_codesigning - ACL subject for signature of calling application -// -#include -#include -#include -#include - - -// -// Code signature credentials are validated globally - they are entirely -// a feature of "the" process (defined by the environment), and take no -// samples whatsoever. -// -bool CodeSignatureAclSubject::validate(const AclValidationContext &context) const -{ - // a suitable environment is required for a match - if (Environment *env = context.environment()) - return env->verifyCodeSignature(*this, context); - else - return false; -} - - -// -// Make a copy of this subject in CSSM_LIST form. -// The format is (head), (type code: Wordid), (signature data: datum), (comment: datum) -// -CssmList CodeSignatureAclSubject::toList(Allocator &alloc) const -{ - assert(path().find('\0') == string::npos); // no embedded nulls in path - uint32_t type = CSSM_ACL_CODE_SIGNATURE_OSX; - TypedList list(alloc, CSSM_ACL_SUBJECT_TYPE_CODE_SIGNATURE, - new(alloc) ListElement(type), - new(alloc) ListElement(alloc, CssmData::wrap(legacyHash(), SHA1::digestLength)), - new(alloc) ListElement(alloc, CssmData::wrap(path().c_str(), path().size() + 1))); - if (requirement()) { - CFRef reqData; - MacOSError::check(SecRequirementCopyData(requirement(), kSecCSDefaultFlags, &reqData.aref())); - list += new(alloc) ListElement(alloc, - CssmData::wrap(CFDataGetBytePtr(reqData), CFDataGetLength(reqData))); - } - for (AuxMap::const_iterator it = beginAux(); it != endAux(); it++) - list += new(alloc) ListElement(alloc, CssmData(*it->second)); - return list; -} - - -// -// Create a CodeSignatureAclSubject -// -CodeSignatureAclSubject *CodeSignatureAclSubject::Maker::make(const TypedList &list) const -{ - // there once was a format with only a hash (length 2+1). It is no longer supported - unsigned total = list.length(); // includes subject type header - if (total >= 3 + 1 - && list[1].is(CSSM_LIST_ELEMENT_WORDID) // [1] == signature type - && list[1] == CSSM_ACL_CODE_SIGNATURE_OSX - && list[2].is(CSSM_LIST_ELEMENT_DATUM) // [2] == legacy hash - && list[2].data().length() == SHA1::digestLength - && list[3].is(CSSM_LIST_ELEMENT_DATUM)) { - // structurally okay - CodeSignatureAclSubject *subj = - new CodeSignatureAclSubject(list[2].data().interpretedAs(), - list[3].data().interpretedAs()); - for (unsigned n = 3 + 1; n < total; n++) { - if (list[n].is(CSSM_LIST_ELEMENT_DATUM)) { - const BlobCore *blob = list[n].data().interpretedAs(); - if (blob->length() < sizeof(BlobCore)) { - secdebug("csblob", "runt blob (0x%x/%zd) slot %d in CSSM_LIST", - blob->magic(), blob->length(), n); - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - } else if (blob->length() != list[n].data().length()) { - secdebug("csblob", "badly sized blob (0x%x/%zd) slot %d in CSSM_LIST", - blob->magic(), blob->length(), n); - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - } - subj->add(blob); - } else - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - } - return subj; - } else - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); -} - -CodeSignatureAclSubject *CodeSignatureAclSubject::Maker::make(Version version, - Reader &pub, Reader &priv) const -{ - assert(version == 0); - Endian sigType; pub(sigType); - const void *data; size_t length; pub.countedData(data, length); - const void *commentData; size_t commentLength; pub.countedData(commentData, commentLength); - if (sigType == CSSM_ACL_CODE_SIGNATURE_OSX - && length == SHA1::digestLength) { - return make((const SHA1::Byte *)data, CssmData::wrap(commentData, commentLength)); - } - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); -} - -CodeSignatureAclSubject *CodeSignatureAclSubject::Maker::make(const SHA1::Byte *hash, - const CssmData &commentBag) const -{ - using namespace LowLevelMemoryUtilities; - const char *path = commentBag.interpretedAs(); - CodeSignatureAclSubject *subj = new CodeSignatureAclSubject(hash, path); - for (const BlobCore *blob = increment(commentBag.data(), alignUp(strlen(path) + 1, commentBagAlignment)); - blob < commentBag.end(); - blob = increment(blob, alignUp(blob->length(), commentBagAlignment))) { - size_t leftInBag = difference(commentBag.end(), blob); - if (leftInBag < sizeof(BlobCore) || blob->length() < sizeof(BlobCore) || blob->length() > leftInBag) { - secdebug("csblob", "invalid blob (0x%x/%zd) [%zd in bag] in code signing ACL for %s - stopping scan", - blob->magic(), blob->length(), leftInBag, subj->path().c_str()); - break; // can't trust anything beyond this blob - } - subj->add(blob); - } - return subj; -} - - -// -// Export the subject to a memory blob -// -void CodeSignatureAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - using LowLevelMemoryUtilities::alignUp; - assert(path().find('\0') == string::npos); // no embedded nulls in path - Endian sigType = CSSM_ACL_CODE_SIGNATURE_OSX; pub(sigType); - pub.countedData(legacyHash(), SHA1::digestLength); - size_t size = path().size() + 1; - if (requirement()) { - CFRef reqData; - MacOSError::check(SecRequirementCopyData(requirement(), kSecCSDefaultFlags, &reqData.aref())); - size = alignUp(size, commentBagAlignment) + CFDataGetLength(reqData); - } - for (AuxMap::const_iterator it = beginAux(); it != endAux(); it++) { - size = alignUp(size, commentBagAlignment) + it->second->length(); - } - pub.countedData(NULL, size); -} - -void CodeSignatureAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - using LowLevelMemoryUtilities::alignUp; - Endian sigType = CSSM_ACL_CODE_SIGNATURE_OSX; pub(sigType); - pub.countedData(legacyHash(), SHA1::digestLength); - CssmAutoData commentBag(Allocator::standard(), path().c_str(), path().size() + 1); - static const uint32_t zero = 0; - if (requirement()) { - CFRef reqData; - MacOSError::check(SecRequirementCopyData(requirement(), kSecCSDefaultFlags, &reqData.aref())); - commentBag.append(&zero, - alignUp(commentBag.length(), commentBagAlignment) - commentBag.length()); - commentBag.append(CFDataGetBytePtr(reqData), CFDataGetLength(reqData)); - } - for (AuxMap::const_iterator it = beginAux(); it != endAux(); it++) { - commentBag.append(&zero, - alignUp(commentBag.length(), commentBagAlignment) - commentBag.length()); - commentBag.append(CssmData(*it->second)); - } - pub.countedData(commentBag); -} - - -#ifdef DEBUGDUMP - -void CodeSignatureAclSubject::debugDump() const -{ - Debug::dump("CodeSigning "); - OSXVerifier::dump(); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_codesigning.h b/OSX/include/security_cdsa_utilities/acl_codesigning.h deleted file mode 100644 index 2dc2b2b3..00000000 --- a/OSX/include/security_cdsa_utilities/acl_codesigning.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_codesigning - ACL subject for signature of calling application -// -// Note: -// Once upon a time, a code signature was a single binary blob, a "signature". -// Then we added an optional second blob, a "comment". The comment was only -// ancilliary (non-security) data first, but then we added more security data -// to it later. Now, the security-relevant data is kept in a (signature, comment) -// pair, all of which is relevant for the security of such subjects. -// Don't read any particular semantics into this separation. It is historical only -// (having to do with backward binary compatibility of ACL blobs). -// -#ifndef _H_ACL_CODESIGNING -#define _H_ACL_CODESIGNING - -#include -#include -#include - -namespace Security { - - -// -// The CodeSignature subject type matches a code signature applied to the -// disk image that originated the client process. -// -class CodeSignatureAclSubject : public AclSubject, public OSXVerifier { -public: - class Maker; friend class Maker; - - static const size_t commentBagAlignment = 4; - - CodeSignatureAclSubject(const SHA1::Byte *hash, const std::string &path) - : AclSubject(CSSM_ACL_SUBJECT_TYPE_CODE_SIGNATURE), OSXVerifier(hash, path) { } - - CodeSignatureAclSubject(const OSXVerifier &verifier) - : AclSubject(CSSM_ACL_SUBJECT_TYPE_CODE_SIGNATURE), OSXVerifier(verifier) { } - - bool validate(const AclValidationContext &baseCtx) const; - CssmList toList(Allocator &alloc) const; - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - -public: - class Environment : public virtual AclValidationEnvironment { - public: - virtual bool verifyCodeSignature(const OSXVerifier &verifier, - const AclValidationContext &context) = 0; - }; - -public: - class Maker : public AclSubject::Maker { - public: - Maker() - : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_CODE_SIGNATURE) { } - CodeSignatureAclSubject *make(const TypedList &list) const; - CodeSignatureAclSubject *make(Version version, Reader &pub, Reader &priv) const; - - private: - CodeSignatureAclSubject *make(const SHA1::Byte *hash, const CssmData &commentBag) const; - }; -}; - -} // end namespace Security - - - -#endif //_H_ACL_CODESIGNING diff --git a/OSX/include/security_cdsa_utilities/acl_comment.cpp b/OSX/include/security_cdsa_utilities/acl_comment.cpp deleted file mode 100644 index 8cf7501f..00000000 --- a/OSX/include/security_cdsa_utilities/acl_comment.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_comment - "ignore" ACL subject type. -// -// CommentAclSubjects were a bad idea, badly implemented. The code below -// exists solely to keep existing (external) ACL forms from blowing up the -// ACL reader machinery and crashing the evaluation host. -// The original serialization code was not architecture independent - for either -// pointer sizes(!) or byte ordering. Yes, that was a stupid mistake. -// The following code is intentionally, wilfully violating the layer separation -// of the ACL reader/writer machine to deduce enough information about the -// originating architecture to cleanly consume (just) the bytes making up this -// ACL's external representation. We make no use of the bytes read; thankfully, -// the semantics of a CommentAclSubject have always been "never matches." -// We do not preserve them on write-out; a newly-written ACL will contain no data -// (and will read cleanly). -// If you use this code as a template for anything (other than a how-not-to-write-code -// seminar), your backups shall rot right after your main harddrive crashes, and -// you have only yourself to blame. -// -#include -#include -#include -#include - -using namespace DataWalkers; - - -// -// The COMMENT subject matches nothing, no matter how pretty. -// -bool CommentAclSubject::validate(const AclValidationContext &) const -{ - return false; -} - - -// -// The list form has no values. -// -CssmList CommentAclSubject::toList(Allocator &alloc) const -{ - return TypedList(Allocator::standard(), CSSM_ACL_SUBJECT_TYPE_COMMENT); -} - - -// -// We completely disregard any data contained in CSSM form COMMENT ACLs. -// -CommentAclSubject *CommentAclSubject::Maker::make(const TypedList &list) const -{ - return new CommentAclSubject(); -} - - -// -// This is the nasty code. We don't really care what data was originally baked -// into this ACL's external (stream) form, but since there's no external framing -// to delimit it, we need to figure out how many bytes to consume to keep the -// reader from going out of sync. And that's not pretty, since the external form -// contains (stupidly!) a pointer, so we have all permutations of byte order and -// pointer size to worry about. -// -CommentAclSubject *CommentAclSubject::Maker::make(Version, Reader &pub, Reader &) const -{ - // - // At this point, the Reader is positioned at data that was once written using - // this code: - // pub(ptr); // yes, that's a pointer - // pub.countedData(ptr, size); - // We know ptr was a non-NULL pointer (4 or 8 bytes, alas). - // CountedData writes a 4-byte NBO length followed by that many bytes. - // The data written starts with a CSSM_LIST structure in native architecture. - // That in turn begins with a CSSM_LIST_TYPE (4 bytes, native, 0<=type<=2). - // So to summarize (h=host byte order, n=network byte order), we might be looking at: - // 32 bits: | P4h | L4n | T4h | (L-4 bytes) | - // 64 bits: | P8h | L4n | (L bytes) | - // It's the T4h-or-L4n bytes that save our day, since we know that - // 0 <= T <= 2 (definition of CSSM_LIST_TYPE) - // 16M > L >= sizeof(CSSM_LIST) >= 12 - // Phew. I'd rather be lucky than good... - // - // So let's get started: -#ifndef NDEBUG - static const size_t minCssmList = 12; // min(sizeof(CSSM_LIST)) of all architectures -#endif - pub.get(4); // skip first 4 bytes - uint32_t lop; pub(lop); // read L4n-or-(bottom of)P8h - uint32_t tol; pub(tol); // read T4h-or-L4n - if (tol <= 2 || flip(tol) <= 2) { // 32 bits - // the latter can't be a very big (flipped) L because we know 12 < L < 16M, - // and you'd have to be a multiple of 2^24 to pass that test - size_t length = n2h(lop); - assert(length >= minCssmList); - pub.get(length - sizeof(tol)); // skip L-4 bytes - } else { // 64 bits - size_t length = n2h(tol); - assert(length >= minCssmList); - pub.get(length); // skip L bytes - } - - // we've successfully thrown out the garbage. What's left is a data-less subject - return new CommentAclSubject(); // no data -} - - -// -// Export to blob form. -// This simply writes the smallest form consistent with the heuristic above. -// -void CommentAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &) -{ - uint32_t zero = 0; - Endian length = 12; - pub(zero); pub(length); pub(zero); pub(zero); pub(zero); -} - -void CommentAclSubject::exportBlob(Writer &pub, Writer &) -{ - uint32_t zero = 0; - Endian length = 12; - pub(zero); pub(length); pub(zero); pub(zero); pub(zero); -} - - -#ifdef DEBUGDUMP - -void CommentAclSubject::debugDump() const -{ - Debug::dump("Comment[never]"); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_comment.h b/OSX/include/security_cdsa_utilities/acl_comment.h deleted file mode 100644 index 98a90b92..00000000 --- a/OSX/include/security_cdsa_utilities/acl_comment.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_comment - "ignore" ACL subject type -// -// This ACL subject is a historical mistake. It has no use in present applications, -// and remains only to support existing keychains with their already-baked item ACLs. -// Do not use this for new applications of ANY kind. -// -// A CommentAclSubject always fails to verify. -// See further (mis-)usage comments in the .cpp. -// -#ifndef _ACL_COMMENT -#define _ACL_COMMENT - -#include - - -namespace Security -{ - -// -// The ANY subject simply matches everything. No sweat. -// -class CommentAclSubject : public AclSubject { -public: - CommentAclSubject() - : AclSubject(CSSM_ACL_SUBJECT_TYPE_COMMENT) { } - - bool validate(const AclValidationContext &ctx) const; - CssmList toList(Allocator &alloc) const; - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - class Maker : public AclSubject::Maker { - public: - Maker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_COMMENT) { } - CommentAclSubject *make(const TypedList &list) const; - CommentAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; - - IFDUMP(void debugDump() const); -}; - -} // end namespace Security - - -#endif //_ACL_COMMENT diff --git a/OSX/include/security_cdsa_utilities/acl_password.cpp b/OSX/include/security_cdsa_utilities/acl_password.cpp deleted file mode 100644 index 96801a94..00000000 --- a/OSX/include/security_cdsa_utilities/acl_password.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_password - password-based ACL subject types -// -#include -#include -#include -#include - - -// -// PasswordAclSubject always pre-loads its secret, and thus never has to -// "get" its secret. If we ever try, it's a bug. -// -bool PasswordAclSubject::getSecret(const AclValidationContext &context, - const TypedList &sample, CssmOwnedData &secret) const -{ - switch (sample.length()) { - case 1: - return false; // no password in sample - case 2: - secret = sample[1]; - return true; - default: - CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE); - } -} - - -// -// Make a copy of this subject in CSSM_LIST form -// -CssmList PasswordAclSubject::toList(Allocator &alloc) const -{ - // the password itself is private and not exported to CSSM - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_PASSWORD); -} - - -// -// Create a PasswordAclSubject -// -PasswordAclSubject *PasswordAclSubject::Maker::make(const TypedList &list) const -{ - Allocator &alloc = Allocator::standard(Allocator::sensitive); - switch (list.length()) { - case 1: - return new PasswordAclSubject(alloc, true); - case 2: - { - ListElement *password; - crack(list, 1, &password, CSSM_LIST_ELEMENT_DATUM); - return new PasswordAclSubject(alloc, password->data()); - } - default: - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - } -} - -PasswordAclSubject *PasswordAclSubject::Maker::make(Version, Reader &pub, Reader &priv) const -{ - Allocator &alloc = Allocator::standard(Allocator::sensitive); - const void *data; size_t length; priv.countedData(data, length); - CssmAutoData passwordData(alloc, data, length); - return new PasswordAclSubject(alloc, passwordData); -} - - -// -// Export the subject to a memory blob -// -void PasswordAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - priv.countedData(secret()); -} - -void PasswordAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - priv.countedData(secret()); -} - - -#ifdef DEBUGDUMP - -void PasswordAclSubject::debugDump() const -{ - Debug::dump("Password"); - SecretAclSubject::debugDump(); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_password.h b/OSX/include/security_cdsa_utilities/acl_password.h deleted file mode 100644 index 46c94b5c..00000000 --- a/OSX/include/security_cdsa_utilities/acl_password.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_password - password-based ACL subject types. -// -// This implements simple password-based subject types as per CSSM standard. -// -#ifndef _ACL_PASSWORD -#define _ACL_PASSWORD - -#include - - -namespace Security { - - -// -// A PasswordAclSubject simply contains its secret. -// The environment is never consulted; we just compare against our known secret. -// -class PasswordAclSubject : public SecretAclSubject { -public: - CssmList toList(Allocator &alloc) const; - - PasswordAclSubject(Allocator &alloc, const CssmData &password) - : SecretAclSubject(alloc, CSSM_ACL_SUBJECT_TYPE_PASSWORD, password) { } - PasswordAclSubject(Allocator &alloc, CssmManagedData &password) - : SecretAclSubject(alloc, CSSM_ACL_SUBJECT_TYPE_PASSWORD, password) { } - PasswordAclSubject(Allocator &alloc, bool cache) - : SecretAclSubject(alloc, CSSM_ACL_SUBJECT_TYPE_PASSWORD, cache) { } - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - -public: - class Maker : public SecretAclSubject::Maker { - public: - Maker() : SecretAclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_PASSWORD) { } - PasswordAclSubject *make(const TypedList &list) const; - PasswordAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; - -protected: - bool getSecret(const AclValidationContext &context, - const TypedList &subject, CssmOwnedData &secret) const; -}; - -} // end namespace Security - - -#endif //_ACL_PASSWORD diff --git a/OSX/include/security_cdsa_utilities/acl_preauth.cpp b/OSX/include/security_cdsa_utilities/acl_preauth.cpp deleted file mode 100644 index 121b2a27..00000000 --- a/OSX/include/security_cdsa_utilities/acl_preauth.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006-2007,2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_preauth - a subject type for modeling PINs and similar slot-specific -// pre-authentication schemes. -// -#include "acl_preauth.h" -#include - - -namespace Security { -namespace PreAuthorizationAcls { - - -// -// Origin forms -// -AclSubject *OriginMaker::make(const TypedList &list) const -{ - ListElement *args[1]; - crack(list, 1, args, CSSM_LIST_ELEMENT_WORDID); - return new OriginAclSubject(*args[0]); -} - -AclSubject *OriginMaker::make(AclSubject::Version version, Reader &pub, Reader &) const -{ - // just an integer containing the auth tag - Endian auth; - pub(auth); - return new OriginAclSubject(AclAuthorization(auth)); -} - - -// -// Validate the origin form. -// This tries to find the source AclObject and hands the question off to it. -// If anything isn't right, fail the validation. -// -bool OriginAclSubject::validate(const AclValidationContext &ctx) const -{ - if (Environment *env = ctx.environment()) - if (ObjectAcl *source = env->preAuthSource()) - if (source->validates(mAuthTag, ctx.cred(), ctx.environment())) - return true; - - // no joy (the sad default) - return false; -} - - -CssmList OriginAclSubject::toList(Allocator &alloc) const -{ - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_PREAUTH, - new(alloc) ListElement(mAuthTag)); -} - -OriginAclSubject::OriginAclSubject(AclAuthorization auth) - : AclSubject(CSSM_ACL_SUBJECT_TYPE_PREAUTH), mAuthTag(auth) -{ - if (auth < CSSM_ACL_AUTHORIZATION_PREAUTH_BASE || auth >= CSSM_ACL_AUTHORIZATION_PREAUTH_END) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); -} - - -// -// Origin exported form is just a four-byte integer (preauth authorization tag) -// -void OriginAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - Endian auth = mAuthTag; - pub(auth); -} - -void OriginAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - Endian auth = mAuthTag; - pub(auth); -} - - -// -// Now for the other side of the coin. -// SourceAclSubjects describe the unusual side (for ACL management) of this game. -// The AclSubject of a preauth source MUST be of PREAUTH_SOURCE type. This subject -// contains the actual validation conditions as a sub-subject, and may provide -// additional information to represent known state of the preauth system. -// -// Think of the extra data in a PreAuthSource ACL as "current state informational" -// that only exists internally, and in the CssmList view. It does not get put into -// persistent (externalized) ACL storage at all. (After all, there's nothing persistent -// about it.) -// -AclSubject *SourceMaker::make(const TypedList &list) const -{ - // minimum requirement: item[1] = sub-subject (sublist) - if (list.length() < 2) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - ListElement &sub = list[1]; - RefPointer subSubject = ObjectAcl::make(sub); - - // anything else is interpreted as tracking state (defaulted if missing) - switch (list.length()) { - case 2: // no tracking state - return new SourceAclSubject(subSubject); - case 3: - if (list[2].type() == CSSM_LIST_ELEMENT_WORDID) - return new SourceAclSubject(subSubject, list[2]); - // fall through - default: - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - } -} - -AclSubject *SourceMaker::make(AclSubject::Version version, Reader &pub, Reader &priv) const -{ - // external form does not contain tracking state - defaults to unknown - RefPointer subSubject = ObjectAcl::importSubject(pub, priv); - return new SourceAclSubject(subSubject); -} - - -// -// Source validation uses its own home-cooked validation context. -// -class SourceValidationContext : public AclValidationContext { -public: - SourceValidationContext(const AclValidationContext &base) - : AclValidationContext(base), mCredTag(base.entryTag()) { } - - uint32 count() const { return cred() ? cred()->samples().length() : 0; } - uint32 size() const { return count(); } - const TypedList &sample(uint32 n) const - { assert(n < count()); return cred()->samples()[n]; } - - const char *credTag() const { return mCredTag; } // override - - void matched(const TypedList *) const { } //@@@ prelim - -private: - const char *mCredTag; -}; - -bool SourceAclSubject::SourceAclSubject::validate(const AclValidationContext &baseCtx) const -{ - // try to authenticate our sub-subject - if (Environment *env = baseCtx.environment()) { - AclAuthorization auth = baseCtx.authorization(); - if (!CSSM_ACL_AUTHORIZATION_IS_PREAUTH(auth)) // all muddled up; bail - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - uint32 slot = CSSM_ACL_AUTHORIZATION_PREAUTH_SLOT(auth); - secdebug("preauth", "using state %d@%p", slot, &env->store(this)); - bool &accepted = env->store(this).attachment((void *)((size_t) slot)).accepted; - if (!accepted) { - secdebug("preauth", "%p needs to authenticate its subject", this); - SourceValidationContext ctx(baseCtx); - if (mSourceSubject->validate(ctx)) { - secdebug("preauth", "%p pre-authenticated", this); - accepted = true; - } - } - return accepted; - } - return false; -} - - -CssmList SourceAclSubject::toList(Allocator &alloc) const -{ - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_PREAUTH_SOURCE, - new(alloc) ListElement(mSourceSubject->toList(alloc))); -} - - -SourceAclSubject::SourceAclSubject(AclSubject *subSubject, CSSM_ACL_PREAUTH_TRACKING_STATE state) - : AclSubject(CSSM_ACL_SUBJECT_TYPE_PREAUTH), - mSourceSubject(subSubject) -{ -} - - -// -// Export the subject to a memory blob -// -void SourceAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - mSourceSubject->exportBlob(pub, priv); -} - -void SourceAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - mSourceSubject->exportBlob(pub, priv); - // tracking state is not exported -} - - -#ifdef DEBUGDUMP - -void OriginAclSubject::debugDump() const -{ - Debug::dump("Preauth(to slot %d)", mAuthTag - CSSM_ACL_AUTHORIZATION_PREAUTH_BASE); -} - -void SourceAclSubject::debugDump() const -{ - Debug::dump("Preauth source: "); - if (mSourceSubject) - mSourceSubject->debugDump(); - else - Debug::dump("NULL?"); -} - -#endif //DEBUGDUMP - - -} // namespace PreAuthorizationAcls -} // namespace Security diff --git a/OSX/include/security_cdsa_utilities/acl_preauth.h b/OSX/include/security_cdsa_utilities/acl_preauth.h deleted file mode 100644 index ee56b95e..00000000 --- a/OSX/include/security_cdsa_utilities/acl_preauth.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2004,2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_preauth - a subject type for modeling PINs and similar slot-specific -// pre-authentication schemes. -// -#ifndef _ACL_PREAUTH -#define _ACL_PREAUTH - -#include -#include - - -namespace Security { -namespace PreAuthorizationAcls { - - -class OriginMaker : public AclSubject::Maker { -protected: - typedef LowLevelMemoryUtilities::Reader Reader; - typedef LowLevelMemoryUtilities::Writer Writer; -public: - OriginMaker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_PREAUTH) { } - AclSubject *make(const TypedList &list) const; - AclSubject *make(AclSubject::Version version, Reader &pub, Reader &priv) const; -}; - -class SourceMaker : public AclSubject::Maker { -protected: - typedef LowLevelMemoryUtilities::Reader Reader; - typedef LowLevelMemoryUtilities::Writer Writer; -public: - SourceMaker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_PREAUTH_SOURCE) { } - AclSubject *make(const TypedList &list) const; - AclSubject *make(AclSubject::Version version, Reader &pub, Reader &priv) const; -}; - - -// -// The actual designation of the PreAuth source AclBearer is provide by the environment. -// -class Environment : public virtual AclValidationEnvironment { -public: - virtual ObjectAcl *preAuthSource() = 0; -}; - - -// -// This is the object that is being "attached" (as an Adornment) to hold -// the pre-authorization state of a SourceAclSubject. -// The Adornable used for storage is determined by the Environment's store() method. -// -struct AclState { - AclState() : accepted(false) { } - bool accepted; // was previously accepted by upstream -}; - - -// -// This is the "origin" subject class that gets created the usual way. -// It models a pre-auth "origin" - i.e. it points at a preauth slot and accepts -// its verdict on validation. Think of it as the "come from" part of the link. -// -class OriginAclSubject : public AclSubject { -public: - bool validate(const AclValidationContext &ctx) const; - CssmList toList(Allocator &alloc) const; - - OriginAclSubject(AclAuthorization auth); - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - -private: - AclAuthorization mAuthTag; // authorization tag referred to (origin only) -}; - - -// -// The "source" subject class describes the other end of the link; the "go to" part -// if you will. Its sourceSubject is consulted for actual validation; and prior validation -// state is remembered (through the environment store facility) so that future validation -// attempts will automaticaly succeed (that's the "pre" in PreAuth). -// -class SourceAclSubject : public AclSubject { -public: - bool validate(const AclValidationContext &ctx) const; - CssmList toList(Allocator &alloc) const; - - SourceAclSubject(AclSubject *subSubject, - CSSM_ACL_PREAUTH_TRACKING_STATE state = CSSM_ACL_PREAUTH_TRACKING_UNKNOWN); - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - -private: - RefPointer mSourceSubject; // subject determining outcome (source only) -}; - - - -} // namespace PreAuthorizationAcls -} // namespace Security - - -#endif //_ACL_PREAUTH diff --git a/OSX/include/security_cdsa_utilities/acl_process.cpp b/OSX/include/security_cdsa_utilities/acl_process.cpp deleted file mode 100644 index f8a8cea9..00000000 --- a/OSX/include/security_cdsa_utilities/acl_process.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_process - Process-attribute ACL subject type. -// -#include -#include -#include - - -// -// Validate a credential set against this subject. -// No credential is required for this match. -// -bool ProcessAclSubject::validate(const AclValidationContext &context) const -{ - // reality check (internal structure was validated when created) - assert(select.uses(CSSM_ACL_MATCH_BITS)); - - // access the environment - Environment *env = context.environment(); - if (env == NULL) { - static Environment localEnvironment; - env = &localEnvironment; - } - - // match uid - if (select.uses(CSSM_ACL_MATCH_UID)) { - uid_t uid = env->getuid(); - if (!(uid == select.uid || (select.uses(CSSM_ACL_MATCH_HONOR_ROOT) && uid == 0))) - return false; - } - - // match gid - if (select.uses(CSSM_ACL_MATCH_GID) && select.gid != env->getgid()) - return false; - - return true; -} - - -// -// Make a copy of this subject in CSSM_LIST form -// -CssmList ProcessAclSubject::toList(Allocator &alloc) const -{ - // all associated data is public (no secrets) - //@@@ ownership of selector data is murky; revisit after leak-plugging pass - CssmData sData(memcpy(alloc.alloc(), - &select, sizeof(select)), sizeof(select)); - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_PROCESS, - new(alloc) ListElement(sData)); -} - - -// -// Create a ProcessAclSubject -// -ProcessAclSubject *ProcessAclSubject::Maker::make(const TypedList &list) const -{ - // crack input apart - ListElement *selectorData; - crack(list, 1, &selectorData, CSSM_LIST_ELEMENT_DATUM); - AclProcessSubjectSelector selector; - selectorData->extract(selector); - - // validate input - if (selector.version != CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - if (!selector.uses(CSSM_ACL_MATCH_BITS)) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - - // okay - return new ProcessAclSubject(selector); -} - -ProcessAclSubject *ProcessAclSubject::Maker::make(Version, Reader &pub, Reader &priv) const -{ - AclProcessSubjectSelector selector; pub(selector); - n2hi(selector.version); - n2hi(selector.mask); - n2hi(selector.uid); - n2hi(selector.gid); - return new ProcessAclSubject(selector); -} - - -// -// Export the subject to a memory blob -// -void ProcessAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - pub(select); -} - -void ProcessAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - AclProcessSubjectSelector temp; - temp.version = h2n (select.version); - temp.mask = h2n (select.mask); - temp.uid = h2n (select.uid); - temp.gid = h2n (select.gid); - pub(temp); -} - - -// -// Implement the default methods of a ProcessEnvironment -// -uid_t ProcessAclSubject::Environment::getuid() const -{ - return ::getuid(); -} - -gid_t ProcessAclSubject::Environment::getgid() const -{ - return ::getgid(); -} - - -#ifdef DEBUGDUMP - -void ProcessAclSubject::debugDump() const -{ - Debug::dump("Process "); - if (select.uses(CSSM_ACL_MATCH_UID)) { - Debug::dump("uid=%d", int(select.uid)); - if (select.uses(CSSM_ACL_MATCH_HONOR_ROOT)) - Debug::dump("+root"); - } - if (select.uses(CSSM_ACL_MATCH_GID)) - Debug::dump("gid=%d", int(select.gid)); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_process.h b/OSX/include/security_cdsa_utilities/acl_process.h deleted file mode 100644 index 79bf66b3..00000000 --- a/OSX/include/security_cdsa_utilities/acl_process.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_process - Process-attribute ACL subject type. -// -// NOTE: -// The default Environment provides data about the current process (the one that -// validate() is run in). If this isn't right for you (e.g. because you want to -// validate against a process on the other side of some IPC connection), you must -// make your own version of Environment and pass it to validate(). -// -#ifndef _ACL_PROCESS -#define _ACL_PROCESS - -#include -#include - -namespace Security -{ - -class AclProcessSubjectSelector - : public PodWrapper { -public: - AclProcessSubjectSelector() - { version = CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION; mask = 0; } - - bool uses(uint32 m) const { return mask & m; } -}; - - -// -// The ProcessAclSubject matches process attributes securely identified -// by the system across IPC channels. -// -class ProcessAclSubject : public AclSubject { -public: - bool validate(const AclValidationContext &baseCtx) const; - CssmList toList(Allocator &alloc) const; - - ProcessAclSubject(const AclProcessSubjectSelector &selector) - : AclSubject(CSSM_ACL_SUBJECT_TYPE_PROCESS), - select(selector) { } - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - -public: - class Environment : public virtual AclValidationEnvironment { - public: - virtual uid_t getuid() const; // retrieve effective userid to match - virtual gid_t getgid() const; // retrieve effective groupid to match - }; - -public: - class Maker : public AclSubject::Maker { - public: - Maker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_PROCESS) { } - ProcessAclSubject *make(const TypedList &list) const; - ProcessAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; - -private: - AclProcessSubjectSelector select; -}; - -} // end namespace Security - - -#endif //_ACL_PROCESS diff --git a/OSX/include/security_cdsa_utilities/acl_prompted.cpp b/OSX/include/security_cdsa_utilities/acl_prompted.cpp deleted file mode 100644 index cc3e85a0..00000000 --- a/OSX/include/security_cdsa_utilities/acl_prompted.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_prompted - password-based validation with out-of-band prompting. -// -#include -#include -#include -#include - - -// -// Construct PromptedAclSubjects from prompts and optional data -// -PromptedAclSubject::PromptedAclSubject(Allocator &alloc, - const CssmData &prompt, const CssmData &password) - : SecretAclSubject(alloc, CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD, password), - mPrompt(alloc, prompt) { } -PromptedAclSubject::PromptedAclSubject(Allocator &alloc, - CssmManagedData &prompt, CssmManagedData &password) - : SecretAclSubject(alloc, CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD, password), - mPrompt(alloc, prompt) { } -PromptedAclSubject::PromptedAclSubject(Allocator &alloc, - const CssmData &prompt, bool cache) - : SecretAclSubject(alloc, CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD, cache), - mPrompt(alloc, prompt) { } - - -// -// PromptedAclSubject will prompt for the secret -// -bool PromptedAclSubject::getSecret(const AclValidationContext &context, - const TypedList &subject, CssmOwnedData &secret) const -{ - if (Environment *env = context.environment()) { - return env->getSecret(secret, mPrompt); - } else { - return false; - } -} - - -// -// Make a copy of this subject in CSSM_LIST form -// -CssmList PromptedAclSubject::toList(Allocator &alloc) const -{ - // the password itself is private and not exported to CSSM - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD, - new(alloc) ListElement(alloc, mPrompt)); -} - - -// -// Create a PromptedAclSubject -// -PromptedAclSubject *PromptedAclSubject::Maker::make(const TypedList &list) const -{ - Allocator &alloc = Allocator::standard(Allocator::sensitive); - switch (list.length()) { - case 2: - { - ListElement *elem[1]; - crack(list, 1, elem, CSSM_LIST_ELEMENT_DATUM); - return new PromptedAclSubject(alloc, elem[0]->data(), true); - } - case 3: - { - ListElement *elem[2]; - crack(list, 2, elem, CSSM_LIST_ELEMENT_DATUM, CSSM_LIST_ELEMENT_DATUM); - return new PromptedAclSubject(alloc, elem[0]->data(), elem[1]->data()); - } - default: - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - } -} - -PromptedAclSubject *PromptedAclSubject::Maker::make(Version, Reader &pub, Reader &priv) const -{ - Allocator &alloc = Allocator::standard(Allocator::sensitive); - const void *data; size_t length; priv.countedData(data, length); - return new PromptedAclSubject(alloc, CssmAutoData(alloc, data, length), true); -} - - -// -// Export the subject to a memory blob -// -void PromptedAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - pub.countedData(mPrompt); -} - -void PromptedAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - pub.countedData(mPrompt); -} - - -#ifdef DEBUGDUMP - -void PromptedAclSubject::debugDump() const -{ - Debug::dump("Prompted-Password"); - SecretAclSubject::debugDump(); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_prompted.h b/OSX/include/security_cdsa_utilities/acl_prompted.h deleted file mode 100644 index 59c92341..00000000 --- a/OSX/include/security_cdsa_utilities/acl_prompted.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_prompted - password-based validation with out-of-band prompting. -// -// This implements simple password-based subject types with out-of-band -// prompting (via SecurityAgent), somewhat as per the CSSM standard. -// -#ifndef _ACL_PROMPTED -#define _ACL_PROMPTED - -#include - - -namespace Security { - - -// -// A PromptedAclSubject obtains its sample by prompting the user interactively -// through some prompting mechanism defined in the environment. -// -class PromptedAclSubject : public SecretAclSubject { -public: - CssmList toList(Allocator &alloc) const; - - PromptedAclSubject(Allocator &alloc, - const CssmData &prompt, const CssmData &password); - PromptedAclSubject(Allocator &alloc, - CssmManagedData &prompt, CssmManagedData &password); - PromptedAclSubject(Allocator &alloc, const CssmData &prompt, bool cache = false); - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - -public: - class Environment : virtual public AclValidationEnvironment { - public: - virtual bool getSecret(CssmOwnedData &secret, - const CssmData &prompt) const = 0; - }; - -public: - class Maker : public SecretAclSubject::Maker { - public: - Maker() : SecretAclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_PROMPTED_PASSWORD) { } - PromptedAclSubject *make(const TypedList &list) const; - PromptedAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; - -protected: - bool getSecret(const AclValidationContext &context, - const TypedList &subject, CssmOwnedData &secret) const; - -private: - CssmAutoData mPrompt; // transparently handled prompt data -}; - -} // end namespace Security - - -#endif //_ACL_PROMPTED diff --git a/OSX/include/security_cdsa_utilities/acl_protectedpw.cpp b/OSX/include/security_cdsa_utilities/acl_protectedpw.cpp deleted file mode 100644 index be4c2587..00000000 --- a/OSX/include/security_cdsa_utilities/acl_protectedpw.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_protectedpw - protected-path password-based ACL subject types. -// -#include -#include -#include - - -// -// Construct a password ACL subject -// -ProtectedPasswordAclSubject::ProtectedPasswordAclSubject(Allocator &alloc, const CssmData &password) - : SimpleAclSubject(CSSM_ACL_SUBJECT_TYPE_PROTECTED_PASSWORD), - allocator(alloc), mPassword(alloc, password) -{ } - -ProtectedPasswordAclSubject::ProtectedPasswordAclSubject(Allocator &alloc, CssmManagedData &password) - : SimpleAclSubject(CSSM_ACL_SUBJECT_TYPE_PROTECTED_PASSWORD), - allocator(alloc), mPassword(alloc, password) -{ } - - -// -// Validate a credential set against this subject -// -bool ProtectedPasswordAclSubject::validate(const AclValidationContext &context, - const TypedList &sample) const -{ - if (sample.length() == 1) { - return true; //@@@ validate against PP - } else if (sample.length() == 2 && sample[1].type() == CSSM_LIST_ELEMENT_DATUM) { - const CssmData &password = sample[1]; - return password == mPassword; - } else - CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE); -} - - -// -// Make a copy of this subject in CSSM_LIST form -// -CssmList ProtectedPasswordAclSubject::toList(Allocator &alloc) const -{ - // the password itself is private and not exported to CSSM - return TypedList(alloc, CSSM_ACL_SUBJECT_TYPE_PROTECTED_PASSWORD); -} - - -// -// Create a ProtectedPasswordAclSubject -// -ProtectedPasswordAclSubject *ProtectedPasswordAclSubject::Maker::make(const TypedList &list) const -{ - CssmAutoData password(Allocator::standard(Allocator::sensitive)); - if (list.length() == 1) { - char pass[] = "secret"; - CssmData password = CssmData::wrap(pass, 6); //@@@ get password from PP - return new ProtectedPasswordAclSubject(Allocator::standard(Allocator::sensitive), password); - } else { - ListElement *password; - crack(list, 1, &password, CSSM_LIST_ELEMENT_DATUM); - return new ProtectedPasswordAclSubject(Allocator::standard(Allocator::sensitive), *password); - } -} - -ProtectedPasswordAclSubject *ProtectedPasswordAclSubject::Maker::make(Version, - Reader &pub, Reader &priv) const -{ - Allocator &alloc = Allocator::standard(Allocator::sensitive); - const void *data; size_t length; priv.countedData(data, length); - return new ProtectedPasswordAclSubject(alloc, CssmAutoData(alloc, data, length)); -} - - -// -// Export the subject to a memory blob -// -void ProtectedPasswordAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ - priv.countedData(mPassword); -} - -void ProtectedPasswordAclSubject::exportBlob(Writer &pub, Writer &priv) -{ - priv.countedData(mPassword); -} - - -#ifdef DEBUGDUMP - -void ProtectedPasswordAclSubject::debugDump() const -{ - Debug::dump("Protected Password "); - Debug::dumpData(mPassword.data(), mPassword.length()); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_protectedpw.h b/OSX/include/security_cdsa_utilities/acl_protectedpw.h deleted file mode 100644 index 10c11fdc..00000000 --- a/OSX/include/security_cdsa_utilities/acl_protectedpw.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_protectedpw - protected-path password-based ACL subject types. -// -// This implements "protected path" password-based subject types as per CSSM standard. -// A "protected path" is something that is outside the scope of the computer proper, -// like e.g. a PINpad directly attached to a smartcard token. -// Note: A password prompted through securityd/SecurityAgent is a "prompted password", -// not a "protected password". See acl_prompted.h. -// -// @@@ Warning: This is not quite implemented. -// -#ifndef _ACL_PROTECTED_PASSWORD -#define _ACL_PROTECTED_PASSWORD - -#include -#include -#include - - -namespace Security { - -class ProtectedPasswordAclSubject : public SimpleAclSubject { -public: - bool validate(const AclValidationContext &baseCtx, const TypedList &sample) const; - CssmList toList(Allocator &alloc) const; - - ProtectedPasswordAclSubject(Allocator &alloc, const CssmData &password); - ProtectedPasswordAclSubject(Allocator &alloc, CssmManagedData &password); - - Allocator &allocator; - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - IFDUMP(void debugDump() const); - - class Maker : public AclSubject::Maker { - public: - Maker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_PROTECTED_PASSWORD) { } - ProtectedPasswordAclSubject *make(const TypedList &list) const; - ProtectedPasswordAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; - -private: - CssmAutoData mPassword; -}; - -} // end namespace Security - - -#endif //_ACL_PROTECTED_PASSWORD diff --git a/OSX/include/security_cdsa_utilities/acl_secret.cpp b/OSX/include/security_cdsa_utilities/acl_secret.cpp deleted file mode 100644 index 87a6c193..00000000 --- a/OSX/include/security_cdsa_utilities/acl_secret.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_secret - secret-validation password ACLs framework. -// -#include -#include -#include -#include -#include - - -// -// Construct a secret-bearing ACL subject -// -SecretAclSubject::SecretAclSubject(Allocator &alloc, - CSSM_ACL_SUBJECT_TYPE type, const CssmData &password) - : SimpleAclSubject(type), allocator(alloc), - mSecret(alloc, password), mSecretValid(true), mCacheSecret(false) -{ } - -SecretAclSubject::SecretAclSubject(Allocator &alloc, - CSSM_ACL_SUBJECT_TYPE type, CssmManagedData &password) - : SimpleAclSubject(type), allocator(alloc), - mSecret(alloc, password), mSecretValid(true), mCacheSecret(false) -{ } - -SecretAclSubject::SecretAclSubject(Allocator &alloc, - CSSM_ACL_SUBJECT_TYPE type, bool doCache) - : SimpleAclSubject(type), allocator(alloc), - mSecret(alloc), mSecretValid(false), mCacheSecret(doCache) -{ } - - -// -// Set the secret after creation. -// -// These are const methods by design, even though they obvious (may) set -// a field in the SecretAclSubject. The fields are mutable, following the -// general convention that transient state in AclSubjects is mutable. -// -void SecretAclSubject::secret(const CssmData &s) const -{ - assert(!mSecretValid); // can't re-set it - if (mCacheSecret) { - mSecret = s; - mSecretValid = true; - secdebug("aclsecret", "%p secret stored", this); - } else - secdebug("aclsecret", "%p refused to store secret", this); -} - -void SecretAclSubject::secret(CssmManagedData &s) const -{ - assert(!mSecretValid); // can't re-set it - if (mCacheSecret) { - mSecret = s; - mSecretValid = true; - secdebug("aclsecret", "%p secret stored", this); - } else - secdebug("aclsecret", "%p refused to store secret", this); -} - - -// -// Validate a secret. -// The subclass has to come up with the secret somehow. We just validate it. -// -bool SecretAclSubject::validate(const AclValidationContext &context, - const TypedList &sample) const -{ - CssmAutoData secret(allocator); - - // try to get the secret; fail if we can't - if (!getSecret(context, sample, secret)) - return false; - - // now validate the secret - if (mSecretValid) { - return mSecret == secret; - } else if (Environment *env = context.environment()) { - TrackingAllocator alloc(Allocator::standard()); - TypedList data(alloc, type(), new(alloc) ListElement(secret.get())); - CssmSample sample(data); - AccessCredentials cred((SampleGroup(sample)), context.credTag()); - return env->validateSecret(this, &cred); - } else { - return false; - } -} - - -#ifdef DEBUGDUMP - -void SecretAclSubject::debugDump() const -{ - if (mSecretValid) { - Debug::dump(" "); - Debug::dumpData(mSecret.data(), mSecret.length()); - } - if (mCacheSecret) - Debug::dump("; CACHING"); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_secret.h b/OSX/include/security_cdsa_utilities/acl_secret.h deleted file mode 100644 index 1166eafa..00000000 --- a/OSX/include/security_cdsa_utilities/acl_secret.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_secret - secret-validation password ACLs framework. -// -#ifndef _ACL_SECRET -#define _ACL_SECRET - -#include -#include -#include - - -namespace Security { - - -// -// SecretAclSubject implements AclSubjects that perform their validation by -// passing their secret through some deterministic validation mechanism. -// As a limiting case, the subject can contain the secret itself and validate -// by comparing for equality. -// -// This is not a fully functional ACL subject. You must subclass it. -// -// There are three elements to consider here: -// (1) How to OBTAIN the secret. This is the job of your subclass; SecretAclSubject -// is agnostic (and abstract) in this respect. -// (2) How to VALIDATE the secret. This is delegated to an environment method, -// which gets this very subject passed as an argument for maximum flexibility. -// (3) Whether to use a locally stored copy of the secret for validation (by equality) -// or hand it off to the environment validator. This is fully implemented here. -// This implementation assumes that the secret, whatever it may be, can be stored -// as a (flat) data blob and can be compared for bit-wise equality. No other -// interpretation is required at this level. -// -class SecretAclSubject : public SimpleAclSubject { -public: - bool validate(const AclValidationContext &ctx, const TypedList &sample) const; - - SecretAclSubject(Allocator &alloc, CSSM_ACL_SUBJECT_TYPE type, const CssmData &secret); - SecretAclSubject(Allocator &alloc, CSSM_ACL_SUBJECT_TYPE type, CssmManagedData &secret); - SecretAclSubject(Allocator &alloc, CSSM_ACL_SUBJECT_TYPE type, bool doCache); - - bool haveSecret() const { return mSecretValid; } - bool cacheSecret() const { return mCacheSecret; } - - void secret(const CssmData &secret) const; - void secret(CssmManagedData &secret) const; - - Allocator &allocator; - - IFDUMP(void debugDump() const); - -public: - class Environment : virtual public AclValidationEnvironment { - public: - virtual bool validateSecret(const SecretAclSubject *me, - const AccessCredentials *secret) = 0; - }; - -protected: - // implement this to get your secret (somehow) - virtual bool getSecret(const AclValidationContext &context, - const TypedList &sample, CssmOwnedData &secret) const = 0; - - const CssmData &secret() const { assert(mSecretValid); return mSecret; } - -private: - mutable CssmAutoData mSecret; // locally known secret - mutable bool mSecretValid; // mSecret is valid - bool mCacheSecret; // cache secret locally and validate from cache -}; - -} // end namespace Security - - -#endif //_ACL_SECRET diff --git a/OSX/include/security_cdsa_utilities/acl_threshold.cpp b/OSX/include/security_cdsa_utilities/acl_threshold.cpp deleted file mode 100644 index 17e568f9..00000000 --- a/OSX/include/security_cdsa_utilities/acl_threshold.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_threshold - Threshold-based group ACL subjects -// -#include -#include -#include - - -// -// Validate a credential set against this subject. -// -// With STRICTCOUNTING set, we assume that every match in the threshold ACL -// "consumes" one sample in the corresponding threshold sample. This will not -// work as expected for subject types that may succeed without a sample (e.g. ANY) -// or subject types that may multiply match against a single sample. You have been -// warned. -// -class SublistValidationContext : public AclValidationContext { -public: - SublistValidationContext(const AclValidationContext &ctx, const TypedList &list) - : AclValidationContext(ctx), sampleList(list) { } - - uint32 count() const { return sampleList.length() - 1; } - const TypedList &sample(uint32 n) const - { return TypedList::overlay(sampleList[n+1].list()); } - - void matched(const TypedList *) const { } //@@@ ignore sub-matches for now - - const TypedList &sampleList; -}; - -bool ThresholdAclSubject::validate(const AclValidationContext &baseCtx, - const TypedList &sample) const -{ -#ifdef STRICTCOUNTING - // Pre-screen for reasonable number of subsamples. - // We could more strictly require subSampleCount == elements.length(); - // this is more flexible in that it allows the caller to abbreviate. - uint32 subSampleCount = sample.length() - 1; // (drop type header) - if (subSampleCount < minimumNeeded) // can't possibly satisfy - CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE); - if (subSampleCount > totalSubjects) // reject attempt at sample stuffing - CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE); -#endif //STRICTCOUNTING - - // evaluate - SublistValidationContext ctx(baseCtx, sample); - uint32 matched = 0; - for (uint32 n = 0; n < totalSubjects; n++) { - if ((matched += elements[n]->validate(ctx)) >= minimumNeeded) - return true; -#ifdef STRICTCOUNTING - else if (matched + subSampleCount - n <= minimumNeeded) - return false; // can't get there anymore -#endif //STRICTCOUNTING - } - return false; -} - - -// -// Make a copy of this subject in CSSM_LIST form -// -CssmList ThresholdAclSubject::toList(Allocator &alloc) const -{ - TypedList result(alloc, CSSM_ACL_SUBJECT_TYPE_THRESHOLD, - new(alloc) ListElement(minimumNeeded), - new(alloc) ListElement(totalSubjects)); - for (uint32 n = 0; n < totalSubjects; n++) - result += new(alloc) ListElement(elements[n]->toList(alloc)); - return result; -} - - -// -// Create a ThresholdAclSubject -// -ThresholdAclSubject *ThresholdAclSubject::Maker::make(const TypedList &list) const -{ - // pick apart the input list - if (list.length() < 4) // head + "n" + "k" + at least one subSubject - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - uint32 minimumNeeded = getWord(list[1], 1); - uint32 totalSubjects = getWord(list[2], minimumNeeded); - if (list.length() != 3 + totalSubjects) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - - // now compile the subSubjects - AclSubjectVector elements(totalSubjects); - const ListElement *subSubject = &list[3]; - for (uint32 n = 0; n < totalSubjects; n++, subSubject = subSubject->next()) - elements[n] = ObjectAcl::make(subSubject->typedList()); - return new ThresholdAclSubject(totalSubjects, minimumNeeded, elements); -} - -ThresholdAclSubject *ThresholdAclSubject::Maker::make(Version, Reader &pub, Reader &priv) const -{ - Endian totalSubjects; pub(totalSubjects); - Endian minimumNeeded; pub(minimumNeeded); - AclSubjectVector subSubjects(totalSubjects); - for (uint32 n = 0; n < totalSubjects; n++) - subSubjects[n] = ObjectAcl::importSubject(pub, priv); - return new ThresholdAclSubject(totalSubjects, minimumNeeded, subSubjects); -} - -ThresholdAclSubject::ThresholdAclSubject(uint32 n, uint32 k, - const AclSubjectVector &subSubjects) -: SimpleAclSubject(CSSM_ACL_SUBJECT_TYPE_THRESHOLD), - minimumNeeded(k), totalSubjects(n), elements(subSubjects) -{ -} - - -// -// Export the subject to a memory blob -// -template -void ThresholdAclSubject::exportBlobForm(Action &pub, Action &priv) -{ - pub(h2n(totalSubjects)); - pub(h2n(minimumNeeded)); - for (uint32 n = 0; n < totalSubjects; n++) - ObjectAcl::exportSubject(elements[n], pub, priv); -} - -void ThresholdAclSubject::exportBlob(Writer::Counter &pub, Writer::Counter &priv) -{ exportBlobForm(pub, priv); } - -void ThresholdAclSubject::exportBlob(Writer &pub, Writer &priv) -{ exportBlobForm(pub, priv); } - - -void ThresholdAclSubject::add(AclSubject *subject, unsigned beforePosition) -{ - secdebug("threshacl", "adding subject %p before position %u", - subject, beforePosition); - elements.insert(elements.begin() + beforePosition, subject); - totalSubjects++; -} - - -#ifdef DEBUGDUMP - -void ThresholdAclSubject::debugDump() const -{ - Debug::dump("Threshold(%u of %u)", minimumNeeded, totalSubjects); - for (unsigned int n = 0; n < elements.size(); n++) { - Debug::dump(" ["); - if (Version v = elements[n]->version()) - Debug::dump("V=%d ", v); - elements[n]->debugDump(); - Debug::dump("]"); - } -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/acl_threshold.h b/OSX/include/security_cdsa_utilities/acl_threshold.h deleted file mode 100644 index 437f78f0..00000000 --- a/OSX/include/security_cdsa_utilities/acl_threshold.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// acl_threshold - Threshold-based group ACL subjects. -// -// This subject type implements threshold (k of n) subjects as per CSSM standard. -// Subsubjects are stored and evaluated in the order received. Any subsubject -// is presented with all subsamples of the corresponding threshold sample, but -// not any other samples possibly present in the credentials. Subsubject evaluation -// stops as soon as the threshold is satisfied, or as soon as it becomes numerically -// impossible to satisfy the threshold with future matches. -// Note that this subject will reject out of hand any threshold sample that -// contains more than subsamples. This defeats "sample stuffing" attacks -// where the attacker provides thousands of samples in the hope that some may -// match by accident. It will however accept threshold samples with fewer than -// subsamples, as long as there are at least subsamples. -// -#ifndef _ACL_THRESHOLD -#define _ACL_THRESHOLD - -#include -#include - - -namespace Security { - -class ThresholdAclSubject : public SimpleAclSubject { - typedef ObjectAcl::AclSubjectPointer AclSubjectPointer; - typedef vector AclSubjectVector; -public: - bool validate(const AclValidationContext &baseCtx, const TypedList &sample) const; - CssmList toList(Allocator &alloc) const; - - ThresholdAclSubject(uint32 n, uint32 k, const AclSubjectVector &subSubjects); - - void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - void exportBlob(Writer &pub, Writer &priv); - - unsigned count() const { return totalSubjects; } - AclSubject *subject(unsigned n) const { return elements[n]; } - void add(AclSubject *subject, unsigned beforePosition); - - IFDUMP(void debugDump() const); - - class Maker : public AclSubject::Maker { - public: - Maker() : AclSubject::Maker(CSSM_ACL_SUBJECT_TYPE_THRESHOLD) { } - ThresholdAclSubject *make(const TypedList &list) const; - ThresholdAclSubject *make(Version, Reader &pub, Reader &priv) const; - }; - -private: - uint32 minimumNeeded; // number of matches needed - uint32 totalSubjects; // number of subSubjects - AclSubjectVector elements; // sub-subject vector - - template - void exportBlobForm(Action &pub, Action &priv); -}; - -} // namespace Security - - -#endif //_ACL_THRESHOLD diff --git a/OSX/include/security_cdsa_utilities/aclsubject.cpp b/OSX/include/security_cdsa_utilities/aclsubject.cpp deleted file mode 100644 index 70ec05e5..00000000 --- a/OSX/include/security_cdsa_utilities/aclsubject.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// aclsubject - abstract ACL subject implementation -// -#include -#include -#include -#include -#include -#include - - -// -// Validation contexts -// -AclValidationContext::~AclValidationContext() -{ /* virtual */ } - - -void AclValidationContext::init(ObjectAcl *acl, AclSubject *subject) -{ - mAcl = acl; - mSubject = subject; -} - - -const char *AclValidationContext::credTag() const -{ - return mCred ? mCred->tag() : NULL; -} - -std::string AclValidationContext::s_credTag() const -{ - const char *s = this->credTag(); - return s ? s : ""; -} - -const char *AclValidationContext::entryTag() const -{ - return mEntryTag; -} - -void AclValidationContext::entryTag(const char *tag) -{ - mEntryTag = (tag && tag[0]) ? tag : NULL; -} - -void AclValidationContext::entryTag(const std::string &tag) -{ - mEntryTag = tag.empty() ? NULL : tag.c_str(); -} - - -// -// Common (basic) features of AclSubjects -// -AclSubject::AclSubject(uint32 type, Version v /* = 0 */) - : mType(type), mVersion(v) -{ - assert(!(type & versionMask)); -} - -AclSubject::~AclSubject() -{ } - -AclValidationEnvironment::~AclValidationEnvironment() -{ } - -Adornable &AclValidationEnvironment::store(const AclSubject *subject) -{ - CssmError::throwMe(CSSM_ERRCODE_ACL_SUBJECT_TYPE_NOT_SUPPORTED); -} - -void AclSubject::exportBlob(Writer::Counter &, Writer::Counter &) -{ } - -void AclSubject::exportBlob(Writer &, Writer &) -{ } - -void AclSubject::importBlob(Reader &, Reader &) -{ } - -void AclSubject::reset() -{ } - -AclSubject::Maker::~Maker() -{ -} - - -// -// A SimpleAclSubject accepts only a single type of sample, validates -// samples independently, and makes no use of certificates. -// -bool SimpleAclSubject::validate(const AclValidationContext &ctx) const -{ - for (uint32 n = 0; n < ctx.count(); n++) { - const TypedList &sample = ctx[n]; - if (!sample.isProper()) - CssmError::throwMe(CSSM_ERRCODE_INVALID_SAMPLE_VALUE); - if (sample.type() == type() && validate(ctx, sample)) { - ctx.matched(ctx[n]); - return true; // matched this sample; validation successful - } - } - return false; -} - - -// -// AclSubjects always have a (virtual) dump method. -// It's empty unless DEBUGDUMP is enabled. -// -void AclSubject::debugDump() const -{ -#if defined(DEBUGDUMP) - switch (type()) { - case CSSM_ACL_SUBJECT_TYPE_ANY: - Debug::dump("ANY"); - break; - default: - Debug::dump("subject type=%d", type()); - break; - } -#endif //DEBUGDUMP -} - -#if defined(DEBUGDUMP) - -void AclSubject::dump(const char *title) const -{ - Debug::dump(" ** %s ", title); - this->debugDump(); - Debug::dump("\n"); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/aclsubject.h b/OSX/include/security_cdsa_utilities/aclsubject.h deleted file mode 100644 index 4ad71347..00000000 --- a/OSX/include/security_cdsa_utilities/aclsubject.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// aclsubject - abstract ACL subject implementation -// -#ifndef _ACLSUBJECT -#define _ACLSUBJECT - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Security { - -class ObjectAcl; -class AclValidationContext; -class AclSubject; - - -// -// An AclValidationEnvironment can be subclassed to add context access to ACL subject -// validation. If you use ACL subject classes that need context beyond the credential -// structure itself, add that context to (a virtual subclass of) AclValidationContext, pass that -// to ObjectAcl::validate() along with the credentials, and have the Subject implementation -// access validationContext.environment(). -// -class AclValidationEnvironment { - friend class AclValidationContext; -public: - virtual ~AclValidationEnvironment(); // ensure virtual methods (need dynamic_cast) - - // provide an Adornable for a given subject to store data in, or throw if none available (default) - virtual Adornable &store(const AclSubject *subject); -}; - - -// -// An AclValidationContext holds all context for an ACL evaluation in one -// package. It's designed to provide a uniform representation of credentials, plus -// any (trusted path and/or implicit) context information useful for ACL validation. -// -// Contexts are immutable (constant) for validators; they do not change at all -// during a validation exercise. Anything that should be mutable must go into -// the environment (which is indirect and modifyable). -// -class AclValidationContext { - friend class ObjectAcl; -public: - AclValidationContext(const AccessCredentials *cred, - AclAuthorization auth, AclValidationEnvironment *env = NULL) - : mAcl((ObjectAcl*) 0xDEADDEADDEADDEAD), mSubject((AclSubject*) 0xDEADDEADDEADDEAD), mCred(cred), - mAuth(auth), mEnv(env), mEntryTag(NULL) { } - AclValidationContext(const AclValidationContext &ctx) - : mAcl(ctx.mAcl), mSubject(ctx.mSubject), mCred(ctx.mCred), - mAuth(ctx.mAuth), mEnv(ctx.mEnv), mEntryTag(NULL) { } - virtual ~AclValidationContext(); - - // access to (suitably focused) sample set - virtual uint32 count() const = 0; // number of samples - uint32 size() const { return count(); } // alias - virtual const TypedList &sample(uint32 n) const = 0; // retrieve one sample - const TypedList &operator [] (uint32 n) const { return sample(n); } - - // context access - AclAuthorization authorization() const { return mAuth; } - const AccessCredentials *cred() const { return mCred; } - AclValidationEnvironment *environment() const { return mEnv; } - template Env *environment() const { return dynamic_cast(mEnv); } - AclSubject *subject() const { return mSubject; } - ObjectAcl *acl() const { return mAcl; } - - // tag manipulation - virtual const char *credTag() const; - virtual const char *entryTag() const; - std::string s_credTag() const; - void entryTag(const char *tag); - void entryTag(const std::string &tag); - - // selective match support - not currently implemented - virtual void matched(const TypedList *match) const = 0; - void matched(const TypedList &match) const { return matched(&match); } - -private: - void init(ObjectAcl *acl, AclSubject *subject); - -private: - ObjectAcl *mAcl; // underlying ObjectAcl - AclSubject *mSubject; // subject being validated - const AccessCredentials *mCred; // original credentials - AclAuthorization mAuth; // action requested - AclValidationEnvironment *mEnv; // environmental context (if any) - const char *mEntryTag; // entry tag -}; - - -// -// The AclSubject class models an ACL "subject" object. If you have a new ACL -// subject type or variant, you make a subclass of this (plus a suitable Maker). -// -// Note that AclSubjects can contain both configuration and state information. -// Configuration is set during AclSubject creation (passwords to check against, -// evaluation options, etc.) and are typically passed on in the externalized form; -// it is persistent. -// On the other hand, state is volatile and is lost when the AclSubject dies. -// This is stuff that accumulates during a particular lifetime, such as results -// of previous evaluations (for caching or more nefarious purposes). -// Be clear what each of your subclass members are, and document accordingly. -// -class AclSubject : public RefCount { -public: - typedef LowLevelMemoryUtilities::Writer Writer; - typedef LowLevelMemoryUtilities::Reader Reader; - - typedef uint8 Version; // binary version marker - static const int versionShift = 24; // highest-order byte of type is version - static const uint32 versionMask = 0xff000000; - -public: - explicit AclSubject(uint32 type, Version v = 0); - virtual ~AclSubject(); - CSSM_ACL_SUBJECT_TYPE type() const { return mType; } - - // validation (evaluation) primitive - virtual bool validate(const AclValidationContext &ctx) const = 0; - - // export to CSSM interface - virtual CssmList toList(Allocator &alloc) const = 0; - - // export/import for save/restore interface - virtual void exportBlob(Writer::Counter &pub, Writer::Counter &priv); - virtual void exportBlob(Writer &pub, Writer &priv); - virtual void importBlob(Reader &pub, Reader &priv); - - // binary compatibility version management. The version defaults to zero - Version version() const { return mVersion; } - - // forget any validation-related state you have acquired - virtual void reset(); - - // debug suupport (dummied out but present for -UDEBUGDUMP) - virtual void debugDump() const; - IFDUMP(void dump(const char *title) const); - -protected: - void version(Version v) { mVersion = v; } - -private: - CSSM_ACL_SUBJECT_TYPE mType; - Version mVersion; - -public: - class Maker { - public: - Maker(CSSM_ACL_SUBJECT_TYPE type); - virtual ~Maker(); - - uint32 type() const { return mType; } - virtual AclSubject *make(const TypedList &list) const = 0; - virtual AclSubject *make(Version version, Reader &pub, Reader &priv) const = 0; - - protected: - // list parsing helpers - static void crack(const CssmList &list, uint32 count, - ListElement **array = NULL, ...); - static CSSM_WORDID_TYPE getWord(const ListElement &list, - int min = 0, int max = INT_MAX); - - private: - CSSM_ACL_SUBJECT_TYPE mType; - }; -}; - - -// -// A SimpleAclSubject validates a credential by scanning its samples -// one at a time, without any interactions between them. Thus its validate() -// can be a lot simpler. -// Note that this layer assumes that subject and sample types have the same -// value, as is typical when both are derived from a WORDID. -// -class SimpleAclSubject : public AclSubject { -public: - SimpleAclSubject(CSSM_ACL_SUBJECT_TYPE type) : AclSubject(type) { } - - bool validate(const AclValidationContext &ctx) const; - virtual bool validate(const AclValidationContext &baseCtx, - const TypedList &sample) const = 0; -}; - - -} // end namespace Security - - -#endif //_ACLSUBJECT diff --git a/OSX/include/security_cdsa_utilities/callback.cpp b/OSX/include/security_cdsa_utilities/callback.cpp deleted file mode 100644 index 72a16361..00000000 --- a/OSX/include/security_cdsa_utilities/callback.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Encapsulate the callback mechanism of CSSM. -// -#include - - -// -// Invoke a callback -// -void ModuleCallback::operator () (CSSM_MODULE_EVENT event, - const Guid &guid, uint32 subId, - CSSM_SERVICE_TYPE serviceType) const -{ - try - { - if (mCallback) - if (CSSM_RETURN err = mCallback(&guid, mContext, subId, serviceType, event)) - CssmError::throwMe(err); - } - catch (...) - { - } -} - - -// -// Manage Callback sets. -// THREADS: Caller is ensuring single-thread access on these calls. -// -void ModuleCallbackSet::insert(const ModuleCallback &newCallback) -{ - callbacks.insert(CallbackMap::value_type(newCallback, new CountingMutex)); -} - -void ModuleCallbackSet::erase(const ModuleCallback &oldCallback) -{ - CallbackMap::iterator it = callbacks.find(oldCallback); - if (it == callbacks.end()) // not registered; fail - CssmError::throwMe(CSSMERR_CSSM_INVALID_ADDIN_HANDLE); - CountingMutex *counter = it->second; - { - StLock _(*counter); - if (!counter->isIdle()) // callbacks are scheduled against this - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_FAILED); // @#module is busy - } - // counter is zero (idle), and we hold the entry lock (via our caller) - delete counter; - callbacks.erase(it); -} - - -// -// Invoke an entire callback set. -// THREADS: Caller is ensuring single-thread access on these calls. -// -void ModuleCallbackSet::operator () (CSSM_MODULE_EVENT event, - const Guid &guid, uint32 subId, - CSSM_SERVICE_TYPE serviceType) const -{ - if (callbacks.empty()) // nothing to do; quick exit - return; - -#if _USE_THREADS == _USE_NO_THREADS || defined(SYNCHRONOUS_CALLBACKS) - // no threading model supported - we HAVE to do this right here - // note that the user better not re-enter CSSM too much, - // or we might deadlock... - for (CallbackMap::const_iterator it = callbacks.begin(); - it != callbacks.end(); it++) { - it->first(event, guid, subId, serviceType); - } -#else // real threads available - // lock down all callback elements - still protected by global lock (via caller) - for (CallbackMap::iterator it = callbacks.begin(); - it != callbacks.end(); it++) - it->second->enter(); - - // get out of this thread - now! - (new Runner(callbacks, event, guid, subId, serviceType))->run(); -#endif -} - -void ModuleCallbackSet::Runner::action() -{ - // - // NOTE WELL: Our callbacks map shares (pointed-to) values with the ModuleCallbackSet - // we were created from. Some of these values may be dangling pointers since they have - // been destroyed by other threads, but only *after* we are done with them, since - // we must call exit() on them before they become eligible for destruction. - // In all cases, it is the responsibility of other threads to destroy those mutexi. - // - // @@@ Could also fan out to multiple callback threads in parallel. - for (CallbackMap::iterator it = callbacks.begin(); - it != callbacks.end(); it++) { - //@@@ safety vs. convenience - recheck - it->first(event, guid, subserviceId, serviceType); - it->second->exit(); - } -} diff --git a/OSX/include/security_cdsa_utilities/callback.h b/OSX/include/security_cdsa_utilities/callback.h deleted file mode 100644 index 05695891..00000000 --- a/OSX/include/security_cdsa_utilities/callback.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Encapsulate the callback mechanism of CSSM. -// -#ifndef _H_CALLBACK -#define _H_CALLBACK - -#include -#include -#include -#include - -namespace Security -{ - -// -// A single module-specific callback as requested by the user. -// -class ModuleCallback { -public: - ModuleCallback() : mCallback(0), mContext(0) { } - ModuleCallback(CSSM_API_ModuleEventHandler callback, void *context) - : mCallback(callback), mContext(context) { } - - void operator () (CSSM_MODULE_EVENT event, - const Guid &guid, uint32 subId, - CSSM_SERVICE_TYPE serviceType) const; - - operator bool () const { return mCallback || mContext; } - bool operator ! () const { return !bool(*this); } - - bool operator == (const ModuleCallback &cb) const - { return mCallback == cb.mCallback && mContext == cb.mContext; } - bool operator < (const ModuleCallback &cb) const - { return mCallback < cb.mCallback - || (mCallback == cb.mCallback && mContext < cb.mContext); } - -private: - CSSM_API_ModuleEventHandler mCallback; - void *mContext; -}; - - -// -// A set of callbacks that can be invoked automatically in a thread-safe manner. -// THREADS: The set itself is not interlocked by the ModuleCallbackSet class; you -// are responsible for ensuring single access to the set object. The class ensures -// that any threads it spawns to execute the callbacks will not step on each other -// or on you, and that you will not be able to erase() a callback while it has -// activity scheduled against it. This also applies to the invocation method -// (operator ()) - you must lock against multiple accesses to it until it returns. -// -class ModuleCallbackSet { -public: - unsigned int size() const { return (int)callbacks.size(); } - void insert(const ModuleCallback &newCallback); - void erase(const ModuleCallback &oldCallback); - - void operator () (CSSM_MODULE_EVENT event, - const Guid &guid, uint32 subId, - CSSM_SERVICE_TYPE serviceType) const; - -private: - // note mutex *: we don't want to rely on copy-ability of Mutex objects - typedef multimap CallbackMap; - mutable CallbackMap callbacks; - - struct Runner : public Thread { - Runner(CallbackMap &inCallbacks, - CSSM_MODULE_EVENT inEvent, - const Guid &inGuid, - uint32 inSSId, - CSSM_SERVICE_TYPE inServiceType) - : callbacks(inCallbacks), event(inEvent), guid(inGuid), - subserviceId(inSSId), serviceType(inServiceType) { } - - CallbackMap callbacks; // note that we share the CountingMutex * values! - const CSSM_MODULE_EVENT event; - const Guid guid; - const uint32 subserviceId; - const CSSM_SERVICE_TYPE serviceType; - - void action(); - }; -}; - -} // end namespace Security - - -#endif //_H_CALLBACK diff --git a/OSX/include/security_cdsa_utilities/constdata.cpp b/OSX/include/security_cdsa_utilities/constdata.cpp deleted file mode 100644 index c3061751..00000000 --- a/OSX/include/security_cdsa_utilities/constdata.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// constdata - shared constant binary data objects -// -#include "constdata.h" -#include - - -namespace Security { - - -// -// Construct a Blob from a source -// -ConstData::Blob::Blob(const void *base, size_t size, bool takeOwnership) : mSize(size) -{ - mData = takeOwnership ? base : memcpy(new char[size], base, size); -} - - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/constdata.h b/OSX/include/security_cdsa_utilities/constdata.h deleted file mode 100644 index dfa716ec..00000000 --- a/OSX/include/security_cdsa_utilities/constdata.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// constdata - shared constant binary data objects -// -#ifndef _H_CONSTDATA -#define _H_CONSTDATA - -#include -#include - - -namespace Security { - - -// -// ConstData represents a contiguous, binary blob of constant data. -// Assignment is by sharing (thus cheap). -// ConstData is a (constant) Dataoid type. -// -class ConstData { -private: - class Blob : public RefCount { - public: - Blob() : mData(NULL), mSize(0) { } - Blob(const void *base, size_t size, bool takeOwnership = false); - ~Blob() { delete[] reinterpret_cast(mData); } - - const void *data() const { return mData; } - size_t length() const { return mSize; } - - private: - const void *mData; - size_t mSize; - }; - -public: - ConstData() { } //@@@ use a nullBlob? - ConstData(const void *base, size_t size, bool takeOwnership = false) - : mBlob(new Blob(base, size, takeOwnership)) { } - - template - static ConstData wrap(const T &obj, bool takeOwnership) - { return ConstData(&obj, sizeof(obj), takeOwnership); } - -public: - const void *data() const { return mBlob ? mBlob->data() : NULL; } - size_t length() const { return mBlob ? mBlob->length() : 0; } - - operator bool() const { return mBlob; } - bool operator !() const { return !mBlob; } - - template operator const T *() const - { return reinterpret_cast(data()); } - - template const T &as() const - { return *static_cast(reinterpret_cast(data())); } - -private: - RefPointer mBlob; -}; - - -} // end namespace Security - - -#endif //_H_CONSTDATA diff --git a/OSX/include/security_cdsa_utilities/context.cpp b/OSX/include/security_cdsa_utilities/context.cpp deleted file mode 100644 index 23137bdf..00000000 --- a/OSX/include/security_cdsa_utilities/context.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// context - manage CSSM (cryptographic) contexts every which way. -// -// A note on memory management: -// Context attributes are allocated from application memory in big chunks comprising -// many attributes as well as the attribute array itself. The CSSM_CONTEXT fields -// NumberOfAttributes and ContextAttributes are handled as a group. Context::Builder -// and Context::copyFrom assume these fields are undefined and fill them. Context::clear -// assumes they are valid and invalides them, freeing memory. -// -// You may also want to look at cssmcontext.h in CSSM proper, where CSSM's internal Context -// objects are built on top of our Context class. -// -#include - - -// -// Construct Context objects -// -Context::Context(CSSM_CONTEXT_TYPE type, CSSM_ALGORITHMS algorithmId) -{ - clearPod(); - ContextType = type; - AlgorithmType = algorithmId; -} - - -// -// Delete a single attribute from a Context by type. -// We implement this by simply nulling out the slot - the memory is not released, -// and will not be reclaimed until the Context is deleted or reconstructed for some reason. -// -void Context::deleteAttribute(CSSM_ATTRIBUTE_TYPE type) -{ - for (uint32 n = 0; n < attributesInUse(); n++) - if (ContextAttributes[n].AttributeType == type) { - ContextAttributes[n].AttributeType = CSSM_ATTRIBUTE_NONE; - ContextAttributes[n].AttributeLength = 0; - return; - } - // not found - CssmError::throwMe(CSSMERR_CSSM_ATTRIBUTE_NOT_IN_CONTEXT); -} - - -// -// This swiss-army-knife function performs a deep copy of all of a Context's attributes, -// bundling them up into a single memory node and storing them into a pointer/count pair. -// It also returns the size of the memory block allocated, in case you care (IPC does). -// -size_t Context::copyAttributes(CSSM_CONTEXT_ATTRIBUTE * &attrs, uint32 &count, - Allocator &alloc) const -{ - Context::Builder builder(alloc); - for (unsigned n = 0; n < attributesInUse(); n++) - builder.setup(ContextAttributes[n]); - size_t size = builder.make(); - for (unsigned n = 0; n < attributesInUse(); n++) - builder.put(ContextAttributes[n]); - builder.done(attrs, count); - return size; -} - - -// -// Locate attribute values by type. -// This function deals in attribute vectors, not contexts; hence the explicit count argument. -// Returns NULL for attribute not found. -// -Context::Attr *Context::find(CSSM_ATTRIBUTE_TYPE theType, - const CSSM_CONTEXT_ATTRIBUTE *attrs, unsigned int count) -{ - for (unsigned n = 0; n < count; n++) - if (attrs[n].AttributeType == theType) - return (Attr *)&attrs[n]; - return NULL; -} - - -// -// Post-IPC context fixup. -// A Context is transmitted via IPC as a two-element blob. The first is the Context -// structure itself, which is taken as flat. The second is the flattened attribute -// vector blob as produced by the Context::Builder class. Since IPC will relocate -// each blob, we need to offset all internal pointers to compensate. -// -void Context::postIPC(void *base, CSSM_CONTEXT_ATTRIBUTE *ipcAttributes) -{ - ReconstituteWalker relocator(LowLevelMemoryUtilities::difference(ipcAttributes, base)); - ContextAttributes = ipcAttributes; // fix context->attr vector link - for (uint32 n = 0; n < attributesInUse(); n++) - walk(relocator, (*this)[n]); -} - - -// -// Context Builders -// -size_t Context::Builder::make() -{ - size_t vectorSize = - LowLevelMemoryUtilities::alignUp(slotCount * sizeof(CSSM_CONTEXT_ATTRIBUTE)); - size_t totalSize = vectorSize + sizer; - attributes = reinterpret_cast(allocator.malloc(totalSize)); - copier = LowLevelMemoryUtilities::increment(attributes, vectorSize); - slot = 0; - return totalSize; -} - -void Context::Builder::done(CSSM_CONTEXT_ATTRIBUTE * &attributes, uint32 &count) -{ - assert(slot == slotCount); // match pass profiles - attributes = this->attributes; - count = slotCount; - this->attributes = NULL; // delivered the goods, no longer our responsibility -} - - -// -// Debugging support -// -#if defined(DEBUGDUMP) - -static void dumpData(CSSM_DATA *data) -{ - if (data == NULL) - Debug::dump("[NULL]"); - else - Debug::dump("[%p,%ld]@%p", data->Data, data->Length, data); -} - -void Context::Attr::dump() const -{ - Debug::dump(" Attr{type=%x, size=%d, value=", int(AttributeType), int(AttributeLength)); - switch (AttributeType & CSSM_ATTRIBUTE_TYPE_MASK) { - case CSSM_ATTRIBUTE_DATA_UINT32: - Debug::dump("%ld", long(Attribute.Uint32)); break; - case CSSM_ATTRIBUTE_DATA_STRING: - Debug::dump("%s@%p", Attribute.String, Attribute.String); break; - case CSSM_ATTRIBUTE_DATA_CSSM_DATA: - dumpData(Attribute.Data); - break; - case CSSM_ATTRIBUTE_DATA_CRYPTO_DATA: - dumpData(&Attribute.CryptoData->Param); - break; - default: - Debug::dump("%p", Attribute.String); break; // (slightly unclean) - }; - Debug::dump("}\n"); -} - -void Context::dump(const char *title, const CSSM_CONTEXT_ATTRIBUTE *attrs) const -{ - if (attrs == NULL) - attrs = ContextAttributes; - Debug::dump("Context %s{type=%d, alg=%d, CSP=%u, %d attributes@%p:\n", - title ? title : "", - int(ContextType), int(AlgorithmType), (unsigned int)CSPHandle, - int(NumberOfAttributes), attrs); - for (unsigned int n = 0; n < NumberOfAttributes; n++) - Attr::overlay(attrs[n]).dump(); - Debug::dump("} // end Context\n"); -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/context.h b/OSX/include/security_cdsa_utilities/context.h deleted file mode 100644 index f5eb57d7..00000000 --- a/OSX/include/security_cdsa_utilities/context.h +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// context - CSSM cryptographic context objects -// -#ifndef _H_CONTEXT -#define _H_CONTEXT - -#include -#include -#include -#include -#include // to serialize/copy access credentials -#include - -namespace Security { - - -// -// Context is a POD overlay for the CSSM_CONTEXT type. It does -// add allocation functions and lots of good stuff. -// Note that if you're outside CSSM proper, you are not supposed to -// memory-manage Context structures on your own. Be a good boy and -// call the CSSM API functions. -// We also provide a POD overlay for CSSM_CONTEXT_ATTRIBUTE, with -// the obvious semantics. -// -class Context : public PodWrapper { -public: - Context(CSSM_CONTEXT_TYPE type, CSSM_ALGORITHMS algorithmId); - - uint32 attributesInUse() const { return NumberOfAttributes; } - CSSM_CONTEXT_TYPE type() const { return ContextType; } - CSSM_ALGORITHMS algorithm() const { return AlgorithmType; } - CSSM_CSP_HANDLE cspHandle() const { return CSPHandle; } - - void deleteAttribute(CSSM_ATTRIBUTE_TYPE type); - size_t copyAttributes(CSSM_CONTEXT_ATTRIBUTE * &attrs, uint32 &count, Allocator &alloc) const; - - void copyFrom(const Context &source, Allocator &alloc) - { source.copyAttributes(ContextAttributes, NumberOfAttributes, alloc); } - -public: - class Attr : public PodWrapper { - public: - Attr() { } - Attr(const CSSM_CONTEXT_ATTRIBUTE &attr) { (CSSM_CONTEXT_ATTRIBUTE &)*this = attr; } - - template - Attr(CSSM_ATTRIBUTE_TYPE typ, T &value, size_t size = 0) - { - AttributeType = typ; - // attribute component pointers are stupidly non-const; allow const input - Attribute.String = const_cast(reinterpret_cast(&value)); - AttributeLength = (uint32_t) (size ? size : sizeof(T)); - } - - Attr(CSSM_ATTRIBUTE_TYPE typ, uint32 value) - { - AttributeType = typ; - Attribute.Uint32 = value; - AttributeLength = 0; - } - - CSSM_ATTRIBUTE_TYPE type() const { return AttributeType; } - uint32 baseType() const { return AttributeType & CSSM_ATTRIBUTE_TYPE_MASK; } - - operator char * () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_STRING); return Attribute.String; } - operator CssmData & () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_CSSM_DATA); - return CssmData::overlay(*Attribute.Data); } - operator CssmCryptoData & () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_CRYPTO_DATA); - return CssmCryptoData::overlay(*Attribute.CryptoData); } - operator CssmKey & () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_KEY); return CssmKey::overlay(*Attribute.Key); } - operator AccessCredentials & () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_ACCESS_CREDENTIALS); - return AccessCredentials::overlay(*Attribute.AccessCredentials); } - operator uint32 () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_UINT32); return Attribute.Uint32; } - operator CSSM_DL_DB_HANDLE &() const - { - assert(baseType() == CSSM_ATTRIBUTE_DATA_DL_DB_HANDLE); - if (Attribute.DLDBHandle == NULL) - CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_DL_DB_HANDLE); - return *Attribute.DLDBHandle; - } - operator CssmDate & () const - { assert(baseType() == CSSM_ATTRIBUTE_DATA_DATE); - return CssmDate::overlay(*Attribute.Date); } - // @@@ etc. etc. - add yours today! - - void operator = (uint32 value) { Attribute.Uint32 = value; } - template - void operator = (T *ptr) { Attribute.String = reinterpret_cast(ptr); } - - IFDUMP(void dump() const;) // debug dump this Attr to stdout (one line) - }; - - // Attributes by position - Attr *attributes() const { return Attr::overlay(ContextAttributes); } - Attr &operator [] (unsigned int ix) - { assert(ix < NumberOfAttributes); return static_cast(ContextAttributes[ix]); } - const Attr &operator [] (unsigned int ix) const - { assert(ix < NumberOfAttributes); return static_cast(ContextAttributes[ix]); } - - // general attribute retrieval by type - Attr *find(CSSM_ATTRIBUTE_TYPE theType) const - { return find(theType, ContextAttributes, NumberOfAttributes); } - - template - Elem &get(CSSM_ATTRIBUTE_TYPE type, CSSM_RETURN err) const - { - if (Attr *attr = find(type)) - return static_cast(*attr); - else - CssmError::throwMe(err); - } - - template - Elem *get(CSSM_ATTRIBUTE_TYPE type) const - { - if (Attr *attr = find(type)) - // @@@ Invoking conversion operator to Elem & on *attr and taking address of result. - return &static_cast(*attr); - else - return NULL; - } - - uint32 getInt(CSSM_ATTRIBUTE_TYPE type, CSSM_RETURN err) const - { - if (Attr *attr = find(type)) - return static_cast(*attr); - else - CssmError::throwMe(err); - } - - uint32 getInt(CSSM_ATTRIBUTE_TYPE type) const - { - if (Attr *attr = find(type)) - return static_cast(*attr); - else - return 0; - } - - bool getInt(CSSM_ATTRIBUTE_TYPE type, uint32 &value) const - { - if (Attr *attr = find(type)) { - value = static_cast(*attr); - return true; - } else - return false; - } - -public: - template - void replace(CSSM_ATTRIBUTE_TYPE type, const T &newValue) const - { - if (Attr *attr = find(type)) - *attr = Attr(type, newValue); - else - CssmError::throwMe(CSSMERR_CSSM_ATTRIBUTE_NOT_IN_CONTEXT); - } - -public: - void *operator new (size_t size, Allocator &alloc) throw(std::bad_alloc) - { return alloc.malloc(size); } - void operator delete (void *addr, size_t, Allocator &alloc) throw() - { return alloc.free(addr); } - static void destroy(Context *context, Allocator &alloc) throw() - { alloc.free(context->ContextAttributes); alloc.free(context); } - -public: - // Post-IPC context fixup. - // This can only be called on a Built Context after IPC transmission. - void postIPC(void *base, CSSM_CONTEXT_ATTRIBUTE *ipcAttributes); - -public: - class Builder; - - // dump to stdout, multiline format - IFDUMP(void dump(const char *title = NULL, - const CSSM_CONTEXT_ATTRIBUTE *attrs = NULL) const;) - -protected: - // find an attribute in a plain array of attribute structures (no context) - static Attr *find(CSSM_ATTRIBUTE_TYPE theType, - const CSSM_CONTEXT_ATTRIBUTE *attrs, unsigned int count); -}; - - -namespace DataWalkers { - - -template -void walk(Action &operate, CSSM_CONTEXT_ATTRIBUTE &attr) -{ - operate(attr); - if (attr.Attribute.String) // non-NULL pointer (imprecise but harmless) - switch (attr.AttributeType & CSSM_ATTRIBUTE_TYPE_MASK) { - case CSSM_ATTRIBUTE_DATA_CSSM_DATA: - walk(operate, attr.Attribute.Data); break; - case CSSM_ATTRIBUTE_DATA_CRYPTO_DATA: - walk(operate, attr.Attribute.CryptoData); break; - case CSSM_ATTRIBUTE_DATA_KEY: - walk(operate, attr.Attribute.Key); break; - case CSSM_ATTRIBUTE_DATA_STRING: - walk(operate, attr.Attribute.String); break; - case CSSM_ATTRIBUTE_DATA_DATE: - walk(operate, attr.Attribute.Date); break; - case CSSM_ATTRIBUTE_DATA_RANGE: - walk(operate, attr.Attribute.Range); break; - case CSSM_ATTRIBUTE_DATA_ACCESS_CREDENTIALS: - walk(operate, attr.Attribute.AccessCredentials); break; - case CSSM_ATTRIBUTE_DATA_VERSION: - walk(operate, attr.Attribute.Version); break; - case CSSM_ATTRIBUTE_DATA_DL_DB_HANDLE: - walk(operate, attr.Attribute.DLDBHandle); break; - case CSSM_ATTRIBUTE_NONE: - case CSSM_ATTRIBUTE_DATA_UINT32: - break; - default: - secdebug("walkers", "invalid attribute (%ux) in context", (unsigned)attr.AttributeType); - break; - } -} - -template -void walk(Action &operate, Context::Attr &attr) -{ - walk(operate, static_cast(attr)); -} - -} // end namespace DataWalkers - - -// -// Context::Builder - make context attributes the fun way. -// -// A Context (aka CSSM_CONTEXT) has a pointer to an array of context attributes, -// most of which contain pointers to other stuff with pointers to God Knows Where. -// Instead of allocating this all over the heap, a Context::Builder performs -// a two-pass algorithm that places all that stuff into a single heap node. -// Specifically, the builder will allocate and create a vector of CSSM_CONTEXT_ATTRIBUTE -// structures and all their subordinate heap storage. -// A Builder does not deal in Context objects and does not care what you do with your -// CSSM_CONTEXT_ATTRIBUTE array once it's delivered. Since it's a single heap node, -// you can just free() it using the appropriate allocator when you're done with it. -// -// Theory of operation: -// Builder works in two phases, called scan and build. During scan, you call setup() -// with the desired data to be placed into the attribute vector. When done, call make() -// to switch to build phase. Then call put() with the SAME sequence of values as in phase 1. -// Finally, call done() to receive the pointer-and-count values. -// @@@ Add comment about IPC use. -// -using namespace DataWalkers; - -class Context::Builder { -protected: -public: - Builder(Allocator &alloc) : allocator(alloc) - { slotCount = 0; attributes = NULL; } - ~Builder() { allocator.free(attributes); } - - Allocator &allocator; - - // switch to build phase - size_t make(); - // deliver result - void done(CSSM_CONTEXT_ATTRIBUTE * &attributes, uint32 &count); - -public: - // - // Phase 1 (scan) dispatch. Call once for each attribute needed. - // - template - void setup(T p, CSSM_RETURN invalidError = CSSM_OK) - { - if (p) { - slotCount++; - walk(sizer, unconst_ref_cast(p)); - } else if (invalidError) - CssmError::throwMe(invalidError); - } - - void setup(uint32 n, CSSM_RETURN invalidError = CSSM_OK) - { - if (n) - slotCount++; - else if (invalidError) - CssmError::throwMe(invalidError); - } - - void setup(CSSM_SIZE n, CSSM_RETURN invalidError = CSSM_OK) - { - if (n) - slotCount++; - else if (invalidError) - CssmError::throwMe(invalidError); - } - - void setup(const CSSM_KEY *k, CSSM_RETURN invalidError = CSSM_OK) - { - if (!invalidError) { - if (k) { - slotCount++; - walk(sizer, unconst_ref_cast(k)); - } - return; // no additional validation performed - } - // perform a basic sanity check of the input CSSM_KEY - if (!(k) || (k->KeyHeader.HeaderVersion > CSSM_KEYHEADER_VERSION)) { - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_REFERENCE); - } - // must not point to an odd address or NULL - if (!(k->KeyData.Data) || ((uint64_t)k->KeyData.Data & (uint64_t)1)) { - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_POINTER); - } - // simplistic key data length check - if ((k->KeyData.Length < 4) || (k->KeyData.Length > 32768)) { - CssmError::throwMe(CSSMERR_CSP_INVALID_KEY_FORMAT); - } - slotCount++; - walk(sizer, unconst_ref_cast(k)); - } - - // dynamic attribute type - void setup(const CSSM_CONTEXT_ATTRIBUTE &attr) - { slotCount++; walk(sizer, const_cast(attr)); } - void setup(const Context::Attr &attr) { setup(static_cast(attr)); } - - // - // Phase 2 (copy) dispatch. Call once for each attribute, in same order as setup(). - // - template - void put(CSSM_ATTRIBUTE_TYPE type, const T *p) - { - if (p) { - assert(slot < slotCount); // check overflow - Attr &attribute = attributes[slot++]; - attribute.AttributeType = type; - attribute.AttributeLength = (uint32)size(p); //@@@ needed? how/when/what for? - T *tmp = const_cast(p); - attribute = walk(copier, tmp); - } - } - void put(CSSM_ATTRIBUTE_TYPE type, uint32 value) - { - if (value) { - assert(slot < slotCount); // check overflow - Attr &attribute = attributes[slot++]; - attribute.AttributeType = type; - attribute.AttributeLength = 0; //@@@ unclear what that should be - attribute = value; // no heap data (immediate value) - } - } - void put(const CSSM_CONTEXT_ATTRIBUTE &attr) - { - assert(slot < slotCount); - Attr &attribute = attributes[slot++]; - attribute = attr; // shallow copy - walk(copier, attribute); // deep copy - } - void put(const Context::Attr &attr) { put(static_cast(attr)); } - -private: - // pass 1 state: collect sizes and counts - unsigned slotCount; // count of attribute slots in use - SizeWalker sizer; // memory size calculator - - // pass 2 state: build the data set - Context::Attr *attributes; // attribute vector and start of block - CopyWalker copier; // data copy engine - uint32 slot; // writer slot position -}; - -} // end namespace Security - -#endif //_H_CONTEXT diff --git a/OSX/include/security_cdsa_utilities/cssmacl.cpp b/OSX/include/security_cdsa_utilities/cssmacl.cpp deleted file mode 100644 index 58a65464..00000000 --- a/OSX/include/security_cdsa_utilities/cssmacl.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmacl - core ACL management interface -// -#include diff --git a/OSX/include/security_cdsa_utilities/cssmacl.h b/OSX/include/security_cdsa_utilities/cssmacl.h deleted file mode 100644 index abb2795f..00000000 --- a/OSX/include/security_cdsa_utilities/cssmacl.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmacl - core ACL management interface. -// -// This header once contain the entire canonical ACL machinery. It's been split up -// since, into objectacl.h and aclsubject.h. What remains is the PodWrapper for -// ResourceControlContext, because nobody else wants it. -// -#ifndef _CSSMACL -#define _CSSMACL - -#include -#include - - -namespace Security { - - -// -// This bastard child of two different data structure sets has no natural home. -// We'll take pity on it here. -// -class ResourceControlContext : public PodWrapper { -public: - ResourceControlContext() { clearPod(); } - ResourceControlContext(const AclEntryInput &initial, - const AccessCredentials *cred = NULL) - { InitialAclEntry = initial; AccessCred = const_cast(cred); } - - AclEntryInput &input() { return AclEntryInput::overlay(InitialAclEntry); } - operator AclEntryInput &() { return input(); } - AccessCredentials *credentials() const { return AccessCredentials::overlay(AccessCred); } - void credentials(const CSSM_ACCESS_CREDENTIALS *creds) - { AccessCred = const_cast(creds); } -}; - -} // end namespace Security - - -#endif //_CSSMACL diff --git a/OSX/include/security_cdsa_utilities/cssmaclpod.cpp b/OSX/include/security_cdsa_utilities/cssmaclpod.cpp deleted file mode 100644 index 96a32b50..00000000 --- a/OSX/include/security_cdsa_utilities/cssmaclpod.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006-2007,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmaclpod - enhanced PodWrappers for ACL-related CSSM data structures -// -#include -#include -#include - - -namespace Security { - - -// -// AclAuthorizationSets -// -AclAuthorizationSet::AclAuthorizationSet(AclAuthorization auth0, AclAuthorization auth, ...) -{ - insert(auth0); - - va_list args; - va_start(args, auth); - while (auth) { - insert(auth); - auth = va_arg(args, AclAuthorization); - } - va_end(args); -} - - -// -// AclAuthorizationGroups -// -AuthorizationGroup::AuthorizationGroup(const AclAuthorizationSet &auths, Allocator &alloc) -{ - NumberOfAuthTags = (uint32)auths.size(); - AuthTags = alloc.alloc(NumberOfAuthTags); - copy(auths.begin(), auths.end(), AuthTags); // happens to be sorted -} - -AuthorizationGroup::AuthorizationGroup(CSSM_ACL_AUTHORIZATION_TAG tag, Allocator &alloc) -{ - AuthTags = alloc.alloc(1); - AuthTags[0] = tag; - NumberOfAuthTags = 1; -} - -void AuthorizationGroup::destroy(Allocator &alloc) -{ - alloc.free(AuthTags); -} - -bool AuthorizationGroup::contains(CSSM_ACL_AUTHORIZATION_TAG tag) const -{ - return find(AuthTags, &AuthTags[NumberOfAuthTags], tag) != &AuthTags[NumberOfAuthTags]; -} - - -AuthorizationGroup::operator AclAuthorizationSet() const -{ - return AclAuthorizationSet(AuthTags, &AuthTags[NumberOfAuthTags]); -} - -AclEntryPrototype::AclEntryPrototype(const AclOwnerPrototype &proto) -{ - memset(this, 0, sizeof(*this)); - TypedSubject = proto.subject(); Delegate = proto.delegate(); - //@@@ set authorization to "is owner" pseudo-auth? See cssmacl.h -} - -void AclEntryPrototype::tag(const char *tagString) -{ - if (tagString == NULL) - EntryTag[0] = '\0'; - else if (strlen(tagString) > CSSM_MODULE_STRING_SIZE) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG); - else - strcpy(EntryTag, tagString); -} - -void AclEntryPrototype::tag(const string &tagString) -{ - if (tagString.length() > CSSM_MODULE_STRING_SIZE) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG); - else - memcpy(EntryTag, tagString.c_str(), tagString.length() + 1); -} - - -AclOwnerPrototype *AutoAclOwnerPrototype::make() -{ - if (!mAclOwnerPrototype) { - mAclOwnerPrototype = (AclOwnerPrototype*) mAllocator->malloc(sizeof(AclOwnerPrototype)); - new (mAclOwnerPrototype) AclOwnerPrototype; - mAclOwnerPrototype->clearPod(); - } - return mAclOwnerPrototype; -} - -AutoAclOwnerPrototype::~AutoAclOwnerPrototype() -{ - if (mAllocator) - DataWalkers::chunkFree(mAclOwnerPrototype, *mAllocator); -} - -void -AutoAclOwnerPrototype::allocator(Allocator &allocator) -{ - mAllocator = &allocator; -} - - -void AutoAclEntryInfoList::size(uint32 newSize) -{ - assert(mAllocator); - mEntries = mAllocator->alloc(mEntries, newSize); - for (uint32 n = mCount; n < newSize; n++) - mEntries[n].clearPod(); - mCount = newSize; -} - - -AclEntryInfo &AutoAclEntryInfoList::at(uint32 ix) -{ - if (ix >= mCount) - size(ix + 1); // expand vector - return mEntries[ix]; -} - - -void AutoAclEntryInfoList::clear() -{ - if (mAllocator) - { - DataWalkers::ChunkFreeWalker w(*mAllocator); - for (uint32 ix = 0; ix < mCount; ix++) - walk(w, mEntries[ix]); - mAllocator->free(mEntries); - mEntries = NULL; - mCount = 0; - } -} - -void AutoAclEntryInfoList::allocator(Allocator &allocator) -{ - mAllocator = &allocator; -} - - -void AutoAclEntryInfoList::add(const TypedList &subj, const AclAuthorizationSet &auths, const char *tag /* = NULL */) -{ - AclEntryInfo &info = at(size()); - info.proto() = AclEntryPrototype(subj); - info.proto().authorization() = AuthorizationGroup(auths, allocator()); - info.proto().tag(tag); - info.handle(size()); -} - -void AutoAclEntryInfoList::addPin(const TypedList &subj, uint32 slot) -{ - char tag[20]; - snprintf(tag, sizeof(tag), "PIN%d", slot); - add(subj, CSSM_ACL_AUTHORIZATION_PREAUTH(slot), tag); -} - -void AutoAclEntryInfoList::addPinState(uint32 slot, uint32 status) -{ - char tag[20]; - snprintf(tag, sizeof(tag), "PIN%d?", slot); - TypedList subj(allocator(), CSSM_WORDID_PIN, - new(allocator()) ListElement(slot), - new(allocator()) ListElement(status)); - add(subj, CSSM_WORDID_PIN, tag); -} - -void AutoAclEntryInfoList::addPinState(uint32 slot, uint32 status, uint32 count) -{ - char tag[20]; - snprintf(tag, sizeof(tag), "PIN%d?", slot); - TypedList subj(allocator(), CSSM_WORDID_PIN, - new(allocator()) ListElement(slot), - new(allocator()) ListElement(status), - new(allocator()) ListElement(count)); - add(subj, CSSM_WORDID_PIN, tag); -} - -uint32 pinFromAclTag(const char *tag, const char *suffix /* = NULL */) -{ - if (tag) { - char format[20]; - snprintf(format, sizeof(format), "PIN%%d%s%%n", suffix ? suffix : ""); - uint32 pin; - unsigned consumed; - sscanf(tag, format, &pin, &consumed); - if (consumed == strlen(tag)) // complete and sufficient - return pin; - } - return 0; -} - -} // namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmaclpod.h b/OSX/include/security_cdsa_utilities/cssmaclpod.h deleted file mode 100644 index bf23f7df..00000000 --- a/OSX/include/security_cdsa_utilities/cssmaclpod.h +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright (c) 2000-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmaclpod - enhanced PodWrappers for ACL-related CSSM data structures -// -#ifndef _CSSMACLPOD -#define _CSSMACLPOD - -#include -#include -#include - -namespace Security { - -// a nicer name for an authorization tag -typedef CSSM_ACL_AUTHORIZATION_TAG AclAuthorization; - - -// -// An STL set of authorization tags, with some convenience features -// -class AclAuthorizationSet : public std::set { -public: - AclAuthorizationSet() { } - AclAuthorizationSet(AclAuthorization auth) { insert(auth); } - AclAuthorizationSet(AclAuthorization *authBegin, AclAuthorization *authEnd) - : set(authBegin, authEnd) { } - AclAuthorizationSet(AclAuthorization a1, AclAuthorization a2, ...); // list of auths, end with zero -}; - - -// -// Enhanced POD Wrappers for the public ACL-related CSSM structures -// -class AuthorizationGroup : public PodWrapper { -public: - AuthorizationGroup() { NumberOfAuthTags = 0; } - AuthorizationGroup(const AclAuthorizationSet &, Allocator &alloc); - AuthorizationGroup(AclAuthorization tag, Allocator &alloc); - void destroy(Allocator &alloc); - - bool empty() const { return NumberOfAuthTags == 0; } - unsigned int size() const { return NumberOfAuthTags; } - unsigned int count() const { return NumberOfAuthTags; } - CSSM_ACL_AUTHORIZATION_TAG operator [] (unsigned ix) const - { assert(ix < size()); return AuthTags[ix]; } - - bool contains(CSSM_ACL_AUTHORIZATION_TAG tag) const; - operator AclAuthorizationSet () const; -}; - -class AclOwnerPrototype; - -class AclEntryPrototype : public PodWrapper { -public: - AclEntryPrototype() { clearPod(); } - explicit AclEntryPrototype(const AclOwnerPrototype &proto); - AclEntryPrototype(const CSSM_LIST &subj, bool delegate = false) - { clearPod(); TypedSubject = subj; Delegate = delegate; } - - TypedList &subject() { return TypedList::overlay(TypedSubject); } - const TypedList &subject() const { return TypedList::overlay(TypedSubject); } - - bool delegate() const { return Delegate; } - void delegate(bool d) { Delegate = d; } - - char *tag() { return EntryTag[0] ? EntryTag : NULL; } - void tag(const char *tagString); - void tag(const std::string &tagString); - const char *tag() const { return EntryTag[0] ? EntryTag : NULL; } - std::string s_tag() const { return EntryTag; } - - AuthorizationGroup &authorization() { return AuthorizationGroup::overlay(Authorization); } - const AuthorizationGroup &authorization() const - { return AuthorizationGroup::overlay(Authorization); } -}; - -class AclOwnerPrototype : public PodWrapper { -public: - AclOwnerPrototype() { clearPod(); } - explicit AclOwnerPrototype(const AclEntryPrototype &proto) - { TypedSubject = proto.subject(); delegate(proto.delegate()); } - AclOwnerPrototype(const CSSM_LIST &subj, bool del = false) - { TypedSubject = subj; delegate(del); } - - TypedList &subject() { return TypedList::overlay(TypedSubject); } - const TypedList &subject() const { return TypedList::overlay(TypedSubject); } - bool delegate() const { return Delegate; } - void delegate(bool d) { Delegate = d; } -}; - -class AclEntryInfo : public PodWrapper { -public: - AclEntryInfo() { clearPod(); } - AclEntryInfo(const AclEntryPrototype &prot, CSSM_ACL_HANDLE h = 0) - { proto() = prot; handle() = h; } - - AclEntryPrototype &proto() { return AclEntryPrototype::overlay(EntryPublicInfo); } - const AclEntryPrototype &proto() const - { return AclEntryPrototype::overlay(EntryPublicInfo); } - - operator AclEntryPrototype &() { return proto(); } - operator const AclEntryPrototype &() const { return proto(); } - - CSSM_ACL_HANDLE &handle() { return EntryHandle; } - const CSSM_ACL_HANDLE &handle() const { return EntryHandle; } - void handle(CSSM_ACL_HANDLE h) { EntryHandle = h; } -}; - -class AclEntryInput : public PodWrapper { -public: - AclEntryInput() { clearPod(); } - AclEntryInput(const CSSM_ACL_ENTRY_PROTOTYPE &prot) - { Prototype = prot; Callback = NULL; CallerContext = NULL; } - - AclEntryInput &operator = (const CSSM_ACL_ENTRY_PROTOTYPE &prot) - { Prototype = prot; Callback = NULL; CallerContext = NULL; return *this; } - - AclEntryPrototype &proto() { return AclEntryPrototype::overlay(Prototype); } - const AclEntryPrototype &proto() const { return AclEntryPrototype::overlay(Prototype); } - //@@@ not supporting callback features (yet) -}; - -class AclEdit : public PodWrapper { -public: - AclEdit(CSSM_ACL_EDIT_MODE m, CSSM_ACL_HANDLE h, const AclEntryInput *data) - { EditMode = m; OldEntryHandle = h; NewEntry = data; } - AclEdit(const AclEntryInput &add) - { EditMode = CSSM_ACL_EDIT_MODE_ADD; OldEntryHandle = CSSM_INVALID_HANDLE; NewEntry = &add; } - AclEdit(CSSM_ACL_HANDLE h, const AclEntryInput &modify) - { EditMode = CSSM_ACL_EDIT_MODE_REPLACE; OldEntryHandle = h; NewEntry = &modify; } - AclEdit(CSSM_ACL_HANDLE h) - { EditMode = CSSM_ACL_EDIT_MODE_DELETE; OldEntryHandle = h; NewEntry = NULL; } - - CSSM_ACL_EDIT_MODE mode() const { return EditMode; } - CSSM_ACL_HANDLE handle() const { return OldEntryHandle; } - const AclEntryInput *newEntry() const { return AclEntryInput::overlay(NewEntry); } -}; - - -// -// Allocating versions of Acl structures -// -class AutoAclOwnerPrototype { - NOCOPY(AutoAclOwnerPrototype) -public: - // allocator can be set after construction - AutoAclOwnerPrototype(Allocator *allocator = NULL) - : mAclOwnerPrototype(NULL), mAllocator(allocator) { } - ~AutoAclOwnerPrototype(); - - operator bool () const { return mAllocator; } - bool operator ! () const { return !mAllocator; } - - operator AclOwnerPrototype * () { return make(); } - operator AclOwnerPrototype & () { return *make(); } - AclOwnerPrototype &operator * () { return *make(); } - - TypedList &subject() { return make()->subject(); } - TypedList &subject() const - { assert(mAclOwnerPrototype); return mAclOwnerPrototype->subject(); } - bool delegate() const - { assert(mAclOwnerPrototype); return mAclOwnerPrototype->delegate(); } - void delegate(bool d) { make()->delegate(d); } - - void allocator(Allocator &allocator); - Allocator &allocator() const { assert(mAllocator); return *mAllocator; } - - AclOwnerPrototype &operator = (const TypedList &subj) - { make()->subject() = subj; make()->delegate(false); return *mAclOwnerPrototype; } - - const AclOwnerPrototype *release() - { AclOwnerPrototype *r = mAclOwnerPrototype; mAclOwnerPrototype = NULL; return r; } - -private: - AclOwnerPrototype *mAclOwnerPrototype; - Allocator *mAllocator; - - AclOwnerPrototype *make(); -}; - - -class AutoAclEntryInfoList { - NOCOPY(AutoAclEntryInfoList) -public: - // allocator can be set after construction - AutoAclEntryInfoList(Allocator *allocator = NULL) - : mEntries(NULL), mCount(0), mAllocator(allocator) { } - ~AutoAclEntryInfoList() { clear(); } - - operator bool () const { return mAllocator; } - bool operator ! () const { return !mAllocator; } - operator uint32 *() { return &mCount; } - operator CSSM_ACL_ENTRY_INFO ** () { return reinterpret_cast(&mEntries); } - - void allocator(Allocator &allocator); - Allocator &allocator() const { assert(mAllocator); return *mAllocator; } - - const AclEntryInfo &at(uint32 ix) const - { assert(ix < mCount); return mEntries[ix]; } - const AclEntryInfo &operator [] (uint32 ix) const { return at(ix); } - AclEntryInfo &at(uint32 ix); - AclEntryInfo &operator[] (uint32 ix) { return at(ix); } - - uint32 size() const { return mCount; } - uint32 count() const { return mCount; } - AclEntryInfo *entries() const { return mEntries; } - - void clear(); - void size(uint32 newSize); - - // structured adders. Inputs must be chunk-allocated with our Allocator - void add(const TypedList &subj, const AclAuthorizationSet &auths, const char *tag = NULL); - void addPin(const TypedList &subj, uint32 slot); - void addPinState(uint32 slot, uint32 state); - void addPinState(uint32 slot, uint32 state, uint32 count); - - void release() { mAllocator = NULL; } - -private: - AclEntryInfo *mEntries; - uint32 mCount; - Allocator *mAllocator; -}; - -// -// Extract the pin number from a "PIN%d?" tag. -// Returns 0 if the tag isn't of that form. -// -uint32 pinFromAclTag(const char *tag, const char *suffix = NULL); - - -class AutoAuthorizationGroup : public AuthorizationGroup { -public: - AutoAuthorizationGroup(Allocator &alloc) : allocator(alloc) { } - explicit AutoAuthorizationGroup(const AclAuthorizationSet &set, - Allocator &alloc) : AuthorizationGroup(set, alloc), allocator(alloc) { } - ~AutoAuthorizationGroup() { destroy(allocator); } - - Allocator &allocator; -}; - - -// -// Walkers for the CSSM API structure types -// -namespace DataWalkers { - -// AclEntryInput -template -AclEntryInput *walk(Action &operate, AclEntryInput * &input) -{ - operate(input); - walk(operate, input->proto()); - return input; -} - -template -void walk(Action &operate, AclEntryInput &input) -{ - operate(input); - walk(operate, input.proto()); -} - -// AclEntryInfo -template -void walk(Action &operate, AclEntryInfo &info) -{ - operate(info); - walk(operate, info.proto()); -} - -// AuthorizationGroup -template -void walk(Action &operate, AuthorizationGroup &auth) -{ - operate(auth); - uint32 count = auth.count(); - operate.blob(auth.AuthTags, count * sizeof(auth.AuthTags[0])); - for (uint32 n = 0; n < count; n++) - operate(auth.AuthTags[n]); -} - -template -void walk(Action &operate, CSSM_AUTHORIZATIONGROUP &auth) -{ walk(operate, static_cast(auth)); } - -// AclEntryPrototype -template -void enumerate(Action &operate, AclEntryPrototype &proto) -{ - walk(operate, proto.subject()); - walk(operate, proto.authorization()); - //@@@ ignoring validity period -} - -template -void walk(Action &operate, AclEntryPrototype &proto) -{ - operate(proto); - enumerate(operate, proto); -} - -template -AclEntryPrototype *walk(Action &operate, AclEntryPrototype * &proto) -{ - operate(proto); - enumerate(operate, *proto); - return proto; -} - -// AclOwnerPrototype -template -void walk(Action &operate, AclOwnerPrototype &proto) -{ - operate(proto); - walk(operate, proto.subject()); -} - -template -AclOwnerPrototype *walk(Action &operate, AclOwnerPrototype * &proto) -{ - operate(proto); - walk(operate, proto->subject()); - return proto; -} - - -} // end namespace DataWalkers - -} // end namespace Security - - -#endif //_CSSMACLPOD diff --git a/OSX/include/security_cdsa_utilities/cssmalloc.cpp b/OSX/include/security_cdsa_utilities/cssmalloc.cpp deleted file mode 100644 index b2a47672..00000000 --- a/OSX/include/security_cdsa_utilities/cssmalloc.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmalloc - memory allocation in the CDSA world. -// -// Don't eat heavily before inspecting this code. -// -#include -#include -#include - - - -namespace Security { - - -// -// CssmMemoryFunctionsAllocators -// -void *CssmMemoryFunctionsAllocator::malloc(size_t size) throw(std::bad_alloc) -{ return functions.malloc(size); } - -void CssmMemoryFunctionsAllocator::free(void *addr) throw() -{ return functions.free(addr); } - -void *CssmMemoryFunctionsAllocator::realloc(void *addr, size_t size) throw(std::bad_alloc) -{ return functions.realloc(addr, size); } - - -// -// CssmAllocatorMemoryFunctions -// -CssmAllocatorMemoryFunctions::CssmAllocatorMemoryFunctions(Allocator &alloc) -{ - AllocRef = &alloc; - malloc_func = relayMalloc; - free_func = relayFree; - realloc_func = relayRealloc; - calloc_func = relayCalloc; -} - -void *CssmAllocatorMemoryFunctions::relayMalloc(size_t size, void *ref) throw(std::bad_alloc) -{ return allocator(ref).malloc(size); } - -void CssmAllocatorMemoryFunctions::relayFree(void *mem, void *ref) throw() -{ allocator(ref).free(mem); } - -void *CssmAllocatorMemoryFunctions::relayRealloc(void *mem, size_t size, void *ref) throw(std::bad_alloc) -{ return allocator(ref).realloc(mem, size); } - -void *CssmAllocatorMemoryFunctions::relayCalloc(uint32 count, size_t size, void *ref) throw(std::bad_alloc) -{ - // Allocator doesn't have a calloc() method - void *mem = allocator(ref).malloc(size * count); - memset(mem, 0, size * count); - return mem; -} - - -// -// CssmVector -// - - -} // namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmalloc.h b/OSX/include/security_cdsa_utilities/cssmalloc.h deleted file mode 100644 index 01a14e37..00000000 --- a/OSX/include/security_cdsa_utilities/cssmalloc.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmalloc - memory allocation in the CDSA world -// -#ifndef _H_CSSMALLOC -#define _H_CSSMALLOC - -#include -#include -#include - - -namespace Security -{ - - -// -// A POD wrapper for the memory functions structure passed around in CSSM. -// -class CssmMemoryFunctions : public PodWrapper { -public: - CssmMemoryFunctions(const CSSM_MEMORY_FUNCS &funcs) - { *(CSSM_MEMORY_FUNCS *)this = funcs; } - CssmMemoryFunctions() { } - - void *malloc(size_t size) const throw(std::bad_alloc); - void free(void *mem) const throw() { free_func(mem, AllocRef); } - void *realloc(void *mem, size_t size) const throw(std::bad_alloc); - void *calloc(uint32 count, size_t size) const throw(std::bad_alloc); - - bool operator == (const CSSM_MEMORY_FUNCS &other) const throw() - { return !memcmp(this, &other, sizeof(*this)); } -}; - -inline void *CssmMemoryFunctions::malloc(size_t size) const throw(std::bad_alloc) -{ - if (void *addr = malloc_func(size, AllocRef)) - return addr; - throw std::bad_alloc(); -} - -inline void *CssmMemoryFunctions::calloc(uint32 count, size_t size) const throw(std::bad_alloc) -{ - if (void *addr = calloc_func(count, size, AllocRef)) - return addr; - throw std::bad_alloc(); -} - -inline void *CssmMemoryFunctions::realloc(void *mem, size_t size) const throw(std::bad_alloc) -{ - if (void *addr = realloc_func(mem, size, AllocRef)) - return addr; - throw std::bad_alloc(); -} - - -// -// A Allocator based on CssmMemoryFunctions -// -class CssmMemoryFunctionsAllocator : public Allocator { -public: - CssmMemoryFunctionsAllocator(const CssmMemoryFunctions &memFuncs) : functions(memFuncs) { } - - void *malloc(size_t size) throw(std::bad_alloc); - void free(void *addr) throw(); - void *realloc(void *addr, size_t size) throw(std::bad_alloc); - - operator const CssmMemoryFunctions & () const throw() { return functions; } - -private: - const CssmMemoryFunctions functions; -}; - - -// -// A MemoryFunctions object based on a Allocator. -// Note that we don't copy the Allocator object. It needs to live (at least) -// as long as any CssmAllocatorMemoryFunctions object based on it. -// -class CssmAllocatorMemoryFunctions : public CssmMemoryFunctions { -public: - CssmAllocatorMemoryFunctions(Allocator &alloc); - CssmAllocatorMemoryFunctions() { /*IFDEBUG(*/ AllocRef = NULL /*)*/ ; } // later assignment req'd - -private: - static void *relayMalloc(size_t size, void *ref) throw(std::bad_alloc); - static void relayFree(void *mem, void *ref) throw(); - static void *relayRealloc(void *mem, size_t size, void *ref) throw(std::bad_alloc); - static void *relayCalloc(uint32 count, size_t size, void *ref) throw(std::bad_alloc); - - static Allocator &allocator(void *ref) throw() - { return *reinterpret_cast(ref); } -}; - - -// -// A generic helper for the unhappily ubiquitous CSSM-style -// (count, pointer-to-array) style of arrays. -// -template -class CssmVector { -public: - CssmVector(uint32 &cnt, Base * &vec, Allocator &alloc = Allocator::standard()) - : count(cnt), vector(reinterpret_cast(vec)), - allocator(alloc) - { - count = 0; - vector = NULL; - } - - ~CssmVector() { allocator.free(vector); } - - uint32 &count; - Wrapper * &vector; - Allocator &allocator; - -public: - Wrapper &operator [] (uint32 ix) - { assert(ix < count); return vector[ix]; } - - void operator += (const Wrapper &add) - { - vector = reinterpret_cast(allocator.realloc(vector, (count + 1) * sizeof(Wrapper))); - //@@@???compiler bug??? vector = allocator.alloc(vector, count + 1); - vector[count++] = add; - } -}; - - -} // end namespace Security - -#endif //_H_CSSMALLOC diff --git a/OSX/include/security_cdsa_utilities/cssmbridge.h b/OSX/include/security_cdsa_utilities/cssmbridge.h deleted file mode 100644 index f2f92dbd..00000000 --- a/OSX/include/security_cdsa_utilities/cssmbridge.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// CSSM-style C/C++ bridge facilities -// -#ifndef _H_CSSMBRIDGE -#define _H_CSSMBRIDGE - -#include -#include -#include - - -namespace Security { - - -// -// API boilerplate macros. These provide a frame for C++ code that is impermeable to exceptions. -// Usage: -// BEGIN_API -// ... your C++ code here ... -// END_API(base) // returns CSSM_RETURN on exception; complete it to 'base' (DL, etc.) class; -// // returns CSSM_OK on fall-through -// END_API0 // completely ignores exceptions; falls through in all cases -// END_API1(bad) // return (bad) on exception; fall through on success -// -#define BEGIN_API try { -#define END_API(base) } \ -catch (const CommonError &err) { return CssmError::cssmError(err, CSSM_ ## base ## _BASE_ERROR); } \ -catch (const std::bad_alloc &) { return CssmError::cssmError(CSSM_ERRCODE_MEMORY_ERROR, CSSM_ ## base ## _BASE_ERROR); } \ -catch (...) { return CssmError::cssmError(CSSM_ERRCODE_INTERNAL_ERROR, CSSM_ ## base ## _BASE_ERROR); } \ - return CSSM_OK; -#define END_API0 } catch (...) { return; } -#define END_API1(bad) } catch (...) { return bad; } - - -} // end namespace Security - - -#endif //_H_CSSMBRIDGE diff --git a/OSX/include/security_cdsa_utilities/cssmcert.cpp b/OSX/include/security_cdsa_utilities/cssmcert.cpp deleted file mode 100644 index dc7c0c05..00000000 --- a/OSX/include/security_cdsa_utilities/cssmcert.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmcert - CSSM layer certificate (CL) related objects. -// -#include -#include - - -namespace Security { - - -// -// Construct an EncodedCertificate -// -EncodedCertificate::EncodedCertificate(CSSM_CERT_TYPE type, CSSM_CERT_ENCODING enc, - const CSSM_DATA *data) -{ - clearPod(); - CertType = type; - CertEncoding = enc; - if (data) - CertBlob = *data; -} - - -// -// Construct an empty CertGroup. -// -CertGroup::CertGroup(CSSM_CERT_TYPE ctype, - CSSM_CERT_ENCODING encoding, CSSM_CERTGROUP_TYPE type) -{ - clearPod(); - CertType = ctype; - CertEncoding = encoding; - CertGroupType = type; -} - - -// -// Free all memory in a CertGroup -// -void CertGroup::destroy(Allocator &allocator) -{ - switch (type()) { - case CSSM_CERTGROUP_DATA: - // array of CSSM_DATA elements - for (uint32 n = 0; n < count(); n++) - allocator.free(blobCerts()[n].data()); - allocator.free (blobCerts ()); - break; - case CSSM_CERTGROUP_ENCODED_CERT: - for (uint32 n = 0; n < count(); n++) - allocator.free(encodedCerts()[n].data()); - allocator.free (blobCerts ()); - break; - case CSSM_CERTGROUP_PARSED_CERT: - // CSSM_PARSED_CERTS array -- unimplemented - case CSSM_CERTGROUP_CERT_PAIR: - // CSSM_CERT_PAIR array -- unimplemented - break; - } -} - - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmcert.h b/OSX/include/security_cdsa_utilities/cssmcert.h deleted file mode 100644 index 551a9a6e..00000000 --- a/OSX/include/security_cdsa_utilities/cssmcert.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmcert - CSSM layer certificate (CL) related objects. -// -#ifndef _H_CSSMCERT -#define _H_CSSMCERT - -#include -#include - - -namespace Security { - - -// -// A CSSM_FIELD, essentially an OID/Data pair. -// -class CssmField : public PodWrapper { -public: - CssmField() { } - CssmField(const CSSM_OID &oid, const CSSM_DATA &value) - { FieldOid = oid; FieldValue = value; } - - CssmField(const CSSM_OID &oid) - { FieldOid = oid; FieldValue = CssmData(); } - -public: - CssmOid &oid() { return CssmOid::overlay(FieldOid); } - CssmOid &value() { return CssmOid::overlay(FieldValue); } - const CssmOid &oid() const { return CssmOid::overlay(FieldOid); } - const CssmOid &value() const { return CssmOid::overlay(FieldValue); } - - bool isComplex() const - { return value().length() == CSSM_FIELDVALUE_COMPLEX_DATA_TYPE; } -}; - - -// -// An encoded certificate -// -class EncodedCertificate : public PodWrapper { -public: - EncodedCertificate(CSSM_CERT_TYPE type = CSSM_CERT_UNKNOWN, - CSSM_CERT_ENCODING enc = CSSM_CERT_ENCODING_UNKNOWN, - const CSSM_DATA *data = NULL); - - CSSM_CERT_TYPE type() const { return CertType; } - CSSM_CERT_ENCODING encoding() const { return CertEncoding; } - const CssmData &blob() const { return CssmData::overlay(CertBlob); } - - // CssmDataoid features - void *data() const { return blob().data(); } - size_t length() const { return blob().length(); } -}; - - -// -// CertGroups - groups of certificates in a bewildering variety of forms -// -class CertGroup : public PodWrapper { -public: - CertGroup() { } - CertGroup(CSSM_CERT_TYPE ctype, CSSM_CERT_ENCODING encoding, CSSM_CERTGROUP_TYPE type); - -public: - CSSM_CERT_TYPE certType() const { return CertType; } - CSSM_CERT_ENCODING encoding() const { return CertEncoding; } - CSSM_CERTGROUP_TYPE type() const { return CertGroupType; } - uint32 count() const { return NumCerts; } - uint32 &count() { return NumCerts; } - -public: - // CSSM_CERTGROUP_DATA version - CssmData * &blobCerts() - { assert(type() == CSSM_CERTGROUP_DATA); return CssmData::overlayVar(GroupList.CertList); } - CssmData *blobCerts() const - { assert(type() == CSSM_CERTGROUP_DATA); return CssmData::overlay(GroupList.CertList); } - - // CSSM_CERTGROUP_ENCODED_CERT version - EncodedCertificate * &encodedCerts() - { return EncodedCertificate::overlayVar(GroupList.EncodedCertList); } - EncodedCertificate *encodedCerts() const - { return EncodedCertificate::overlay(GroupList.EncodedCertList); } - -public: - // free all memory in this group with the given allocator - void destroy(Allocator &allocator); -}; - - -// -// Walkers -// -namespace DataWalkers { - - - - -} // end namespace DataWalkers -} // end namespace Security - -#endif //_H_CSSMCERT diff --git a/OSX/include/security_cdsa_utilities/cssmcred.cpp b/OSX/include/security_cdsa_utilities/cssmcred.cpp deleted file mode 100644 index ff7d0925..00000000 --- a/OSX/include/security_cdsa_utilities/cssmcred.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmcred - enhanced PodWrappers and construction aids for ACL credentials -// -#include - - -namespace Security { - - -// -// The null credential constant. -// -static const CSSM_ACCESS_CREDENTIALS null_credentials = { "" }; // and more nulls -#if BUG_GCC -const AccessCredentials &AccessCredentials::null = - *static_cast(&null_credentials); -#else -const AccessCredentials &AccessCredentials::null = - static_cast(null_credentials); -#endif - - -// -// Scan a SampleGroup for samples with a given CSSM_SAMPLE_TYPE. -// Collect all matching samples into a list (which is cleared to begin with). -// Return true if any were found, false if none. -// Throw if any of the samples are obviously malformed. -// -bool SampleGroup::collect(CSSM_SAMPLE_TYPE sampleType, list &matches) const -{ - for (uint32 n = 0; n < length(); n++) { - TypedList sample = (*this)[n]; - sample.checkProper(); - if (sample.type() == sampleType) { - sample.snip(); // skip sample type - matches.push_back(sample); - } - } - return !matches.empty(); -} - - -// -// AccessCredentials -// -void AccessCredentials::tag(const char *tagString) -{ - if (tagString == NULL) - EntryTag[0] = '\0'; - else if (strlen(tagString) > CSSM_MODULE_STRING_SIZE) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG); - else - strcpy(EntryTag, tagString); -} - - -// -// AutoCredentials self-constructing credentials structure -// -AutoCredentials::AutoCredentials(Allocator &alloc) : allocator(alloc) -{ - init(); -} - -AutoCredentials::AutoCredentials(Allocator &alloc, uint32 nSamples) : allocator(alloc) -{ - init(); - getSample(nSamples - 1); // extend array to nSamples elements -} - -void AutoCredentials::init() -{ - sampleArray = NULL; - nSamples = 0; -} - - -CssmSample &AutoCredentials::getSample(uint32 n) -{ - if (n >= nSamples) { - sampleArray = allocator.alloc(sampleArray, nSamples = n + 1); - Samples.Samples = sampleArray; - Samples.NumberOfSamples = nSamples; - } - return sampleArray[n]; -} - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmcred.h b/OSX/include/security_cdsa_utilities/cssmcred.h deleted file mode 100644 index e0e8aae3..00000000 --- a/OSX/include/security_cdsa_utilities/cssmcred.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmcred - enhanced PodWrappers and construction aids for ACL credentials -// -#ifndef _CSSMCRED -#define _CSSMCRED - -#include -#include -#include -#include - -namespace Security { - - -// -// PodWrappers for samples and sample groups -// -class CssmSample : public PodWrapper { -public: - CssmSample(const TypedList &list) - { TypedSample = list; Verifier = NULL; } - CssmSample(const TypedList &list, const CssmSubserviceUid &ver) - { TypedSample = list; Verifier = &ver; } - - TypedList &value() { return TypedList::overlay(TypedSample); } - const TypedList &value() const { return TypedList::overlay(TypedSample); } - operator TypedList & () { return value(); } - - const CssmSubserviceUid *verifier() const { return CssmSubserviceUid::overlay(Verifier); } - CssmSubserviceUid * &verifier() - { return const_cast(CssmSubserviceUid::overlayVar(Verifier)); } -}; - -class SampleGroup : public PodWrapper { -public: - SampleGroup() { clearPod(); } - SampleGroup(CssmSample &single) { NumberOfSamples = 1; Samples = &single; } - - uint32 size() const { return NumberOfSamples; } - uint32 length() const { return size(); } // legacy; prefer size() - CssmSample *&samples() { return CssmSample::overlayVar(const_cast(Samples)); } - CssmSample *samples() const { return CssmSample::overlay(const_cast(Samples)); } - - CssmSample &operator [] (uint32 ix) const - { assert(ix < size()); return samples()[ix]; } - -public: - // extract all samples of a given sample type. return true if any found - // note that you get a shallow copy of the sample structures for temporary use ONLY - bool collect(CSSM_SAMPLE_TYPE sampleType, list &samples) const; -}; - - -// -// The PodWrapper for the top-level CSSM credentials structure -// -class AccessCredentials : public PodWrapper { -public: - AccessCredentials() { clearPod(); } - explicit AccessCredentials(const SampleGroup &samples, const char *tag = NULL) - { this->samples() = samples; this->tag(tag); } - explicit AccessCredentials(const SampleGroup &samples, const std::string &tag) - { this->samples() = samples; this->tag(tag); } - - const char *tag() const { return EntryTag[0] ? EntryTag : NULL; } - std::string s_tag() const { return EntryTag; } - void tag(const char *tagString); - void tag(const std::string &tagString) { return tag(tagString.c_str()); } - - SampleGroup &samples() { return SampleGroup::overlay(Samples); } - const SampleGroup &samples() const { return SampleGroup::overlay(Samples); } - - // pass-throughs to our SampleGroup - uint32 size() const { return samples().size(); } - CssmSample &operator [] (uint32 ix) const { return samples()[ix]; } - -public: - static const AccessCredentials &null; // all null credential - - // turn NULL into a null credential if needed - static const AccessCredentials *needed(const CSSM_ACCESS_CREDENTIALS *cred) - { return cred ? overlay(cred) : &null; } -}; - - -// -// An AccessCredentials object with some construction help. -// Note that this is NOT a PodWrapper. -// -class AutoCredentials : public AccessCredentials { -public: - AutoCredentials(Allocator &alloc); - AutoCredentials(Allocator &alloc, uint32 nSamples); - - Allocator &allocator; - - CssmSample &sample(uint32 n) { return getSample(n); } - - CssmSample &append(const CssmSample &sample) - { return getSample(samples().length()) = sample; } - TypedList &append(const TypedList &exhibit) - { return (getSample(samples().length()) = exhibit).value(); } - - CssmSample &operator += (const CssmSample &sample) { return append(sample); } - TypedList &operator += (const TypedList &exhibit) { return append(exhibit); } - -private: - void init(); - CssmSample &getSample(uint32 n); - - CssmSample *sampleArray; - uint32 nSamples; -}; - - -// -// Walkers for the CSSM API structure types. -// Note that there are irrational "const"s strewn about the credential sub-structures. -// They make it essentially impossible to incrementally construction them without -// violating them. Since we know what we're doing, we do. -// -namespace DataWalkers -{ - -// CssmSample (with const override) -template -void walk(Action &operate, CssmSample &sample) -{ - operate(sample); - walk(operate, sample.value()); - if (sample.verifier()) - walk(operate, sample.verifier()); -} - -// SampleGroup -template -void walk(Action &operate, SampleGroup &samples) -{ - operate(samples); - enumerateArray(operate, samples, &SampleGroup::samples); -} - -// AccessCredentials -template -AccessCredentials *walk(Action &operate, AccessCredentials * &cred) -{ - operate(cred); - //@@@ ignoring BaseCerts - walk(operate, cred->samples()); - //@@@ ignoring challenge callback - return cred; -} - -template -CSSM_ACCESS_CREDENTIALS *walk(Action &operate, CSSM_ACCESS_CREDENTIALS * &cred) -{ return walk(operate, AccessCredentials::overlayVar(cred)); } - -template -AutoCredentials *walk(Action &operate, AutoCredentials * &cred) -{ return (AutoCredentials *)walk(operate, (AccessCredentials * &)cred); } - - -} // end namespace DataWalkers -} // end namespace Security - - -#endif //_CSSMCRED diff --git a/OSX/include/security_cdsa_utilities/cssmdata.cpp b/OSX/include/security_cdsa_utilities/cssmdata.cpp deleted file mode 100644 index 5dec094e..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdata.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmdata.cpp -- Manager different CssmData types -// -#include -#include -#include -#include - - -namespace Security { - - -// -// Comparing raw CSSM_DATA things -// -bool operator == (const CSSM_DATA &d1, const CSSM_DATA &d2) -{ - if (&d1 == &d2) - return true; // identical - if (d1.Length != d2.Length) - return false; // can't be - if (d1.Data == d2.Data) - return true; // points to same data - return !memcmp(d1.Data, d2.Data, d1.Length); -} - - -// -// CssmData out of line members -// -string CssmData::toString() const -{ - return data() ? - string(reinterpret_cast(data()), length()) - : - string(); -} - - -// -// Conversion from/to hex digits. -// This could be separate functions, or Rep templates, but we just hang -// it onto generic CssmData. -// -string CssmData::toHex() const -{ - static const char digits[] = "0123456789abcdef"; - string result; - unsigned char *p = Data; - for (uint32 n = 0; n < length(); n++) { - result.push_back(digits[p[n] >> 4]); - result.push_back(digits[p[n] & 0xf]); - } - return result; -} - -static unsigned char hexValue(char c) -{ - static const char digits[] = "0123456789abcdef"; - if (const char *p = strchr(digits, tolower(c))) - return p - digits; - else - return 0; -} - -void CssmData::fromHex(const char *hexDigits) -{ - size_t bytes = strlen(hexDigits) / 2; // (discards malformed odd end) - length(bytes); // (will assert if we try to grow it) - for (size_t n = 0; n < bytes; n++) { - Data[n] = hexValue(hexDigits[2*n]) << 4 | hexValue(hexDigits[2*n+1]); - } -} - - -// -// Conversion from/to OID strings. -// These are not strict; invalid inputs are not necessarily flagged as errors. -// -static unsigned long getOid(const CssmData &data, unsigned int &pos) -{ - unsigned long q = 0; - do { - q = q * 128 + (data.byte(pos) & ~0x80); - } while (pos < data.length() && data.byte(pos++) & 0x80); - return q; -} - -string CssmData::toOid() const -{ - if (length() == 0) - return ""; - - unsigned int pos = 0; - - // first byte is composite (q1,q2) - char buffer[10]; - unsigned long oid1 = getOid(*this, pos); - unsigned long q1 = min(oid1 / 40, 2ul); - snprintf(buffer, sizeof(buffer), "%lu.%lu", q1, oid1 - q1 * 40); - string s = buffer; - - // now for the rest - while (pos < length()) { - char buffer[20]; - snprintf(buffer, sizeof(buffer), ".%lu", getOid(*this, pos)); - s += buffer; - } - return s; -} - -static void putOid(CssmOwnedData &data, unsigned long id) -{ - unsigned char buffer[sizeof(unsigned long) * 2]; // * (8/7) + 1, conservative - unsigned char *p = buffer + sizeof(buffer); - do { - *--p = 0x80 | (id & 0x7F); // last 7 bits, high bit set - } while ((id >>= 7) > 0); - buffer[sizeof(buffer) - 1] &= ~0x80; // clear last high bit (end of number) - data.append(p, buffer + sizeof(buffer) - p); // append generated byte string -} - -// -// Convert OID string (1.2.3...) into CssmOid form. -// Allocates the data, replacing current contents. -// Will not process oid elements out of unsigned long range. -// -void CssmOwnedData::fromOid(const char *oid) -{ - this->length(0); // make empty - - // first two elements get combined in weird&wacky ways - unsigned long q1 = strtoul(oid, (char **)&oid, 10); - if (*oid++ != '.') - return; - unsigned long q2 = strtoul(oid, (char **)&oid, 10); - putOid(*this, 40 * q1 + q2); - while (oid[0] == '.') { - oid++; - putOid(*this, strtoul(oid, (char **)&oid, 10)); - } -} - - -// -// Managed data objects -// -CssmManagedData::~CssmManagedData() -{ } - - -// -// CssmOwnedData -// -void CssmOwnedData::set(CssmManagedData &source) -{ - if (source.length() == 0) { // source is empty - reset(); // so just clear old data - } else if (allocator == source.allocator) { // compatible allocators - if (referent.data() == source.data()) { // same data *and* we own it?! - assert(this == &source); // this better *be* me! - } else { // different data - reset(); // give up our old data - referent = source.release(); // take over source's data - } - } else { // different allocators - copy(source); // make a copy with our allocator - source.reset(); // release source's data - } -} - - -// -// CssmAutoData -// -CssmData CssmAutoData::release() -{ - CssmData result = mData; - mData.clear(); - return result; -} - -void CssmAutoData::reset() -{ - allocator.free(mData); - mData.clear(); -} - - -// -// CssmRemoteData -// -CssmData CssmRemoteData::release() -{ - iOwnTheData = false; - return referent; -} - -void CssmRemoteData::reset() -{ - if (iOwnTheData) - allocator.free(referent); - referent.clear(); -} - - -// -// Date stuff -// -CssmDateData::CssmDateData(const CSSM_DATE &date) -: CssmData(buffer, sizeof(buffer)) -{ - memcpy(buffer, date.Year, 4); - memcpy(buffer + 4, date.Month, 2); - memcpy(buffer + 6, date.Day, 2); -} - - -CssmData& CssmOwnedData::get() const throw() -{ - return referent; -} - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmdata.h b/OSX/include/security_cdsa_utilities/cssmdata.h deleted file mode 100644 index eee84a0a..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdata.h +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmdata.h -- Manager different CssmData types -// -#ifndef _H_CDSA_UTILITIES_CSSMDATA -#define _H_CDSA_UTILITIES_CSSMDATA - -#include -#include -#include -#include -#include - -namespace Security { - - -// -// User-friendlier CSSM_DATA thingies. -// CssmData is a PODWrapper for CSSM_DATA, but is also used throughout -// the security code as a "byte blob" representation. -// -class CssmData : public PodWrapper { -public: - CssmData() { Data = 0; Length = 0; } - - size_t length() const { return Length; } - void *data() const { return Data; } - void *end() const { return Data + Length; } - - // - // Create a CssmData from any pointer-to-byte-sized-object and length. - // - CssmData(void *data, size_t length) - { Data = reinterpret_cast(data); Length = length; } - CssmData(char *data, size_t length) - { Data = reinterpret_cast(data); Length = length; } - CssmData(unsigned char *data, size_t length) - { Data = reinterpret_cast(data); Length = length; } - CssmData(signed char *data, size_t length) - { Data = reinterpret_cast(data); Length = length; } - - CssmData(CFDataRef cf) - { Data = const_cast(CFDataGetBytePtr(cf)); Length = CFDataGetLength(cf); } - - // the void * form accepts too much; explicitly deny all other types - private: template CssmData(T *, size_t); public: - - // explicitly construct from a data-oid source - template - explicit CssmData(const T &obj) - { Data = (UInt8 *)obj.data(); Length = obj.length(); } - - // - // Do allow generic "wrapping" of any data structure, but make it conspicuous - // since it's not necessarily the Right Thing (alignment and byte order wise). - // Also note that the T & form removes const-ness, since there is no ConstCssmData. - // - template - static CssmData wrap(const T &it) - { return CssmData(const_cast(reinterpret_cast(&it)), sizeof(it)); } - - template - static CssmData wrap(T *data, size_t length) - { return CssmData(const_cast(static_cast(data)), length); } - - // - // Automatically convert a CssmData to any pointer-to-byte-sized-type. - // - operator signed char * () const { return reinterpret_cast(Data); } - operator unsigned char * () const { return reinterpret_cast(Data); } - operator char * () const { return reinterpret_cast(Data); } - operator void * () const { return reinterpret_cast(Data); } - - // - // If you want to interpret the contents of a CssmData blob as a particular - // type, you have to be more explicit to show that you know what you're doing. - // See wrap() above. - // - template - T *interpretedAs() const { return reinterpret_cast(Data); } - - template - T *interpretedAs(CSSM_RETURN error) const - { return interpretedAs(sizeof(T), error); } - - template - T *interpretedAs(size_t len, CSSM_RETURN error) const - { - if (data() == NULL || length() != len) CssmError::throwMe(error); - return interpretedAs(); - } - -public: - void length(size_t newLength) // shorten only - { assert(newLength <= Length); Length = newLength; } - - void *at(off_t offset) const - { assert(offset >= 0 && (CSSM_SIZE)offset <= Length); return Data + offset; } - void *at(off_t offset, size_t size) const // length-checking version - { assert(offset >= 0 && (CSSM_SIZE)offset + size <= Length); return Data + offset; } - - template T *at(off_t offset) const { return reinterpret_cast(at(offset)); } - template T *at(off_t offset, size_t size) const - { return reinterpret_cast(at(offset, size)); } - - unsigned char byte(off_t offset) const { return *at(offset); } - unsigned char &byte(off_t offset) { return *at(offset); } - - void *use(size_t taken) // logically remove some bytes - { assert(taken <= Length); void *r = Data; Length -= taken; Data += taken; return r; } - - void clear() - { Data = NULL; Length = 0; } - - string toString () const; // convert to string type (no trailing null) - string toHex() const; // hex string of binary blob - string toOid() const; // standard OID string encoding (1.2.3...) - void fromHex(const char *digits); // fill myself with hex data (no allocation) - - operator bool () const { return Data != NULL; } - bool operator ! () const { return Data == NULL; } - bool operator < (const CssmData &other) const; - bool operator == (const CssmData &other) const - { return length() == other.length() && !memcmp(data(), other.data(), length()); } - bool operator != (const CssmData &other) const - { return !(*this == other); } - - // Extract fixed-format data from a CssmData. Fixes any alignment trouble for you. - template - void extract(T &destination, CSSM_RETURN error = CSSM_ERRCODE_INVALID_DATA) const - { - if (length() != sizeof(destination) || data() == NULL) - CssmError::throwMe(error); - memcpy(&destination, data(), sizeof(destination)); - } -}; - - -inline bool CssmData::operator < (const CssmData &other) const -{ - if (Length != other.Length) // If lengths are not equal the shorter data is smaller. - return Length < other.Length; - if (Length == 0) // If lengths are both zero ignore the Data. - return false; - if (Data == NULL || other.Data == NULL) // arbitrary (but consistent) ordering - return Data < other.Data; - return memcmp(Data, other.Data, Length) < 0; // Do a lexicographic compare on equal sized Data. -} - - -// -// CSSM_OIDs are CSSM_DATAs but will probably have different wrapping characteristics. -// -typedef CssmData CssmOid; - - -// -// A convenient way to make a CssmData from a (const) string. -// Note that the underlying string is not memory-managed, so it -// should either be static or of sufficient (immutable) lifetime. -// -class StringData : public CssmData { -public: - StringData(const char *s) : CssmData(const_cast(s), strlen(s)) { } - StringData(const std::string &s) : CssmData(const_cast(s.c_str()), s.size()) { } -}; - - -// -// A CssmData bundled up with a data buffer it refers to -// -template -struct DataBuffer : public CssmData { - unsigned char buffer[size]; - DataBuffer() : CssmData(buffer, size) { } -}; - - -// -// Comparing CssmDatas for equality. -// Note: No ordering is established here. -// Both CSSM_DATAs have to exist. -// -bool operator == (const CSSM_DATA &d1, const CSSM_DATA &d2); -inline bool operator != (const CSSM_DATA &d1, const CSSM_DATA &d2) -{ return !(d1 == d2); } - - -// -// The following pseudo-code describes what (at minimum) is required for a class -// to be a "PseudoData". PseudoData arguments ("DataOids") are used in templates. -// -// class PseudoData { -// void *data() const ... -// size_t length() const ... -// operator const CssmData &() const ... -// } -// -// All this can be satisfied, of course, by inheriting from CssmData. -// - - -// -// A common virtual parent for CssmData-like objects that actively manage the -// allocation status of their data blob. Note that this is about allocating -// the data(), not the CssmData structure itself. -// The ManagedData layer provides for little active memory management, since -// the underlying strategies are potentially very disparate. It does however -// have a well defined interface for *yielding up* its data for copying or transfer. -// -class CssmManagedData { -public: - CssmManagedData(Allocator &alloc) : allocator(alloc) { } - virtual ~CssmManagedData(); - - Allocator &allocator; - - virtual operator const CssmData & () const { return get(); } - template T *data() const { return reinterpret_cast(data()); } - void *data() const { return get().data(); } - size_t length() const { return get().length(); } - - virtual CssmData &get() const throw() = 0; // get shared copy, no ownership change - virtual CssmData release() = 0; // give up copy, ownership is transferred - virtual void reset() = 0; // give up copy, data is discarded -}; - - -inline bool operator == (const CssmManagedData &d1, const CssmData &d2) -{ return d1.get() == d2; } - -inline bool operator == (const CssmData &d1, const CssmManagedData &d2) -{ return d1 == d2.get(); } - -inline bool operator == (const CssmManagedData &d1, const CssmManagedData &d2) -{ return d1.get() == d2.get(); } - -inline bool operator != (const CssmManagedData &d1, const CssmData &d2) -{ return d1.get() != d2; } - -inline bool operator != (const CssmData &d1, const CssmManagedData &d2) -{ return d1 != d2.get(); } - -inline bool operator != (const CssmManagedData &d1, const CssmManagedData &d2) -{ return d1.get() != d2.get(); } - - -// -// A CssmOwnedData is a CssmManagedData that unilaterally owns its data storage. -// It has its CssmData object provided during construction. -// -class CssmOwnedData : public CssmManagedData { -public: - CssmOwnedData(Allocator &alloc, CssmData &mine) : CssmManagedData(alloc), referent(mine) { } - - CssmOwnedData(Allocator &alloc, CSSM_DATA &mine) - : CssmManagedData(alloc), referent(CssmData::overlay(mine)) { referent.clear(); } - - // - // Basic retrievals (this echoes features of CssmData) - // - operator void * () const { return referent; } - operator char * () const { return referent; } - operator signed char * () const { return referent; } - operator unsigned char * () const { return referent; } - - operator bool () const { return referent; } - bool operator ! () const { return !referent; } - - size_t length() const { return referent.length(); } - - - // - // Basic allocators - // - void *malloc(size_t len) - { - // pseudo-atomic reallocation semantics - CssmAutoPtr alloc(allocator, allocator.malloc(len)); - reset(); - return referent = CssmData(alloc.release(), len); - } - - void *realloc(size_t newLen) - { - // Allocator::realloc() should be pseudo-atomic (i.e. throw on error) - return referent = CssmData(allocator.realloc(referent.data(), newLen), newLen); - } - - void length(size_t len) { realloc(len); } - - - // - // Manipulate existing data - // - void *append(const void *addData, size_t addLength) - { - size_t oldLength = length(); - realloc(oldLength + addLength); - return memcpy(referent.at(oldLength), addData, addLength); - } - - void *append(const CssmData &data) - { return append(data.data(), data.length()); } - - - // - // set() replaces current data with new, taking over ownership to the extent possible. - // - template - void set(T *data, size_t length) - { - // assume that data was allocated by our allocator -- we can't be sure - reset(); - referent = CssmData(data, length); - } - - void set(CssmManagedData &source); - void set(const CSSM_DATA &source) { set(source.Data, source.Length); } - // NOTE: General template set() cannot be used because all subclasses of CssmManagedData - // need to receive the special handling above. Use set(*.data(), *.length()) instead. - - - // - // copy() replaces current data with new, making a copy and leaving - // the source intact. - // - template - void copy(const T *data, size_t length) - { - CssmAutoPtr newData(allocator, memcpy(allocator.malloc(length), data, length)); - reset(); - referent = CssmData(newData.release(), length); - } - - void copy(const CssmData &source) - { if (&source != &referent) copy(source.data(), source.length()); } - void copy(const CSSM_DATA &source) - { if (&source != &referent) copy(source.Data, source.Length); } - void copy(CssmManagedData &source) { copy(source.get()); } - template - void copy(const Data &source) { copy(source.data(), source.length()); } - - - // - // Assignment conservatively uses copy if allocator unknown, set if known - // - void operator = (CssmManagedData &source) { set(source); } - void operator = (CssmOwnedData &source) { set(source); } - void operator = (const CSSM_DATA &source) { copy(source); } - - CssmData &get() const throw(); - -public: - void fromOid(const char *oid); // fill from text OID form (1.2.3...) - -protected: - CssmData &referent; -}; - - -// -// A CssmAutoData is a CssmOwnedData that includes its CssmData object. -// This is the very simple case: The object includes ownership, data object, -// and data storage. -// -class CssmAutoData : public CssmOwnedData { -public: - CssmAutoData(Allocator &alloc) : CssmOwnedData(alloc, mData) { } - - template - CssmAutoData(Allocator &alloc, const Data &source) : CssmOwnedData(alloc, mData) - { *this = source; } - - CssmAutoData(CssmAutoData &source) : CssmOwnedData(source.allocator, mData) - { set(source); } - - explicit CssmAutoData(CssmManagedData &source) : CssmOwnedData(source.allocator, mData) - { set(source); } - - CssmAutoData(Allocator &alloc, const void *data, size_t length) - : CssmOwnedData(alloc, mData) { copy(data, length); } - - ~CssmAutoData() { allocator.free(mData); } - - CssmData release(); - void reset(); - - // assignment (not usefully inherited) - void operator = (CssmManagedData &source) { set(source); } - void operator = (CssmOwnedData &source) { set(source); } - void operator = (CssmAutoData &source) { set(source); } - template - void operator = (const Data &source) { copy(source); } - -private: - CssmData mData; -}; - - -// -// A CssmRemoteData is a CssmOwnedData that uses an external CssmData object. -// Its release operation clears an internal ownership flag but does not clear -// the CssmData values so they can be used to return values to an outside scope. -// -class CssmRemoteData : public CssmOwnedData { -public: - CssmRemoteData(Allocator &alloc, CssmData &mine) - : CssmOwnedData(alloc, mine), iOwnTheData(true) { } - - CssmRemoteData(Allocator &alloc, CSSM_DATA &mine) - : CssmOwnedData(alloc, mine), iOwnTheData(true) { } - - ~CssmRemoteData() - { if (iOwnTheData) allocator.free(referent); } - - CssmData release(); - void reset(); - - // assignment (not usefully inherited) - void operator = (CssmManagedData &source) { set(source); } - void operator = (CssmOwnedData &source) { set(source); } - void operator = (CssmAutoData &source) { set(source); } - template - void operator = (const Data &source) { copy(source); } - -private: - bool iOwnTheData; -}; - - -// -// CssmPolyData -// -// Used by functions that take a CssmData and would like to allow it to be -// initialized with a static string, int or other basic type. The function *must* -// copy the Data of the CssmPolyData when doing so if it is to be used -// after the function returns. (For example by creating a CssmDataContainer from it). -class CssmPolyData : public CssmData { - template - uint8 *set(const T &it) - { return const_cast(reinterpret_cast(&it)); } -public: - template - CssmPolyData(const char_T *s) : CssmData(const_cast(s), strlen(s)) {} - CssmPolyData(const string &s) : CssmData(const_cast(s.c_str()), s.size()) {} - CssmPolyData(const CSSM_DATA &data) : CssmData(data.Data, data.Length) {} - - // Don't use a template constructor (for T &) here - it would eat way too much - CssmPolyData(const bool &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const uint32 &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const sint32 &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const sint64 &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const double &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const unsigned long &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const CSSM_GUID &t) : CssmData(set(t), sizeof(t)) { } - CssmPolyData(const StringPtr s) : CssmData (reinterpret_cast(s + 1), uint32 (s[0])) {} -}; - -class CssmDateData : public CssmData -{ -public: - CssmDateData(const CSSM_DATE &date); -private: - uint8 buffer[8]; -}; - - -// -// Non POD refcounted CssmData wrapper that own the data it refers to. -// -class CssmDataContainer : public CssmData, public RefCount -{ -public: - CssmDataContainer(Allocator &inAllocator = Allocator::standard()) : - CssmData(), mAllocator(inAllocator) {} - template - CssmDataContainer(const T *data, size_t length, Allocator &inAllocator = Allocator::standard()) : - CssmData(inAllocator.malloc(length), length), mAllocator(inAllocator) - { if (length) ::memcpy(Data, data, length); } - void clear() { if (Data) { mAllocator.free(Data); Data = NULL; Length = 0; } } - void invalidate () {Data = NULL; Length = 0;} - ~CssmDataContainer() { if (Data) mAllocator.free(Data); } - void append(const CssmPolyData &data) - { - size_t newLength = Length + data.Length; - Data = reinterpret_cast(mAllocator.realloc(Data, newLength)); - memcpy(Data + Length, data.Data, data.Length); - Length = newLength; - } - CssmDataContainer(const CssmDataContainer &other) - : mAllocator(other.mAllocator) - { - Data = reinterpret_cast(mAllocator.malloc(other.Length)); - memcpy(Data, other.Data, other.Length); - Length = other.Length; - } - CssmDataContainer & operator = (const CSSM_DATA &other) - { - clear(); - Data = reinterpret_cast(mAllocator.malloc(other.Length)); - memcpy(Data, other.Data, other.Length); - Length = other.Length; - return *this; - } - -public: - Allocator &mAllocator; - -private: - operator CssmDataContainer * () const; // prohibit conversion-to-my-pointer -}; - -// -// CSSM_OIDs are CSSM_DATAs but will probably have different wrapping characteristics. -// -typedef CssmDataContainer CssmOidContainer; - -template -class CssmBuffer : public RefPointer -{ -public: - CssmBuffer() : RefPointer(new Container()) {} // XXX This should may just set ptr to NULL. - template - CssmBuffer(const T *data, size_t length, Allocator &inAllocator = Allocator::standard()) : - RefPointer(new Container(data, length, inAllocator)) {} - CssmBuffer(const CSSM_DATA &data, Allocator &inAllocator = Allocator::standard()) : - RefPointer(new Container(data.Data, data.Length, inAllocator)) {} - CssmBuffer(const CssmBuffer& other) : RefPointer(other) {} - CssmBuffer(Container *p) : RefPointer(p) {} - bool operator < (const CssmBuffer &other) const { return (**this) < (*other); } -}; - - -} // end namespace Security - -#endif // _H_CDSA_UTILITIES_CSSMDATA diff --git a/OSX/include/security_cdsa_utilities/cssmdates.cpp b/OSX/include/security_cdsa_utilities/cssmdates.cpp deleted file mode 100644 index e5b46b8c..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdates.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Manage the Tower of Babel of CSSM dates and times -// -#include -#include -#include -#include - - -// -// A (private) PODwrapper for CFGregorianDate -// -struct Gregorian : public PodWrapper { - Gregorian() { } - - Gregorian(int y, int m, int d, int h = 0, int min = 0, double sec = 0) - { - year = y; month = m; day = d; - hour = h; minute = min; second = sec; - } - - Gregorian(CFAbsoluteTime ref) - { static_cast(*this) = CFAbsoluteTimeGetGregorianDate(ref, NULL); } - - operator CFAbsoluteTime () const - { return CFGregorianDateGetAbsoluteTime(*this, NULL); } -}; - - -// -// The CssmDate PODwrapper -// -CssmDate::CssmDate(const char *y, const char *m, const char *d) -{ - assign(years(), 4, y); - assign(months(), 2, m); - assign(days(), 2, d); -} - -CssmDate::CssmDate(int y, int m, int d) -{ - // internal format is "yyyymmdd" (no null termination) - char str[9]; - if (8 != snprintf(str, 9, "%4.4d%2.2d%2.2d", y, m, d)) - CssmError::throwMe(CSSM_ERRCODE_UNKNOWN_FORMAT); - memcpy(this, str, 8); -} - -int CssmDate::year() const -{ return atoi(string(years(), 4).c_str()); } - -int CssmDate::month() const -{ return atoi(string(months(), 2).c_str()); } - -int CssmDate::day() const -{ return atoi(string(days(), 2).c_str()); } - -// right-adjust fill -void CssmDate::assign(char *dest, int width, const char *src) -{ - // pick last width characters of src at most - size_t len = strlen(src); - if (len > width) - CssmError::throwMe(CSSM_ERRCODE_UNKNOWN_FORMAT); - memset(dest, '0', width - len); - memcpy(dest + width - len, src, len); -} - - -// -// CssmUniformDate core functions -// - - -// -// Uniform conversions with CFDateRef -// -CssmUniformDate::CssmUniformDate(CFDateRef ref) -{ - mTime = CFDateGetAbsoluteTime(ref); -} - -CssmUniformDate::operator CFDateRef() const -{ - return CFDateCreate(NULL, mTime); -} - - -// -// Uniform conversions with CssmDates -// -CssmUniformDate::CssmUniformDate(const CssmDate &date) -{ - mTime = CFGregorianDateGetAbsoluteTime(Gregorian(date.year(), date.month(), date.day()), - NULL); -} - -CssmUniformDate::operator CssmDate () const -{ - Gregorian greg(mTime); - return CssmDate(greg.year, greg.month, greg.day); -} - - -// -// Uniform conversions with CssmData (1999-06-30_15:05:39 form) -// -CssmUniformDate::CssmUniformDate(const CSSM_DATA &inData) -{ - const CssmData &data = CssmData::overlay(inData); - if (data.length() != 19) - CssmError::throwMe(CSSM_ERRCODE_UNKNOWN_FORMAT); - setFromString(reinterpret_cast(inData.Data), "%ld-%d-%d_%d:%d:%lf", 19); -} - -void CssmUniformDate::convertTo(CssmOwnedData &data) const -{ - Gregorian greg(mTime); - char str[20]; - if (19 != snprintf(str, 20, "%4.4d-%2.2d-%2.2d_%2.2d:%2.2d:%2.2d", - int(greg.year), greg.month, greg.day, greg.hour, greg.minute, int(greg.second))) - CssmError::throwMe(CSSM_ERRCODE_UNKNOWN_FORMAT); - data = CssmData(str, 19); -} - - -// -// Uniform conversions with CSSM_TIMESTRING (19990630150539 form) -// -CssmUniformDate::CssmUniformDate(const char *src) -{ - setFromString(src, "%4ld%2d%2d%2d%2d%2lf", 14); -} - -void CssmUniformDate::convertTo(char *dst, size_t length) const -{ - if (length < 14) - CssmError::throwMe(CSSMERR_CSSM_BUFFER_TOO_SMALL); - Gregorian greg(mTime); - char str[15]; - if (14 != snprintf(str, 15, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d", - int(greg.year), greg.month, greg.day, greg.hour, greg.minute, int(greg.second))) - CssmError::throwMe(CSSM_ERRCODE_UNKNOWN_FORMAT); - memcpy(dst, str, length == 14 ? 14 : 15); // null terminate if there's room -} - - -// -// Generalized parse-from-string setup -// -void CssmUniformDate::setFromString(const char *src, const char *format, size_t fieldWidth) -{ - // use a stack buffer - char str[20]; - assert(fieldWidth < sizeof(str)); - - // make a copy with proper null terminator - memcpy(str, src, fieldWidth); - str[fieldWidth] = '\0'; - - // parse (with limited checks for bad field formats) - long year; - int month, day, hour, minute; - double second; - if (6 != sscanf(str, format, - &year, &month, &day, &hour, &minute, &second)) - CssmError::throwMe(CSSM_ERRCODE_UNKNOWN_FORMAT); - - // success - mTime = Gregorian((int)year, month, day, hour, minute, second); -} diff --git a/OSX/include/security_cdsa_utilities/cssmdates.h b/OSX/include/security_cdsa_utilities/cssmdates.h deleted file mode 100644 index a452308b..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdates.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Manage the Tower of Babel of CSSM dates and times. -// -#ifndef _H_CSSMDATES -#define _H_CSSMDATES - -#include -#include -#include - - -namespace Security { - - -// -// A PodWrapper for CSSM_DATE -// -class CssmDate : public PodWrapper { -public: - CssmDate() { } - CssmDate(const char *y, const char *m, const char *d); - CssmDate(int y, int m, int d); - - const char *years() const { return reinterpret_cast(Year); } - const char *months() const { return reinterpret_cast(Month); } - const char *days() const { return reinterpret_cast(Day); } - char *years() { return reinterpret_cast(Year); } - char *months() { return reinterpret_cast(Month); } - char *days() { return reinterpret_cast(Day); } - - int year() const; - int month() const; - int day() const; - -private: - static void assign(char *dest, int width, const char *src); -}; - -inline bool operator == (const CSSM_DATE &d1, const CSSM_DATE &d2) -{ return !memcmp(&d1, &d2, sizeof(d1)); } - -inline bool operator != (const CSSM_DATE &d1, const CSSM_DATE &d2) -{ return !memcmp(&d1, &d2, sizeof(d1)); } - - -// -// Yet another CSSM date/time format is CSSM_TIMESTRING. This is -// defined as "char *", just so you can't use the type system -// to keep things sane, so we can't really PodWrap it the usual way. -// What *were* they thinking? -// The format is allegedly "yyyymmddhhmmss", and the standard says -// nothing about trailing null characters. -// - - -// -// A unified date-and-time object. -// This is based on CFDate objects and converts to various CSSM -// inspired formats. -// -class CssmUniformDate { -public: - CssmUniformDate() { } - - // convert to/from CFDateRef - CssmUniformDate(CFDateRef ref); - operator CFDateRef() const; - - // convert to/from CFAbsoluteTime - CssmUniformDate(CFAbsoluteTime ct) : mTime(ct) { } - operator CFAbsoluteTime() const { return mTime; } - - // convert to/from CSSM_DATE - CssmUniformDate(const CssmDate &src); - operator CssmDate () const; - - // convert to/from DATA format (1999-06-30_15:05:39 form) - CssmUniformDate(const CSSM_DATA &src); - void convertTo(CssmOwnedData &data) const; - - // convert to/from CSSM_TIMESTRING format (19990630150539) - CssmUniformDate(const char *src); - void convertTo(char *dest, size_t length) const; - - // native comparisons - bool operator < (const CssmUniformDate &other) const { return mTime < other.mTime; } - bool operator == (const CssmUniformDate &other) const { return mTime == other.mTime; } - bool operator > (const CssmUniformDate &other) const { return mTime > other.mTime; } - bool operator <= (const CssmUniformDate &other) const { return mTime <= other.mTime; } - bool operator >= (const CssmUniformDate &other) const { return mTime >= other.mTime; } - bool operator != (const CssmUniformDate &other) const { return mTime != other.mTime; } - -private: - void setFromString(const char *src, const char *format, size_t fieldLength); - -private: - CFAbsoluteTime mTime; -}; - - -} // end namespace Security - -#endif //_H_CSSMDATES diff --git a/OSX/include/security_cdsa_utilities/cssmdb.cpp b/OSX/include/security_cdsa_utilities/cssmdb.cpp deleted file mode 100644 index e3546459..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdb.cpp +++ /dev/null @@ -1,590 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// cssmdb.cpp -// -// -#include - -bool DLDbIdentifier::Impl::operator < (const DLDbIdentifier::Impl &other) const -{ - if (mCssmSubserviceUid < other.mCssmSubserviceUid) - return true; - if (mCssmSubserviceUid != other.mCssmSubserviceUid) // i.e. greater than - return false; - - // This test will produce unreproducible results, - // depending on what items are being compared. To do this properly, we need to - // assign a lexical value to NULL. - // - // if (mDbName.canonicalName() == NULL || other.mDbName.canonicalName() == NULL) - // { - // return false; - // } - - // this is the correct way - const char* a = mDbName.canonicalName(); - const char* b = other.mDbName.canonicalName(); - - if (a == NULL && b != NULL) - { - return true; // NULL is always < something - } - - if (a != NULL && b == NULL) - { - return false; // something is always >= NULL - } - - if (a == NULL && b == NULL) - { - return false; // since == is not < - } - - // if we get to this point, both are not null. No crash and the lexical value is correct. - return strcmp(a, b) < 0; -} - -bool DLDbIdentifier::Impl::operator == (const Impl &other) const -{ - bool subserviceIdEqual = mCssmSubserviceUid == other.mCssmSubserviceUid; - if (!subserviceIdEqual) - { - return false; - } - - const char* a = mDbName.canonicalName(); - const char* b = other.mDbName.canonicalName(); - - if (a == NULL && b != NULL) - { - return false; - } - - if (a != NULL && b == NULL) - { - return false; - } - - if (a == NULL && b == NULL) - { - return true; - } - - bool namesEqual = strcmp(a, b) == 0; - return namesEqual; -} - -// -// CssmDLPolyData -// -CssmDLPolyData::operator CSSM_DATE () const -{ - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_BLOB); - if (mData.Length != 8) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - CSSM_DATE date; - memcpy(date.Year, mData.Data, 4); - memcpy(date.Month, mData.Data + 4, 2); - memcpy(date.Day, mData.Data + 6, 2); - return date; -} - -CssmDLPolyData::operator Guid () const -{ - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_BLOB); - if (mData.Length != Guid::stringRepLength + 1) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - return Guid(reinterpret_cast(mData.Data)); -} - - -// -// CssmDbAttributeInfo -// -CssmDbAttributeInfo::CssmDbAttributeInfo(const char *name, CSSM_DB_ATTRIBUTE_FORMAT vFormat) -{ - clearPod(); - AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - Label.AttributeName = const_cast(name); // silly CDSA - AttributeFormat = vFormat; -} - -CssmDbAttributeInfo::CssmDbAttributeInfo(const CSSM_OID &oid, CSSM_DB_ATTRIBUTE_FORMAT vFormat) -{ - clearPod(); - AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_OID; - Label.AttributeOID = oid; - AttributeFormat = vFormat; -} - -CssmDbAttributeInfo::CssmDbAttributeInfo(uint32 id, CSSM_DB_ATTRIBUTE_FORMAT vFormat) -{ - clearPod(); - AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - Label.AttributeID = id; - AttributeFormat = vFormat; -} - - -bool -CssmDbAttributeInfo::operator <(const CssmDbAttributeInfo& other) const -{ - if (nameFormat() < other.nameFormat()) return true; - if (other.nameFormat() < nameFormat()) return false; - // nameFormat's are equal. - switch (nameFormat()) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - { - int res = strcmp(static_cast(*this), static_cast(other)); - if (res < 0) return true; - if (res > 0) return false; - break; - } - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - if (static_cast(*this) < static_cast(other)) return true; - if (static_cast(other) < static_cast(*this)) return false; - break; - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - if (static_cast(*this) < static_cast(other)) return true; - if (static_cast(other) < static_cast(*this)) return false; - break; - default: - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - } - - return format() < other.format(); -} - -bool -CssmDbAttributeInfo::operator ==(const CssmDbAttributeInfo& other) const -{ - if (nameFormat() != other.nameFormat()) return false; - if (format() != other.format()) return false; - switch (nameFormat()) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - return !strcmp(static_cast(*this), static_cast(other)); - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - return static_cast(*this) == static_cast(other); - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - return static_cast(*this) == static_cast(other); - default: - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - } -} - -// -// CssmDbAttributeData -// -CssmDbAttributeData::operator string() const -{ - switch (format()) { - case CSSM_DB_ATTRIBUTE_FORMAT_STRING: - case CSSM_DB_ATTRIBUTE_FORMAT_BLOB: - return at(0).toString(); - default: - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); - } -} -CssmDbAttributeData::operator const Guid &() const -{ - if (format() == CSSM_DB_ATTRIBUTE_FORMAT_BLOB) - return *at(0).interpretedAs(); - else - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); -} - -CssmDbAttributeData::operator bool() const -{ - switch (format()) { - case CSSM_DB_ATTRIBUTE_FORMAT_UINT32: - case CSSM_DB_ATTRIBUTE_FORMAT_SINT32: - return *at(0).interpretedAs(); - default: - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); - } -} - -CssmDbAttributeData::operator uint32() const -{ - if (format() == CSSM_DB_ATTRIBUTE_FORMAT_UINT32) - return *at(0).interpretedAs(); - else - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); -} - -CssmDbAttributeData::operator const uint32 *() const -{ - if (format() == CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32) - return reinterpret_cast(Value[0].Data); - else - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); -} - -CssmDbAttributeData::operator sint32() const -{ - if (format() == CSSM_DB_ATTRIBUTE_FORMAT_SINT32) - return *at(0).interpretedAs(); - else - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); -} - -CssmDbAttributeData::operator double() const -{ - if (format() == CSSM_DB_ATTRIBUTE_FORMAT_REAL) - return *at(0).interpretedAs(); - else - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); -} - -CssmDbAttributeData::operator const CssmData &() const -{ - switch (format()) { - case CSSM_DB_ATTRIBUTE_FORMAT_STRING: - case CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM: - case CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE: - case CSSM_DB_ATTRIBUTE_FORMAT_BLOB: - case CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32: - return at(0); - default: - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); - } -} - -void CssmDbAttributeData::set(const CSSM_DB_ATTRIBUTE_INFO &inInfo, const CssmPolyData &inValue, - Allocator &inAllocator) -{ - info(inInfo); - NumberOfValues = 0; - Value = inAllocator.alloc(); - Value[0].Length = 0; - Value[0].Data = inAllocator.alloc((UInt32)inValue.Length); - Value[0].Length = inValue.Length; - memcpy(Value[0].Data, inValue.Data, inValue.Length); - NumberOfValues = 1; -} - -void CssmDbAttributeData::add(const CssmPolyData &inValue, Allocator &inAllocator) -{ - Value = reinterpret_cast(inAllocator.realloc(Value, sizeof(*Value) * (NumberOfValues + 1))); - CssmAutoData valueCopy(inAllocator, inValue); - Value[NumberOfValues++] = valueCopy.release(); -} - - -void CssmDbAttributeData::copyValues(const CssmDbAttributeData &source, Allocator &alloc) -{ - assert(size() == 0); // must start out empty - - // we're too lazy to arrange for exception safety here - CssmData *vector = alloc.alloc(source.size()); - for (uint32 n = 0; n < source.size(); n++) - vector[n] = CssmAutoData(alloc, source[n]).release(); - - // atomic set results - info().format(source.info().format()); - NumberOfValues = source.size(); - values() = vector; -} - -void CssmDbAttributeData::deleteValues(Allocator &alloc) -{ - // Loop over all values and delete each one. - if (values()) - { - for (uint32 n = 0; n < size(); n++) - { - alloc.free(at(n).data()); - } - alloc.free(values()); - } - NumberOfValues = 0; - values() = NULL; -} - -bool CssmDbAttributeData::operator <(const CssmDbAttributeData &other) const -{ - if (info() < other.info()) return true; - if (other.info() < info()) return false; - - uint32 minSize = min(size(), other.size()); - for (uint32 ix = 0; ix < minSize; ++ix) - { - if (at(ix) < other.at(ix)) - return true; - if (other.at(ix) < at(ix)) - return false; - } - - return size() < other.size(); -} - -void -CssmDbAttributeData::add(const CssmDbAttributeData &src, Allocator &inAllocator) -{ - // Add all the values from another attribute into this attribute. - - Value = reinterpret_cast(inAllocator.realloc(Value, - sizeof(*Value) * (NumberOfValues + src.NumberOfValues))); - - for (uint32 srcIndex = 0; srcIndex < src.NumberOfValues; srcIndex++) { - uint32 destIndex = NumberOfValues + srcIndex; - - Value[destIndex].Length = 0; - Value[destIndex].Data = inAllocator.alloc((UInt32)src.Value[srcIndex].Length); - Value[destIndex].Length = src.Value[srcIndex].Length; - memcpy(Value[destIndex].Data, src.Value[srcIndex].Data, src.Value[srcIndex].Length); - } - - NumberOfValues += src.NumberOfValues; -} - -bool -CssmDbAttributeData::deleteValue(const CssmData &src, Allocator &inAllocator) -{ - // Delete a single value from this attribute, if it is present. - - for (uint32 i = 0; i < NumberOfValues; i++) - if (CssmData::overlay(Value[i]) == src) - { - inAllocator.free(Value[i].Data); - Value[i].Length = 0; - - NumberOfValues--; - Value[i].Data = Value[NumberOfValues].Data; - Value[i].Length = Value[NumberOfValues].Length; - - return true; - } - - return false; -} - -// Delete those values found in src from this object, if they are present. -// Warning: This is O(N^2) worst case; if this becomes a performance bottleneck -// then it will need to be changed. - -void -CssmDbAttributeData::deleteValues(const CssmDbAttributeData &src, Allocator &inAllocator) -{ - for (uint32 i = 0; i < src.NumberOfValues; i++) - deleteValue(CssmData::overlay(src.Value[i]), inAllocator); -} - -// -// CssmDbRecordAttributeData -// -CssmDbAttributeData * -CssmDbRecordAttributeData::find(const CSSM_DB_ATTRIBUTE_INFO &inInfo) -{ - const CssmDbAttributeInfo &anInfo = CssmDbAttributeInfo::overlay(inInfo); - for (uint32 ix = 0; ix < size(); ++ix) - { - if (at(ix).info() == anInfo) - return &at(ix); - } - - return NULL; -} - -bool -CssmDbRecordAttributeData::operator <(const CssmDbRecordAttributeData &other) const -{ - if (recordType() < other.recordType()) return true; - if (other.recordType() < recordType()) return false; - if (semanticInformation() < other.semanticInformation()) return true; - if (other.semanticInformation() < semanticInformation()) return false; - - uint32 minSize = min(size(), other.size()); - for (uint32 ix = 0; ix < minSize; ++ix) - { - if (at(ix) < other.at(ix)) - return true; - if (other.at(ix) < at(ix)) - return false; - } - - return size() < other.size(); -} - - -// -// CssmAutoDbRecordAttributeData -// -CssmAutoDbRecordAttributeData::~CssmAutoDbRecordAttributeData() -{ - clear(); -} - -void -CssmAutoDbRecordAttributeData::invalidate() -{ - NumberOfAttributes = 0; -} - - - -void -CssmAutoDbRecordAttributeData::clear() -{ - deleteValues(); - ArrayBuilder::clear(); -} - - - -static bool CompareAttributeInfos (const CSSM_DB_ATTRIBUTE_INFO &a, const CSSM_DB_ATTRIBUTE_INFO &b) -{ - // check the format of the names - if (a.AttributeNameFormat != b.AttributeNameFormat) - { - return false; - } - - switch (a.AttributeNameFormat) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - { - return strcmp (a.Label.AttributeName, b.Label.AttributeName) == 0; - } - - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - { - if (a.Label.AttributeOID.Length != b.Label.AttributeOID.Length) - { - return false; - } - - return memcmp (a.Label.AttributeOID.Data, b.Label.AttributeOID.Data, a.Label.AttributeOID.Length) == 0; - } - - - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - { - return a.Label.AttributeID == b.Label.AttributeID; - } - } - - return true; // just to keep the compiler from complaining -} - - - -CssmDbAttributeData* CssmAutoDbRecordAttributeData::findAttribute (const CSSM_DB_ATTRIBUTE_INFO &info) -{ - // walk through the data, looking for an attribute of the same type - unsigned i; - for (i = 0; i < size (); ++i) - { - CssmDbAttributeData& d = at (i); - CSSM_DB_ATTRIBUTE_INFO &inInfo = d.info (); - - if (CompareAttributeInfos (info, inInfo)) - { - return &d; - } - } - - // found nothing? - return NULL; -} - - - -CssmDbAttributeData& CssmAutoDbRecordAttributeData::getAttributeReference (const CSSM_DB_ATTRIBUTE_INFO &info) -{ - // Either find an existing reference to an attribute in the list, or make a new one. - CssmDbAttributeData *anAttr = findAttribute (info); - if (anAttr) // was this already in the list? - { - // clean it up - anAttr->deleteValues (mValueAllocator); - } - else - { - // make a new one - anAttr = &add(); - } - - return *anAttr; -} - - - -CssmDbAttributeData & -CssmAutoDbRecordAttributeData::add(const CSSM_DB_ATTRIBUTE_INFO &info) -{ - CssmDbAttributeData& anAttr = getAttributeReference (info); - anAttr.info(info); - return anAttr; -} - -CssmDbAttributeData & -CssmAutoDbRecordAttributeData::add(const CSSM_DB_ATTRIBUTE_INFO &info, const CssmPolyData &value) -{ - CssmDbAttributeData &anAttr = getAttributeReference (info); - anAttr.set(info, value, mValueAllocator); - return anAttr; -} - -// -// CssmAutoQuery -// -CssmAutoQuery::CssmAutoQuery(const CSSM_QUERY &query, Allocator &allocator) -: ArrayBuilder(CssmSelectionPredicate::overlayVar(SelectionPredicate), - NumSelectionPredicates, - query.NumSelectionPredicates, allocator) -{ - RecordType = query.RecordType; - Conjunctive = query.Conjunctive; - QueryLimits = query.QueryLimits; - QueryFlags = query.QueryFlags; - for (uint32 ix = 0; ix < query.NumSelectionPredicates; ++ix) - add().set(query.SelectionPredicate[ix], allocator); -} - -CssmAutoQuery::~CssmAutoQuery() -{ - clear(); -} - -void -CssmAutoQuery::clear() -{ - deleteValues(); - ArrayBuilder::clear(); -} - -CssmSelectionPredicate & -CssmAutoQuery::add(CSSM_DB_OPERATOR dbOperator, const CSSM_DB_ATTRIBUTE_INFO &info, const CssmPolyData &value) -{ - CssmSelectionPredicate &predicate = add(); - predicate.dbOperator(dbOperator); - predicate.set(info, value, allocator()); - return predicate; -} diff --git a/OSX/include/security_cdsa_utilities/cssmdb.h b/OSX/include/security_cdsa_utilities/cssmdb.h deleted file mode 100644 index 5ecb5a29..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdb.h +++ /dev/null @@ -1,873 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// cssmdb.h -// -// classes for the DL related data structures -// - -#ifndef _H_CDSA_UTILITIES_CSSMDB -#define _H_CDSA_UTILITIES_CSSMDB - -#include -#include -#include -#include -#include - - -namespace Security { - - -// -// Template class to build and maintain external arrays. -// Feel free to add and vector<> member functions and behaviours as needed. -// -// This class differs from vector mainly because it does not construct or -// destruct any of the elements it contains. Rather it zero fills the -// storage and returns references to elements. -// Also it does not implement insert(), erase() or assign(). It does implement -// which is equivalent to calling *insert(end()) on a vector. -// -template -class ArrayBuilder { -public: - typedef _Tp value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type* iterator; - typedef const value_type* const_iterator; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef uint32 size_type; - typedef ptrdiff_t difference_type; - - typedef reverse_iterator const_reverse_iterator; - typedef reverse_iterator reverse_iterator; - -protected: - void insert_aux(iterator __position, const _Tp& __x); - void insert_aux(iterator __position); - -public: - iterator begin() { return mArray; } - const_iterator begin() const { return mArray; } - iterator end() { return &mArray[mSize]; } - const_iterator end() const { return &mArray[mSize]; } - - reverse_iterator rbegin() - { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const - { return const_reverse_iterator(end()); } - reverse_iterator rend() - { return reverse_iterator(begin()); } - const_reverse_iterator rend() const - { return const_reverse_iterator(begin()); } - - // Must be defined in base class. - //size_type size() const - //{ return mSize; } - size_type max_size() const - { return size_type(-1) / sizeof(_Tp); } - size_type capacity() const - { return mCapacity; } - bool empty() const - { return begin() == end(); } - - ArrayBuilder(pointer &array, size_type &size, size_type capacity = 0, Allocator &allocator = Allocator::standard()) : - mArray(array), mSize(size), mCapacity(capacity), mAllocator(allocator) - { -#if BUG_GCC - mArray = reinterpret_cast(mAllocator.malloc(sizeof(value_type) * mCapacity)); -#else - mArray = reinterpret_cast(mAllocator.malloc(sizeof(value_type) * mCapacity)); - //mArray = mAllocator.alloc(mCapacity); -#endif - memset(mArray, 0, sizeof(value_type) * mCapacity); - mSize = 0; - } - ~ArrayBuilder() { mAllocator.free(mArray); } - - reference front() { return *begin(); } - const_reference front() const { return *begin(); } - reference back() { return *(end() - 1); } - const_reference back() const { return *(end() - 1); } - - void reserve(size_type newCapacity) - { - if (newCapacity > mCapacity) - { -#if BUG_GCC - mArray = reinterpret_cast(mAllocator.realloc(mArray, sizeof(value_type) * newCapacity)); -#else - mArray = reinterpret_cast(mAllocator.realloc(mArray, sizeof(value_type) * newCapacity)); - //mArray = mAllocator.realloc(mArray, newCapacity)); -#endif - memset(&mArray[mCapacity], 0, sizeof(value_type) * (newCapacity - mCapacity)); - mCapacity = newCapacity; - } - } - - // XXX Replace by push_back and insert. - reference add() - { - if (mSize >= mCapacity) - reserve(max(mSize + 1, mCapacity ? 2 * mCapacity : 1)); - - return mArray[mSize++]; - } - - const_pointer get() const { return mArray; } - pointer release() { const_pointer array = mArray; mArray = NULL; return array; } - void clear() { if (mSize) { memset(mArray, 0, sizeof(value_type) * mSize); } mSize = 0; } - - // Must be defined in base class. - //reference at(size_type ix) { return mArray[ix]; } - //const_reference at(size_type ix) const { return mArray[ix]; } - //reference operator[] (size_type ix) { assert(ix < size()); return at(ix); } - //const_reference operator[] (size_type ix) const { assert(ix < size()); return at(ix); } -protected: - Allocator &allocator() const { return mAllocator; } - -private: - - pointer &mArray; - size_type &mSize; - size_type mCapacity; - Allocator &mAllocator; -}; - - -// -// A CSSM_DL_DB_LIST wrapper. -// Note that there is a DLDBList class elsewhere that is quite -// unrelated to this structure. -// -class CssmDlDbHandle : public PodWrapper { -public: - CssmDlDbHandle() { clearPod(); } - CssmDlDbHandle(CSSM_DL_HANDLE dl, CSSM_DB_HANDLE db) { DLHandle = dl; DBHandle = db; } - - CSSM_DL_HANDLE dl() const { return DLHandle; } - CSSM_DB_HANDLE db() const { return DBHandle; } - - operator bool() const { return DLHandle && DBHandle; } -}; - -inline bool operator < (const CSSM_DL_DB_HANDLE &h1, const CSSM_DL_DB_HANDLE &h2) -{ - return h1.DLHandle < h2.DLHandle - || (h1.DLHandle == h2.DLHandle && h1.DBHandle < h2.DBHandle); -} - -inline bool operator == (const CSSM_DL_DB_HANDLE &h1, const CSSM_DL_DB_HANDLE &h2) -{ - return h1.DLHandle == h2.DLHandle && h1.DBHandle == h2.DBHandle; -} - -inline bool operator != (const CSSM_DL_DB_HANDLE &h1, const CSSM_DL_DB_HANDLE &h2) -{ - return h1.DLHandle != h2.DLHandle || h1.DBHandle != h2.DBHandle; -} - - -class CssmDlDbList : public PodWrapper { -public: - uint32 count() const { return NumHandles; } - uint32 &count() { return NumHandles; } - CssmDlDbHandle *handles() const { return CssmDlDbHandle::overlay(DLDBHandle); } - CssmDlDbHandle * &handles() { return CssmDlDbHandle::overlayVar(DLDBHandle); } - - CssmDlDbHandle &operator [] (uint32 ix) const - { assert(ix < count()); return CssmDlDbHandle::overlay(DLDBHandle[ix]); } - - void setDlDbList(uint32 n, CSSM_DL_DB_HANDLE *list) - { count() = n; handles() = CssmDlDbHandle::overlay(list); } -}; - - -// -// CssmDLPolyData -// -class CssmDLPolyData -{ -public: - CssmDLPolyData(const CSSM_DATA &data, CSSM_DB_ATTRIBUTE_FORMAT format) - : mData(CssmData::overlay(data)) -#ifndef NDEBUG - , mFormat(format) -#endif - {} - - // @@@ Don't use assert, but throw an exception. - // @@@ Do a size check on mData as well. - - // @@@ This method is dangerous since the returned string is not guaranteed to be zero terminated. - operator const char *() const - { - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_STRING - || mFormat == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE); - return reinterpret_cast(mData.Data); - } - operator bool() const - { - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_UINT32 || mFormat == CSSM_DB_ATTRIBUTE_FORMAT_SINT32); - return *reinterpret_cast(mData.Data); - } - operator uint32() const - { - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_UINT32); - return *reinterpret_cast(mData.Data); - } - operator const uint32 *() const - { - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32); - return reinterpret_cast(mData.Data); - } - operator sint32() const - { - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_SINT32); - return *reinterpret_cast(mData.Data); - } - operator double() const - { - assert(mFormat == CSSM_DB_ATTRIBUTE_FORMAT_REAL); - return *reinterpret_cast(mData.Data); - } - operator CSSM_DATE () const; - operator Guid () const; - operator const CssmData &() const - { - return mData; - } - -private: - const CssmData &mData; -#ifndef NDEBUG - CSSM_DB_ATTRIBUTE_FORMAT mFormat; -#endif -}; - - -// -// CssmDbAttributeInfo pod wrapper for CSSM_DB_ATTRIBUTE_INFO -// -class CssmDbAttributeInfo : public PodWrapper -{ -public: - CssmDbAttributeInfo(const CSSM_DB_ATTRIBUTE_INFO &attr) - { assignPod(attr); } - - CssmDbAttributeInfo(const char *name, - CSSM_DB_ATTRIBUTE_FORMAT vFormat = CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX); - CssmDbAttributeInfo(const CSSM_OID &oid, - CSSM_DB_ATTRIBUTE_FORMAT vFormat = CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX); - CssmDbAttributeInfo(uint32 id, - CSSM_DB_ATTRIBUTE_FORMAT vFormat = CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX); - - CSSM_DB_ATTRIBUTE_NAME_FORMAT nameFormat() const { return AttributeNameFormat; } - void nameFormat(CSSM_DB_ATTRIBUTE_NAME_FORMAT nameFormat) { AttributeNameFormat = nameFormat; } - - CSSM_DB_ATTRIBUTE_FORMAT format() const { return AttributeFormat; } - void format(CSSM_DB_ATTRIBUTE_FORMAT format) { AttributeFormat = format; } - - const char *stringName() const - { - assert(nameFormat() == CSSM_DB_ATTRIBUTE_NAME_AS_STRING); - return Label.AttributeName; - } - const CssmOid &oidName() const - { - assert(nameFormat() == CSSM_DB_ATTRIBUTE_NAME_AS_OID); - return CssmOid::overlay(Label.AttributeOID); - } - uint32 intName() const - { - assert(nameFormat() == CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER); - return Label.AttributeID; - } - - operator const char *() const { return stringName(); } - operator const CssmOid &() const { return oidName(); } - operator uint32() const { return intName(); } - - bool operator <(const CssmDbAttributeInfo& other) const; - bool operator ==(const CssmDbAttributeInfo& other) const; - bool operator !=(const CssmDbAttributeInfo& other) const - { return !(*this == other); } -}; - -// -// CssmDbRecordAttributeInfo pod wrapper for CSSM_DB_RECORD_ATTRIBUTE_INFO -// -class CssmDbRecordAttributeInfo : public PodWrapper -{ -public: - CssmDbRecordAttributeInfo() - { DataRecordType = CSSM_DL_DB_RECORD_ANY; } - - CssmDbRecordAttributeInfo(CSSM_DB_RECORDTYPE recordType, uint32 numberOfAttributes, - CSSM_DB_ATTRIBUTE_INFO_PTR attributeInfo) - { - DataRecordType = recordType; - NumberOfAttributes = numberOfAttributes; - AttributeInfo = attributeInfo; - } - - CSSM_DB_RECORDTYPE recordType() const { return DataRecordType; } - void recordType(CSSM_DB_RECORDTYPE recordType) { DataRecordType = recordType; } - - uint32 size() const { return NumberOfAttributes; } - - // attribute access - CssmDbAttributeInfo *&attributes() - { return CssmDbAttributeInfo::overlayVar(AttributeInfo); } - CssmDbAttributeInfo *attributes() const - { return CssmDbAttributeInfo::overlay(AttributeInfo); } - CssmDbAttributeInfo &at(uint32 ix) const - { assert(ix < size()); return attributes()[ix]; } - - CssmDbAttributeInfo &operator [] (uint32 ix) const { return at(ix); } -}; - -// -// CssmAutoDbRecordAttributeInfo pod wrapper for CSSM_DB_RECORD_ATTRIBUTE_INFO -// -class CssmAutoDbRecordAttributeInfo: public CssmDbRecordAttributeInfo, public ArrayBuilder -{ -public: - CssmAutoDbRecordAttributeInfo(uint32 capacity = 0, Allocator &allocator = Allocator::standard()) : - CssmDbRecordAttributeInfo(), - ArrayBuilder(CssmDbAttributeInfo::overlayVar(AttributeInfo), - NumberOfAttributes, capacity, allocator) {} -}; - - -// -// CssmDbAttributeData pod wrapper for CSSM_DB_ATTRIBUTE_DATA -// -class CssmDbAttributeData : public PodWrapper -{ -public: - CssmDbAttributeData() { NumberOfValues = 0; Value = NULL; } - CssmDbAttributeData(const CSSM_DB_ATTRIBUTE_DATA &attr) - { assignPod(attr); } - CssmDbAttributeData(const CSSM_DB_ATTRIBUTE_INFO &info) - { Info = info; NumberOfValues = 0; Value = NULL; } - - CssmDbAttributeInfo &info() { return CssmDbAttributeInfo::overlay(Info); } - const CssmDbAttributeInfo &info() const { return CssmDbAttributeInfo::overlay(Info); } - void info (const CSSM_DB_ATTRIBUTE_INFO &inInfo) { Info = inInfo; } - - CSSM_DB_ATTRIBUTE_FORMAT format() const { return info().format(); } - void format(CSSM_DB_ATTRIBUTE_FORMAT f) { info().format(f); } - - uint32 size() const { return NumberOfValues; } - CssmData *&values() { return CssmData::overlayVar(Value); } - CssmData *values() const { return CssmData::overlay(Value); } - - CssmData &at(unsigned int ix) const - { - if (ix >= size()) CssmError::throwMe(CSSMERR_DL_MISSING_VALUE); - return values()[ix]; - } - - CssmData &operator [] (unsigned int ix) const { return at(ix); } - - template - T at(unsigned int ix) const { return CssmDLPolyData(Value[ix], format()); } - - // this is intentionally unspecified since it could lead to bugs; the - // data is not guaranteed to be NULL-terminated - // operator const char *() const; - - operator string() const; - operator const Guid &() const; - operator bool() const; - operator uint32() const; - operator const uint32 *() const; - operator sint32() const; - operator double() const; - operator const CssmData &() const; - - // set values without allocation (caller owns the data contents) - void set(CssmData &data) { set(1, &data); } - void set(uint32 count, CssmData *datas) { NumberOfValues = count; Value = datas; } - - // Set the value of this Attr (assuming it was not set before). - void set(const CSSM_DB_ATTRIBUTE_INFO &inInfo, const CssmPolyData &inValue, - Allocator &inAllocator); - - // copy (just) the return-value part from another AttributeData to this one - void copyValues(const CssmDbAttributeData &source, Allocator &alloc); - - // Set the value of this Attr (which must be unset so far) - void set(const CSSM_DB_ATTRIBUTE_DATA &source, Allocator &alloc) - { - info(source.Info); - copyValues(source, alloc); - } - - // Add a value to this attribute. - void add(const CssmPolyData &inValue, Allocator &inAllocator); - - void add(const char *value, Allocator &alloc) - { format(CSSM_DB_ATTRIBUTE_FORMAT_STRING); add(CssmPolyData(value), alloc); } - - void add(const std::string &value, Allocator &alloc) - { format(CSSM_DB_ATTRIBUTE_FORMAT_STRING); add(CssmPolyData(value), alloc); } - - void add(uint32 value, Allocator &alloc) - { format(CSSM_DB_ATTRIBUTE_FORMAT_UINT32); add(CssmPolyData(value), alloc); } - - void add(sint32 value, Allocator &alloc) - { format(CSSM_DB_ATTRIBUTE_FORMAT_SINT32); add(CssmPolyData(value), alloc); } - - void add(const CssmData &value, Allocator &alloc) - { format(CSSM_DB_ATTRIBUTE_FORMAT_BLOB); add(CssmPolyData(value), alloc); } - - void add(const CssmDbAttributeData &src, Allocator &inAllocator); - - // delete specific values if they are present in this attribute data - bool deleteValue(const CssmData &src, Allocator &inAllocator); - void deleteValues(const CssmDbAttributeData &src, Allocator &inAllocator); - - void deleteValues(Allocator &inAllocator); - - bool operator <(const CssmDbAttributeData& other) const; -}; - - -// -// CssmDbRecordAttributeData pod wrapper for CSSM_DB_RECORD_ATTRIBUTE_DATA -// -class CssmDbRecordAttributeData : public PodWrapper -{ -public: - CssmDbRecordAttributeData() - { clearPod(); DataRecordType = CSSM_DL_DB_RECORD_ANY; } - - CSSM_DB_RECORDTYPE recordType() const { return DataRecordType; } - void recordType(CSSM_DB_RECORDTYPE recordType) { DataRecordType = recordType; } - - uint32 semanticInformation() const { return SemanticInformation; } - void semanticInformation(uint32 semanticInformation) { SemanticInformation = semanticInformation; } - - uint32 size() const { return NumberOfAttributes; } - CssmDbAttributeData *&attributes() - { return CssmDbAttributeData::overlayVar(AttributeData); } - CssmDbAttributeData *attributes() const - { return CssmDbAttributeData::overlay(AttributeData); } - - // Attributes by position - CssmDbAttributeData &at(unsigned int ix) const - { assert(ix < size()); return attributes()[ix]; } - - CssmDbAttributeData &operator [] (unsigned int ix) const { return at(ix); } - - void deleteValues(Allocator &allocator) - { for (uint32 ix = 0; ix < size(); ++ix) at(ix).deleteValues(allocator); } - - CssmDbAttributeData *find(const CSSM_DB_ATTRIBUTE_INFO &inInfo); - - bool operator <(const CssmDbRecordAttributeData& other) const; -}; - - -// -// CssmAutoDbRecordAttributeData -// -class CssmAutoDbRecordAttributeData : public CssmDbRecordAttributeData, public ArrayBuilder -{ -public: - CssmAutoDbRecordAttributeData(uint32 capacity = 0, - Allocator &valueAllocator = Allocator::standard(), - Allocator &dataAllocator = Allocator::standard()) : - CssmDbRecordAttributeData(), - ArrayBuilder(CssmDbAttributeData::overlayVar(AttributeData), - NumberOfAttributes, capacity, dataAllocator), - mValueAllocator(valueAllocator) {} - ~CssmAutoDbRecordAttributeData(); - - void clear(); - void deleteValues() { CssmDbRecordAttributeData::deleteValues(mValueAllocator); } - void invalidate(); - - CssmDbAttributeData &add() { return ArrayBuilder::add(); } // XXX using doesn't work here. - CssmDbAttributeData &add(const CSSM_DB_ATTRIBUTE_INFO &info); - CssmDbAttributeData &add(const CSSM_DB_ATTRIBUTE_INFO &info, const CssmPolyData &value); - - // So clients can pass this as the allocator argument to add() - operator Allocator &() const { return mValueAllocator; } -private: - Allocator &mValueAllocator; - - CssmDbAttributeData* findAttribute (const CSSM_DB_ATTRIBUTE_INFO &info); - CssmDbAttributeData& getAttributeReference (const CSSM_DB_ATTRIBUTE_INFO &info); -}; - - -// -// CssmSelectionPredicate a PodWrapper for CSSM_SELECTION_PREDICATE -// -class CssmSelectionPredicate : public PodWrapper { -public: - CssmSelectionPredicate() { clearPod(); } - - CSSM_DB_OPERATOR dbOperator() const { return DbOperator; } - void dbOperator(CSSM_DB_OPERATOR dbOperator) { DbOperator = dbOperator; } - - CssmSelectionPredicate(CSSM_DB_OPERATOR inDbOperator) - { dbOperator(inDbOperator); Attribute.NumberOfValues = 0; Attribute.Value = NULL; } - - CssmDbAttributeData &attribute() { return CssmDbAttributeData::overlay(Attribute); } - const CssmDbAttributeData &attribute() const { return CssmDbAttributeData::overlay(Attribute); } - - // Set the value of this CssmSelectionPredicate (assuming it was not set before). - void set(const CSSM_DB_ATTRIBUTE_INFO &inInfo, - const CssmPolyData &inValue, Allocator &inAllocator) - { attribute().set(inInfo, inValue, inAllocator); } - - // Set the value of this CssmSelectionPredicate using another CssmSelectionPredicate's value. - void set(const CSSM_SELECTION_PREDICATE &other, Allocator &inAllocator) - { DbOperator = other.DbOperator; attribute().set(other.Attribute, inAllocator); } - - // Add a value to the list of values for this CssmSelectionPredicate. - void add(const CssmPolyData &inValue, Allocator &inAllocator) - { attribute().add(inValue, inAllocator); } - - void deleteValues(Allocator &inAllocator) { attribute().deleteValues(inAllocator); } -}; - -class CssmQuery : public PodWrapper { -public: - CssmQuery(CSSM_DB_RECORDTYPE type = CSSM_DL_DB_RECORD_ANY) - { clearPod(); RecordType = type; } - - // copy or assign flat from CSSM_QUERY - CssmQuery(const CSSM_QUERY &q) { assignPod(q); } - CssmQuery &operator = (const CSSM_QUERY &q) { assignPod(q); return *this; } - - // flat copy and change record type - CssmQuery(const CssmQuery &q, CSSM_DB_RECORDTYPE type) - { *this = q; RecordType = type; } - - CSSM_DB_RECORDTYPE recordType() const { return RecordType; } - void recordType(CSSM_DB_RECORDTYPE recordType) { RecordType = recordType; } - - CSSM_DB_CONJUNCTIVE conjunctive() const { return Conjunctive; } - void conjunctive(CSSM_DB_CONJUNCTIVE conjunctive) { Conjunctive = conjunctive; } - - CSSM_QUERY_LIMITS queryLimits() const { return QueryLimits; } - void queryLimits(CSSM_QUERY_LIMITS queryLimits) { QueryLimits = queryLimits; } - - CSSM_QUERY_FLAGS queryFlags() const { return QueryFlags; } - void queryFlags(CSSM_QUERY_FLAGS queryFlags) { QueryFlags = queryFlags; } - - uint32 size() const { return NumSelectionPredicates; } - - CssmSelectionPredicate *&predicates() - { return CssmSelectionPredicate::overlayVar(SelectionPredicate); } - CssmSelectionPredicate *predicates() const - { return CssmSelectionPredicate::overlay(SelectionPredicate); } - - CssmSelectionPredicate &at(uint32 ix) const - { assert(ix < size()); return predicates()[ix]; } - - CssmSelectionPredicate &operator[] (uint32 ix) const { return at(ix); } - - void set(uint32 count, CSSM_SELECTION_PREDICATE *preds) - { NumSelectionPredicates = count; SelectionPredicate = preds; } - - void deleteValues(Allocator &allocator) - { for (uint32 ix = 0; ix < size(); ++ix) at(ix).deleteValues(allocator); } -}; - - -class CssmAutoQuery : public CssmQuery, public ArrayBuilder { -public: - CssmAutoQuery(const CSSM_QUERY &query, Allocator &allocator = Allocator::standard()); - CssmAutoQuery(uint32 capacity = 0, Allocator &allocator = Allocator::standard()) : - ArrayBuilder(CssmSelectionPredicate::overlayVar(SelectionPredicate), - NumSelectionPredicates, - capacity, allocator) {} - ~CssmAutoQuery(); - void clear(); - void deleteValues() { CssmQuery::deleteValues(allocator()); } - - CssmSelectionPredicate &add() { return ArrayBuilder::add(); } - CssmSelectionPredicate &add(CSSM_DB_OPERATOR dbOperator, const CSSM_DB_ATTRIBUTE_INFO &info, const CssmPolyData &value); - - // So clients can pass this as the allocator argument to add() - operator Allocator &() const { return allocator(); } -}; - - -// -// DLDbIdentifier -// -class DLDbIdentifier -{ -protected: - class Impl : public RefCount - { - NOCOPY(Impl) - public: - Impl(const CSSM_SUBSERVICE_UID &ssuid,const char *DbName,const CSSM_NET_ADDRESS *DbLocation) : - mCssmSubserviceUid(ssuid),mDbName(DbName,DbLocation) {} - - ~Impl() {} // Must be public since RefPointer uses it. - - // Accessors - const CssmSubserviceUid &ssuid() const { return mCssmSubserviceUid; } - const char *dbName() const { return mDbName.dbName(); } - const CssmNetAddress *dbLocation() const { return mDbName.dbLocation(); } - - // comparison (simple lexicographic) - bool operator < (const Impl &other) const; - bool operator == (const Impl &other) const; - private: - // Private member variables - CssmSubserviceUid mCssmSubserviceUid; - DbName mDbName; - }; - -public: - // Constructors - DLDbIdentifier() {} - DLDbIdentifier(const CSSM_SUBSERVICE_UID &ssuid, const char *DbName, const CSSM_NET_ADDRESS *DbLocation) - : mImpl(new Impl(ssuid, DbName, DbLocation)) {} - DLDbIdentifier(const char *name, const Guid &guid, uint32 ssid, uint32 sstype, - const CSSM_NET_ADDRESS *location = NULL) - : mImpl(new Impl(CssmSubserviceUid(guid, NULL, ssid, sstype), name, location)) { } - - // Conversion Operators - bool operator !() const { return !mImpl; } - operator bool() const { return mImpl; } - - // Operators - bool operator <(const DLDbIdentifier &other) const - { return mImpl && other.mImpl ? *mImpl < *other.mImpl : mImpl.get() < other.mImpl.get(); } - bool operator ==(const DLDbIdentifier &other) const - { return mImpl && other.mImpl ? *mImpl == *other.mImpl : mImpl.get() == other.mImpl.get(); } - DLDbIdentifier &operator =(const DLDbIdentifier &other) - { mImpl = other.mImpl; return *this; } - - // Accessors - const CssmSubserviceUid &ssuid() const { return mImpl->ssuid(); } - const char *dbName() const { return mImpl->dbName(); } - const CssmNetAddress *dbLocation() const { return mImpl->dbLocation(); } - bool IsImplEmpty() const {return mImpl == NULL;} - - RefPointer mImpl; -}; - -// Wrappers for index-related CSSM objects. - -class CssmDbIndexInfo : public PodWrapper -{ -public: - CssmDbIndexInfo(const CSSM_DB_INDEX_INFO &attr) - { (CSSM_DB_INDEX_INFO &)*this = attr; } - - CSSM_DB_INDEX_TYPE indexType() const { return IndexType; } - void indexType(CSSM_DB_INDEX_TYPE indexType) { IndexType = indexType; } - - CSSM_DB_INDEXED_DATA_LOCATION dataLocation() const { return IndexedDataLocation; } - void dataLocation(CSSM_DB_INDEXED_DATA_LOCATION dataLocation) - { - IndexedDataLocation = dataLocation; - } - - const CssmDbAttributeInfo &attributeInfo() const - { - return CssmDbAttributeInfo::overlay(Info); - } -}; - - -namespace DataWalkers { - - -// -// DLDbIdentifiers don't walk directly because they have Impl structure and use strings. -// Happily, they are easily transcribed into a walkable form. -// -struct DLDbFlatIdentifier { - CssmSubserviceUid *uid; // module reference - char *name; // string name - CssmNetAddress *address; // optional network address - - DLDbFlatIdentifier(const DLDbIdentifier &ident) : - uid(const_cast(&ident.ssuid())), - name(const_cast(ident.dbName())), - address(const_cast(ident.dbLocation())) - { } - - operator DLDbIdentifier () { return DLDbIdentifier(*uid, name, address); } -}; - -template -DLDbFlatIdentifier *walk(Action &operate, DLDbFlatIdentifier * &ident) -{ - operate(ident); - if (ident->uid) - walk(operate, ident->uid); - walk(operate, ident->name); - if (ident->address) - walk(operate, ident->address); - return ident; -} - - -// -// Walkers for the byzantine data structures of the DL universe. -// Geez, what WERE they smoking when they invented this? -// - -// DbAttributeInfos -template -void enumerate(Action &operate, CssmDbAttributeInfo &info) -{ - switch (info.nameFormat()) { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - walk(operate, info.Label.AttributeName); - break; - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - walk(operate, info.Label.AttributeOID); - break; - default: - break; - } -} - -template -void walk(Action &operate, CssmDbAttributeInfo &info) -{ - operate(info); - enumerate(operate, info); -} - -template -CssmDbAttributeInfo *walk(Action &operate, CssmDbAttributeInfo * &info) -{ - operate(info); - enumerate(operate, *info); - return info; -} - -// DbRecordAttributeInfo -template -void walk(Action &operate, CssmDbRecordAttributeInfo &info) -{ - operate(info); - enumerateArray(operate, info, &CssmDbRecordAttributeInfo::attributes); -} - -template -CssmDbRecordAttributeInfo *walk(Action &operate, CssmDbRecordAttributeInfo * &info) -{ - operate(info); - enumerateArray(operate, *info, &CssmDbRecordAttributeInfo::attributes); - return info; -} - -// DbAttributeData (Info + value vector) -template -void walk(Action &operate, CssmDbAttributeData &data) -{ - operate(data); - walk(operate, data.info()); - enumerateArray(operate, data, &CssmDbAttributeData::values); -} - -template -CssmDbAttributeData *walk(Action &operate, CssmDbAttributeData * &data) -{ - operate(data); - walk(operate, data->info()); - enumerateArray(operate, *data, &CssmDbAttributeData::values); - return data; -} - -// DbRecordAttributeData (array of ...datas) -template -void walk(Action &operate, CssmDbRecordAttributeData &data) -{ - operate(data); - enumerateArray(operate, data, &CssmDbRecordAttributeData::attributes); -} - -template -CssmDbRecordAttributeData *walk(Action &operate, CssmDbRecordAttributeData * &data) -{ - operate(data); - enumerateArray(operate, *data, &CssmDbRecordAttributeData::attributes); - return data; -} - -// SelectionPredicates -template -CssmSelectionPredicate *walk(Action &operate, CssmSelectionPredicate * &predicate) -{ - operate(predicate); - walk(operate, predicate->attribute()); - return predicate; -} - -template -void walk(Action &operate, CssmSelectionPredicate &predicate) -{ - operate(predicate); - walk(operate, predicate.attribute()); -} - -// Queries -template -void walk(Action &operate, CssmQuery &query) -{ - operate(query); - enumerateArray(operate, query, &CssmQuery::predicates); -} - -template -CssmQuery *walk(Action &operate, CssmQuery * &query) -{ - operate(query); - enumerateArray(operate, *query, &CssmQuery::predicates); - return query; -} - -template -CSSM_QUERY *walk(Action &operate, CSSM_QUERY * &query) -{ - return walk(operate, CssmQuery::overlayVar(query)); -} - - -} // end namespace DataWalkers -} // end namespace Security - - -#endif // _H_CDSA_UTILITIES_CSSMDB diff --git a/OSX/include/security_cdsa_utilities/cssmdbname.cpp b/OSX/include/security_cdsa_utilities/cssmdbname.cpp deleted file mode 100644 index 48706c99..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdbname.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include -#include -#include - -CssmNetAddress::CssmNetAddress(CSSM_DB_RECORDTYPE inAddressType, const CssmData &inAddress) -{ - AddressType = inAddressType; - Address.Length = inAddress.Length; - if (Address.Length > 0) - { - Address.Data = new uint8[Address.Length]; - memcpy (Address.Data, inAddress.Data, Address.Length); - } - else - Address.Data = NULL; -} - -CssmNetAddress::CssmNetAddress(const CSSM_NET_ADDRESS &other) -{ - AddressType = other.AddressType; - Address.Length = other.Address.Length; - if (Address.Length > 0) - { - Address.Data = new uint8[Address.Length]; - memcpy (Address.Data, other.Address.Data, Address.Length); - } - else - Address.Data = NULL; -} - -CssmNetAddress::~CssmNetAddress() -{ - if (Address.Length > 0) - delete Address.Data; -} - -void DbName::CanonicalizeName() -{ - if (mDbNameValid) - { - char* s = cached_realpath(mDbName.c_str(), NULL); - if (s != NULL) - { - mCanonicalName = s; - free(s); - } - else - { - // the most likely situation here is that the file doesn't exist. - // we will pull the path apart and try again. - - // search backward for the delimiter - ptrdiff_t n = mDbName.length() - 1; - - // all subpaths must be tested, because there may be more than just - // the file name that doesn't exist. - while (n > 0) - { - while (n > 0 && mDbName[n] != '/') // if the delimiter is 0, we would never - // have gotten here in the first place - { - n -= 1; - } - - if (n > 0) - { - string tmpPath = mDbName.substr(0, n); - s = cached_realpath(tmpPath.c_str(), NULL); - if (s != NULL) - { - mCanonicalName = s; - free(s); - mCanonicalName += mDbName.substr(n, mDbName.length() - n); - return; - } - } - - n -= 1; - } - - // if we get here, all other paths have failed. Just reuse the original string. - mCanonicalName = mDbName; - } - } -} - - - -DbName::DbName(const char *inDbName, const CSSM_NET_ADDRESS *inDbLocation) - : mDbName(inDbName ? inDbName : ""), mDbNameValid(inDbName), mDbLocation(NULL) -{ - if (inDbLocation) - { - mDbLocation = new CssmNetAddress(*inDbLocation); - } - - CanonicalizeName(); -} - -DbName::DbName(const DbName &other) - : mDbName(other.mDbName), mDbNameValid(other.mDbNameValid), mDbLocation(NULL) -{ - if (other.mDbLocation) - { - mDbLocation = new CssmNetAddress(*other.mDbLocation); - } - - CanonicalizeName(); -} - -DbName & -DbName::operator =(const DbName &other) -{ - mDbName = other.mDbName; - mDbNameValid = other.mDbNameValid; - if (other.mDbLocation) - { - mDbLocation = new CssmNetAddress(*other.mDbLocation); - } - - return *this; -} - -DbName::~DbName() -{ - delete mDbLocation; -} diff --git a/OSX/include/security_cdsa_utilities/cssmdbname.h b/OSX/include/security_cdsa_utilities/cssmdbname.h deleted file mode 100644 index a4954935..00000000 --- a/OSX/include/security_cdsa_utilities/cssmdbname.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#ifndef _DBNAME_H_ -#define _DBNAME_H_ 1 - -#include -#include -#include -#include - -#ifdef _CPP_DBNAME -# pragma export on -#endif - -// @@@ Should not use using in headers. -using namespace std; - -namespace Security -{ - -//---------------------------------------------------------------- -//typedef struct cssm_net_address { -// CSSM_NET_ADDRESS_TYPE AddressType; -// CSSM_DATA Address; -//} CSSM_NET_ADDRESS, *CSSM_NET_ADDRESS_PTR; -//---------------------------------------------------------------- - -// XXX TODO: Make CssmNetAddress use a factory to constuct netadrress objects based on CSSM_NET_ADDRESS_TYPE! -class CssmNetAddress : public PodWrapper -{ -public: - // Create a CssmNetAddress wrapper. Copies inAddress.Data - CssmNetAddress(CSSM_DB_RECORDTYPE inAddressType, const CssmData &inAddress); - CssmNetAddress(const CSSM_NET_ADDRESS &other); - ~CssmNetAddress(); - CSSM_DB_RECORDTYPE addressType() const { return AddressType; } - const CssmData &address() const { return CssmData::overlay(Address); } - bool operator <(const CssmNetAddress &other) const - { - return AddressType != other.AddressType ? AddressType < other.AddressType : address() < other.address(); - } -}; - -class DbName -{ -public: - DbName (const char *inDbName = NULL, const CSSM_NET_ADDRESS *inDbLocation = NULL); - DbName(const DbName &other); - DbName &operator =(const DbName &other); - ~DbName (); - const char *dbName() const { return mDbNameValid ? mDbName.c_str() : NULL; } - const char *canonicalName() const { return mDbNameValid ? mCanonicalName.c_str() : NULL; } - const CssmNetAddress *dbLocation() const { return mDbLocation; } - bool operator <(const DbName &other) const - { - // invalid is always smaller than valid - if (!mDbNameValid || !other.mDbNameValid) - return mDbNameValid < other.mDbNameValid; - - // If mDbNames are not equal return whether our mDbName is less than others mDbName. - if (canonicalName() != other.canonicalName()) - return mDbName < other.mDbName; - - // DbNames are equal so check for pointer equality of DbLocations - if (mDbLocation == other.mDbLocation) - return false; - - // If either DbLocations is nil the one that is nil is less than the other. - if (mDbLocation == nil || other.mDbLocation == nil) - return mDbLocation < other.mDbLocation; - - // Return which mDbLocation is smaller. - return *mDbLocation < *other.mDbLocation; - } - bool operator ==(const DbName &other) const - { return (!(*this < other)) && (!(other < *this)); } - bool operator !=(const DbName &other) const - { return *this < other || other < *this; } - -private: - void CanonicalizeName(); - - string mDbName; - string mCanonicalName; - bool mDbNameValid; - CssmNetAddress *mDbLocation; -}; - - -namespace DataWalkers -{ - -template -CssmNetAddress *walk(Action &operate, CssmNetAddress * &addr) -{ - operate(addr); - walk(operate, addr->Address); - return addr; -} - -} // end namespace DataWalkers - -} // end namespace Security - -#ifdef _CPP_DBNAME -# pragma export off -#endif - -#endif //_DBNAME_H_ diff --git a/OSX/include/security_cdsa_utilities/cssmendian.cpp b/OSX/include/security_cdsa_utilities/cssmendian.cpp deleted file mode 100644 index 687489ab..00000000 --- a/OSX/include/security_cdsa_utilities/cssmendian.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2002-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Byte order ("endian-ness") handling -// -#include - -namespace Security { - - -void n2hi(CssmKey::Header &header) -{ - header.HeaderVersion = n2h(header.HeaderVersion); - header.BlobType = n2h(header.BlobType); - header.Format = n2h(header.Format); - header.AlgorithmId = n2h(header.AlgorithmId); - header.KeyClass = n2h(header.KeyClass); - header.LogicalKeySizeInBits = n2h(header.LogicalKeySizeInBits); - header.KeyAttr = n2h(header.KeyAttr); - header.KeyUsage = n2h(header.KeyUsage); - header.WrapAlgorithmId = n2h(header.WrapAlgorithmId); - header.WrapMode = n2h(header.WrapMode); - header.Reserved = n2h(header.Reserved); -} - -void h2ni(CssmKey::Header &key) -{ - n2hi(key); -} - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmendian.h b/OSX/include/security_cdsa_utilities/cssmendian.h deleted file mode 100644 index 99edcf91..00000000 --- a/OSX/include/security_cdsa_utilities/cssmendian.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2002-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * cssm utilities - */ -#ifndef _H_CSSMENDIAN -#define _H_CSSMENDIAN - -#include -#include - -namespace Security { - - -// -// Some structs we may want swapped in-place -// -void n2hi(CssmKey::Header &key); -void h2ni(CssmKey::Header &key); - -inline void n2hi(CSSM_KEYHEADER &key) { n2hi(CssmKey::Header::overlay (key));} -inline void h2ni(CSSM_KEYHEADER &key) { h2ni(CssmKey::Header::overlay (key));} - -} // end namespace Security - - -#endif //_H_CSSMENDIAN - diff --git a/OSX/include/security_cdsa_utilities/cssmerrors.cpp b/OSX/include/security_cdsa_utilities/cssmerrors.cpp deleted file mode 100644 index 0d0f7c29..00000000 --- a/OSX/include/security_cdsa_utilities/cssmerrors.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmerrors -// -#include -#include -#include -#include - -namespace Security { - - -CssmError::CssmError(CSSM_RETURN err) : error(err) -{ - SECURITY_EXCEPTION_THROW_CSSM(this, err); -} - - -const char *CssmError::what() const throw () -{ - return "CSSM exception"; -} - - -OSStatus CssmError::osStatus() const -{ - if (error == CSSM_ERRCODE_INVALID_POINTER) - { - return errSecParam; - } - - return error; -} - - -int CssmError::unixError() const -{ - OSStatus err = osStatus(); - - // embedded UNIX errno values are returned verbatim - if (err >= errSecErrnoBase && err <= errSecErrnoLimit) - return err - errSecErrnoBase; - - // re-map certain CSSM errors - switch (err) { - case CSSM_ERRCODE_MEMORY_ERROR: - return ENOMEM; - case CSSMERR_APPLEDL_DISK_FULL: - return ENOSPC; - case CSSMERR_APPLEDL_QUOTA_EXCEEDED: - return EDQUOT; - case CSSMERR_APPLEDL_FILE_TOO_BIG: - return EFBIG; - default: - // cannot map this to errno space - return -1; - } -} - - -void CssmError::throwMe(CSSM_RETURN err) -{ - throw CssmError(err); -} - - -CSSM_RETURN CssmError::merge(CSSM_RETURN error, CSSM_RETURN base) -{ - if (0 < error && error < CSSM_ERRORCODE_COMMON_EXTENT) { - return base + error; - } else { - return error; - } -} - -// -// Get a CSSM_RETURN from a CommonError -// -CSSM_RETURN CssmError::cssmError(const CommonError &error, CSSM_RETURN base) -{ - if (const CssmError *cssm = dynamic_cast(&error)) { - return cssmError(cssm->error, base); - } else if (const MachPlusPlus::Error *mach = dynamic_cast(&error)) { - switch (mach->error) { - case BOOTSTRAP_UNKNOWN_SERVICE: - case MIG_SERVER_DIED: - return CSSM_ERRCODE_SERVICE_NOT_AVAILABLE; - default: - return CSSM_ERRCODE_INTERNAL_ERROR; - } - } else { - return error.osStatus(); - } -} - -CSSM_RETURN CssmError::cssmError(CSSM_RETURN error, CSSM_RETURN base) -{ - if (0 < error && error < CSSM_ERRORCODE_COMMON_EXTENT) { - return base + error; - } else { - return error; - } -} - - -} // namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmerrors.h b/OSX/include/security_cdsa_utilities/cssmerrors.h deleted file mode 100644 index fc83b898..00000000 --- a/OSX/include/security_cdsa_utilities/cssmerrors.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * cssmerrors - */ -#ifndef _H_CSSMERRORS -#define _H_CSSMERRORS - -#include -#include - -namespace Security -{ - -// -// A CSSM-originated error condition, represented by a CSSM_RETURN value. -// This can represent both a convertible base error, or a module-specific -// error condition. -// -class CssmError : public CommonError { -protected: - CssmError(CSSM_RETURN err); -public: - const CSSM_RETURN error; - virtual OSStatus osStatus() const; - virtual int unixError() const; - virtual const char *what () const throw (); - - static CSSM_RETURN merge(CSSM_RETURN error, CSSM_RETURN base); - - static void check(CSSM_RETURN error) { if (error != CSSM_OK) throwMe(error); } - static void throwMe(CSSM_RETURN error) __attribute__((noreturn)); - - // - // Obtain a CSSM_RETURN from any CommonError - // - static CSSM_RETURN cssmError(CSSM_RETURN error, CSSM_RETURN base); - static CSSM_RETURN cssmError(const CommonError &error, CSSM_RETURN base); -}; - - - -} // end namespace Security - - -#endif //_H_CSSMERRORS diff --git a/OSX/include/security_cdsa_utilities/cssmkey.cpp b/OSX/include/security_cdsa_utilities/cssmkey.cpp deleted file mode 100644 index 111d9594..00000000 --- a/OSX/include/security_cdsa_utilities/cssmkey.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// PODWrapper for CssmKey and related types -// -#include - - -// -// Methods for the CssmKey class -// -CssmKey::CssmKey(const CSSM_KEY &key) -{ - KeyHeader = key.KeyHeader; - KeyData = key.KeyData; -} - -CssmKey::CssmKey(const CSSM_DATA &keyData) -{ - clearPod(); - KeyData = keyData; - KeyHeader.HeaderVersion = CSSM_KEYHEADER_VERSION; - KeyHeader.BlobType = CSSM_KEYBLOB_RAW; - KeyHeader.Format = CSSM_KEYBLOB_RAW_FORMAT_NONE; -} - -CssmKey::CssmKey(uint32 length, void *data) -{ - clearPod(); - KeyData = CssmData(data, length); - KeyHeader.HeaderVersion = CSSM_KEYHEADER_VERSION; - KeyHeader.BlobType = CSSM_KEYBLOB_RAW; - KeyHeader.Format = CSSM_KEYBLOB_RAW_FORMAT_NONE; -} diff --git a/OSX/include/security_cdsa_utilities/cssmkey.h b/OSX/include/security_cdsa_utilities/cssmkey.h deleted file mode 100644 index 74a7f918..00000000 --- a/OSX/include/security_cdsa_utilities/cssmkey.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// PODWrapper for CssmKey and related types -// -#ifndef _H_CSSMKEY -#define _H_CSSMKEY - -#include -#include -#include -#include - - -namespace Security { - - -// -// User-friendlier CSSM_KEY objects -// -class CssmKey : public PodWrapper { -public: - CssmKey() { clearPod(); KeyHeader.HeaderVersion = CSSM_KEYHEADER_VERSION; } - // all of the following constructors take over ownership of the key data - CssmKey(const CSSM_KEY &key); - CssmKey(const CSSM_DATA &keyData); - CssmKey(uint32 length, void *data); - -public: - class Header : public PodWrapper { - public: - // access to components of the key header - CSSM_KEYBLOB_TYPE blobType() const { return BlobType; } - void blobType(CSSM_KEYBLOB_TYPE blobType) { BlobType = blobType; } - - CSSM_KEYBLOB_FORMAT blobFormat() const { return Format; } - void blobFormat(CSSM_KEYBLOB_FORMAT blobFormat) { Format = blobFormat; } - - CSSM_KEYCLASS keyClass() const { return KeyClass; } - void keyClass(CSSM_KEYCLASS keyClass) { KeyClass = keyClass; } - - CSSM_KEY_TYPE algorithm() const { return AlgorithmId; } - void algorithm(CSSM_KEY_TYPE algorithm) { AlgorithmId = algorithm; } - - CSSM_KEY_TYPE wrapAlgorithm() const { return WrapAlgorithmId; } - void wrapAlgorithm(CSSM_KEY_TYPE wrapAlgorithm) { WrapAlgorithmId = wrapAlgorithm; } - - CSSM_ENCRYPT_MODE wrapMode() const { return WrapMode; } - void wrapMode(CSSM_ENCRYPT_MODE mode) { WrapMode = mode; } - - bool isWrapped() const { return WrapAlgorithmId != CSSM_ALGID_NONE; } - - const Guid &cspGuid() const { return Guid::overlay(CspId); } - void cspGuid(const Guid &guid) { Guid::overlay(CspId) = guid; } - - uint32 attributes() const { return KeyAttr; } - bool attribute(uint32 attr) const { return KeyAttr & attr; } - void setAttribute(uint32 attr) { KeyAttr |= attr; } - void clearAttribute(uint32 attr) { KeyAttr &= ~attr; } - - uint32 usage() const { return KeyUsage; } - bool useFor(uint32 u) const { return KeyUsage & u; } - - void usage(uint32 u) { KeyUsage |= u; } - void clearUsage(uint32 u) { KeyUsage &= ~u; } - - }; - - // access to the key header - Header &header() { return Header::overlay(KeyHeader); } - const Header &header() const { return Header::overlay(KeyHeader); } - - CSSM_KEYBLOB_TYPE blobType() const { return header().blobType(); } - void blobType(CSSM_KEYBLOB_TYPE blobType) { header().blobType(blobType); } - - CSSM_KEYBLOB_FORMAT blobFormat() const { return header().blobFormat(); } - void blobFormat(CSSM_KEYBLOB_FORMAT blobFormat) { header().blobFormat(blobFormat); } - - CSSM_KEYCLASS keyClass() const { return header().keyClass(); } - void keyClass(CSSM_KEYCLASS keyClass) { header().keyClass(keyClass); } - - CSSM_KEY_TYPE algorithm() const { return header().algorithm(); } - void algorithm(CSSM_KEY_TYPE algorithm) { header().algorithm(algorithm); } - - CSSM_KEY_TYPE wrapAlgorithm() const { return header().wrapAlgorithm(); } - void wrapAlgorithm(CSSM_KEY_TYPE wrapAlgorithm) { header().wrapAlgorithm(wrapAlgorithm); } - - CSSM_ENCRYPT_MODE wrapMode() const { return header().wrapMode(); } - void wrapMode(CSSM_ENCRYPT_MODE mode) { header().wrapMode(mode); } - - bool isWrapped() const { return header().isWrapped(); } - const Guid &cspGuid() const { return header().cspGuid(); } - - uint32 attributes() const { return header().attributes(); } - bool attribute(uint32 a) const { return header().attribute(a); } - void setAttribute(uint32 attr) { header().setAttribute(attr); } - void clearAttribute(uint32 attr) { header().clearAttribute(attr); } - - uint32 usage() const { return header().usage(); } - bool useFor(uint32 u) const { return header().useFor(u); } - - void usage(uint32 u) { header().usage(u); } - void clearUsage(uint32 u) { header().clearUsage(u); } - -public: - // access to the key data - size_t length() const { return KeyData.Length; } - void *data() const { return KeyData.Data; } - operator void * () const { return data(); } - CssmData &keyData() { return CssmData::overlay(KeyData); } - const CssmData &keyData() const { return CssmData::overlay(KeyData); } - operator CssmData & () { return keyData(); } - operator const CssmData & () const { return keyData(); } - operator bool () const { return KeyData.Data != NULL; } - void operator = (const CssmData &data) { KeyData = data; } -}; - - -// -// Wrapped keys are currently identically structured to normal keys. -// But perhaps in the future... -// -typedef CssmKey CssmWrappedKey; - - -} // end namespace Security - - -#endif //_H_CSSMUTILITIES diff --git a/OSX/include/security_cdsa_utilities/cssmlist.cpp b/OSX/include/security_cdsa_utilities/cssmlist.cpp deleted file mode 100644 index 911cf2c6..00000000 --- a/OSX/include/security_cdsa_utilities/cssmlist.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmlist - CSSM_LIST operational utilities -// -#include -#include - - -// -// Managing list elements -// -ListElement *ListElement::last() -{ - for (ListElement *p = this; ; p = p->next()) - if (p->next() == NULL) - return p; - // not reached -} - - -ListElement::ListElement(CSSM_WORDID_TYPE word) -{ - ElementType = CSSM_LIST_ELEMENT_WORDID; - WordID = word; -} - -ListElement::ListElement(const CssmData &data) -{ - ElementType = CSSM_LIST_ELEMENT_DATUM; - WordID = 0; - Element.Word = data; -} - -ListElement::ListElement(Allocator &alloc, const CssmData &data) -{ - ElementType = CSSM_LIST_ELEMENT_DATUM; - WordID = 0; - Element.Word = CssmAutoData(alloc, data).release(); -} - -ListElement::ListElement(Allocator &alloc, const string &s) -{ - ElementType = CSSM_LIST_ELEMENT_DATUM; - WordID = 0; - Element.Word = CssmAutoData(alloc, s.data(), s.size()).release(); -} - -ListElement::ListElement(const CssmList &list) -{ - ElementType = CSSM_LIST_ELEMENT_SUBLIST; - WordID = 0; - Element.Sublist = list; -} - - -CssmData &ListElement::data() -{ - assert(type() == CSSM_LIST_ELEMENT_DATUM); - return CssmData::overlay(Element.Word); -} - -const CssmData &ListElement::data() const -{ - assert(type() == CSSM_LIST_ELEMENT_DATUM); - return CssmData::overlay(Element.Word); -} - -ListElement &ListElement::operator = (const CssmData &data) -{ - assert(type() == CSSM_LIST_ELEMENT_DATUM); - Element.Word = data; - return *this; -} - - -CssmList &ListElement::list() -{ - assert(type() == CSSM_LIST_ELEMENT_SUBLIST); - return CssmList::overlay(Element.Sublist); -} - -const CssmList &ListElement::list() const -{ - assert(type() == CSSM_LIST_ELEMENT_SUBLIST); - return CssmList::overlay(Element.Sublist); -} - -TypedList &ListElement::typedList() -{ - return static_cast(list()); -} - -const TypedList &ListElement::typedList() const -{ - return static_cast(list()); -} - -ListElement &ListElement::operator = (const CssmList &list) -{ - assert(type() == CSSM_LIST_ELEMENT_SUBLIST); - Element.Sublist = list; - return *this; -} - - -CSSM_WORDID_TYPE ListElement::word() const -{ - assert(type() == CSSM_LIST_ELEMENT_WORDID); - return WordID; -} - -ListElement &ListElement::operator = (CSSM_WORDID_TYPE word) -{ - assert(type() == CSSM_LIST_ELEMENT_WORDID); - WordID = word; - return *this; -} - - -// -// List operations -// -ListElement &CssmList::operator [] (unsigned ix) const -{ - for (ListElement *elem = first(); elem; elem = elem->next(), ix--) { - if (ix == 0) - return *elem; - } - throw 999; //@@@ -} - -unsigned int CssmList::length() const -{ - unsigned int len = 0; - for (ListElement *elem = first(); elem; elem = elem->next()) - len++; - return len; -} - -CssmList &CssmList::append(ListElement *elem) -{ - if (Tail == NULL) { // first element - Head = Tail = elem; - } else { - Tail->NextElement = elem; - Tail = elem; - } - elem->NextElement = NULL; - return *this; -} - -CssmList &CssmList::insert(ListElement *elem, ListElement *before) -{ - // null before -> append - if (before == NULL) - return append(elem); - - // we have a real position - assert(!empty()); - if (Head == before) { // before first element - elem->NextElement = before; - Head = elem; - } else { // before is not first - for (CSSM_LIST_ELEMENT *p = Head; p; p = p->NextElement) { - if (p->NextElement == before) { - elem->NextElement = before; - p->NextElement = elem; - return *this; - } - } - // end of list, before not in list - throw 999; //@@@ - } - return *this; -} - -CssmList &CssmList::remove(ListElement *elem) -{ - assert(elem); - if (elem == Head) { // remove first element - Head = Head->NextElement; - } else { // subsequent element - for (CSSM_LIST_ELEMENT *p = Head; p; p = p->NextElement) - if (p->NextElement == elem) { - p->NextElement = elem->NextElement; - if (elem->NextElement == NULL) // removing last element - Tail = p; - return *this; - } - // end of list, elem not found - throw 999; //@@@ - } - return *this; -} - -void CssmList::snip() -{ - assert(Head); // can't be empty - if (Head == Tail) { // single element, empty when snipped - Head = Tail = NULL; - } else { // more than one, bypass first - Head = first()->next(); - } -} - - -// -// Deep-destruction of CssmLists and ListElements. -// The underlying assumption is that all components were allocated from a single -// Allocator in canonical chunks. -// -void ListElement::clear(Allocator &alloc) -{ - switch (type()) { - case CSSM_LIST_ELEMENT_WORDID: - break; // no substructure - case CSSM_LIST_ELEMENT_DATUM: - alloc.free(data().data()); - break; - case CSSM_LIST_ELEMENT_SUBLIST: - list().clear(alloc); - break; - default: - assert(false); - } -} - -void CssmList::clear(Allocator &alloc) -{ - ListElement *elem = first(); - while (elem) { - ListElement *next = elem->next(); - destroy(elem, alloc); - elem = next; - } -} - - -// -// Building TypedLists -// -TypedList::TypedList(Allocator &alloc, CSSM_WORDID_TYPE type) -{ - append(new(alloc) ListElement(type)); -} - -TypedList::TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1) -{ - append(new(alloc) ListElement(type)); - append(elem1); -} - -TypedList::TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1, ListElement *elem2) -{ - append(new(alloc) ListElement(type)); - append(elem1); - append(elem2); -} - -TypedList::TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1, ListElement *elem2, ListElement *elem3) -{ - append(new(alloc) ListElement(type)); - append(elem1); - append(elem2); - append(elem3); -} - -TypedList::TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1, ListElement *elem2, ListElement *elem3, ListElement *elem4) -{ - append(new(alloc) ListElement(type)); - append(elem1); - append(elem2); - append(elem3); - append(elem4); -} - - -// -// Verify that a TypedList is "proper", i.e. has a first element of WORDID form -// -bool TypedList::isProper() const -{ - return first() && first()->type() == CSSM_LIST_ELEMENT_WORDID; -} - -void TypedList::checkProper(CSSM_RETURN error) const -{ - if (!isProper()) - CssmError::throwMe(error); -} diff --git a/OSX/include/security_cdsa_utilities/cssmlist.h b/OSX/include/security_cdsa_utilities/cssmlist.h deleted file mode 100644 index 6506b0df..00000000 --- a/OSX/include/security_cdsa_utilities/cssmlist.h +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmlist - CSSM_LIST operational utilities -// -#ifndef _H_CSSMLIST -#define _H_CSSMLIST - -#include -#include -#include - - -namespace Security { - -class CssmList; -class TypedList; - - -// -// A POD Wrapper for CSSM_LIST_ELEMENTs. -// List elements are pseudo-polymorphic, so we provide ways to get and -// set their three personalities. It's up to the caller to get this right; -// you mustn't (for example) call the data() method on a list element that -// is not of (element) type CSSM_LIST_ELEMENT_DATUM. To violate this rule -// will get you an assertion (not exception). -// -class ListElement : public PodWrapper { -public: - // type control - CSSM_LIST_ELEMENT_TYPE type() const { return ElementType; } - bool is(CSSM_LIST_ELEMENT_TYPE t) const { return type() == t; } - - // list element chaining - ListElement * &next() { return ListElement::overlayVar(NextElement); } - ListElement *next() const { return ListElement::overlay(NextElement); } - ListElement *last(); - - // CssmData personality - explicit ListElement(const CssmData &data); - explicit ListElement(Allocator &alloc, const CssmData &data); - explicit ListElement(Allocator &alloc, const std::string &stringData); - - CssmData &data(); - string toString() const { return data().toString(); } - const CssmData &data() const; - ListElement &operator = (const CssmData &data); - operator CssmData &() { return data(); } - operator std::string () const { return toString(); } - bool operator == (const CssmData &other) const { return data() == other; } - bool operator != (const CssmData &other) const { return data() != other; } - - template - void extract(T &destination, CSSM_RETURN error = CSSM_ERRCODE_INVALID_DATA) - { data().extract(destination, error); } - - // CssmList (sublist) personality - explicit ListElement(const CssmList &list); - CssmList &list(); - const CssmList &list() const; - TypedList &typedList(); - const TypedList &typedList() const; - ListElement &operator = (const CssmList &list); - operator CssmList &() { return list(); } - operator TypedList &(); - - // WORDID (number) personality - explicit ListElement(CSSM_WORDID_TYPE word); - CSSM_WORDID_TYPE word() const; - ListElement &operator = (CSSM_WORDID_TYPE word); - operator CSSM_WORDID_TYPE () const { return word(); } - -public: - void *operator new (size_t size, Allocator &alloc) - { return alloc.malloc(size); } - - void clear(Allocator &alloc); // free my contents -}; - -} // end namespace Security - -// specialize destroy() to call clear() for cleanup -inline void destroy(ListElement *elem, Allocator &alloc) -{ - elem->clear(alloc); - alloc.free(elem); -} - -namespace Security { - - -// -// A POD Wrapper for CSSM_LIST. -// CssmList does no memory allocations. Retrieval functions return pointers or -// references into existing content, and modifiers modify in-place without any -// attempt to release previous dynamic content. May the Leaking God be with You. -// -class CssmList : public PodWrapper { -public: - CssmList() { ListType = CSSM_LIST_TYPE_UNKNOWN; Head = Tail = NULL; } - CssmList(const CssmList &list) { *(CssmList *)this = list; } - -public: - CSSM_LIST_TYPE kind() const { return ListType; } // type() reserved for TypedList - - ListElement &operator [] (unsigned ix) const; - unsigned int length() const; - ListElement * &first() { return ListElement::overlayVar(Head); } - ListElement *first() const { return ListElement::overlay(Head); } - ListElement *last() const { return ListElement::overlay(Tail); } - bool empty() const { return first() == NULL; } - - CssmList &append(ListElement *elem); - CssmList &insert(ListElement *elem, ListElement *before); - CssmList &remove(ListElement *elem); - CssmList &operator += (ListElement *elem) { return append(elem); } - CssmList &operator -= (ListElement *elem) { return remove(elem); } - - // logically remove the first element (skip it) - void snip(); - -public: - void clear(Allocator &alloc); // free my contents -}; - -} // end namespace Security - -inline void destroy(CssmList *list, Allocator &alloc) -{ - list->clear(alloc); - alloc.free(list); -} - -namespace Security -{ - -// -// Enhanced overlay for CssmLists whose first element is known to be a wordid. -// -class TypedList : public CssmList { -public: - explicit TypedList(const CSSM_LIST &list) { *(CSSM_LIST *)this = list; } - TypedList(Allocator &alloc, CSSM_WORDID_TYPE type); - TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1); - TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1, - ListElement *elem2); - TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1, - ListElement *elem2, ListElement *elem3); - TypedList(Allocator &alloc, CSSM_WORDID_TYPE type, ListElement *elem1, - ListElement *elem2, ListElement *elem3, ListElement *elem4); - - bool isProper() const; // format check (does not throw) - void checkProper(CSSM_RETURN error = CSSM_ERRCODE_INVALID_SAMPLE_VALUE) const; - static TypedList &overlay(CSSM_LIST &list) - { return static_cast(list); } - static const TypedList &overlay(const CSSM_LIST &list) - { return static_cast(list); } - - CSSM_WORDID_TYPE type() const - { assert(isProper()); return first()->word(); } -}; - -inline ListElement::operator TypedList &() -{ return TypedList::overlay(operator CssmList &()); } - - -// -// Data walkers to parse list elements and lists. -// @@@ Walking lists by recursing over next() is stack intensive. Do this in CssmList walker by loop? -// -namespace DataWalkers { - -// ListElement -template -ListElement *walk(Action &operate, ListElement * &elem) -{ - operate(elem); - switch (elem->type()) { - case CSSM_LIST_ELEMENT_DATUM: - walk(operate, elem->data()); - break; - case CSSM_LIST_ELEMENT_SUBLIST: - walk(operate, elem->list()); - break; - case CSSM_LIST_ELEMENT_WORDID: - break; - default: - secdebug("walkers", "invalid list element type (%ux)", (unsigned)elem->type()); - break; - } - if (elem->next()) - walk(operate, elem->next()); - return elem; -} - -template -ListElement *walk(Action &operate, CSSM_LIST_ELEMENT * &elem) -{ return walk(operate, ListElement::overlayVar(elem)); } - -// CssmList -template -void enumerate(Action &operate, CssmList &list) -{ - if (!list.empty()) { - walk(operate, list.first()); - if (operate.needsRelinking) - list.Tail = list.first()->last(); // re-establish "tail" link - } -} - -template -CssmList *walk(Action &operate, CssmList * &list) -{ - operate(list); - enumerate(operate, *list); - return list; -} - -template -void walk(Action &operate, CssmList &list) -{ - operate(list); - enumerate(operate, list); -} - -template -void walk(Action &operate, CSSM_LIST &list) -{ walk(operate, CssmList::overlay(list)); } - -template -CSSM_LIST *walk(Action &operate, CSSM_LIST * &list) -{ return walk(operate, CssmList::overlayVar(list)); } - -template -TypedList *walk(Action &operate, TypedList * &list) -{ return static_cast(walk(operate, reinterpret_cast(list))); } - -template -void walk(Action &operate, TypedList &list) -{ walk(operate, static_cast(list)); } - - -} // end namespace DataWalkers -} // end namespace Security - - -#endif //_H_CSSMLIST diff --git a/OSX/include/security_cdsa_utilities/cssmpods.cpp b/OSX/include/security_cdsa_utilities/cssmpods.cpp deleted file mode 100644 index 8915894d..00000000 --- a/OSX/include/security_cdsa_utilities/cssmpods.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Miscellaneous CSSM PODWrappers -// -#include -#include -#include - -// -// GUID <-> string conversions. -// Note that we DO check for {} on input and insist on rigid formatting. -// We don't require a terminating null byte on input, but generate it on output. -// -char *Guid::toString(char buffer[stringRepLength+1]) const -{ - sprintf(buffer, "{%8.8x-%4.4hx-%4.4hx-", - int(n2h(Data1)), n2h(Data2), n2h(Data3)); - for (int n = 0; n < 2; n++) - sprintf(buffer + 20 + 2*n, "%2.2hhx", Data4[n]); - buffer[24] = '-'; - for (int n = 2; n < 8; n++) - sprintf(buffer + 21 + 2*n, "%2.2hhx", Data4[n]); - buffer[37] = '}'; - buffer[38] = '\0'; - return buffer; -} - -string Guid::toString() const -{ - char buffer[stringRepLength+1]; - return toString(buffer); -} - -Guid::Guid(const char *s) -{ - parseGuid(s); -} - -Guid::Guid(const string &s) -{ - parseGuid(s.c_str()); -} - -void Guid::parseGuid(const char *string) -{ - // Arguably, we should be more flexible on input. But exactly what - // padding rules should we follow, and how should we try to interprete - // "doubtful" variations? Given that GUIDs are essentially magic - // cookies, everybody's better off if we just cut-and-paste them - // around the universe... - - // do sanity checking, don't assume that what's passed in makes sense - if (string == NULL) - { - CssmError::throwMe(CSSM_ERRCODE_INVALID_GUID); - } - - // what follows had better be big enough - if (strlen(string) < 37) // needed because the code hard codes the length - { - CssmError::throwMe(CSSM_ERRCODE_INVALID_GUID); - } - - int d1; - uint16 d2, d3; - if (sscanf(string, "{%8x-%4hx-%4hx-", &d1, &d2, &d3) != 3) - CssmError::throwMe(CSSM_ERRCODE_INVALID_GUID); - Data1 = h2n(uint32(d1)); - Data2 = h2n(d2); - Data3 = h2n(d3); - // once, we did not expect the - after byte 2 of Data4 - bool newForm = string[24] == '-'; - for (int n = 0; n < 8; n++) { - unsigned char dn; - if (sscanf(string + 20 + 2*n + (newForm && n >= 2), "%2hhx", &dn) != 1) - CssmError::throwMe(CSSM_ERRCODE_INVALID_GUID); - Data4[n] = dn; - } - if (string[37 - !newForm] != '}') - CssmError::throwMe(CSSM_ERRCODE_INVALID_GUID); -} - - -CssmGuidData::CssmGuidData(const CSSM_GUID &guid) : CssmData(buffer, sizeof(buffer)) -{ - Guid::overlay(guid).toString(buffer); -} - - -// -// CssmSubserviceUids. -// Note that for comparison, we ignore the version field. -// This is not necessarily the Right Choice, but suits certain -// constraints in the Sec* layer. Perhaps we might reconsider -// this after a thorough code review to determine the intended -// (by the standard) semantics and proper use. Yeah, right. -// -CssmSubserviceUid::CssmSubserviceUid(const CSSM_GUID &guid, - const CSSM_VERSION *version, uint32 subserviceId, CSSM_SERVICE_TYPE subserviceType) -{ - Guid = guid; - SubserviceId = subserviceId; - SubserviceType = subserviceType; - if (version) - Version = *version; - else - Version.Major = Version.Minor = 0; -} - - -bool CssmSubserviceUid::operator == (const CSSM_SUBSERVICE_UID &otherUid) const -{ - // make sure we don't crash if we get bad data -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wtautological-undefined-compare" - if (&otherUid == 0x0) { return false; } -#pragma clang diagnostic pop - - const CssmSubserviceUid &other = CssmSubserviceUid::overlay(otherUid); - return subserviceId() == other.subserviceId() - && subserviceType() == other.subserviceType() - && guid() == other.guid(); -} - -bool CssmSubserviceUid::operator < (const CSSM_SUBSERVICE_UID &otherUid) const -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wtautological-undefined-compare" - if (&otherUid == 0x0) { return false; } -#pragma clang diagnostic pop - - const CssmSubserviceUid &other = CssmSubserviceUid::overlay(otherUid); - if (subserviceId() < other.subserviceId()) - return true; - if (subserviceId() > other.subserviceId()) - return false; - if (subserviceType() < other.subserviceType()) - return true; - if (subserviceType() > other.subserviceType()) - return false; - return guid() < other.guid(); -} - - -// -// CryptoData & friends -// -CryptoDataClass::~CryptoDataClass() -{ } - -CSSM_RETURN CryptoDataClass::callbackShim(CSSM_DATA *output, void *ctx) -{ - BEGIN_API - *output = reinterpret_cast(ctx)->yield(); - END_API(CSSM) -} diff --git a/OSX/include/security_cdsa_utilities/cssmpods.h b/OSX/include/security_cdsa_utilities/cssmpods.h deleted file mode 100644 index c1b1c542..00000000 --- a/OSX/include/security_cdsa_utilities/cssmpods.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Miscellaneous CSSM PODWrappers -// -#ifndef _H_CSSMPODS -#define _H_CSSMPODS - -#include -#include -#include - - -namespace Security { - - -// -// User-friendly GUIDs -// -class Guid : public PodWrapper { -public: - Guid() { /*IFDEBUG(*/ memset(this, 0, sizeof(*this)) /*)*/ ; } - Guid(const CSSM_GUID &rGuid) { memcpy(this, &rGuid, sizeof(*this)); } - Guid(const char *string); - Guid(const std::string &s); - - Guid &operator = (const CSSM_GUID &rGuid) - { memcpy(this, &rGuid, sizeof(CSSM_GUID)); return *this; } - - bool operator == (const CSSM_GUID &other) const - { return (this == &other) || !memcmp(this, &other, sizeof(CSSM_GUID)); } - bool operator != (const CSSM_GUID &other) const - { return (this != &other) && memcmp(this, &other, sizeof(CSSM_GUID)); } - bool operator < (const CSSM_GUID &other) const - { return memcmp(this, &other, sizeof(CSSM_GUID)) < 0; } - size_t hash() const { //@@@ revisit this hash - return Data1 + (Data2 << 3) + (Data3 << 11) + (Data4[3]) + (Data4[6] << 22); - } - - static const unsigned stringRepLength = 38; // "{x8-x4-x4-x4-x12}" - char *toString(char buffer[stringRepLength+1]) const; // will append \0 - string toString() const; // make std::string - -private: - void parseGuid(const char *string); -}; - -class CssmGuidData : public CssmData { -public: - CssmGuidData(const CSSM_GUID &guid); - -private: - char buffer[Guid::stringRepLength + 1]; -}; - - -// -// User-friendly CSSM_SUBSERVICE_UIDs -// -class CssmSubserviceUid : public PodWrapper { -public: - CssmSubserviceUid() { clearPod(); } - CssmSubserviceUid(const CSSM_SUBSERVICE_UID &rSSuid) { memcpy(this, &rSSuid, sizeof(*this)); } - - CssmSubserviceUid &operator = (const CSSM_SUBSERVICE_UID &rSSuid) - { memcpy(this, &rSSuid, sizeof(CSSM_SUBSERVICE_UID)); return *this; } - - bool operator == (const CSSM_SUBSERVICE_UID &other) const; - bool operator != (const CSSM_SUBSERVICE_UID &other) const { return !(*this == other); } - bool operator < (const CSSM_SUBSERVICE_UID &other) const; - - CssmSubserviceUid(const CSSM_GUID &guid, const CSSM_VERSION *version = NULL, - uint32 subserviceId = 0, - CSSM_SERVICE_TYPE subserviceType = CSSM_SERVICE_DL); - - const ::Guid &guid() const { return ::Guid::overlay(Guid); } - uint32 subserviceId() const { return SubserviceId; } - CSSM_SERVICE_TYPE subserviceType() const { return SubserviceType; } - CSSM_VERSION version() const { return Version; } -}; - - -// -// User-friendler CSSM_CRYPTO_DATA objects -// -class CryptoCallback { -public: - CryptoCallback(CSSM_CALLBACK func, void *ctx = NULL) : mFunction(func), mCtx(ctx) { } - CSSM_CALLBACK function() const { return mFunction; } - void *context() const { return mCtx; } - - CssmData operator () () const - { - CssmData output; - if (CSSM_RETURN err = mFunction(&output, mCtx)) - CssmError::throwMe(err); - return output; - } - -private: - CSSM_CALLBACK mFunction; - void *mCtx; -}; - -class CssmCryptoData : public PodWrapper { -public: - CssmCryptoData() { } - - CssmCryptoData(const CssmData ¶m, CSSM_CALLBACK callback = NULL, void *ctx = NULL) - { Param = const_cast(param); Callback = callback; CallerCtx = ctx; } - - CssmCryptoData(const CssmData ¶m, CryptoCallback &cb) - { Param = const_cast(param); Callback = cb.function(); CallerCtx = cb.context(); } - - CssmCryptoData(CSSM_CALLBACK callback, void *ctx = NULL) - { /* ignore Param */ Callback = callback; CallerCtx = ctx; } - - explicit CssmCryptoData(CryptoCallback &cb) - { /* ignore Param */ Callback = cb.function(); CallerCtx = cb.context(); } - - // member access - CssmData ¶m() { return CssmData::overlay(Param); } - const CssmData ¶m() const { return CssmData::overlay(Param); } - bool hasCallback() const { return Callback != NULL; } - CryptoCallback callback() const { return CryptoCallback(Callback, CallerCtx); } - - // get the value, whichever way is appropriate - CssmData operator () () const - { return hasCallback() ? callback() () : param(); } -}; - -// a CssmCryptoContext whose callback is a virtual class member -class CryptoDataClass : public CssmCryptoData { -public: - CryptoDataClass() : CssmCryptoData(callbackShim, this) { } - virtual ~CryptoDataClass(); - -protected: - virtual CssmData yield() = 0; // must subclass and implement this - -private: - static CSSM_RETURN callbackShim(CSSM_DATA *output, void *ctx); -}; - - -// -// Other PodWrappers for stuff that is barely useful... -// -class CssmKeySize : public PodWrapper { -public: - CssmKeySize() { } - CssmKeySize(uint32 nom, uint32 eff) { LogicalKeySizeInBits = nom; EffectiveKeySizeInBits = eff; } - CssmKeySize(uint32 size) { LogicalKeySizeInBits = EffectiveKeySizeInBits = size; } - - uint32 logical() const { return LogicalKeySizeInBits; } - uint32 effective() const { return EffectiveKeySizeInBits; } - operator uint32 () const { return effective(); } -}; - -inline bool operator == (const CSSM_KEY_SIZE &s1, const CSSM_KEY_SIZE &s2) -{ - return s1.LogicalKeySizeInBits == s2.LogicalKeySizeInBits - && s1.EffectiveKeySizeInBits == s2.EffectiveKeySizeInBits; -} - -inline bool operator != (const CSSM_KEY_SIZE &s1, const CSSM_KEY_SIZE &s2) -{ return !(s1 == s2); } - - -class QuerySizeData : public PodWrapper { -public: - QuerySizeData() { } - QuerySizeData(uint32 in) { SizeInputBlock = in; SizeOutputBlock = 0; } - - uint32 inputSize() const { return SizeInputBlock; } - uint32 inputSize(uint32 size) { return SizeInputBlock = size; } - uint32 outputSize() const { return SizeOutputBlock; } -}; - -inline bool operator == (const CSSM_QUERY_SIZE_DATA &s1, const CSSM_QUERY_SIZE_DATA &s2) -{ - return s1.SizeInputBlock == s2.SizeInputBlock - && s1.SizeOutputBlock == s2.SizeOutputBlock; -} - -inline bool operator != (const CSSM_QUERY_SIZE_DATA &s1, const CSSM_QUERY_SIZE_DATA &s2) -{ return !(s1 == s2); } - - -class CSPOperationalStatistics : - public PodWrapper { -public: -}; - - -} // end namespace Security - - -#endif //_H_CSSMPODS diff --git a/OSX/include/security_cdsa_utilities/cssmtrust.cpp b/OSX/include/security_cdsa_utilities/cssmtrust.cpp deleted file mode 100644 index d3192024..00000000 --- a/OSX/include/security_cdsa_utilities/cssmtrust.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmtrust - CSSM layer Trust (TP) related objects. -// -#include -#include - - -namespace Security { - - -// -// Cleanly release the memory in a TPEvidenceInfo -// -void TPEvidenceInfo::destroy(Allocator &allocator) -{ - // status code array - if (codes() > 0 && StatusCodes) - allocator.free(StatusCodes); - - //@@@ need to free unique id if present -} - - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/cssmtrust.h b/OSX/include/security_cdsa_utilities/cssmtrust.h deleted file mode 100644 index 7dcc79f7..00000000 --- a/OSX/include/security_cdsa_utilities/cssmtrust.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmtrust - CSSM layer Trust (TP) related objects. -// -#ifndef _H_CSSMTRUST -#define _H_CSSMTRUST - -#include -#include -#include -#include - - -namespace Security { - - -// -// A TP "POLICYINFO" structure, essentially an OID/Data pair. -// -class PolicyInfo : public PodWrapper { -public: - uint32 count() const { return NumberOfPolicyIds; } - uint32 &count() { return NumberOfPolicyIds; } - CssmField *policies() const { return CssmField::overlay(PolicyIds); } - CssmField * &policies() { return CssmField::overlayVar(PolicyIds); } - void *control() const { return PolicyControl; } - - CssmField &operator [] (uint32 ix) - { assert(ix < count()); return policies()[ix]; } - - void setPolicies(uint32 n, CSSM_FIELD *p) - { count() = n; policies() = CssmField::overlay(p); } -}; - - -// -// TP caller authentication contexts -// -class TPCallerAuth : public PodWrapper { -public: - CSSM_TP_STOP_ON stopCriterion() const { return VerificationAbortOn; } - void stopCriterion(CSSM_TP_STOP_ON stop) { VerificationAbortOn = stop; } - - CSSM_TIMESTRING time() const { return VerifyTime; } - void time(CSSM_TIMESTRING newTime) { VerifyTime = newTime; } - - PolicyInfo &policies() { return PolicyInfo::overlay(Policy); } - const PolicyInfo &policies() const { return PolicyInfo::overlay(Policy); } - void setPolicies(uint32 n, CSSM_FIELD *p) { policies().setPolicies(n, p); } - - AccessCredentials *creds() const - { return AccessCredentials::optional(CallerCredentials); } - void creds(AccessCredentials *newCreds) { CallerCredentials = newCreds; } - - uint32 anchorCount() const { return NumberOfAnchorCerts; } - uint32 &anchorCount() { return NumberOfAnchorCerts; } - CssmData *anchors() const { return CssmData::overlay(AnchorCerts); } - CssmData * &anchors() { return CssmData::overlayVar(AnchorCerts); } - - CssmDlDbList *dlDbList() const { return CssmDlDbList::overlay(DBList); } - CssmDlDbList * &dlDbList() { return CssmDlDbList::overlayVar(DBList); } -}; - - -// -// TP Verify Contexts - a monster collection of possibly useful stuff -// when verifying a certificate against trust policies -// -class TPVerifyContext : public PodWrapper { -public: - CSSM_TP_ACTION action() const { return Action; } - CssmData &actionData() { return CssmData::overlay(ActionData); } - const CssmData &actionData() const { return CssmData::overlay(ActionData); } - - // set and reference the CallerAuth component - TPCallerAuth &callerAuth() const { return TPCallerAuth::required(Cred); } - operator TPCallerAuth &() const { return callerAuth(); } - TPCallerAuth *callerAuthPtr() const { return TPCallerAuth::optional(Cred); } - void callerAuthPtr(CSSM_TP_CALLERAUTH_CONTEXT *p) { Cred = p; } - - // forward CallerAuth operations - - CSSM_TP_STOP_ON stopCriterion() const { return callerAuth().stopCriterion(); } - void stopCriterion(CSSM_TP_STOP_ON stop) { return callerAuth().stopCriterion(stop); } - PolicyInfo &policies() const { return callerAuth().policies(); } - void setPolicies(uint32 n, CSSM_FIELD *p) { policies().setPolicies(n, p); } - CSSM_TIMESTRING time() const { return callerAuth().time(); } - void time(CSSM_TIMESTRING newTime) { return callerAuth().time(newTime); } - AccessCredentials *creds() const { return callerAuth().creds(); } - void creds(AccessCredentials *newCreds) const { return callerAuth().creds(newCreds); } - uint32 anchorCount() const { return callerAuth().anchorCount(); } - uint32 &anchorCount() { return callerAuth().anchorCount(); } - CssmData *anchors() const { return callerAuth().anchors(); } - CssmData * &anchors() { return callerAuth().anchors(); } - void anchors(uint32 count, CSSM_DATA *vector) - { anchorCount() = count; anchors() = CssmData::overlay(vector); } - void setDlDbList(uint32 n, CSSM_DL_DB_HANDLE *list) - { callerAuth().dlDbList()->setDlDbList(n, list); } -}; - - -// -// The result of a (raw) TP trust verification call -// -class TPEvidence : public PodWrapper { -public: - CSSM_EVIDENCE_FORM form() const { return EvidenceForm; } - void *data() const { return Evidence; } - operator void *() const { return data(); } - - template - T *as() const { return reinterpret_cast(Evidence); } -}; - -class TPVerifyResult : public PodWrapper { -public: - uint32 count() const { return NumberOfEvidences; } - const TPEvidence &operator [] (uint32 ix) const - { assert(ix < count()); return TPEvidence::overlay(Evidence[ix]); } -}; - - -// -// A PodWrapper for Apple's TP supporting-evidence structure -// -class TPEvidenceInfo : public PodWrapper { -public: - CSSM_TP_APPLE_CERT_STATUS status() const { return StatusBits; } - CSSM_TP_APPLE_CERT_STATUS status(CSSM_TP_APPLE_CERT_STATUS flags) const - { return status() & flags; } - - uint32 index() const { return Index; } - const CssmDlDbHandle &dldb() const { return CssmDlDbHandle::overlay(DlDbHandle); } - CSSM_DB_UNIQUE_RECORD_PTR recordId() const { return UniqueRecord; } - - uint32 codes() const { return NumStatusCodes; } - CSSM_RETURN operator [] (uint32 ix) - { assert(ix < NumStatusCodes); return StatusCodes[ix]; } - - void destroy(Allocator &allocator); -}; - - -// -// Walkers -// -namespace DataWalkers { - - - - -} // end namespace DataWalkers -} // end namespace Security - -#endif //_H_CSSMTRUST diff --git a/OSX/include/security_cdsa_utilities/cssmwalkers.cpp b/OSX/include/security_cdsa_utilities/cssmwalkers.cpp deleted file mode 100644 index 3a94fe2e..00000000 --- a/OSX/include/security_cdsa_utilities/cssmwalkers.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmwalkers - walkers for standard CSSM datatypes and wrappers -// -#include diff --git a/OSX/include/security_cdsa_utilities/cssmwalkers.h b/OSX/include/security_cdsa_utilities/cssmwalkers.h deleted file mode 100644 index bf6f0941..00000000 --- a/OSX/include/security_cdsa_utilities/cssmwalkers.h +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// cssmwalkers - walkers for standard CSSM datatypes and wrappers -// -#ifndef _H_CSSMWALKERS -#define _H_CSSMWALKERS - -#include -#include -#include -#include - - - -namespace Security { -namespace DataWalkers { - - -// -// There are lots of CSSM data structures that are variable-length records -// of the form { count, pointer-to-array }. If you have a regular PodWrapper -// for it, we can enumerate the array for you right here. Minimum requirement: -// size_t size() const; -// Element &operator [] (uint32 index); -// // and some Element *&foo() that returns a reference-to-array-pointer -// and a reference walker for the element type (as returned by operator []). -// -template -void enumerateArray(Action &operate, Record &record, Element *& (Record::*pointer)()) -{ - if (record.size()) { - Element *&root = (record.*pointer)(); - operate.blob(root, record.size() * sizeof(Element)); - for (uint32 ix = 0; ix < record.size(); ++ix) - walk(operate, record[ix]); - } -} - - -// -// The full set of walkers for CssmData in all its forms. -// -template -void walk(Action &operate, CssmData &data) -{ - operate(data); - operate.blob(data.Data, data.Length); -} - -template -CssmData *walk(Action &operate, CssmData * &data) -{ - operate(data); - operate.blob(data->Data, data->Length); - return data; -} - -template -void walk(Action &operate, CSSM_DATA &data) -{ walk(operate, CssmData::overlay(data)); } - -template -CSSM_DATA *walk(Action &operate, CSSM_DATA * &data) -{ return walk(operate, CssmData::overlayVar(data)); } - - - -// -// Walking a C string is almost regular (the size comes from strlen()). -// Just make sure you honor the needsSize preference of the operator. -// -template -char *walk(Action &operate, char * &s) -{ - if (s) - operate(s, operate.needsSize ? (strlen(s) + 1) : 0); - return s; -} - - -// -// Flattener functions for common CSSM data types that have internal structure. -// -template -CssmKey *walk(Action &operate, CssmKey * &key) -{ - operate(key); - walk(operate, key->keyData()); - return key; -} - -template -CSSM_KEY *walk(Action &operate, CSSM_KEY * &data) -{ return walk(operate, CssmKey::overlayVar(data)); } - -template -CssmCryptoData *walk(Action &operate, CssmCryptoData * &data) -{ - operate(data); - walk(operate, data->param()); - return data; -} - -template -CSSM_CRYPTO_DATA *walk(Action &operate, CSSM_CRYPTO_DATA * &data) -{ return walk(operate, CssmCryptoData::overlayVar(data)); } - -template -void walk(Action &operate, CSSM_PKCS5_PBKDF2_PARAMS &data) -{ - operate(data); - walk(operate, data.Passphrase); -} - -// -// Walkers for flat datatypes -// -template -CSSM_DATE_PTR walk(Action &operate, CSSM_DATE_PTR &date) -{ - operate(date); - return date; -} - -template -CSSM_RANGE_PTR walk(Action &operate, CSSM_RANGE_PTR &range) -{ - operate(range); - return range; -} - -template -CSSM_VERSION_PTR walk(Action &operate, CSSM_VERSION_PTR &version) -{ - operate(version); - return version; -} - -template -CSSM_DL_DB_HANDLE_PTR walk(Action &operate, CSSM_DL_DB_HANDLE_PTR &dlDbHandle) -{ - operate(dlDbHandle); - return dlDbHandle; -} - -template -CssmSubserviceUid *walk(Action &operate, CssmSubserviceUid * &ssUid) -{ - operate(ssUid); - return ssUid; -} - - -// -// A synthetic variant of CssmData to model key derivation (input) parameters, -// which have algorithm dependent structure. This is not likely to be useful -// for anything else; but here's the common ancestor of all its users. -// -class CssmDeriveData { -public: - CssmDeriveData(const CssmData &dat, CSSM_ALGORITHMS alg) - : baseData(dat), algorithm(alg) { } - - CssmData baseData; - CSSM_ALGORITHMS algorithm; - - template - void enumerate(Action &operate) - { - walk(operate, baseData); - switch (algorithm) { - case CSSM_ALGID_PKCS5_PBKDF2: -#if BUG_3762664 - walk(operate, *baseData.interpretedAs - (CSSMERR_CSP_INVALID_ATTR_ALG_PARAMS)); -#else - if (baseData.length() != sizeof(CSSM_PKCS5_PBKDF2_PARAMS)) - CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_ALG_PARAMS); - walk(operate, *(CSSM_PKCS5_PBKDF2_PARAMS *)baseData.data()); -#endif - break; - default: - break; - } - } -}; - - -template -void walk(Action &operate, CssmDeriveData &data) -{ - operate(data); - data.enumerate(operate); -} - -template -CssmDeriveData *walk(Action &operate, CssmDeriveData * &data) -{ - operate(data); - if (data) - data->enumerate(operate); - return data; -} - - - -} // end namespace DataWalkers -} // end namespace Security - -#endif //_H_CSSMWALKERS diff --git a/OSX/include/security_cdsa_utilities/db++.cpp b/OSX/include/security_cdsa_utilities/db++.cpp deleted file mode 100644 index 94874b5a..00000000 --- a/OSX/include/security_cdsa_utilities/db++.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// dbm++ - generic C++ layer interface to [n]dbm -// -#include "db++.h" -#include - - -namespace Security { -namespace UnixPlusPlus { - -UnixDb::UnixDb() : mDb(NULL) -{ -} - -UnixDb::UnixDb(const char *path, int flags, int mode, DBTYPE type) : mDb(NULL) -{ - open(path, flags, mode); -} - -UnixDb::UnixDb(const std::string &path, int flags, int mode, DBTYPE type) : mDb(NULL) -{ - open(path, flags, mode); -} - -UnixDb::~UnixDb() -{ - close(); -} - -void UnixDb::open(const char *path, int flags, int mode, DBTYPE type) -{ - if (DB* newDb = ::dbopen(path, flags, mode, type, NULL)) { - close(); - mDb = newDb; - setFd(mDb->fd(mDb)); - secdebug("unixdb", "open(%s,0x%x,0x%x,type=%d)=%p", path, flags, mode, type, mDb); - } else - UnixError::throwMe(); -} - -void UnixDb::open(const std::string &path, int flags, int mode, DBTYPE type) -{ - open(path.c_str(), flags, mode); -} - -void UnixDb::close() -{ - if (mDb) { - secdebug("unixdb", "close(%p)", mDb); - mDb->close(mDb); - mDb = NULL; - setFd(invalidFd); - } -} - -bool UnixDb::get(const CssmData &key, CssmData &value, int flags) const -{ - Data dKey(key); - Data val; - int rc = mDb->get(mDb, &dKey, &val, flags); - secdebug("unixdb", "get(%p,[:%ld],flags=0x%x)=%d[:%ld]", - mDb, key.length(), flags, rc, value.length()); - checkError(rc); - if (!rc) { - value = val; - return true; - } else - return false; -} - -bool UnixDb::get(const CssmData &key, CssmOwnedData &value, int flags) const -{ - CssmData val; - if (get(key, val, flags)) { - value = val; - return true; - } else - return false; -} - -bool UnixDb::put(const CssmData &key, const CssmData &value, int flags) -{ - Data dKey(key); - Data dValue(value); - int rc = mDb->put(mDb, &dKey, &dValue, flags); - secdebug("unixdb", "put(%p,[:%ld],[:%ld],flags=0x%x)=%d", - mDb, key.length(), value.length(), flags, rc); - checkError(rc); - return !rc; -} - -void UnixDb::erase(const CssmData &key, int flags) -{ - Data dKey(key); - secdebug("unixdb", "delete(%p,[:%ld],flags=0x%x)", mDb, key.length(), flags); - checkError(mDb->del(mDb, &dKey, flags)); -} - -bool UnixDb::next(CssmData &key, CssmData &value, int flags /* = R_NEXT */) const -{ - Data dKey, dValue; - int rc = mDb->seq(mDb, &dKey, &dValue, flags); - checkError(rc); - if (!rc) { - key = dKey; - value = dValue; - return true; - } else - return false; -} - - -void UnixDb::flush(int flags) -{ - checkError(mDb->sync(mDb, flags)); -} - - -} // end namespace UnixPlusPlus -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/db++.h b/OSX/include/security_cdsa_utilities/db++.h deleted file mode 100644 index 79d84a5e..00000000 --- a/OSX/include/security_cdsa_utilities/db++.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// dbm++ - generic C++ layer interface to [n]dbm -// -#ifndef _H_DBMPP -#define _H_DBMPP - -#include -#include -#include -#include -#include - - -namespace Security { -namespace UnixPlusPlus { - - -class UnixDb : public FileDesc { -public: - UnixDb(); - UnixDb(const char *path, int flags = O_RDWR, int mode = 0666, DBTYPE type = DB_HASH); - UnixDb(const std::string &path, int flags = O_RDWR, int mode = 0666, DBTYPE type = DB_HASH); - - virtual ~UnixDb(); - - void open(const char *path, int flags = O_RDWR, int mode = 0666, DBTYPE type = DB_HASH); - void open(const std::string &path, int flags = O_RDWR, int mode = 0666, DBTYPE type = DB_HASH); - void close(); - - bool get(const CssmData &key, CssmData &value, int flags = 0) const; - bool get(const CssmData &key, CssmOwnedData &value, int flags = 0) const; - bool put(const CssmData &key, const CssmData &value, int flags = 0); - void erase(const CssmData &key, int flags = 0); - void flush(int flags = 0); - - bool next(CssmData &key, CssmData &value, int flags = R_NEXT) const; - bool first(CssmData &key, CssmData &value) const - { return next(key, value, R_FIRST); } - - operator bool () const - { return mDb; } - -public: - struct Data : public PodWrapper { - template - Data(const T &src) { DBT::data = src.data(); DBT::size = src.length(); } - - Data() { } - Data(void *data, size_t length) { DBT::data = data; DBT::size = length; } - Data(const DBT &dat) { DBT::data = dat.data; DBT::size = dat.size; } - - void *data() const { return DBT::data; } - size_t length() const { return size; } - operator bool () const { return DBT::data != NULL; } - operator CssmData () const { return CssmData(data(), length()); } - }; - -private: - DB *mDb; -}; - - -} // end namespace UnixPlusPlus -} // end namespace Security - - -#endif //_H_DBMPP diff --git a/OSX/include/security_cdsa_utilities/digestobject.h b/OSX/include/security_cdsa_utilities/digestobject.h deleted file mode 100644 index 0698974b..00000000 --- a/OSX/include/security_cdsa_utilities/digestobject.h +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * digestobject.h - generic virtual Digest base class - */ - -#ifndef _DIGEST_OBJECT_H_ -#define _DIGEST_OBJECT_H_ - -#include - -/* common virtual digest class */ -class DigestObject { -public: - DigestObject() : mInitFlag(false), mIsDone(false) { } - virtual ~DigestObject() { } - - /* - * The remaining functions must be implemented by subclass. - */ - /* init is reusable */ - virtual void digestInit() = 0; - - /* add some data */ - virtual void digestUpdate( - const void *data, - size_t len) = 0; - - /* obtain digest (once only per init, update, ... cycle) */ - virtual void digestFinal( - void *digest) = 0; /* RETURNED, alloc'd by caller */ - - /* sublass-specific copy */ - virtual DigestObject *digestClone() const = 0; - - virtual size_t digestSizeInBytes() const = 0; - -protected: - bool mInitFlag; - bool mIsDone; - - bool initFlag() { return mInitFlag; } - void setInitFlag(bool flag) { mInitFlag = flag; } - bool isDone() { return mIsDone; } - void setIsDone(bool done) { mIsDone = done; } -}; - -/* - * NullDigest.h - nop digest for use with raw signature algorithms. - * NullDigest(someData) = someData. - */ -class NullDigest : public DigestObject -{ -public: - NullDigest() : mInBuf(NULL), mInBufSize(0) - { - } - - void digestInit() - { - /* reusable - reset */ - if(mInBufSize) { - assert(mInBuf != NULL); - memset(mInBuf, 0, mInBufSize); - Allocator::standard().free(mInBuf); - mInBufSize = 0; - mInBuf = NULL; - } - } - - ~NullDigest() - { - digestInit(); - } - - void digestUpdate( - const void *data, - size_t len) - { - mInBuf = Allocator::standard().realloc(mInBuf, mInBufSize + len); - memmove((uint8 *)mInBuf + mInBufSize, data, len); - mInBufSize += len; - } - - virtual void digestFinal( - void *digest) - { - memmove(digest, mInBuf, mInBufSize); - } - - virtual DigestObject *digestClone() const - { - NullDigest *cloned = new NullDigest; - cloned->digestUpdate(mInBuf, mInBufSize); - return cloned; - } - - /* unique to NullDigest - just obtain current data ptr, no copy */ - virtual const void *digestPtr() { return mInBuf; } - - size_t digestSizeInBytes() const - { - return mInBufSize; - } - -private: - void *mInBuf; - size_t mInBufSize; -}; - -#endif /* _DIGEST_OBJECT_H_ */ diff --git a/OSX/include/security_cdsa_utilities/generator.mk b/OSX/include/security_cdsa_utilities/generator.mk deleted file mode 100644 index 2e701383..00000000 --- a/OSX/include/security_cdsa_utilities/generator.mk +++ /dev/null @@ -1,26 +0,0 @@ -# Makefile for generated files. - -PERL=/usr/bin/perl - -CDSA_HEADERS_DIR = Headers/cdsa -CDSA_UTILITIES_DIR = Sources/cdsa_utilities - -GEN_ERRORCODES = $(CDSA_UTILITIES_DIR)/generator.pl -ERRORCODES_GEN = $(patsubst %,$(CDSA_UTILITIES_DIR)/%,errorcodes.gen) -ERRORCODES_DEPENDS = $(GEN_ERRORCODES)\ - $(patsubst %,$(CDSA_HEADERS_DIR)/%,cssmerr.h) - -build: $(ERRORCODES_GEN) - -clean: - rm -f $(ERRORCODES_GEN) - -debug: build - -profile: build - -.PHONY: build clean debug profile - -$(ERRORCODES_GEN): $(ERRORCODE_DEPENDS) - (cd $(CDSA_UTILITIES_DIR);\ - $(PERL) ./generator.pl ../../$(CDSA_HEADERS_DIR) .) diff --git a/OSX/include/security_cdsa_utilities/generator.pl b/OSX/include/security_cdsa_utilities/generator.pl deleted file mode 100644 index 1b3fd9ad..00000000 --- a/OSX/include/security_cdsa_utilities/generator.pl +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/perl -# -# generator.pl - derive various and sundry C++ code from the CDSA header files -# -# Usage: -# perl generator.pl input-directory output-directory -# -# Perry The Cynic, Fall 1999. -# -$ERR_H="cssmerr.h"; -$APPLE_ERR_H="cssmapple.h"; - -$SOURCEDIR=$ARGV[0]; # directory with cdsa headers -$TARGETDIR=$ARGV[1]; # where to put the output file -@INPUTFILES=@ARGV[2 .. 9999]; # list of input files - -$TABLES="$TARGETDIR/errorcodes.gen"; # error name tables - -$tabs = "\t\t\t"; # argument indentation (noncritical) -$warning = "This file was automatically generated. Do not edit on penalty of futility!"; - - -# -# Parse CSSM error header and build table of all named codes -# -open(ERR, "$SOURCEDIR/$ERR_H") or die "Cannot open $ERR_H: $^E"; -open(APPLE_ERR, "$SOURCEDIR/$APPLE_ERR_H") or die "Cannot open $APPLE_ERR_H: $^E"; -$/=undef; # big gulp mode -$errors = . ; -close(ERR); close(APPLE_ERR); - -@fullErrors = $errors =~ /^\s+CSSMERR_([A-Z_]+)/gm; -@convertibles = $errors =~ /^\s+CSSM_ERRCODE_([A-Z_]+)\s*=\s*([0-9xXA-Fa-f]+)/gm; - -while ($name = shift @convertibles) { - $value = shift @convertibles or die; - $convErrors[hex $value] = $name; -}; - - -# -# Read Keychain-level headers for more error codes (errSecBlahBlah) -# -open(ERR, "cat " . join(" ", @INPUTFILES) . "|") or die "Cannot open error header files"; -$/=undef; # still gulping -$_ = ; -@kcerrors = /err((?:Sec|Authorization)\w+)\s*=\s*-?\d+/gm; -close(ERR); - - -# -# Now we will generate the error name tables. -# -open(OUT, ">$TABLES") or die "Cannot write $TABLES: $^E"; -select OUT; - -print < -#include - diff --git a/OSX/include/security_cdsa_utilities/handleobject.h b/OSX/include/security_cdsa_utilities/handleobject.h deleted file mode 100644 index 8636a599..00000000 --- a/OSX/include/security_cdsa_utilities/handleobject.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2000-2008,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// handleobject - give an object a process-global unique handle -// -#ifndef _H_HANDLEOBJECT -#define _H_HANDLEOBJECT - -#include -#include - -// -// definitions kept here so other code doesn't have to modify #includes -// - -namespace Security -{ - -typedef TypedHandle HandledObject; - -typedef MappingHandle HandleObject; - -} // end namespace Security - -#endif //_H_HANDLEOBJECT diff --git a/OSX/include/security_cdsa_utilities/handletemplates.cpp b/OSX/include/security_cdsa_utilities/handletemplates.cpp deleted file mode 100644 index 4d550d79..00000000 --- a/OSX/include/security_cdsa_utilities/handletemplates.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2008,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#include -#include -#include - -// -// Instantiate the explicit MappingHandle subclasses. If there start to be -// a lot of these, break this into multiple .cpp files so useless classes -// aren't linked in everywhere. -// - -template struct TypedHandle; // HandledObject - -template class MappingHandle; // HandleObject - -template class MappingHandle; // U32HandleObject diff --git a/OSX/include/security_cdsa_utilities/handletemplates.h b/OSX/include/security_cdsa_utilities/handletemplates.h deleted file mode 100644 index 9791072a..00000000 --- a/OSX/include/security_cdsa_utilities/handletemplates.h +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (c) 2008,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Templates to support HandleObject-like objects -// -#ifndef _H_HANDLETEMPLATES -#define _H_HANDLETEMPLATES - -#include -#include -#include -#include -#include - -#include - -namespace Security -{ - -// -// A TypedHandle is a trivial mixin class whose only feature is that -// it has a *handle* whose type is of the caller's choosing. Subclasses -// need to assign such a handle during creation. -// -template -struct TypedHandle -{ -public: - typedef _Handle Handle; - - static const _Handle invalidHandle = 0; - - _Handle handle() const { return mMyHandle; } - bool validHandle() const { return mValid; } - -protected: - TypedHandle(_Handle h); - TypedHandle(); - - void setHandle(_Handle h) - { - assert(!mValid); // guard against redefinition - mMyHandle = h; - mValid = true; - } - void clearHandle() - { - assert(mValid); - mValid = false; - } - -private: - _Handle mMyHandle; // our handle value - bool mValid; // is the handle (still) valid? -}; - -// -// MappingHandle wraps a map indexed by handles of the chosen type. -// A MappingHandle makes up its own handle based on some mechanism that you -// know nothing about. -// -// Please be very careful about the limits of the object contract here. -// We promise to invent a suitable, unique handle for each MappingHandle in -// existence within one address space. We promise that if you hand that -// handle to the various MappingHandle<>::find() variants, we will give you -// back the MappingHandle that created it. We promise to throw if you pass -// a bad handle to those MappingHandle<>::find() variants. This is the -// entire contract. -// -template -class MappingHandle : public TypedHandle<_Handle> -{ -protected: - class State; - -public: - typedef typename TypedHandle<_Handle>::Handle Handle; - virtual ~MappingHandle() - { - State &st = state(); - StLock _(st); - st.erase(this); - } - - template - static SubType &find(_Handle handle, CSSM_RETURN error); - - template - static Subtype &findAndLock(_Handle handle, CSSM_RETURN error); - - template - static Subtype &findAndKill(_Handle handle, CSSM_RETURN error); - - template - static RefPointer findRef(_Handle handle, CSSM_RETURN error); - - template - static RefPointer findRefAndLock(_Handle handle, CSSM_RETURN error); - - template - static RefPointer findRefAndKill(_Handle handle, CSSM_RETURN error); - - // @@@ Remove when 4003540 is fixed - template - static void findAllRefs(std::vector<_Handle> &refs) { - state().template findAllRefs(refs); - } - -protected: - virtual void lock(); - virtual bool tryLock(); - - typedef std::unordered_map<_Handle, MappingHandle<_Handle> *> HandleMap; - - MappingHandle(); - - class State : public Mutex, public HandleMap - { - public: - State(); - uint32_t nextSeq() { return ++sequence; } - - bool handleInUse(_Handle h); - MappingHandle<_Handle> *find(_Handle h, CSSM_RETURN error); - typename HandleMap::iterator locate(_Handle h, CSSM_RETURN error); - void add(_Handle h, MappingHandle<_Handle> *obj); - void erase(MappingHandle<_Handle> *obj); - void erase(typename HandleMap::iterator &it); - // @@@ Remove when 4003540 is fixed - template void findAllRefs(std::vector<_Handle> &refs); - - private: - uint32_t sequence; - }; - -private: - // - // Create the handle to be used by the map - // - void make(); - - static ModuleNexus::State> state; -}; - -// -// MappingHandle class methods -// Type-specific ways to access the map in various ways -// -template -template -inline Subclass &MappingHandle<_Handle>::find(_Handle handle, CSSM_RETURN error) -{ - Subclass *sub; - if (!(sub = dynamic_cast(state().find(handle, error)))) - CssmError::throwMe(error); - return *sub; -} - -template -template -inline Subclass &MappingHandle<_Handle>::findAndLock(_Handle handle, - CSSM_RETURN error) -{ - for (;;) { - typename HandleMap::iterator it = state().locate(handle, error); - StLock _(state(), true); // locate() locked it - Subclass *sub; - if (!(sub = dynamic_cast(it->second))) - CssmError::throwMe(error); // bad type - if (it->second->tryLock()) // try to lock it - return *sub; // okay, go - Thread::yield(); // object lock failed, backoff and retry - } -} - -template -template -inline Subclass &MappingHandle<_Handle>::findAndKill(_Handle handle, - CSSM_RETURN error) -{ - for (;;) { - typename HandleMap::iterator it = state().locate(handle, error); - StLock _(state(), true); // locate() locked it - Subclass *sub; - if (!(sub = dynamic_cast(it->second))) - CssmError::throwMe(error); // bad type - if (it->second->tryLock()) { // try to lock it - state().erase(it); // kill the handle - return *sub; // okay, go - } - Thread::yield(); // object lock failed, backoff and retry - } -} - -template -template -inline RefPointer MappingHandle<_Handle>::findRef(_Handle handle, - CSSM_RETURN error) -{ - typename HandleMap::iterator it = state().locate(handle, error); - StLock _(state(), true); // locate() locked it - Subclass *sub; - if (!(sub = dynamic_cast(it->second))) - CssmError::throwMe(error); - return sub; -} - -template -template -inline RefPointer MappingHandle<_Handle>::findRefAndLock(_Handle handle, - CSSM_RETURN error) -{ - for (;;) { - typename HandleMap::iterator it = state().locate(handle, error); - StLock _(state(), true); // locate() locked it - Subclass *sub; - if (!(sub = dynamic_cast(it->second))) - CssmError::throwMe(error); // bad type - if (it->second->tryLock()) // try to lock it - return sub; // okay, go - Thread::yield(); // object lock failed, backoff and retry - } -} - -template -template -inline RefPointer MappingHandle<_Handle>::findRefAndKill(_Handle handle, - CSSM_RETURN error) -{ - for (;;) { - typename HandleMap::iterator it = state().locate(handle, error); - StLock _(state(), true); // locate() locked it - Subclass *sub; - if (!(sub = dynamic_cast(it->second))) - CssmError::throwMe(error); // bad type - if (it->second->tryLock()) { // try to lock it - state().erase(it); // kill the handle - return sub; // okay, go - } - Thread::yield(); // object lock failed, backoff and retry - } -} - -// -// @@@ Remove when 4003540 is fixed -// -// This is a hack to fix 3981388 and should NOT be used elsewhere. -// Also, do not follow this code's example: State methods should not -// implement type-specific behavior. -// -template -template -void MappingHandle<_Handle>::State::findAllRefs(std::vector<_Handle> &refs) -{ - StLock _(*this); - typename HandleMap::iterator it = (*this).begin(); - for (; it != (*this).end(); ++it) - { - Subtype *obj = dynamic_cast(it->second); - if (obj) - refs.push_back(it->first); - } -} - - -} // end namespace Security - -#endif //_H_HANDLETEMPLATES diff --git a/OSX/include/security_cdsa_utilities/handletemplates_defs.h b/OSX/include/security_cdsa_utilities/handletemplates_defs.h deleted file mode 100644 index 1d365838..00000000 --- a/OSX/include/security_cdsa_utilities/handletemplates_defs.h +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) 2008,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// adjunct to handletemplates.h -// -// this header should only be #included by source files defining -// TypedHandle or MappingHandle subclasses -// -// @@@ Should use non-CSSM error codes -// -#ifndef _H_HANDLETEMPLATES_DEFS -#define _H_HANDLETEMPLATES_DEFS - -#include -#include -#include -#include -#include -#include - -namespace Security -{ - -// -// TypedHandle -// -template -TypedHandle<_Handle>::TypedHandle() - : mMyHandle(invalidHandle), mValid(false) -{ -} - -template -TypedHandle<_Handle>::TypedHandle(_Handle h) - : mMyHandle(h), mValid(true) -{ -} - - -// -// MappingHandle instance methods -// -template -MappingHandle<_Handle>::MappingHandle() : TypedHandle<_Handle>() -{ - make(); -} - -template -void MappingHandle<_Handle>::make() -{ - StLock _(state()); - - _Handle hbase = (_Handle)reinterpret_cast(this); - for (;;) { - _Handle handle = hbase ^ state().nextSeq(); - if (!state().handleInUse(handle)) { - // assumes sizeof(unsigned long) >= sizeof(handle) - secdebug("handleobj", "create %#lx for %p", static_cast(handle), this); - TypedHandle<_Handle>::setHandle(handle); - state().add(handle, this); - return; - } - } -} - -// The default locking virtual methods do nothing and succeed. -template -void MappingHandle<_Handle>::lock() { } - -template -bool MappingHandle<_Handle>::tryLock() { return true; } - - -// -// MappingHandle::State -// - -// The default State constructor should not be inlined in a standard -// header: its use via ModuleNexus would result in the inlined code -// appearing *everywhere* the State object might have to be constructed. -template -MappingHandle<_Handle>::State::State() - : sequence(1) -{ -} - -// -// Check if the handle is already in the map. Caller must already hold -// the map lock. Intended for use by a subclass' implementation of -// MappingHandle<...>::make(). -// -template -bool MappingHandle<_Handle>::State::handleInUse(_Handle h) -{ - return (HandleMap::find(h) != (*this).end()); -} - -// -// Observing proper map locking, locate a handle in the global handle map -// and return a pointer to its object. Throw CssmError(error) if it cannot -// be found, or it is corrupt. -// -template -MappingHandle<_Handle> *MappingHandle<_Handle>::State::find(_Handle h, CSSM_RETURN error) -{ - StLock _(*this); - typename HandleMap::const_iterator it = HandleMap::find(h); - if (it == (*this).end()) - CssmError::throwMe(error); - MappingHandle<_Handle> *obj = it->second; - if (obj == NULL || obj->handle() != h) - CssmError::throwMe(error); - return obj; -} - -// -// Look up the handle given in the global handle map. -// If not found, or if the object is corrupt, throw an exception. -// Otherwise, hold the State lock and return an iterator to the map entry. -// Caller must release the State lock in a timely manner. -// -template -typename MappingHandle<_Handle>::HandleMap::iterator -MappingHandle<_Handle>::State::locate(_Handle h, CSSM_RETURN error) -{ - StLock locker(*this); - typename HandleMap::iterator it = HandleMap::find(h); - if (it == (*this).end()) - CssmError::throwMe(error); - MappingHandle<_Handle> *obj = it->second; - if (obj == NULL || obj->handle() != h) - CssmError::throwMe(error); - locker.release(); - return it; -} - -// -// Add a handle and its associated object to the map. Caller must already -// hold the map lock, and is responsible for collision-checking prior to -// calling this method. Intended for use by a subclass' implementation of -// MappingHandle<...>::make(). -// -template -void MappingHandle<_Handle>::State::add(_Handle h, MappingHandle<_Handle> *obj) -{ - (*this)[h] = obj; -} - -// -// Clean up the handle for an object that dies. Caller must already hold -// the map lock. -// Note that an object MAY clear its handle before (in which case we do nothing). -// In particular, killHandle will do this. -// -template -void MappingHandle<_Handle>::State::erase(MappingHandle<_Handle> *obj) -{ - if (obj->validHandle()) - HandleMap::erase(obj->handle()); -} - -template -void MappingHandle<_Handle>::State::erase(typename HandleMap::iterator &it) -{ - if (it->second->validHandle()) - HandleMap::erase(it); -} - - -// -// All explicit instantiations of MappingHandle subclasses get the -// generation of their 'state' member for free (if they #include this -// file). -// -template -ModuleNexus::State> MappingHandle<_Handle>::state; - - -} // end namespace Security - -#endif //_H_HANDLETEMPLATES_DEFS diff --git a/OSX/include/security_cdsa_utilities/objectacl.cpp b/OSX/include/security_cdsa_utilities/objectacl.cpp deleted file mode 100644 index c89cb273..00000000 --- a/OSX/include/security_cdsa_utilities/objectacl.cpp +++ /dev/null @@ -1,662 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// objectacl - core implementation of an ACL-bearing object -// -#include -#include -#include -#include -#include -#include - -#include //@@@ impure - will be removed - -using namespace DataWalkers; - - -// -// The static map of available ACL subject makers. -// These are the kinds of ACL subjects we can deal with. -// -ModuleNexus ObjectAcl::makers; - - -// -// Create an ObjectAcl -// -ObjectAcl::ObjectAcl(Allocator &alloc) : allocator(alloc), mNextHandle(1) -{ -} - -ObjectAcl::ObjectAcl(const AclEntryPrototype &proto, Allocator &alloc) - : allocator(alloc), mNextHandle(1) -{ - cssmSetInitial(proto); -} - -ObjectAcl::~ObjectAcl() -{ } - - -// -// Set an "initial ACL" from a CSSM-style initial ACL argument. -// This will replace the owner, as well as replace the entire ACL -// with a single-item slot, as per CSSM specification. -// -void ObjectAcl::cssmSetInitial(const AclEntryPrototype &proto) -{ - mOwner = OwnerEntry(proto); - add(proto.s_tag(), proto); - IFDUMPING("acl", debugDump("create/proto")); -} - -void ObjectAcl::cssmSetInitial(const AclSubjectPointer &subject) -{ - mOwner = OwnerEntry(subject); - add("", subject); - IFDUMPING("acl", debugDump("create/subject")); -} - -ObjectAcl::Entry::~Entry() -{ -} - - -// -// ObjectAcl::validate validates an access authorization claim. -// Returns normally if 'auth' is granted to the bearer of 'cred'. -// Otherwise, throws a suitable (ACL-related) CssmError exception. -// -class BaseValidationContext : public AclValidationContext { -public: - BaseValidationContext(const AccessCredentials *cred, - AclAuthorization auth, AclValidationEnvironment *env) - : AclValidationContext(cred, auth, env) { } - - uint32 count() const { return cred() ? cred()->samples().length() : 0; } - uint32 size() const { return count(); } - const TypedList &sample(uint32 n) const - { assert(n < count()); return cred()->samples()[n]; } - - void matched(const TypedList *) const { } // ignore match info -}; - - -bool ObjectAcl::validates(AclAuthorization auth, const AccessCredentials *cred, - AclValidationEnvironment *env) -{ - BaseValidationContext ctx(cred, auth, env); - return validates(ctx); -} - -bool ObjectAcl::validates(AclValidationContext &ctx) -{ - // make sure we are ready to go - instantiateAcl(); - - IFDUMPING("acleval", Debug::dump("< range; - if (getRange(ctx.s_credTag(), range) == 0) // no such tag - CssmError::throwMe(CSSM_ERRCODE_ACL_ENTRY_TAG_NOT_FOUND); - // try each entry in turn - for (EntryMap::const_iterator it = range.first; it != range.second; it++) { - const AclEntry &slot = it->second; - IFDUMPING("acleval", (Debug::dump(" EVAL["), slot.debugDump(), Debug::dump("]"))); - if (slot.authorizes(ctx.authorization())) { - ctx.init(this, slot.subject); - ctx.entryTag(slot.tag); - if (slot.validate(ctx)) { - IFDUMPING("acleval", Debug::dump(">PASS>>\n")); - return true; // passed - } - IFDUMPING("acleval", Debug::dump(" NO")); - } - } - IFDUMPING("acleval", Debug::dump(">FAIL>>\n")); - return false; // no joy -} - -void ObjectAcl::validate(AclAuthorization auth, const AccessCredentials *cred, - AclValidationEnvironment *env) -{ - if (!validates(auth, cred, env)) - CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED); -} - -void ObjectAcl::validate(AclValidationContext &ctx) -{ - if (!validates(ctx)) - CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED); -} - - -void ObjectAcl::validateOwner(AclAuthorization authorizationHint, - const AccessCredentials *cred, AclValidationEnvironment *env) -{ - BaseValidationContext ctx(cred, authorizationHint, env); - validateOwner(ctx); -} - -void ObjectAcl::validateOwner(AclValidationContext &ctx) -{ - instantiateAcl(); - - ctx.init(this, mOwner.subject); - if (mOwner.validate(ctx)) - return; - CssmError::throwMe(CSSM_ERRCODE_OPERATION_AUTH_DENIED); -} - - -// -// Export an ObjectAcl to two memory blobs: public and private data separated. -// This is a standard two-pass size+copy operation. -// -void ObjectAcl::exportBlob(CssmData &publicBlob, CssmData &privateBlob) -{ - instantiateAcl(); - Writer::Counter pubSize, privSize; - Endian entryCount = (uint32)mEntries.size(); - mOwner.exportBlob(pubSize, privSize); - pubSize(entryCount); - for (EntryMap::iterator it = begin(); it != end(); it++) - it->second.exportBlob(pubSize, privSize); - publicBlob = CssmData(allocator.malloc(pubSize), pubSize); - privateBlob = CssmData(allocator.malloc(privSize), privSize); - Writer pubWriter(publicBlob), privWriter(privateBlob); - mOwner.exportBlob(pubWriter, privWriter); - pubWriter(entryCount); - for (EntryMap::iterator it = begin(); it != end(); it++) - it->second.exportBlob(pubWriter, privWriter); - IFDUMPING("acl", debugDump("exported")); -} - - -// -// Import an ObjectAcl's contents from two memory blobs representing public and -// private contents, respectively. These blobs must have been generated by the -// export method. -// Prior contents (if any) are deleted and replaced. -// -void ObjectAcl::importBlob(const void *publicBlob, const void *privateBlob) -{ - Reader pubReader(publicBlob), privReader(privateBlob); - mOwner.importBlob(pubReader, privReader); - Endian entryCountIn; pubReader(entryCountIn); - uint32 entryCount = entryCountIn; - - mEntries.erase(begin(), end()); - for (uint32 n = 0; n < entryCount; n++) { - AclEntry newEntry; - newEntry.importBlob(pubReader, privReader); - add(newEntry.tag, newEntry); - } - IFDUMPING("acl", debugDump("imported")); -} - - -// -// Import/export helpers for subjects. -// This is exported to (subject implementation) callers to maintain consistency -// in binary format handling. -// -AclSubject *ObjectAcl::importSubject(Reader &pub, Reader &priv) -{ - Endian typeAndVersion; pub(typeAndVersion); - return make(typeAndVersion, pub, priv); -} - - -// -// Setup/update hooks -// -void ObjectAcl::instantiateAcl() -{ - // nothing by default -} - -void ObjectAcl::changedAcl() -{ - // nothing by default -} - - -// -// ACL utility methods -// -unsigned int ObjectAcl::getRange(const std::string &tag, - pair &range) const -{ - if (!tag.empty()) { // tag restriction in effect - range = mEntries.equal_range(tag); - unsigned int count = (unsigned int)mEntries.count(tag); - if (count == 0) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG); - return count; - } else { // try all tags - range.first = mEntries.begin(); - range.second = mEntries.end(); - return (unsigned int)mEntries.size(); - } -} - -ObjectAcl::EntryMap::iterator ObjectAcl::findEntryHandle(CSSM_ACL_HANDLE handle) -{ - for (EntryMap::iterator it = mEntries.begin(); it != mEntries.end(); it++) - if (it->second.handle == handle) - return it; - CssmError::throwMe(CSSMERR_CSSM_INVALID_HANDLE_USAGE); //%%% imprecise error code -} - - -// -// CSSM style ACL access and modification functions. -// -void ObjectAcl::cssmGetAcl(const char *tag, uint32 &count, AclEntryInfo * &acls) -{ - instantiateAcl(); - pair range; - count = getRange(tag ? tag : "", range); - acls = allocator.alloc(count); - uint32 n = 0; - for (EntryMap::const_iterator it = range.first; it != range.second; it++, n++) { - acls[n].EntryHandle = it->second.handle; - it->second.toEntryInfo(acls[n].EntryPublicInfo, allocator); - } - count = n; -} - -void ObjectAcl::cssmChangeAcl(const AclEdit &edit, - const AccessCredentials *cred, AclValidationEnvironment *env) -{ - IFDUMPING("acl", debugDump("acl-change-from")); - - // make sure we're ready to go - instantiateAcl(); - - // validate access credentials - validateOwner(CSSM_ACL_AUTHORIZATION_CHANGE_ACL, cred, env); - - // what is Thy wish, effendi? - switch (edit.EditMode) { - case CSSM_ACL_EDIT_MODE_ADD: { - const AclEntryInput &input = Required(edit.newEntry()); - add(input.proto().s_tag(), input.proto()); - } - break; - case CSSM_ACL_EDIT_MODE_REPLACE: { - // keep the handle, and try for some modicum of atomicity - EntryMap::iterator it = findEntryHandle(edit.handle()); - AclEntryPrototype proto = Required(edit.newEntry()).proto(); // (bypassing callbacks) - add(proto.s_tag(), proto, edit.handle()); - mEntries.erase(it); - } - break; - case CSSM_ACL_EDIT_MODE_DELETE: - mEntries.erase(findEntryHandle(edit.OldEntryHandle)); - break; - default: - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_EDIT_MODE); - } - - // notify change - changedAcl(); - - IFDUMPING("acl", debugDump("acl-change-to")); -} - -void ObjectAcl::cssmGetOwner(AclOwnerPrototype &outOwner) -{ - instantiateAcl(); - outOwner.TypedSubject = mOwner.subject->toList(allocator); - outOwner.Delegate = mOwner.delegate; -} - -void ObjectAcl::cssmChangeOwner(const AclOwnerPrototype &newOwner, - const AccessCredentials *cred, AclValidationEnvironment *env) -{ - IFDUMPING("acl", debugDump("owner-change-from")); - - instantiateAcl(); - - // only the owner entry can match - validateOwner(CSSM_ACL_AUTHORIZATION_CHANGE_OWNER, cred, env); - - // okay, replace it - mOwner = newOwner; - - changedAcl(); - - IFDUMPING("acl", debugDump("owner-change-to")); -} - - -// -// Load a set of ACL entries from an AclEntryInfo array. -// This completely replaces the ACL's entries. -// Note that we will adopt the handles in the infos, so they better be proper -// (unique, nonzero). -// -template -void ObjectAcl::owner(const Input &input) -{ - IFDUMPING("acl", debugDump("owner-load-old")); - mOwner = OwnerEntry(input); - IFDUMPING("acl", debugDump("owner-load-new")); -} - -template void ObjectAcl::owner(const AclOwnerPrototype &); -template void ObjectAcl::owner(const AclSubjectPointer &); - - -void ObjectAcl::entries(uint32 count, const AclEntryInfo *info) -{ - IFDUMPING("acl", debugDump("entries-load-old")); - mEntries.erase(mEntries.begin(), mEntries.end()); - for (uint32 n = 0; n < count; n++, info++) - add(info->proto().s_tag(), info->proto()); - IFDUMPING("acl", debugDump("entries-load-new")); -} - - -// -// Clear out the ACL and return it to un-initialized state -// -void ObjectAcl::clear() -{ - mOwner = OwnerEntry(); - mEntries.erase(mEntries.begin(), mEntries.end()); - secdebug("acl", "%p cleared", this); -} - - -// -// Common gate to add an ACL entry -// -void ObjectAcl::add(const std::string &tag, const AclEntry &newEntry) -{ - add(tag, newEntry, mNextHandle++); -} - -void ObjectAcl::add(const std::string &tag, AclEntry newEntry, CSSM_ACL_HANDLE handle) -{ - //@@@ This should use a hook-registry mechanism. But for now, we are explicit: - if (!newEntry.authorizesAnything) { - for (AclAuthorizationSet::const_iterator it = newEntry.authorizations.begin(); - it != newEntry.authorizations.end(); it++) - if (*it >= CSSM_ACL_AUTHORIZATION_PREAUTH_BASE && - *it < CSSM_ACL_AUTHORIZATION_PREAUTH_END) { - // preauthorization right - special handling - if (newEntry.subject->type() != CSSM_ACL_SUBJECT_TYPE_PREAUTH_SOURCE) - newEntry.subject = - new PreAuthorizationAcls::SourceAclSubject(newEntry.subject); - } - } - - mEntries.insert(make_pair(tag, newEntry))->second.handle = handle; - if (handle >= mNextHandle) - mNextHandle = handle + 1; // don't reuse this handle (in this ACL) -} - - -// -// Common features of ACL entries/owners -// -void ObjectAcl::Entry::init(const AclSubjectPointer &subject, bool delegate) -{ - this->subject = subject; - this->delegate = delegate; -} - -void ObjectAcl::Entry::importBlob(Reader &pub, Reader &priv) -{ - // the delegation flag is 4 bytes for historic reasons - Endian del; - pub(del); - delegate = del; - - subject = importSubject(pub, priv); -} - - -// -// An OwnerEntry is a restricted EntryPrototype for use as the ACL owner. -// -bool ObjectAcl::OwnerEntry::authorizes(AclAuthorization) const -{ - return true; // owner can do anything -} - -bool ObjectAcl::OwnerEntry::validate(const AclValidationContext &ctx) const -{ - return subject->validate(ctx); // simple subject match - no strings attached -} - - -// -// An AclEntry has some extra goodies -// -ObjectAcl::AclEntry::AclEntry(const AclEntryPrototype &proto) : Entry(proto) -{ - tag = proto.s_tag(); - if (proto.authorization().contains(CSSM_ACL_AUTHORIZATION_ANY)) - authorizesAnything = true; // anything else wouldn't add anything - else if (proto.authorization().empty()) - authorizesAnything = true; // not in standard, but common sense - else { - authorizesAnything = false; - authorizations = proto.authorization(); - } - //@@@ not setting time range - // handle = not set here. Set by caller when the AclEntry is created. -} - -ObjectAcl::AclEntry::AclEntry(const AclSubjectPointer &subject) : Entry(subject) -{ - authorizesAnything = true; // by default, everything - //@@@ not setting time range -} - -void ObjectAcl::AclEntry::toEntryInfo(CSSM_ACL_ENTRY_PROTOTYPE &info, Allocator &alloc) const -{ - info.TypedSubject = subject->toList(alloc); - info.Delegate = delegate; - info.Authorization = authorizesAnything ? - AuthorizationGroup(CSSM_ACL_AUTHORIZATION_ANY, alloc) : - AuthorizationGroup(authorizations, alloc); - //@@@ info.TimeRange = - assert(tag.length() <= CSSM_MODULE_STRING_SIZE); - memcpy(info.EntryTag, tag.c_str(), tag.length() + 1); -} - -bool ObjectAcl::AclEntry::authorizes(AclAuthorization auth) const -{ - return authorizesAnything || authorizations.find(auth) != authorizations.end(); -} - -bool ObjectAcl::AclEntry::validate(const AclValidationContext &ctx) const -{ - //@@@ not checking time ranges - return subject->validate(ctx); -} - -void ObjectAcl::AclEntry::importBlob(Reader &pub, Reader &priv) -{ - Entry::importBlob(pub, priv); - const char *s; pub(s); tag = s; - - // authorizesAnything is on disk as a 4-byte flag - Endian tmpAuthorizesAnything; - pub(tmpAuthorizesAnything); - authorizesAnything = tmpAuthorizesAnything; - - authorizations.erase(authorizations.begin(), authorizations.end()); - if (!authorizesAnything) { - Endian countIn; pub(countIn); - uint32 count = countIn; - - for (uint32 n = 0; n < count; n++) { - Endian auth; pub(auth); - authorizations.insert(auth); - } - } - //@@@ import time range -} - - -// -// Subject factory and makers -// -AclSubject::Maker::Maker(CSSM_ACL_SUBJECT_TYPE type) - : mType(type) -{ - ObjectAcl::makers()[type] = this; -} - -AclSubject *ObjectAcl::make(const TypedList &list) -{ - if (!list.isProper()) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - return makerFor(list.type()).make(list); -} - -AclSubject *ObjectAcl::make(uint32 typeAndVersion, Reader &pub, Reader &priv) -{ - // this type is encoded as (version << 24) | type - return makerFor(typeAndVersion & ~AclSubject::versionMask).make(typeAndVersion >> AclSubject::versionShift, pub, priv); -} - -AclSubject::Maker &ObjectAcl::makerFor(CSSM_ACL_SUBJECT_TYPE type) -{ - AclSubject::Maker *maker = makers()[type]; - if (maker == NULL) - CssmError::throwMe(CSSM_ERRCODE_ACL_SUBJECT_TYPE_NOT_SUPPORTED); - return *maker; -} - - -// -// Parsing helper for subject makers. -// Note that count/array exclude the first element of list, which is the subject type wordid. -// -void AclSubject::Maker::crack(const CssmList &list, uint32 count, ListElement **array, ...) -{ - if (count != list.length() - 1) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - if (count > 0) { - va_list args; - va_start(args, array); - ListElement *elem = list.first()->next(); - for (uint32 n = 0; n < count; n++, elem = elem->next()) { - CSSM_LIST_ELEMENT_TYPE expectedType = va_arg(args, CSSM_LIST_ELEMENT_TYPE); - if (elem->type() != expectedType) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - array[n] = elem; - } - va_end(args); - } -} - -CSSM_WORDID_TYPE AclSubject::Maker::getWord(const ListElement &elem, - int min /*= 0*/, int max /*= INT_MAX*/) -{ - if (elem.type() != CSSM_LIST_ELEMENT_WORDID) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - CSSM_WORDID_TYPE value = elem; - if (value < min || value > max) - CssmError::throwMe(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - return value; -} - - -// -// Debug dumping support. -// Leave the ObjectAcl::debugDump method in (stubbed out) -// to keep the virtual table layout stable, and to allow -// proper linking in weird mix-and-match scenarios. -// -void ObjectAcl::debugDump(const char *what) const -{ -#if defined(DEBUGDUMP) - if (!what) - what = "Dump"; - Debug::dump("%p ACL %s: %d entries\n", this, what, int(mEntries.size())); - Debug::dump(" OWNER ["); mOwner.debugDump(); Debug::dump("]\n"); - for (EntryMap::const_iterator it = begin(); it != end(); it++) { - const AclEntry &ent = it->second; - Debug::dump(" (%ld:%s) [", ent.handle, ent.tag.c_str()); - ent.debugDump(); - Debug::dump("]\n"); - } - Debug::dump("%p ACL END\n", this); -#endif //DEBUGDUMP -} - -#if defined(DEBUGDUMP) - -void ObjectAcl::Entry::debugDump() const -{ - if (subject) { - if (AclSubject::Version v = subject->version()) - Debug::dump("V=%d ", v); - subject->debugDump(); - } else { - Debug::dump("NULL subject"); - } - if (delegate) - Debug::dump(" DELEGATE"); -} - -void ObjectAcl::AclEntry::debugDump() const -{ - Entry::debugDump(); - if (authorizesAnything) { - Debug::dump(" auth(ALL)"); - } else { - Debug::dump(" auth("); - for (AclAuthorizationSet::iterator it = authorizations.begin(); - it != authorizations.end(); it++) { - if (*it >= CSSM_ACL_AUTHORIZATION_PREAUTH_BASE - && *it < CSSM_ACL_AUTHORIZATION_PREAUTH_END) - Debug::dump(" PRE(%d)", *it - CSSM_ACL_AUTHORIZATION_PREAUTH_BASE); - else - Debug::dump(" %d", *it); - } - Debug::dump(")"); - } -} - -#endif //DEBUGDUMP diff --git a/OSX/include/security_cdsa_utilities/objectacl.h b/OSX/include/security_cdsa_utilities/objectacl.h deleted file mode 100644 index c1d08253..00000000 --- a/OSX/include/security_cdsa_utilities/objectacl.h +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2000-2004,2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// objectacl - core implementation of an ACL-bearing object -// -#ifndef _OBJECTACL -#define _OBJECTACL - -#include -#include -#include -#include -#include - - -namespace Security { - - -// -// An in-memory ACL object. -// This class implements an ACL-for-a-protected-object. It is complete in that -// it provides full ACL management functionality. You still need to (globally) -// register makers for the ACL subject types you want to use. -// Note that ObjectAcl does no integrity checking. ObjectAcl objects need to be -// protected from hostile access (by e.g. address space separation), and exported -// ACLs need to be protected somehow (by hiding, signing, or whatever works in -// your situation). -// -class ObjectAcl { - friend AclSubject::Maker::Maker(CSSM_ACL_SUBJECT_TYPE); - -public: - typedef RefPointer AclSubjectPointer; - - typedef LowLevelMemoryUtilities::Writer Writer; - typedef LowLevelMemoryUtilities::Reader Reader; - -public: - ObjectAcl(Allocator &alloc); - ObjectAcl(const AclEntryPrototype &proto, Allocator &alloc); - virtual ~ObjectAcl(); - - Allocator &allocator; - - - // - // access control validation (evaluation) - // - - // validate(): succeed or throw exception - void validate(AclAuthorization auth, const AccessCredentials *cred, - AclValidationEnvironment *env = NULL); - void validate(AclValidationContext &ctx); - - // validates(): return true or false (or throw on error) - bool validates(AclAuthorization auth, const AccessCredentials *cred, - AclValidationEnvironment *env = NULL); - bool validates(AclValidationContext &ctx); - - // owner validation (simpler) - void validateOwner(AclAuthorization authorizationHint, const AccessCredentials *cred, - AclValidationEnvironment *env = NULL); - void validateOwner(AclValidationContext &ctx); - - // CSSM-style ACL access operations - // (Gets are not const because underlying implementations usually want them writable) - void cssmGetAcl(const char *tag, uint32 &count, AclEntryInfo * &acls); - void cssmChangeAcl(const AclEdit &edit, const AccessCredentials *cred, - AclValidationEnvironment *env = NULL); - void cssmGetOwner(AclOwnerPrototype &owner); - void cssmChangeOwner(const AclOwnerPrototype &newOwner, const AccessCredentials *cred, - AclValidationEnvironment *env = NULL); - - void cssmSetInitial(const AclEntryPrototype &proto); - void cssmSetInitial(const AclSubjectPointer &subject); - - // Acl I/O (to/from memory blobs) - void exportBlob(CssmData &publicBlob, CssmData &privateBlob); - void importBlob(const void *publicBlob, const void *privateBlob); - - // clear everything from this ACL (return it to un-initialized state) - void clear(); - - // setup hooks (called to delayed-construct the contents before use) - empty defaults - virtual void instantiateAcl(); // called before ACL contents are used by external calls - virtual void changedAcl(); // called after an ACL has been (possibly) changed - - // debug dump support (always there but stubbed out unless DEBUGDUMP) - virtual void debugDump(const char *what = NULL) const; - -public: - class Entry { - public: - AclSubjectPointer subject; // subject representation - bool delegate; // delegation flag - - Entry() { } // make invalid Entry - - void toOwnerInfo(CSSM_ACL_OWNER_PROTOTYPE &info, - Allocator &alloc) const; // encode copy in CSSM format - - virtual bool authorizes(AclAuthorization auth) const = 0; - virtual bool validate(const AclValidationContext &ctx) const = 0; - - template - void exportBlob(Action &pub, Action &priv) - { - Endian del = delegate; pub(del); // 4 bytes delegate flag - exportSubject(subject, pub, priv); // subject itself (polymorphic) - } - void importBlob(Reader &pub, Reader &priv); - - IFDUMP(virtual void debugDump() const); - - private: - void init(const AclSubjectPointer &subject, bool delegate = false); - void init(const TypedList &subject, bool delegate = false) { init(make(subject), delegate); } - - protected: - Entry(const AclEntryPrototype &proto) { init(proto.subject(), proto.delegate()); } - Entry(const AclOwnerPrototype &proto) { init(proto.subject()); } - Entry(const AclSubjectPointer &subject) { init(subject); } - virtual ~Entry(); - }; - - class OwnerEntry : public Entry { - public: - OwnerEntry() { } // invalid OwnerEntry - template - OwnerEntry(const Input &owner) : Entry(owner) { } - - bool authorizes(AclAuthorization auth) const; - bool validate(const AclValidationContext &ctx) const; - }; - - class AclEntry : public Entry { - public: - std::string tag; // entry tag - AclAuthorizationSet authorizations; // set of authorizations - bool authorizesAnything; // has the _ANY authorization tag - //@@@ time range not yet implemented - CSSM_ACL_HANDLE handle; // entry handle - - AclEntry() { } // invalid AclEntry - AclEntry(const AclSubjectPointer &subject); - AclEntry(const AclEntryPrototype &proto); - - void toEntryInfo(CSSM_ACL_ENTRY_PROTOTYPE &info, - Allocator &alloc) const; // encode copy in CSSM format - - bool authorizes(AclAuthorization auth) const; - bool validate(const AclValidationContext &ctx) const; - - template - void exportBlob(Action &pub, Action &priv) - { - Entry::exportBlob(pub, priv); - const char *s = tag.c_str(); pub(s); - uint32 aa = authorizesAnything; pub(aa); - if (!authorizesAnything) { - Endian count = (uint32)authorizations.size(); pub(count); - for (AclAuthorizationSet::iterator it = authorizations.begin(); - it != authorizations.end(); it++) { - Endian auth = *it; pub(auth); - } - } - //@@@ export time range - } - void importBlob(Reader &pub, Reader &priv); - - IFDUMP(void debugDump() const); - }; - -public: - // These helpers deal with transferring one subject from/to reader/writer streams. - // You'd usually only call those from complex subject implementations (e.g. threshold) - template - static void exportSubject(AclSubject *subject, Action &pub, Action &priv) - { - Endian typeAndVersion = subject->type() | subject->version() << AclSubject::versionShift; - pub(typeAndVersion); - subject->exportBlob(pub, priv); - } - static AclSubject *importSubject(Reader &pub, Reader &priv); - -public: - typedef std::multimap EntryMap; - - EntryMap::iterator begin() { return mEntries.begin(); } - EntryMap::iterator end() { return mEntries.end(); } - EntryMap::const_iterator begin() const { return mEntries.begin(); } - EntryMap::const_iterator end() const { return mEntries.end(); } - - unsigned int getRange(const std::string &tag, - pair &range) const; - EntryMap::iterator findEntryHandle(CSSM_ACL_HANDLE handle); - - // construct an AclSubject through the Maker registry (by subject type) - static AclSubject *make(const TypedList &list); // make from CSSM form - static AclSubject *make(uint32 typeAndVersion, - Reader &pub, Reader &priv); // make from export form - -protected: - template - void owner(const Input &input); - void entries(uint32 count, const AclEntryInfo *infos); - -private: - void add(const std::string &tag, const AclEntry &newEntry); - void add(const std::string &tag, AclEntry newEntry, CSSM_ACL_HANDLE handle); - -private: - EntryMap mEntries; // ACL entries indexed by tag - OwnerEntry mOwner; // ACL owner entry - CSSM_ACL_HANDLE mNextHandle; // next unused entry handle value - -private: - typedef map MakerMap; - static ModuleNexus makers; // registered subject Makers - - static AclSubject::Maker &makerFor(CSSM_ACL_SUBJECT_TYPE type); -}; - - -} // end namespace Security - - -#endif //_OBJECTACL diff --git a/OSX/include/security_cdsa_utilities/osxverifier.cpp b/OSX/include/security_cdsa_utilities/osxverifier.cpp deleted file mode 100644 index 3bf4520b..00000000 --- a/OSX/include/security_cdsa_utilities/osxverifier.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// osxsigner - MacOS X's standard code signing algorithm. -// -#include -#include -#include -#include -#include -#include -#include // debug only - - -using namespace CodeSigning; - - -namespace Security { - - -// -// Create a Verifier from a code object. -// -// This does not add any auxiliary information blobs. You can do that -// by calling add() after construction, of course. -// -OSXVerifier::OSXVerifier(OSXCode *code) -{ - mPath = code->canonicalPath(); - secdebug("codesign", "building verifier for %s", mPath.c_str()); - - // build new-style verifier - CFRef staticCode = code->codeRef(); - switch (OSStatus rc = SecCodeCopyDesignatedRequirement(staticCode, - kSecCSDefaultFlags, &mRequirement.aref())) { - case errSecSuccess: - secdebug("codesign", " is signed; canonical requirement loaded"); - break; - case errSecCSUnsigned: - secdebug("codesign", " is unsigned; no requirement"); - break; - default: - MacOSError::throwMe(rc); - } - - // build old-style verifier - makeLegacyHash(code, mLegacyHash); - secdebug("codesign", " hash generated"); -} - - -// -// Create a Verifier from hash, path, and requirement. -// Again, this has no auxiliary data when constructed. -// -OSXVerifier::OSXVerifier(const SHA1::Byte *hash, const std::string &path) - : mPath(path) -{ - secdebug("codesign", "building verifier from hash %p and path=%s", hash, path.c_str()); - if (hash) - memcpy(mLegacyHash, hash, sizeof(mLegacyHash)); - else - memset(mLegacyHash, 0, sizeof(mLegacyHash)); -} - - -OSXVerifier::~OSXVerifier() -{ - secdebug("codesign", "%p verifier destroyed", this); -} - - -// -// Add an auxiliary comment blob. -// Note that we only allow one auxiliary blob for each magic number. -// -void OSXVerifier::add(const BlobCore *blob) -{ - if (blob->is()) { -#if defined(NDEBUG) - secdebug("codesign", "%p verifier adds requirement", this); -#else - secdebug("codesign", "%p verifier adds requirement %s", this, - Dumper::dump(Requirement::specific(blob), true).c_str()); -#endif //NDEBUG - MacOSError::check(SecRequirementCreateWithData(CFTempData(*blob), - kSecCSDefaultFlags, &mRequirement.aref())); - } else { - secdebug("codesign", "%p verifier adds blob (0x%x,%zd)", - this, blob->magic(), blob->length()); - BlobCore * &slot = mAuxiliary[blob->magic()]; - if (slot) - ::free(slot); - slot = blob->clone(); - } -} - - -// -// Find a comment blob, by magic number -// -const BlobCore *OSXVerifier::find(BlobCore::Magic magic) -{ - AuxMap::const_iterator it = mAuxiliary.find(magic); - return (it == mAuxiliary.end()) ? NULL : it->second; -} - - -void OSXVerifier::makeLegacyHash(OSXCode *code, SHA1::Digest digest) -{ - secdebug("codesign", "calculating legacy hash for %s", code->canonicalPath().c_str()); - UnixPlusPlus::AutoFileDesc fd(code->executablePath(), O_RDONLY); - char buffer[legacyHashLimit]; - size_t size = fd.read(buffer, legacyHashLimit); - SHA1 hash; - hash(buffer, size); - hash.finish(digest); -} - - -// -// The AuxMap helper class provides a map-to-Blob-pointers with automatic memory management. -// -OSXVerifier::AuxMap::AuxMap(const OSXVerifier::AuxMap &src) -{ - for (const_iterator it = src.begin(); it != src.end(); it++) - this->insert(*it); -} - -OSXVerifier::AuxMap::~AuxMap() -{ - for (const_iterator it = this->begin(); it != this->end(); ++it) - ::free(it->second); -} - - -#if DEBUGDUMP - -void OSXVerifier::dump() const -{ - static const SHA1::Digest nullDigest = { 0 }; - if (!memcmp(mLegacyHash, nullDigest, sizeof(mLegacyHash))) { - Debug::dump("(no hash)"); - } else { - Debug::dump("oldHash="); - Debug::dumpData(mLegacyHash, sizeof(mLegacyHash)); - } - if (mRequirement) { - CFRef reqData; - if (!SecRequirementCopyData(mRequirement, 0, &reqData.aref())) { - Debug::dump(" Requirement =>"); - ((const Requirement *)CFDataGetBytePtr(reqData))->dump(); - } - } else { - Debug::dump(" NO REQ"); - } -} - -#endif //DEBUGDUMP - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/osxverifier.h b/OSX/include/security_cdsa_utilities/osxverifier.h deleted file mode 100644 index 0703c57d..00000000 --- a/OSX/include/security_cdsa_utilities/osxverifier.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// osxsigner - MacOS X's standard code signing algorithm. -// -#ifndef _H_OSXVERIFIER -#define _H_OSXVERIFIER - -#include -#include -#include -#include -#include -#include -#include - -namespace Security { - - -// -// A standard OS X style signature verifier. -// This encapsulates the different modes of signing/verifying currently -// supported. It knows nothing about the way this is represented in -// keychain access control lists; this knowledge resides exclusively -// in acl_codesigning. -// -class OSXVerifier { -public: - static const size_t legacyHashLimit = 16 * 1024; - static const uint32_t commentAlignment = 4; - -public: - // make a Verifier from a code reference object - OSXVerifier(OSXCode *code); // makes both legacy hash and SecRequirement - OSXVerifier(const SHA1::Byte *hash, const std::string &path); // just hash - ~OSXVerifier(); - - // components - const unsigned char *legacyHash() const { return mLegacyHash; } - const std::string& path() const { return mPath; } - SecRequirementRef requirement() const { return mRequirement; } - -public: - // handle other (not explicitly understood) information in the verifier - class AuxMap : public std::map { - public: - AuxMap() { } - AuxMap(const AuxMap &src); - ~AuxMap(); - }; - - AuxMap::const_iterator beginAux() const { return mAuxiliary.begin(); } - AuxMap::const_iterator endAux() const { return mAuxiliary.end(); } - - void add(const BlobCore *info); - const BlobCore *find(BlobCore::Magic magic); - - template - static const BlobType *find() - { return static_cast(find(BlobType::typeMagic)); } - -public: - static void makeLegacyHash(OSXCode *code, SHA1::Digest digest); - - IFDUMP(void dump() const); - -private: - SHA1::Digest mLegacyHash; // legacy page hash - std::string mPath; // path to originating code (comment) - CFCopyRef mRequirement; // CS-style requirement - AuxMap mAuxiliary; // other data (does not include mRequirement) -}; - -} // end namespace Security - - -#endif //_H_OSXVERIFIER diff --git a/OSX/include/security_cdsa_utilities/u32handleobject.cpp b/OSX/include/security_cdsa_utilities/u32handleobject.cpp deleted file mode 100644 index 647b1132..00000000 --- a/OSX/include/security_cdsa_utilities/u32handleobject.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2008,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#include -#include - diff --git a/OSX/include/security_cdsa_utilities/u32handleobject.h b/OSX/include/security_cdsa_utilities/u32handleobject.h deleted file mode 100644 index b9e44c95..00000000 --- a/OSX/include/security_cdsa_utilities/u32handleobject.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2008,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#ifndef _H_U32HANDLEOBJECT -#define _H_U32HANDLEOBJECT - -#include -#include - -// -// 32-bit unsigned handle object -// Specifically meant for securityd handles sent to clients -// - -namespace Security -{ - -typedef MappingHandle U32HandleObject; - -} // end namespace Security - -#endif //_H_U32HANDLEOBJECT diff --git a/OSX/include/security_cdsa_utilities/uniformrandom.cpp b/OSX/include/security_cdsa_utilities/uniformrandom.cpp deleted file mode 100644 index 92c6f507..00000000 --- a/OSX/include/security_cdsa_utilities/uniformrandom.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// uniformrandom - uniformly distributed random number operators -// - -#include - - -namespace Security { - - - - -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/uniformrandom.h b/OSX/include/security_cdsa_utilities/uniformrandom.h deleted file mode 100644 index ecbdae36..00000000 --- a/OSX/include/security_cdsa_utilities/uniformrandom.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// uniformrandom - uniformly distributed random number operators -// -#ifndef _H_UNIFORMRANDOM -#define _H_UNIFORMRANDOM - -#include - - -namespace Security { - - -// -// Uniform binary blob generator. -// This operator deals exclusively in byte arrays. -// -template -class UniformRandomBlobs : public Generator { -public: - using Generator::random; - - template - void random(Object &obj) { random(&obj, sizeof(obj)); } - - void random(CssmData &data) { random(data.data(), data.length()); } -}; - - -}; // end namespace Security - - -#endif //_H_UNIFORMRANDOM diff --git a/OSX/include/security_cdsa_utilities/walkers.cpp b/OSX/include/security_cdsa_utilities/walkers.cpp deleted file mode 100644 index c0a23774..00000000 --- a/OSX/include/security_cdsa_utilities/walkers.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003-2004,2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// walkers - facilities for traversing and manipulating recursive data structures -// -#include - - -namespace Security { -namespace DataWalkers { - - -// -// Free all recorded storage nodes for a ChunkFreeWalker -// -void ChunkFreeWalker::free() -{ - for (set::iterator it = freeSet.begin(); it != freeSet.end(); it++) - allocator.free(*it); - freeSet.erase(freeSet.begin(), freeSet.end()); -} - - -} // end namespace DataWalkers -} // end namespace Security diff --git a/OSX/include/security_cdsa_utilities/walkers.h b/OSX/include/security_cdsa_utilities/walkers.h deleted file mode 100644 index 6178a359..00000000 --- a/OSX/include/security_cdsa_utilities/walkers.h +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Copyright (c) 2000-2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// walkers - facilities for traversing and manipulating recursive data structures -// -// Very briefly, this facility allows for deep traversals of (potentially) recursive -// data structures through templated structure "walkers." Standard operations include -// deep copying to a contiguous memory buffer, size calculation, deep freeing, reconstitution -// after relocation (e.g. via IPC), and others. You can add other operations (e.g. scattered deep -// copy, debug dumping, etc.) by defining operations classes and applying them to the -// existing walkers. You can also extend the reach of the facility to new data structures -// by writing appropriate walker functions for them. -// -// NOTE: We no longer have a default walker for flat structures. You must define -// a walk(operate, foo * &) function for every data type encountered during a walk -// or you will get compile-time errors. -// -// For more detailed rules and regulations, see the accompanying documentation. -// -#ifndef _H_WALKERS -#define _H_WALKERS - -#include -#include -#include -#include -#include - - -namespace Security { -namespace DataWalkers { - -#define WALKERDEBUG 0 - - -#if WALKERDEBUG -# define DEBUGWALK(who) secdebug("walkers", "walk " who " %s@%p (%ld)", \ - Debug::typeName(addr).c_str(), addr, size) -#else -# define DEBUGWALK(who) /* nothing */ -#endif - - -// -// SizeWalker simply walks a structure and calculates how many bytes -// CopyWalker would use to make a flat copy. This is naturally at least -// the sum of all relevant sizes, but can be more due to alignment and -// counting overhead. -// -class SizeWalker : public LowLevelMemoryUtilities::Writer::Counter { -public: - template - void operator () (T &obj, size_t size = sizeof(T)) { } - - template - void operator () (T *addr, size_t size = sizeof(T)) - { DEBUGWALK("size"); LowLevelMemoryUtilities::Writer::Counter::insert(size); } - - void blob(void *addr, size_t size) - { (*this)(addr, size); } - - void reserve(size_t space) - { LowLevelMemoryUtilities::Writer::Counter::insert(space); } - - static const bool needsRelinking = false; - static const bool needsSize = true; -}; - - -// -// CopyWalker makes a deep, flat copy of a structure. The result will work -// just like the original (with all elements recursively copied), except that -// it occupies contiguous memory. -// -class CopyWalker : public LowLevelMemoryUtilities::Writer { -public: - CopyWalker() { } - CopyWalker(void *base) : LowLevelMemoryUtilities::Writer(base) { } - -public: - template - void operator () (T &obj, size_t size = sizeof(T)) - { } - - template - void operator () (T * &addr, size_t size = sizeof(T)) - { - DEBUGWALK("copy"); - if (addr) - addr = reinterpret_cast(LowLevelMemoryUtilities::Writer::operator () (addr, size)); - } - - template - void blob(T * &addr, size_t size) - { (*this)(addr, size); } - - static const bool needsRelinking = true; - static const bool needsSize = true; -}; - - -// -// Walk a structure and apply a constant linear shift to all pointers -// encountered. This is useful when a structure and its deep components -// have been linearly shifted by something (say, an IPC transit). -// -class ReconstituteWalker { -public: - ReconstituteWalker(off_t offset) : mOffset(offset) { } - ReconstituteWalker(void *ptr, void *base) - : mOffset(LowLevelMemoryUtilities::difference(ptr, base)) { } - - template - void operator () (T &obj, size_t size = sizeof(T)) - { } - - template - void operator () (T * &addr, size_t size = 0) - { - DEBUGWALK("reconstitute"); - if (addr) - addr = LowLevelMemoryUtilities::increment(addr, (ptrdiff_t)mOffset); - } - - template - void blob(T * &addr, size_t size) - { (*this)(addr, size); } - - static const bool needsRelinking = true; - static const bool needsSize = false; - -private: - off_t mOffset; -}; - - -// -// Make an element-by-element copy of a structure. Each pointer followed -// uses a separate allocation for its pointed-to storage. -// -class ChunkCopyWalker { -public: - ChunkCopyWalker(Allocator &alloc = Allocator::standard()) : allocator(alloc) { } - - Allocator &allocator; - - template - void operator () (T &obj, size_t size = sizeof(T)) - { } - - template - void operator () (T * &addr, size_t size = sizeof(T)) - { - DEBUGWALK("chunkcopy"); -#if BUG_GCC - T *copy = reinterpret_cast(allocator.malloc(size)); -#else - T *copy = allocator.malloc(size); -#endif - memcpy(copy, addr, size); - addr = copy; - } - - template - void blob(T * &addr, size_t size) - { (*this)(addr, size); } - - static const bool needsRelinking = true; - static const bool needsSize = true; -}; - - -// -// Walk a structure and call an Allocator to separate free each node. -// This is safe for non-trees (i.e. shared subsidiary nodes); such will -// only be freed once. -// -class ChunkFreeWalker { -public: - ChunkFreeWalker(Allocator &alloc = Allocator::standard()) : allocator(alloc) { } - - Allocator &allocator; - - template - void operator () (T &obj, size_t size = 0) - { } - - template - void operator () (T *addr, size_t size = 0) - { - DEBUGWALK("chunkfree"); - freeSet.insert(addr); - } - - void blob(void *addr, size_t size) - { (*this)(addr, 0); } - - void free(); - ~ChunkFreeWalker() { free(); } - - static const bool needsRelinking = false; - static const bool needsSize = false; - -private: - std::set freeSet; -}; - - -// -// Stand-alone operations for a single structure web. -// These simply create, use, and discard their operator objects internally. -// -template -size_t size(T obj) -{ - SizeWalker w; - walk(w, obj); - return w; -} - -// Special version for const pointer's -template -size_t size(const T *obj) -{ return size(const_cast(obj)); } - - -template -T *copy(const T *obj, void *addr) -{ - if (obj == NULL) - return NULL; - CopyWalker w(addr); - walk(w, const_cast(obj)); - return const_cast(obj); -} - -template -T *copy(const T *obj, Allocator &alloc, size_t size) -{ - if (obj == NULL) - return NULL; - return copy(obj, alloc.malloc(size)); -} - -template -T *copy(const T *obj, Allocator &alloc = Allocator::standard()) -{ - return obj ? copy(obj, alloc, size(obj)) : NULL; -} - - -template -void relocate(T *obj, T *base) -{ - if (obj) { - ReconstituteWalker w(LowLevelMemoryUtilities::difference(obj, base)); - walk(w, base); - } -} - - -// -// chunkCopy and chunkFree can take pointer and non-pointer arguments. -// Don't try to declare the T arguments const (overload resolution will -// mess you over if you try). Just take const and nonconst Ts and take -// the const away internally. -// -template -typename Nonconst::Type *chunkCopy(T *obj, Allocator &alloc = Allocator::standard()) -{ - if (obj) { - ChunkCopyWalker w(alloc); - return walk(w, unconst_ref_cast(obj)); - } else - return NULL; -} - -template -T chunkCopy(T obj, Allocator &alloc = Allocator::standard()) -{ - ChunkCopyWalker w(alloc); - walk(w, obj); - return obj; -} - -template -void chunkFree(T *obj, Allocator &alloc = Allocator::standard()) -{ - if (obj) { - ChunkFreeWalker w(alloc); - walk(w, unconst_ref_cast(obj)); - } -} - -template -void chunkFree(const T &obj, Allocator &alloc = Allocator::standard()) -{ - ChunkFreeWalker w(alloc); - walk(w, obj); -} - - -// -// Copier combines SizeWalker and CopyWalker into one operational package. -// this is useful if you need both the copy and its size (and don't want -// to re-run size()). Copier (like copy()) only applies to one object. -// -template -class Copier { -public: - Copier(const T *obj, Allocator &alloc = Allocator::standard()) : allocator(alloc) - { - if (obj == NULL) { - mValue = NULL; - mLength = 0; - } else { - mLength = size(const_cast(obj)); -#if BUG_GCC - mValue = reinterpret_cast(alloc.malloc(mLength)); -#else - mValue = alloc.malloc(mLength); -#endif - mValue = copy(obj, mValue); - } - } - - Copier(const T *obj, uint32 count, Allocator &alloc = Allocator::standard()) - : allocator(alloc) - { - if (obj == NULL) { - mValue = NULL; - mLength = 0; - } else { - SizeWalker sizer; - sizer.reserve(sizeof(T) * count); // initial vector size - for (uint32 n = 0; n < count; n++) - walk(sizer, const_cast(obj[n])); // dependent data sizes - mLength = sizer; -#if BUG_GCC - mValue = reinterpret_cast(alloc.malloc(mLength)); -#else - mValue = alloc.malloc(mLength); -#endif - CopyWalker copier(LowLevelMemoryUtilities::increment(mValue, sizeof(T) * count)); - for (uint32 n = 0; n < count; n++) { - mValue[n] = obj[n]; - walk(copier, mValue[n]); - } - } - } - - Allocator &allocator; - - ~Copier() { allocator.free(mValue); } - - T *value() const { return mValue; } - operator T *() const { return value(); } - size_t length() const { return mLength; } - - T *keep() { T *result = mValue; mValue = NULL; return result; } - -private: - T *mValue; - size_t mLength; -}; - - -} // end namespace DataWalkers -} // end namespace Security - -#endif //_H_WALKERS diff --git a/OSX/include/security_cdsa_utils b/OSX/include/security_cdsa_utils new file mode 120000 index 00000000..f3e5247e --- /dev/null +++ b/OSX/include/security_cdsa_utils @@ -0,0 +1 @@ +./libsecurity_cdsa_utils/lib \ No newline at end of file diff --git a/OSX/include/security_cdsa_utils/cuCdsaUtils.cpp b/OSX/include/security_cdsa_utils/cuCdsaUtils.cpp deleted file mode 100644 index a516d362..00000000 --- a/OSX/include/security_cdsa_utils/cuCdsaUtils.cpp +++ /dev/null @@ -1,778 +0,0 @@ -/* - * Copyright (c) 2001-2003,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuCdsaUtils.cpp - - Description: common CDSA access utilities - - Author: dmitch -*/ - -#include "cuCdsaUtils.h" -#include -#include -#include -#include /* for cssmPerror() */ -#include -#include -#include - -static CSSM_VERSION vers = {2, 0}; -static const CSSM_GUID testGuid = { 0xFADE, 0, 0, { 1,2,3,4,5,6,7,0 }}; - -/* - * Standard app-level memory functions required by CDSA. - */ -void * cuAppMalloc (CSSM_SIZE size, void *allocRef) { - return( malloc(size) ); -} - -void cuAppFree (void *mem_ptr, void *allocRef) { - free(mem_ptr); - return; -} - -void * cuAppRealloc (void *ptr, CSSM_SIZE size, void *allocRef) { - return( realloc( ptr, size ) ); -} - -void * cuAppCalloc (uint32 num, CSSM_SIZE size, void *allocRef) { - return( calloc( num, size ) ); -} - -static CSSM_API_MEMORY_FUNCS memFuncs = { - cuAppMalloc, - cuAppFree, - cuAppRealloc, - cuAppCalloc, - NULL - }; - -CSSM_BOOL cuCompareCssmData(const CSSM_DATA *d1, - const CSSM_DATA *d2) -{ - if(d1->Length != d2->Length) { - return CSSM_FALSE; - } - if(memcmp(d1->Data, d2->Data, d1->Length)) { - return CSSM_FALSE; - } - return CSSM_TRUE; -} - -/* - * Init CSSM; returns CSSM_FALSE on error. Reusable. - */ -static CSSM_BOOL cssmInitd = CSSM_FALSE; - -CSSM_BOOL cuCssmStartup() -{ - CSSM_RETURN crtn; - CSSM_PVC_MODE pvcPolicy = CSSM_PVC_NONE; - - if(cssmInitd) { - return CSSM_TRUE; - } - crtn = CSSM_Init (&vers, - CSSM_PRIVILEGE_SCOPE_NONE, - &testGuid, - CSSM_KEY_HIERARCHY_NONE, - &pvcPolicy, - NULL /* reserved */); - if(crtn != CSSM_OK) - { - cuPrintError("CSSM_Init", crtn); - return CSSM_FALSE; - } - else { - cssmInitd = CSSM_TRUE; - return CSSM_TRUE; - } -} - -/* - * Attach to CSP. Returns zero on error. - */ -CSSM_CSP_HANDLE cuCspStartup( - CSSM_BOOL bareCsp) // true ==> CSP, false ==> CSP/DL -{ - CSSM_CSP_HANDLE cspHand; - CSSM_RETURN crtn; - const CSSM_GUID *guid; - - /* common CSSM init */ - if(cuCssmStartup() == CSSM_FALSE) { - return 0; - } - if(bareCsp) { - guid = &gGuidAppleCSP; - } - else { - guid = &gGuidAppleCSPDL; - } - crtn = CSSM_ModuleLoad(guid, - CSSM_KEY_HIERARCHY_NONE, - NULL, // eventHandler - NULL); // AppNotifyCallbackCtx - if(crtn) { - cuPrintError("CSSM_ModuleLoad()", crtn); - return 0; - } - crtn = CSSM_ModuleAttach (guid, - &vers, - &memFuncs, // memFuncs - 0, // SubserviceID - CSSM_SERVICE_CSP, - 0, // AttachFlags - CSSM_KEY_HIERARCHY_NONE, - NULL, // FunctionTable - 0, // NumFuncTable - NULL, // reserved - &cspHand); - if(crtn) { - cuPrintError("CSSM_ModuleAttach()", crtn); - return 0; - } - return cspHand; -} - -/* Attach to DL side of CSPDL */ -CSSM_DL_HANDLE cuDlStartup() -{ - CSSM_DL_HANDLE dlHand = 0; - CSSM_RETURN crtn; - - if(cuCssmStartup() == CSSM_FALSE) { - return 0; - } - crtn = CSSM_ModuleLoad(&gGuidAppleCSPDL, - CSSM_KEY_HIERARCHY_NONE, - NULL, // eventHandler - NULL); // AppNotifyCallbackCtx - if(crtn) { - cuPrintError("CSSM_ModuleLoad(Apple CSPDL)", crtn); - return 0; - } - crtn = CSSM_ModuleAttach (&gGuidAppleCSPDL, - &vers, - &memFuncs, // memFuncs - 0, // SubserviceID - CSSM_SERVICE_DL, - 0, // AttachFlags - CSSM_KEY_HIERARCHY_NONE, - NULL, // FunctionTable - 0, // NumFuncTable - NULL, // reserved - &dlHand); - if(crtn) { - cuPrintError("CSSM_ModuleAttach(Apple CSPDL)", crtn); - return 0; - } - return dlHand; -} - -CSSM_CL_HANDLE cuClStartup() -{ - CSSM_CL_HANDLE clHand; - CSSM_RETURN crtn; - - if(cuCssmStartup() == CSSM_FALSE) { - return 0; - } - crtn = CSSM_ModuleLoad(&gGuidAppleX509CL, - CSSM_KEY_HIERARCHY_NONE, - NULL, // eventHandler - NULL); // AppNotifyCallbackCtx - if(crtn) { - cuPrintError("CSSM_ModuleLoad(AppleCL)", crtn); - return 0; - } - crtn = CSSM_ModuleAttach (&gGuidAppleX509CL, - &vers, - &memFuncs, // memFuncs - 0, // SubserviceID - CSSM_SERVICE_CL, // SubserviceFlags - Where is this used? - 0, // AttachFlags - CSSM_KEY_HIERARCHY_NONE, - NULL, // FunctionTable - 0, // NumFuncTable - NULL, // reserved - &clHand); - if(crtn) { - cuPrintError("CSSM_ModuleAttach(AppleCL)", crtn); - return 0; - } - else { - return clHand; - } -} - -CSSM_TP_HANDLE cuTpStartup() -{ - CSSM_TP_HANDLE tpHand; - CSSM_RETURN crtn; - - if(cuCssmStartup() == CSSM_FALSE) { - return 0; - } - crtn = CSSM_ModuleLoad(&gGuidAppleX509TP, - CSSM_KEY_HIERARCHY_NONE, - NULL, // eventHandler - NULL); // AppNotifyCallbackCtx - if(crtn) { - cuPrintError("CSSM_ModuleLoad(AppleTP)", crtn); - return 0; - } - crtn = CSSM_ModuleAttach (&gGuidAppleX509TP, - &vers, - &memFuncs, // memFuncs - 0, // SubserviceID - CSSM_SERVICE_TP, // SubserviceFlags - 0, // AttachFlags - CSSM_KEY_HIERARCHY_NONE, - NULL, // FunctionTable - 0, // NumFuncTable - NULL, // reserved - &tpHand); - if(crtn) { - cuPrintError("CSSM_ModuleAttach(AppleTP)", crtn); - return 0; - } - else { - return tpHand; - } -} - -/* detach and unload */ -CSSM_RETURN cuCspDetachUnload( - CSSM_CSP_HANDLE cspHand, - CSSM_BOOL bareCsp) // true ==> CSP, false ==> CSP/DL -{ - CSSM_RETURN crtn = CSSM_ModuleDetach(cspHand); - if(crtn) { - return crtn; - } - const CSSM_GUID *guid; - if(bareCsp) { - guid = &gGuidAppleCSP; - } - else { - guid = &gGuidAppleCSPDL; - } - return CSSM_ModuleUnload(guid, NULL, NULL); -} - -CSSM_RETURN cuClDetachUnload( - CSSM_CL_HANDLE clHand) -{ - CSSM_RETURN crtn = CSSM_ModuleDetach(clHand); - if(crtn) { - return crtn; - } - return CSSM_ModuleUnload(&gGuidAppleX509CL, NULL, NULL); - -} - -CSSM_RETURN cuDlDetachUnload( - CSSM_DL_HANDLE dlHand) -{ - CSSM_RETURN crtn = CSSM_ModuleDetach(dlHand); - if(crtn) { - return crtn; - } - return CSSM_ModuleUnload(&gGuidAppleCSPDL, NULL, NULL); - -} -CSSM_RETURN cuTpDetachUnload( - CSSM_TP_HANDLE tpHand) -{ - CSSM_RETURN crtn = CSSM_ModuleDetach(tpHand); - if(crtn) { - return crtn; - } - return CSSM_ModuleUnload(&gGuidAppleX509TP, NULL, NULL); - -} - -/* - * open a DB, ensure it's empty. - */ -CSSM_DB_HANDLE cuDbStartup( - CSSM_DL_HANDLE dlHand, // from dlStartup() - const char *dbName) -{ - CSSM_DB_HANDLE dbHand = 0; - CSSM_RETURN crtn; - CSSM_DBINFO dbInfo; - - /* first delete possible existing DB, ignore error */ - crtn = CSSM_DL_DbDelete(dlHand, dbName, NULL, NULL); - switch(crtn) { - /* only allowed error is "no such file" */ - case CSSM_OK: - case CSSMERR_DL_DATASTORE_DOESNOT_EXIST: - break; - default: - cuPrintError("CSSM_DL_DbDelete", crtn); - return 0; - } - - memset(&dbInfo, 0, sizeof(CSSM_DBINFO)); - - /* now create it */ - crtn = CSSM_DL_DbCreate(dlHand, - dbName, - NULL, // DbLocation - &dbInfo, - // &Security::KeychainCore::Schema::DBInfo, - CSSM_DB_ACCESS_PRIVILEGED, - NULL, // CredAndAclEntry - NULL, // OpenParameters - &dbHand); - if(crtn) { - cuPrintError("CSSM_DL_DbCreate", crtn); - } - return dbHand; -} - -/* - * Attach to existing DB or create an empty new one. - */ -CSSM_DB_HANDLE cuDbStartupByName(CSSM_DL_HANDLE dlHand, - char *dbName, - CSSM_BOOL doCreate, - CSSM_BOOL quiet) -{ - CSSM_RETURN crtn; - CSSM_DB_HANDLE dbHand; - - /* try open existing DB in either case */ - - crtn = CSSM_DL_DbOpen(dlHand, - dbName, - NULL, // DbLocation - CSSM_DB_ACCESS_READ | CSSM_DB_ACCESS_WRITE, - NULL, // CSSM_ACCESS_CREDENTIALS *AccessCred - NULL, // void *OpenParameters - &dbHand); - if(crtn == CSSM_OK) { - return dbHand; - } - if(!doCreate) { - if(!quiet) { - printf("***no such data base (%s)\n", dbName); - cuPrintError("CSSM_DL_DbOpen", crtn); - } - return 0; - } - /* have to create one */ - return cuDbStartup(dlHand, dbName); -} - -/* - * Given a context specified via a CSSM_CC_HANDLE, add a new - * CSSM_CONTEXT_ATTRIBUTE to the context as specified by AttributeType, - * AttributeLength, and an untyped pointer. - */ -static -CSSM_RETURN cuAddContextAttribute(CSSM_CC_HANDLE CCHandle, - uint32 AttributeType, - uint32 AttributeLength, - const void *AttributePtr) -{ - CSSM_CONTEXT_ATTRIBUTE newAttr; - CSSM_RETURN crtn; - - newAttr.AttributeType = AttributeType; - newAttr.AttributeLength = AttributeLength; - newAttr.Attribute.Data = (CSSM_DATA_PTR)AttributePtr; - crtn = CSSM_UpdateContextAttributes(CCHandle, 1, &newAttr); - if(crtn) { - cuPrintError("CSSM_UpdateContextAttributes", crtn); - } - return crtn; -} - - -/* - * Derive symmetric key. - * Note in the X CSP, we never return an IV. - */ -CSSM_RETURN cuCspDeriveKey(CSSM_CSP_HANDLE cspHand, - uint32 keyAlg, // CSSM_ALGID_RC5, etc. - const char *keyLabel, - unsigned keyLabelLen, - uint32 keyUsage, // CSSM_KEYUSE_ENCRYPT, etc. - uint32 keySizeInBits, - CSSM_DATA_PTR password, // in PKCS-5 lingo - CSSM_DATA_PTR salt, // ditto - uint32 iterationCnt, // ditto - CSSM_KEY_PTR key) -{ - CSSM_RETURN crtn; - CSSM_CC_HANDLE ccHand; - uint32 keyAttr; - CSSM_DATA dummyLabel; - CSSM_PKCS5_PBKDF2_PARAMS pbeParams; - CSSM_DATA pbeData; - CSSM_ACCESS_CREDENTIALS creds; - - memset(key, 0, sizeof(CSSM_KEY)); - memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS)); - crtn = CSSM_CSP_CreateDeriveKeyContext(cspHand, - CSSM_ALGID_PKCS5_PBKDF2, - keyAlg, - keySizeInBits, - &creds, - NULL, // BaseKey - iterationCnt, - salt, - NULL, // seed - &ccHand); - if(crtn) { - cuPrintError("CSSM_CSP_CreateDeriveKeyContext", crtn); - return crtn; - } - keyAttr = CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_RETURN_REF | - CSSM_KEYATTR_SENSITIVE; - dummyLabel.Length = keyLabelLen; - dummyLabel.Data = (uint8 *)keyLabel; - - /* passing in password is pretty strange....*/ - pbeParams.Passphrase = *password; - pbeParams.PseudoRandomFunction = CSSM_PKCS5_PBKDF2_PRF_HMAC_SHA1; - pbeData.Data = (uint8 *)&pbeParams; - pbeData.Length = sizeof(pbeParams); - crtn = CSSM_DeriveKey(ccHand, - &pbeData, - keyUsage, - keyAttr, - &dummyLabel, - NULL, // cred and acl - key); - if(crtn) { - cuPrintError("CSSM_DeriveKey", crtn); - return crtn; - } - crtn = CSSM_DeleteContext(ccHand); - if(crtn) { - cuPrintError("CSSM_DeleteContext", crtn); - } - return crtn; -} - -/* - * Generate key pair of arbitrary algorithm. - */ - -/* CSP DL currently does not perform DSA generate params; let CSP do it implicitly */ -#define DO_DSA_GEN_PARAMS 0 - -CSSM_RETURN cuCspGenKeyPair(CSSM_CSP_HANDLE cspHand, - CSSM_DL_DB_HANDLE *dlDbHand, // optional - uint32 algorithm, - const char *keyLabel, - unsigned keyLabelLen, - uint32 keySize, // in bits - CSSM_KEY_PTR pubKey, // mallocd by caller - CSSM_KEYUSE pubKeyUsage, // CSSM_KEYUSE_ENCRYPT, etc. - CSSM_KEYATTR_FLAGS pubAttrs, // CSSM_KEYATTR_EXTRACTABLE, etc. - CSSM_KEY_PTR privKey, // mallocd by caller - CSSM_KEYUSE privKeyUsage, // CSSM_KEYUSE_DECRYPT, etc. - CSSM_KEYATTR_FLAGS privAttrs) // CSSM_KEYATTR_EXTRACTABLE, etc. -{ - CSSM_RETURN crtn; - CSSM_RETURN ocrtn; - CSSM_CC_HANDLE ccHand; - CSSM_DATA keyLabelData; - - keyLabelData.Data = (uint8 *)keyLabel, - keyLabelData.Length = keyLabelLen; - memset(pubKey, 0, sizeof(CSSM_KEY)); - memset(privKey, 0, sizeof(CSSM_KEY)); - - crtn = CSSM_CSP_CreateKeyGenContext(cspHand, - algorithm, - keySize, - NULL, // Seed - NULL, // Salt - NULL, // StartDate - NULL, // EndDate - NULL, // Params - &ccHand); - if(crtn) { - cuPrintError("CSSM_CSP_CreateKeyGenContext", crtn); - return crtn; - } - - /* post-context-create algorithm-specific stuff */ - switch(algorithm) { - #if DO_DSA_GEN_PARAMS - case CSSM_ALGID_DSA: - /* - * extra step - generate params - this just adds some - * info to the context - */ - { - CSSM_DATA dummy = {0, NULL}; - crtn = CSSM_GenerateAlgorithmParams(ccHand, - keySize, &dummy); - if(crtn) { - cuPrintError("CSSM_GenerateAlgorithmParams", crtn); - CSSM_DeleteContext(ccHand); - return crtn; - } - cuAppFree(dummy.Data, NULL); - } - break; - #endif /* DO_DSA_GEN_PARAMS */ - default: - break; - } - - /* optionally specify DL/DB storage location */ - if(dlDbHand) { - crtn = cuAddContextAttribute(ccHand, - CSSM_ATTRIBUTE_DL_DB_HANDLE, - sizeof(CSSM_ATTRIBUTE_DL_DB_HANDLE), - dlDbHand); - if(crtn) { - CSSM_DeleteContext(ccHand); - return crtn; - } - } - ocrtn = CSSM_GenerateKeyPair(ccHand, - pubKeyUsage, - pubAttrs, - &keyLabelData, - pubKey, - privKeyUsage, - privAttrs, - &keyLabelData, // same labels - NULL, // CredAndAclEntry - privKey); - if(ocrtn) { - cuPrintError("CSSM_GenerateKeyPair", ocrtn); - } - crtn = CSSM_DeleteContext(ccHand); - if(crtn) { - cuPrintError("CSSM_DeleteContext", crtn); - if(ocrtn == CSSM_OK) { - /* error on CSSM_GenerateKeyPair takes precedence */ - ocrtn = crtn; - } - } - return ocrtn; -} - - -/* - * Add a certificate to an open Keychain. - */ -CSSM_RETURN cuAddCertToKC( - SecKeychainRef keychain, - const CSSM_DATA *cert, - CSSM_CERT_TYPE certType, - CSSM_CERT_ENCODING certEncoding, - const char *printName, // C string - const CSSM_DATA *keyLabel) // ?? -{ - SecCertificateRef certificate; - - OSStatus rslt = SecCertificateCreateFromData(cert, certType, certEncoding, &certificate); - if (!rslt) - { - rslt = SecCertificateAddToKeychain(certificate, keychain); - CFRelease(certificate); - } - - return rslt; -} - -/* - * Convert a CSSM_DATA_PTR, referring to a DER-encoded int, to an - * unsigned. - */ -unsigned cuDER_ToInt(const CSSM_DATA *DER_Data) -{ - uint32 rtn = 0; - unsigned i = 0; - - while(i < DER_Data->Length) { - rtn |= DER_Data->Data[i]; - if(++i == DER_Data->Length) { - break; - } - rtn <<= 8; - } - return rtn; -} - -/* - * Log CSSM error. - */ -void cuPrintError(const char *op, CSSM_RETURN err) -{ - cssmPerror(op, err); -} - -/* - * Verify a CRL against system anchors and intermediate certs. - */ -CSSM_RETURN cuCrlVerify( - CSSM_TP_HANDLE tpHand, - CSSM_CL_HANDLE clHand, - CSSM_CSP_HANDLE cspHand, - const CSSM_DATA *crlData, - CSSM_DL_DB_HANDLE_PTR certKeychain, // intermediate certs - const CSSM_DATA *anchors, // optional - if NULL, use Trust Settings - uint32 anchorCount) -{ - /* main job is building a CSSM_TP_VERIFY_CONTEXT and its components */ - CSSM_TP_VERIFY_CONTEXT vfyCtx; - CSSM_TP_CALLERAUTH_CONTEXT authCtx; - - memset(&vfyCtx, 0, sizeof(CSSM_TP_VERIFY_CONTEXT)); - memset(&authCtx, 0, sizeof(CSSM_TP_CALLERAUTH_CONTEXT)); - - /* CSSM_TP_CALLERAUTH_CONTEXT components */ - /* - typedef struct cssm_tp_callerauth_context { - CSSM_TP_POLICYINFO Policy; - CSSM_TIMESTRING VerifyTime; - CSSM_TP_STOP_ON VerificationAbortOn; - CSSM_TP_VERIFICATION_RESULTS_CALLBACK CallbackWithVerifiedCert; - uint32 NumberOfAnchorCerts; - CSSM_DATA_PTR AnchorCerts; - CSSM_DL_DB_LIST_PTR DBList; - CSSM_ACCESS_CREDENTIALS_PTR CallerCredentials; - } CSSM_TP_CALLERAUTH_CONTEXT, *CSSM_TP_CALLERAUTH_CONTEXT_PTR; - */ - CSSM_FIELD policyId; - CSSM_APPLE_TP_CRL_OPTIONS crlOpts; - policyId.FieldOid = CSSMOID_APPLE_TP_REVOCATION_CRL; - policyId.FieldValue.Data = (uint8 *)&crlOpts; - policyId.FieldValue.Length = sizeof(crlOpts); - crlOpts.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION; - /* perhaps this should be user-specifiable */ - crlOpts.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET; - crlOpts.crlStore = NULL; - - authCtx.Policy.NumberOfPolicyIds = 1; - authCtx.Policy.PolicyIds = &policyId; - authCtx.Policy.PolicyControl = NULL; - - authCtx.VerifyTime = NULL; - authCtx.VerificationAbortOn = CSSM_TP_STOP_ON_POLICY; - authCtx.CallbackWithVerifiedCert = NULL; - - /* anchors */ - authCtx.NumberOfAnchorCerts = anchorCount; - authCtx.AnchorCerts = const_cast(anchors); - - /* DBList of intermediate certs, plus possible System.keychain and - * system roots */ - CSSM_DL_DB_HANDLE handles[3]; - unsigned numDbs = 0; - CSSM_DL_HANDLE dlHand = 0; - if(certKeychain != NULL) { - handles[0] = *certKeychain; - numDbs++; - } - if(anchors == NULL) { - /* Trust Settings requires two more DBs */ - if(numDbs == 0) { - /* new DL handle */ - dlHand = cuDlStartup(); - handles[numDbs].DLHandle = dlHand; - handles[numDbs + 1].DLHandle = dlHand; - } - else { - /* use the same one passed in for certKeychain */ - handles[numDbs].DLHandle = handles[0].DLHandle; - handles[numDbs + 1].DLHandle = handles[0].DLHandle; - } - handles[numDbs].DBHandle = cuDbStartupByName(handles[numDbs].DLHandle, - (char*) ADMIN_CERT_STORE_PATH, CSSM_FALSE, CSSM_TRUE); - numDbs++; - - handles[numDbs].DBHandle = cuDbStartupByName(handles[numDbs].DLHandle, - (char*) SYSTEM_ROOT_STORE_PATH, CSSM_FALSE, CSSM_TRUE); - numDbs++; - } - CSSM_DL_DB_LIST dlDbList; - dlDbList.DLDBHandle = handles; - dlDbList.NumHandles = numDbs; - - authCtx.DBList = &dlDbList; - authCtx.CallerCredentials = NULL; - - /* CSSM_TP_VERIFY_CONTEXT */ - vfyCtx.ActionData.Data = NULL; - vfyCtx.ActionData.Length = 0; - vfyCtx.Action = CSSM_TP_ACTION_DEFAULT; - vfyCtx.Cred = &authCtx; - - /* CSSM_APPLE_TP_ACTION_DATA */ - CSSM_APPLE_TP_ACTION_DATA tpAction; - if(anchors == NULL) { - /* enable Trust Settings */ - tpAction.Version = CSSM_APPLE_TP_ACTION_VERSION; - tpAction.ActionFlags = CSSM_TP_ACTION_TRUST_SETTINGS; - vfyCtx.ActionData.Data = (uint8 *)&tpAction; - vfyCtx.ActionData.Length = sizeof(tpAction); - } - - /* cook up CSSM_ENCODED_CRL */ - CSSM_ENCODED_CRL encCrl; - encCrl.CrlType = CSSM_CRL_TYPE_X_509v2; - encCrl.CrlEncoding = CSSM_CRL_ENCODING_DER; - encCrl.CrlBlob = *crlData; - - /* CDSA API requires a SignerCertGroup; for us, all the certs are in - * certKeyChain... */ - CSSM_CERTGROUP certGroup; - certGroup.CertType = CSSM_CERT_X_509v1; - certGroup.CertEncoding = CSSM_CERT_ENCODING_DER; - certGroup.NumCerts = 0; - certGroup.GroupList.CertList = NULL; - certGroup.CertGroupType = CSSM_CERTGROUP_DATA; - - CSSM_RETURN crtn = CSSM_TP_CrlVerify(tpHand, - clHand, - cspHand, - &encCrl, - &certGroup, - &vfyCtx, - NULL); // RevokerVerifyResult - if(crtn) { - cuPrintError("CSSM_TP_CrlVerify", crtn); - } - if(anchors == NULL) { - /* close the DBs and maybe the DL we opened */ - unsigned dexToClose = (certKeychain == NULL) ? 0 : 1; - CSSM_DL_DbClose(handles[dexToClose++]); - CSSM_DL_DbClose(handles[dexToClose]); - if(dlHand != 0) { - cuDlDetachUnload(dlHand); - } - } - return crtn; -} - diff --git a/OSX/include/security_cdsa_utils/cuCdsaUtils.h b/OSX/include/security_cdsa_utils/cuCdsaUtils.h deleted file mode 100644 index cac544eb..00000000 --- a/OSX/include/security_cdsa_utils/cuCdsaUtils.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2001-2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuCdsaUtils.h - - Description: common CDSA access utilities - - Author: dmitch -*/ - -#ifndef _COMMON_CDSA_UTILS_H_ -#define _COMMON_CDSA_UTILS_H_ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* common memory allocators shared by app and CSSM */ -extern void * cuAppMalloc (CSSM_SIZE size, void *allocRef); -extern void cuAppFree (void *mem_ptr, void *allocRef); -extern void * cuAppRealloc (void *ptr, CSSM_SIZE size, void *allocRef); -extern void * cuAppCalloc (uint32 num, CSSM_SIZE size, void *allocRef); - -#define APP_MALLOC(s) cuAppMalloc(s, NULL) -#define APP_FREE(p) cuAppFree(p, NULL) -#define APP_REALLOC(p, s) cuAppRealloc(p, s, NULL) -#define APP_CALLOC(n, s) cuAppRealloc(n, s, NULL) - -extern CSSM_BOOL cuCompareCssmData( - const CSSM_DATA *d1, - const CSSM_DATA *d2); - -/* OID flavor of same, which will break when an OID is not a CSSM_DATA */ -#define cuCompareOid(o1, o2) cuCompareCssmData(o1, o2) - -void cuPrintError(const char *op, CSSM_RETURN err); - -/* Init CSSM; returns CSSM_FALSE on error. Reusable. */ -extern CSSM_BOOL cuCssmStartup(); - -/* Attach to CSP. Returns zero on error. */ -extern CSSM_CSP_HANDLE cuCspStartup( - CSSM_BOOL bareCsp); // true ==> CSP, false ==> CSP/DL - -/* Attach to DL side of CSPDL. */ -extern CSSM_DL_HANDLE cuDlStartup(); - -/* Attach to CL, TP */ -extern CSSM_CL_HANDLE cuClStartup(); -extern CSSM_TP_HANDLE cuTpStartup(); - -/* Open a DB, ensure it's empty. */ -CSSM_DB_HANDLE cuDbStartup( - CSSM_DL_HANDLE dlHand, // from dlStartup() - const char *dbName); - -/* Attach to existing DB or create an empty new one. */ -CSSM_DB_HANDLE cuDbStartupByName(CSSM_DL_HANDLE dlHand, - char *dbName, - CSSM_BOOL doCreate, - CSSM_BOOL quiet); - -/* detach and unload */ -CSSM_RETURN cuCspDetachUnload( - CSSM_CSP_HANDLE cspHand, - CSSM_BOOL bareCsp); // true ==> CSP, false ==> CSP/DL -CSSM_RETURN cuClDetachUnload( - CSSM_CL_HANDLE clHand); -CSSM_RETURN cuDlDetachUnload( - CSSM_DL_HANDLE dlHand); -CSSM_RETURN cuTpDetachUnload( - CSSM_TP_HANDLE tpHand); -/* - * Derive symmetric key using PBE. - */ -extern CSSM_RETURN cuCspDeriveKey(CSSM_CSP_HANDLE cspHand, - uint32 keyAlg, // CSSM_ALGID_RC5, etc. - const char *keyLabel, - unsigned keyLabelLen, - uint32 keyUsage, // CSSM_KEYUSE_ENCRYPT, etc. - uint32 keySizeInBits, - CSSM_DATA_PTR password, // in PKCS-5 lingo - CSSM_DATA_PTR salt, // ditto - uint32 iterationCnt, // ditto - CSSM_KEY_PTR key); - -/* - * Generate key pair of arbitrary algorithm. - */ -extern CSSM_RETURN cuCspGenKeyPair(CSSM_CSP_HANDLE cspHand, - CSSM_DL_DB_HANDLE *dlDbHand, // optional - uint32 algorithm, - const char *keyLabel, - unsigned keyLabelLen, - uint32 keySize, // in bits - CSSM_KEY_PTR pubKey, // mallocd by caller - CSSM_KEYUSE pubKeyUsage, // CSSM_KEYUSE_ENCRYPT, etc. - CSSM_KEYATTR_FLAGS pubAttrs, // CSSM_KEYATTR_EXTRACTABLE, etc. - CSSM_KEY_PTR privKey, // mallocd by caller - CSSM_KEYUSE privKeyUsage, // CSSM_KEYUSE_DECRYPT, etc. - CSSM_KEYATTR_FLAGS privAttrs); // CSSM_KEYATTR_EXTRACTABLE, etc. - -/* Convert a reference key to a raw key. */ -CSSM_RETURN cuRefKeyToRaw(CSSM_CSP_HANDLE cspHand, - const CSSM_KEY *refKey, - CSSM_KEY_PTR rawKey); // RETURNED - -/* - * Add a certificate to a keychain. - */ -CSSM_RETURN cuAddCertToKC( - SecKeychainRef keychain, - const CSSM_DATA *cert, - CSSM_CERT_TYPE certType, - CSSM_CERT_ENCODING certEncoding, - const char *printName, // C string - const CSSM_DATA *keyLabel); // ?? - -/* - * Convert a CSSM_DATA_PTR, referring to a DER-encoded int, to an - * unsigned. - */ -unsigned cuDER_ToInt( - const CSSM_DATA *DER_Data); - -/* - * Verify a CRL against system anchors and intermediate certs. - */ -CSSM_RETURN cuCrlVerify( - CSSM_TP_HANDLE tpHand, - CSSM_CL_HANDLE clHand, - CSSM_CSP_HANDLE cspHand, - const CSSM_DATA *crlData, - CSSM_DL_DB_HANDLE_PTR certKeychain, // intermediate certs - const CSSM_DATA *anchors, // optional - if NULL, use Trust Settings - uint32 anchorCount); - -#ifdef __cplusplus -} -#endif - -#endif /* _COMMON_CDSA_UTILS_H_ */ diff --git a/OSX/include/security_cdsa_utils/cuDbUtils.cpp b/OSX/include/security_cdsa_utils/cuDbUtils.cpp deleted file mode 100644 index 9e8f65a0..00000000 --- a/OSX/include/security_cdsa_utils/cuDbUtils.cpp +++ /dev/null @@ -1,574 +0,0 @@ -/* - * Copyright (c) 2002-2003,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. - * Please obtain a copy of the License at http://www.apple.com/publicsource - * and read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights - * and limitations under the License. - */ - -/* - File: cuDbUtils.cpp - - Description: CDSA DB access utilities - - Author: dmitch -*/ - -#include "cuCdsaUtils.h" -#include "cuTimeStr.h" -#include "cuDbUtils.h" -#include "cuPrintCert.h" -#include -#include -#include -#include /* private SecInferLabelFromX509Name() */ -#include /* for cssmPerror() */ -#include -#include -#include -#include -#include /* private API */ - -#ifndef NDEBUG -#define dprintf(args...) printf(args) -#else -#define dprintf(args...) -#endif - -/* - * Add a certificate to an open DLDB. - */ -CSSM_RETURN cuAddCertToDb( - CSSM_DL_DB_HANDLE dlDbHand, - const CSSM_DATA *cert, - CSSM_CERT_TYPE certType, - CSSM_CERT_ENCODING certEncoding, - const char *printName, // C string - const CSSM_DATA *publicKeyHash) -{ - CSSM_DB_ATTRIBUTE_DATA attrs[6]; - CSSM_DB_RECORD_ATTRIBUTE_DATA recordAttrs; - CSSM_DB_ATTRIBUTE_DATA_PTR attr = &attrs[0]; - CSSM_DATA certTypeData; - CSSM_DATA certEncData; - CSSM_DATA printNameData; - CSSM_RETURN crtn; - CSSM_DB_UNIQUE_RECORD_PTR recordPtr; - - /* issuer and serial number required, fake 'em */ - CSSM_DATA issuer = {6, (uint8 *)"issuer"}; - CSSM_DATA serial = {6, (uint8 *)"serial"}; - - /* we spec six attributes, skipping alias */ - certTypeData.Data = (uint8 *)&certType; - certTypeData.Length = sizeof(CSSM_CERT_TYPE); - certEncData.Data = (uint8 *)&certEncoding; - certEncData.Length = sizeof(CSSM_CERT_ENCODING); - printNameData.Data = (uint8 *)printName; - printNameData.Length = strlen(printName) + 1; - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "CertType"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_UINT32; - attr->NumberOfValues = 1; - attr->Value = &certTypeData; - - attr++; - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "CertEncoding"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_UINT32; - attr->NumberOfValues = 1; - attr->Value = &certEncData; - - attr++; - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "PrintName"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &printNameData; - - attr++; - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "PublicKeyHash"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = (CSSM_DATA_PTR)publicKeyHash; - - attr++; - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "Issuer"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &issuer; - - attr++; - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "SerialNumber"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &serial; - - recordAttrs.DataRecordType = CSSM_DL_DB_RECORD_X509_CERTIFICATE; - recordAttrs.SemanticInformation = 0; - recordAttrs.NumberOfAttributes = 6; - recordAttrs.AttributeData = attrs; - - crtn = CSSM_DL_DataInsert(dlDbHand, - CSSM_DL_DB_RECORD_X509_CERTIFICATE, - &recordAttrs, - cert, - &recordPtr); - if(crtn) { - cuPrintError("CSSM_DL_DataInsert", crtn); - } - else { - CSSM_DL_FreeUniqueRecord(dlDbHand, recordPtr); - } - return crtn; -} - -static CSSM_RETURN cuAddCrlSchema( - CSSM_DL_DB_HANDLE dlDbHand); - -static void cuInferCrlLabel( - const CSSM_X509_NAME *x509Name, - CSSM_DATA *label) // not mallocd; contents are from the x509Name -{ - /* use private API for common "infer label" logic */ - const CSSM_DATA *printValue = SecInferLabelFromX509Name(x509Name); - if(printValue == NULL) { - /* punt! */ - label->Data = (uint8 *)"X509 CRL"; - label->Length = 8; - } - else { - *label = *printValue; - } -} - -/* - * Search extensions for specified OID, assumed to have underlying - * value type of uint32; returns the value and true if found. - */ -static bool cuSearchNumericExtension( - const CSSM_X509_EXTENSIONS *extens, - const CSSM_OID *oid, - uint32 *val) -{ - for(uint32 dex=0; dexnumberOfExtensions; dex++) { - const CSSM_X509_EXTENSION *exten = &extens->extensions[dex]; - if(!cuCompareOid(&exten->extnId, oid)) { - continue; - } - if(exten->format != CSSM_X509_DATAFORMAT_PARSED) { - dprintf("***Malformed extension\n"); - continue; - } - *val = *((uint32 *)exten->value.parsedValue); - return true; - } - return false; -} - -/* - * Add a CRL to an existing DL/DB. - */ -#define MAX_CRL_ATTRS 9 - -CSSM_RETURN cuAddCrlToDb( - CSSM_DL_DB_HANDLE dlDbHand, - CSSM_CL_HANDLE clHand, - const CSSM_DATA *crl, - const CSSM_DATA *URI) // optional -{ - CSSM_DB_ATTRIBUTE_DATA attrs[MAX_CRL_ATTRS]; - CSSM_DB_RECORD_ATTRIBUTE_DATA recordAttrs; - CSSM_DB_ATTRIBUTE_DATA_PTR attr = &attrs[0]; - CSSM_DATA crlTypeData; - CSSM_DATA crlEncData; - CSSM_DATA printNameData; - CSSM_RETURN crtn; - CSSM_DB_UNIQUE_RECORD_PTR recordPtr; - CSSM_DATA_PTR issuer = NULL; // mallocd by CL - CSSM_DATA_PTR crlValue = NULL; // ditto - uint32 numFields; - CSSM_HANDLE result; - CSSM_CRL_ENCODING crlEnc = CSSM_CRL_ENCODING_DER; - const CSSM_X509_SIGNED_CRL *signedCrl; - const CSSM_X509_TBS_CERTLIST *tbsCrl; - CSSM_CRL_TYPE crlType; - CSSM_DATA thisUpdateData = {0, NULL}; - CSSM_DATA nextUpdateData = {0, NULL}; - char *thisUpdate = NULL; - char *nextUpdate = NULL; - unsigned timeLen; - uint32 crlNumber; - uint32 deltaCrlNumber; - CSSM_DATA crlNumberData; - CSSM_DATA deltaCrlNumberData; - bool crlNumberPresent = false; - bool deltaCrlPresent = false; - CSSM_DATA attrUri; - - /* get normalized issuer name as Issuer attr */ - crtn = CSSM_CL_CrlGetFirstFieldValue(clHand, - crl, - &CSSMOID_X509V1IssuerName, - &result, - &numFields, - &issuer); - if(crtn) { - cuPrintError("CSSM_CL_CrlGetFirstFieldValue(Issuer)", crtn); - return crtn; - } - CSSM_CL_CrlAbortQuery(clHand, result); - - /* get parsed CRL from the CL */ - crtn = CSSM_CL_CrlGetFirstFieldValue(clHand, - crl, - &CSSMOID_X509V2CRLSignedCrlCStruct, - &result, - &numFields, - &crlValue); - if(crtn) { - cuPrintError("CSSM_CL_CrlGetFirstFieldValue(Issuer)", crtn); - goto errOut; - } - CSSM_CL_CrlAbortQuery(clHand, result); - if(crlValue == NULL) { - dprintf("***CSSM_CL_CrlGetFirstFieldValue: value error (1)\n"); - crtn = CSSMERR_CL_INVALID_CRL_POINTER; - goto errOut; - } - if((crlValue->Data == NULL) || - (crlValue->Length != sizeof(CSSM_X509_SIGNED_CRL))) { - dprintf("***CSSM_CL_CrlGetFirstFieldValue: value error (2)\n"); - crtn = CSSMERR_CL_INVALID_CRL_POINTER; - goto errOut; - } - signedCrl = (const CSSM_X509_SIGNED_CRL *)crlValue->Data; - tbsCrl = &signedCrl->tbsCertList; - - /* CrlType inferred from version */ - if(tbsCrl->version.Length == 0) { - /* should never happen... */ - crlType = CSSM_CRL_TYPE_X_509v1; - } - else { - uint8 vers = tbsCrl->version.Data[tbsCrl->version.Length - 1]; - switch(vers) { - case 0: - crlType = CSSM_CRL_TYPE_X_509v1; - break; - case 1: - crlType = CSSM_CRL_TYPE_X_509v2; - break; - default: - dprintf("***Unknown version in CRL (%u)\n", vers); - crlType = CSSM_CRL_TYPE_X_509v1; - break; - } - } - crlTypeData.Data = (uint8 *)&crlType; - crlTypeData.Length = sizeof(CSSM_CRL_TYPE); - /* encoding more-or-less assumed here */ - crlEncData.Data = (uint8 *)&crlEnc; - crlEncData.Length = sizeof(CSSM_CRL_ENCODING); - - /* printName inferred from issuer */ - cuInferCrlLabel(&tbsCrl->issuer, &printNameData); - - /* cook up CSSM_TIMESTRING versions of this/next update */ - thisUpdate = cuX509TimeToCssmTimestring(&tbsCrl->thisUpdate, &timeLen); - if(thisUpdate == NULL) { - dprintf("***Badly formatted thisUpdate\n"); - } - else { - thisUpdateData.Data = (uint8 *)thisUpdate; - thisUpdateData.Length = timeLen; - } - if(tbsCrl->nextUpdate.time.Data != NULL) { - nextUpdate = cuX509TimeToCssmTimestring(&tbsCrl->nextUpdate, &timeLen); - if(nextUpdate == NULL) { - dprintf("***Badly formatted nextUpdate\n"); - } - else { - nextUpdateData.Data = (uint8 *)nextUpdate; - nextUpdateData.Length = timeLen; - } - } - else { - /* - * NextUpdate not present; fake it by using "virtual end of time" - */ - CSSM_X509_TIME tempTime = { 0, // timeType, not used - { strlen(CSSM_APPLE_CRL_END_OF_TIME), - (uint8 *)CSSM_APPLE_CRL_END_OF_TIME} }; - nextUpdate = cuX509TimeToCssmTimestring(&tempTime, &timeLen); - nextUpdateData.Data = (uint8 *)nextUpdate; - nextUpdateData.Length = CSSM_TIME_STRLEN; - } - - /* optional CrlNumber and DeltaCrlNumber */ - if(cuSearchNumericExtension(&tbsCrl->extensions, - &CSSMOID_CrlNumber, - &crlNumber)) { - crlNumberData.Data = (uint8 *)&crlNumber; - crlNumberData.Length = sizeof(uint32); - crlNumberPresent = true; - } - if(cuSearchNumericExtension(&tbsCrl->extensions, - &CSSMOID_DeltaCrlIndicator, - &deltaCrlNumber)) { - deltaCrlNumberData.Data = (uint8 *)&deltaCrlNumber; - deltaCrlNumberData.Length = sizeof(uint32); - deltaCrlPresent = true; - } - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "CrlType"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_UINT32; - attr->NumberOfValues = 1; - attr->Value = &crlTypeData; - attr++; - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "CrlEncoding"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_UINT32; - attr->NumberOfValues = 1; - attr->Value = &crlEncData; - attr++; - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "PrintName"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &printNameData; - attr++; - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "Issuer"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = issuer; - attr++; - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "ThisUpdate"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &thisUpdateData; - attr++; - - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "NextUpdate"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &nextUpdateData; - attr++; - - /* now the optional attributes */ - if(crlNumberPresent) { - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "CrlNumber"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_UINT32; - attr->NumberOfValues = 1; - attr->Value = &crlNumberData; - attr++; - } - if(deltaCrlPresent) { - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "DeltaCrlNumber"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_UINT32; - attr->NumberOfValues = 1; - attr->Value = &deltaCrlNumberData; - attr++; - } - if(URI) { - /* ensure URI string does not contain NULL */ - attrUri = *URI; - if((attrUri.Length != 0) && - (attrUri.Data[attrUri.Length - 1] == 0)) { - attrUri.Length--; - } - attr->Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_STRING; - attr->Info.Label.AttributeName = (char*) "URI"; - attr->Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB; - attr->NumberOfValues = 1; - attr->Value = &attrUri; - attr++; - } - recordAttrs.DataRecordType = CSSM_DL_DB_RECORD_X509_CRL; - recordAttrs.SemanticInformation = 0; - recordAttrs.NumberOfAttributes = (uint32)(attr - attrs); - recordAttrs.AttributeData = attrs; - - crtn = CSSM_DL_DataInsert(dlDbHand, - CSSM_DL_DB_RECORD_X509_CRL, - &recordAttrs, - crl, - &recordPtr); - if(crtn == CSSMERR_DL_INVALID_RECORDTYPE) { - /* gross hack of inserting this "new" schema that Keychain didn't specify */ - crtn = cuAddCrlSchema(dlDbHand); - if(crtn == CSSM_OK) { - /* Retry with a fully capable DLDB */ - crtn = CSSM_DL_DataInsert(dlDbHand, - CSSM_DL_DB_RECORD_X509_CRL, - &recordAttrs, - crl, - &recordPtr); - } - } - if(crtn == CSSM_OK) { - CSSM_DL_FreeUniqueRecord(dlDbHand, recordPtr); - } - -errOut: - /* free all the stuff we allocated to get here */ - if(issuer) { - CSSM_CL_FreeFieldValue(clHand, &CSSMOID_X509V1IssuerName, issuer); - } - if(crlValue) { - CSSM_CL_FreeFieldValue(clHand, &CSSMOID_X509V2CRLSignedCrlCStruct, crlValue); - } - if(thisUpdate) { - free(thisUpdate); - } - if(nextUpdate) { - free(nextUpdate); - } - return crtn; -} - - -/* - * Update an existing DLDB to be CRL-capable. - */ -static CSSM_RETURN cuAddCrlSchema( - CSSM_DL_DB_HANDLE dlDbHand) -{ - return CSSM_DL_CreateRelation(dlDbHand, - CSSM_DL_DB_RECORD_X509_CRL, - "CSSM_DL_DB_RECORD_X509_CRL", - Security::KeychainCore::Schema::X509CrlSchemaAttributeCount, - Security::KeychainCore::Schema::X509CrlSchemaAttributeList, - Security::KeychainCore::Schema::X509CrlSchemaIndexCount, - Security::KeychainCore::Schema::X509CrlSchemaIndexList); -} - -/* - * Search DB for all records of type CRL or cert, calling appropriate - * parse/print routine for each record. - */ -CSSM_RETURN cuDumpCrlsCerts( - CSSM_DL_DB_HANDLE dlDbHand, - CSSM_CL_HANDLE clHand, - CSSM_BOOL isCert, - unsigned &numItems, // returned - CSSM_BOOL verbose) -{ - CSSM_QUERY query; - CSSM_DB_UNIQUE_RECORD_PTR record = NULL; - CSSM_HANDLE resultHand; - CSSM_RETURN crtn; - CSSM_DATA certCrl; - const char *itemStr; - - numItems = 0; - itemStr = isCert ? "Certificate" : "CRL"; - - /* just search by recordType, no predicates, no attributes */ - if(isCert) { - query.RecordType = CSSM_DL_DB_RECORD_X509_CERTIFICATE; - } - else { - query.RecordType = CSSM_DL_DB_RECORD_X509_CRL; - } - query.Conjunctive = CSSM_DB_NONE; - query.NumSelectionPredicates = 0; - query.SelectionPredicate = NULL; - query.QueryLimits.TimeLimit = 0; // FIXME - meaningful? - query.QueryLimits.SizeLimit = 1; // FIXME - meaningful? - query.QueryFlags = 0; // CSSM_QUERY_RETURN_DATA...FIXME - used? - - certCrl.Data = NULL; - certCrl.Length = 0; - crtn = CSSM_DL_DataGetFirst(dlDbHand, - &query, - &resultHand, - NULL, // no attrs - &certCrl, - &record); - switch(crtn) { - case CSSM_OK: - break; // proceed - case CSSMERR_DL_ENDOFDATA: - /* no data, otherwise OK */ - return CSSM_OK; - case CSSMERR_DL_INVALID_RECORDTYPE: - /* invalid record type just means "this hasn't been set up - * for certs yet". */ - return crtn; - default: - cuPrintError("DataGetFirst", crtn); - return crtn; - } - - /* got one; print it */ - dprintf("%s %u:\n", itemStr, numItems); - if(isCert) { - printCert(certCrl.Data, (unsigned)certCrl.Length, verbose); - } - else { - printCrl(certCrl.Data, (unsigned)certCrl.Length, verbose); - } - CSSM_DL_FreeUniqueRecord(dlDbHand, record); - APP_FREE(certCrl.Data); - certCrl.Data = NULL; - certCrl.Length = 0; - numItems++; - - /* get the rest */ - for(;;) { - crtn = CSSM_DL_DataGetNext(dlDbHand, - resultHand, - NULL, - &certCrl, - &record); - switch(crtn) { - case CSSM_OK: - dprintf("%s %u:\n", itemStr, numItems); - if(isCert) { - printCert(certCrl.Data, (unsigned)certCrl.Length, verbose); - } - else { - printCrl(certCrl.Data, (unsigned)certCrl.Length, verbose); - } - CSSM_DL_FreeUniqueRecord(dlDbHand, record); - APP_FREE(certCrl.Data); - certCrl.Data = NULL; - certCrl.Length = 0; - numItems++; - break; // and go again - case CSSMERR_DL_ENDOFDATA: - /* normal termination */ - return CSSM_OK; - default: - cuPrintError("DataGetNext", crtn); - return crtn; - } - } - /* NOT REACHED */ -} - diff --git a/OSX/include/security_cdsa_utils/cuDbUtils.h b/OSX/include/security_cdsa_utils/cuDbUtils.h deleted file mode 100644 index c2c0d76d..00000000 --- a/OSX/include/security_cdsa_utils/cuDbUtils.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2002-2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuDbUtils.h - - Description: CDSA DB access utilities - - Author: dmitch -*/ - -#ifndef _CU_DB_UTILS_H_ -#define _CU_DB_UTILS_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Add a certificate to an open DLDB. - */ -CSSM_RETURN cuAddCertToDb( - CSSM_DL_DB_HANDLE dlDbHand, - const CSSM_DATA *cert, - CSSM_CERT_TYPE certType, - CSSM_CERT_ENCODING certEncoding, - const char *printName, // C string - const CSSM_DATA *publicKeyHash); // ?? - -/* - * Add a CRL to an open DL/DB. - */ -CSSM_RETURN cuAddCrlToDb( - CSSM_DL_DB_HANDLE dlDbHand, - CSSM_CL_HANDLE clHand, - const CSSM_DATA *crl, - const CSSM_DATA *URI); // optional - -/* - * Search DB for all records of type CRL or cert, calling appropriate - * parse/print routine for each record. - */ -CSSM_RETURN cuDumpCrlsCerts( - CSSM_DL_DB_HANDLE dlDbHand, - CSSM_CL_HANDLE clHand, - CSSM_BOOL isCert, - unsigned &numItems, // returned - CSSM_BOOL verbose); - -#ifdef __cplusplus -} -#endif - -#endif /* _CU_DB_UTILS_H_ */ diff --git a/OSX/include/security_cdsa_utils/cuEnc64.c b/OSX/include/security_cdsa_utils/cuEnc64.c deleted file mode 100644 index 41e0b005..00000000 --- a/OSX/include/security_cdsa_utils/cuEnc64.c +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Copyright (c) 1998-2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * cuEnc64.c - encode/decode in 64-char IA5 format, per RFC 1421 - */ - -#include "cuEnc64.h" -#include - -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ - -/* - * map a 6-bit binary value to a printable character. - */ -static const -unsigned char bintoasc[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -/* - * Map an 7-bit printable character to its corresponding binary value. - * Any illegal characters return high bit set. - */ -static const -unsigned char asctobin[] = -{ - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x3e, 0x80, 0x80, 0x80, 0x3f, - 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, - 0x3c, 0x3d, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, - 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, - 0x17, 0x18, 0x19, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, 0x33, 0x80, 0x80, 0x80, 0x80, 0x80 -}; - -/* - * map 6 bits to a printing char - */ -#define ENC(c) (bintoasc[((c) & 0x3f)]) - -#define PAD '=' - -/* - * map one group of up to 3 bytes at inp to 4 bytes at outp. - * Count is number of valid bytes in *inp; if less than 3, the - * 1 or two extras must be zeros. - */ -static void encChunk(const unsigned char *inp, - unsigned char *outp, - int count) -{ - unsigned char c1, c2, c3, c4; - - c1 = *inp >> 2; - c2 = ((inp[0] << 4) & 0x30) | ((inp[1] >> 4) & 0xf); - c3 = ((inp[1] << 2) & 0x3c) | ((inp[2] >> 6) & 0x3); - c4 = inp[2] & 0x3f; - *outp++ = ENC(c1); - *outp++ = ENC(c2); - if (count == 1) { - *outp++ = PAD; - *outp = PAD; - } else { - *outp++ = ENC(c3); - if (count == 2) { - *outp = PAD; - } - else { - *outp = ENC(c4); - } - } -} - -/* - * Given input buffer inbuf, length inlen, encode to 64-char IA5 format. - * Result is fmalloc'd and returned; it is terminated by Microsoft-style - * newline and NULL. Its length (including the trailing newline and NULL) - * is returned in *outlen. - */ - -unsigned char *cuEnc64(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen) // RETURNED -{ - return cuEnc64WithLines(inbuf, inlen, 0, outlen); -} - -unsigned char *cuEnc64WithLines(const unsigned char *inbuf, - unsigned inlen, - unsigned linelen, - unsigned *outlen) -{ - unsigned outTextLen; - unsigned len; // to malloc, liberal - unsigned olen = 0; // actual output size - unsigned char *outbuf; - unsigned char endbuf[3]; - unsigned i; - unsigned char *outp; - unsigned numLines; - unsigned thisLine; - - outTextLen = ((inlen + 2) / 3) * 4; - if(linelen) { - /* - * linelen must be 0 mod 4 for this to work; round up... - */ - if((linelen & 0x03) != 0) { - linelen = (linelen + 3) & 0xfffffffc; - } - numLines = (outTextLen + linelen - 1)/ linelen; - } - else { - numLines = 1; - } - - /* - * Total output size = encoded text size plus one newline per - * line of output, plus trailing NULL. We always generate newlines - * as \n; when decoding, we tolerate \r\n (Microsoft) or \n. - */ - len = outTextLen + (2 * numLines) + 1; - outbuf = (unsigned char*)malloc(len); - outp = outbuf; - thisLine = 0; - - while(inlen) { - if(inlen < 3) { - for(i=0; i<3; i++) { - if(i < inlen) { - endbuf[i] = inbuf[i]; - } - else { - endbuf[i] = 0; - } - } - encChunk(endbuf, outp, inlen); - inlen = 0; - } - else { - encChunk(inbuf, outp, 3); - inlen -= 3; - inbuf += 3; - } - outp += 4; - thisLine += 4; - olen += 4; - if((linelen != 0) && (thisLine >= linelen) && inlen) { - /* - * last trailing newline added below - * Note we don't split 4-byte output chunks over newlines - */ - *outp++ = '\n'; - olen++; - thisLine = 0; - } - } - *outp++ = '\n'; - *outp = '\0'; - olen += 2; - *outlen = olen; - return outbuf; -} - -static inline int isWhite(unsigned char c) -{ - switch(c) { - case '\n': - case '\r': - case ' ': - case '\t': - case '\0': - return 1; - default: - return 0; - } -} - -/* - * Strip off all whitespace from a (supposedly) enc64-format string. - * Returns a malloc'd string. - */ -static unsigned char *stringCleanse(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen) -{ - unsigned char *news; // cleansed inbuf - unsigned newsDex; // index into news - unsigned i; - - news = (unsigned char*)malloc(inlen); - newsDex = 0; - for(i=0; i 0) { - goto errorOut; - } - } - else { - goto errorOut; - } - } else if (*bp & 0x80 || (c3 = asctobin[*bp]) & 0x80) { - goto errorOut; - } else { - bp++; - inlen--; - if (*bp == PAD) { - /* - * Three input bytes, two output - */ - c4 = 0; - thisOlen = 2; - if (c3 & 3) { - goto errorOut; - } - } else if (*bp & 0x80 || (c4 = asctobin[*bp]) & 0x80) { - goto errorOut; - } else { - /* - * Normal non-pad case - */ - thisOlen = 3; - } - bp++; - inlen--; - } - j = (c1 << 2) | (c2 >> 4); - *outp++ = j; - if(thisOlen > 1) { - j = (c2 << 4) | (c3 >> 2); - *outp++ = j; - if(thisOlen == 3) { - j = (c3 << 6) | c4; - *outp++ = j; - } - } - olen += thisOlen; - } - free(news); - *outlen = olen; - return outbuf; /* normal return */ - -errorOut: - free(news); - free(outbuf); - return (unsigned char*) NULL; -} - -/* - * Determine if specified input data is valid enc64 format. Returns 1 - * if valid, 0 if not. - * This doesn't do a full enc64 parse job; it scans for legal characters - * and proper sync when a possible pad is found. - */ -int cuIsValidEnc64(const unsigned char *inbuf, - unsigned inlen) -{ - int padChars = 0; // running count of PAD chars - int validEncChars = 0; - unsigned char c; - - /* - * -- scan inbuf - * -- skip whitespace - * -- count valid chars - * -- ensure not more than 2 PAD chars, only at end - * -- ensure valid chars mod 4 == 0 - */ - - while(inlen) { - c = *inbuf++; - inlen--; - if(isWhite(c)) { - continue; - } - if(c == PAD) { - if(++padChars > 2) { - return 0; // max of 2 PAD chars at end - } - } - else if(padChars > 0) { - return 0; // no normal chars after seeing PAD - } - else if((c & 0x80) || ((asctobin[c]) & 0x80)) { - return 0; // invalid encoded char - } - validEncChars++; - } - if((validEncChars & 0x03) != 0) { - return 0; - } - else { - return 1; - } -} diff --git a/OSX/include/security_cdsa_utils/cuEnc64.h b/OSX/include/security_cdsa_utils/cuEnc64.h deleted file mode 100644 index 925e98b6..00000000 --- a/OSX/include/security_cdsa_utils/cuEnc64.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 1998-2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * cuEnc64.h - encode/decode in 64-char IA5 format, per RFC 1421 - */ - -#ifndef _CU_ENC64_H_ -#define _CU_ENC64_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Given input buffer inbuf, length inlen, decode from 64-char IA5 format to - * binary. Result is malloced and returned; its length is returned in *outlen. - * NULL return indicates corrupted input. - */ -unsigned char *cuEnc64(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen); // RETURNED - -/* - * Enc64, with embedded newlines every lineLen in result. A newline is - * the UNIX \n. Result is mallocd. - */ -unsigned char *cuEnc64WithLines(const unsigned char *inbuf, - unsigned inlen, - unsigned linelen, - unsigned *outlen); // RETURNED - -/* - * Given input buffer inbuf, length inlen, decode from 64-char IA5 format to - * binary. Result is malloced and returned; its length is returned in *outlen. - * NULL return indicates corrupted input. All whitespace in inbuf is - * ignored. - */ -unsigned char *cuDec64(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen); - -/* - * Determine if specified input data is valid enc64 format. Returns 1 - * if valid, 0 if not. - */ -int cuIsValidEnc64(const unsigned char *inbuf, - unsigned inbufLen); - -#ifdef __cplusplus -} -#endif - -#endif /*_CU_ENC64_H_*/ diff --git a/OSX/include/security_cdsa_utils/cuFileIo.c b/OSX/include/security_cdsa_utils/cuFileIo.c deleted file mode 100644 index bb1403e0..00000000 --- a/OSX/include/security_cdsa_utils/cuFileIo.c +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2001-2003,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuFileIo.c - - Description: simple file read/write utilities -*/ - -#include -#include -#include -#include -#include -#include -#include -#include "cuFileIo.h" - -int writeFile( - const char *fileName, - const unsigned char *bytes, - unsigned numBytes) -{ - int rtn; - int fd; - - fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600); - if(fd < 0) { - return errno; - } - rtn = (int)lseek(fd, 0, SEEK_SET); - if(rtn < 0) { - return errno; - } - rtn = (int)write(fd, bytes, (size_t)numBytes); - if(rtn != (int)numBytes) { - if(rtn >= 0) { - printf("writeFile: short write\n"); - } - rtn = EIO; - } - else { - rtn = 0; - } - close(fd); - return rtn; -} - -/* - * Read entire file. - */ -int readFile( - const char *fileName, - unsigned char **bytes, // mallocd and returned - unsigned *numBytes) // returned -{ - int rtn; - int fd; - unsigned char *buf; - struct stat sb; - unsigned size; - - *numBytes = 0; - *bytes = NULL; - fd = open(fileName, O_RDONLY, 0); - if(fd < 0) { - return errno; - } - rtn = fstat(fd, &sb); - if(rtn) { - goto errOut; - } - size = (unsigned)sb.st_size; - buf = malloc(size); - if(buf == NULL) { - rtn = ENOMEM; - goto errOut; - } - rtn = (int)lseek(fd, 0, SEEK_SET); - if(rtn < 0) { - goto errOut; - } - rtn = (int)read(fd, buf, (size_t)size); - if(rtn != (int)size) { - if(rtn >= 0) { - printf("readFile: short read\n"); - } - rtn = EIO; - } - else { - rtn = 0; - *bytes = buf; - *numBytes = size; - } -errOut: - close(fd); - return rtn; -} diff --git a/OSX/include/security_cdsa_utils/cuFileIo.h b/OSX/include/security_cdsa_utils/cuFileIo.h deleted file mode 100644 index c02fdbde..00000000 --- a/OSX/include/security_cdsa_utils/cuFileIo.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2001-2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuFileIo.h - - Description: simple file read/write utilities -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -int readFile( - const char *fileName, - unsigned char **bytes, // mallocd and returned - unsigned *numBytes); // returned - -int writeFile( - const char *fileName, - const unsigned char *bytes, - unsigned numBytes); - -#ifdef __cplusplus -} -#endif diff --git a/OSX/include/security_cdsa_utils/cuOidParser.cpp b/OSX/include/security_cdsa_utils/cuOidParser.cpp deleted file mode 100644 index 7b2b7def..00000000 --- a/OSX/include/security_cdsa_utils/cuOidParser.cpp +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2002-2003,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. - * Please obtain a copy of the License at http://www.apple.com/publicsource - * and read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights - * and limitations under the License. - */ - -/* - * cuOidParser.cpp - parse an Intel-style OID, with the assistance - * of dumpasn1.cfg - */ - -#include -#include -#include -#include -#include "cuOidParser.h" -#include "cuFileIo.h" -#include -#include -#include -#include -#include -#include -#include - -/* get config file from .. or from . */ -#define CONFIG_FILE_NAME "dumpasn1.cfg" -static const char *CONFIG_FILE1 = "../"CONFIG_FILE_NAME; -static const char *CONFIG_FILE2 = CONFIG_FILE_NAME; -/* or from here via getenv */ -#define CONFIG_FILE_ENV "LOCAL_BUILD_DIR" - -static const char *OID_ENTRY_START = "OID = "; -static const char *OID_DESCR_START = "Description = "; -/* - * Read entire file with extra bytes left over in the mallocd buffer. - */ -static -int readFileExtra( - const char *fileName, - unsigned extraBytes, - unsigned char **bytes, // mallocd and returned - CSSM_SIZE *numBytes) // returned -{ - int rtn; - int fd; - unsigned char *buf; - struct stat sb; - size_t size; - - *numBytes = 0; - *bytes = NULL; - fd = open(fileName, O_RDONLY, 0); - if(fd < 0) { - return 1; - } - rtn = fstat(fd, &sb); - if(rtn) { - goto errOut; - } - size = (size_t)sb.st_size; - buf = (unsigned char *)malloc(size + extraBytes); - if(buf == NULL) { - rtn = ENOMEM; - goto errOut; - } - rtn = (int)lseek(fd, 0, SEEK_SET); - if(rtn < 0) { - goto errOut; - } - rtn = (int)read(fd, buf, (size_t)size); - if(rtn != (int)size) { - if(rtn >= 0) { - printf("readFile: short read\n"); - } - rtn = EIO; - } - else { - rtn = 0; - *bytes = buf; - *numBytes = size; - } -errOut: - close(fd); - return rtn; -} - -/* - * Attempt to read dumpasn1.cfg from various places. If we can't find it, - * printOid() function will just print raw bytes as it - * would if the .cfg file did not contain the desired OID. - */ -static CSSM_DATA_PTR readConfig() -{ - CSSM_DATA_PTR configData = NULL; - int rtn; - - configData = (CSSM_DATA_PTR)malloc(sizeof(CSSM_DATA)); - if(configData == NULL) { - return NULL; - } - /* malloc one extra byte, we'll null it later */ - rtn = readFileExtra(CONFIG_FILE1, 1, &configData->Data, - &configData->Length); - if(rtn) { - rtn = readFileExtra(CONFIG_FILE2, 1, &configData->Data, - &configData->Length); - } - if(rtn) { - char fileName[100]; - char *localBuildDir = getenv(CONFIG_FILE_ENV); - if(localBuildDir == NULL) { - rtn = 1; - } - else { - sprintf(fileName, "%s/%s", localBuildDir, CONFIG_FILE_NAME); - rtn = readFileExtra(fileName, 1, &configData->Data, - &configData->Length); - } - } - if(rtn == 0) { - /* make the whole shebang one long C string */ - configData->Data[configData->Length++] = '\0'; - return configData; - } - else { - free(configData); - return NULL; - } -} - -/* - * The heart of this module. - * - * -- Convert Intel-style OID to a string which might be found - * in the config file - * -- search config file for that string - * -- if found, use that entry in config file to output meaningful - * string and return CSSM_TRUE. Else return CSSM_FALSE. - */ -static CSSM_BOOL parseOidWithConfig( - const CSSM_DATA_PTR configData, - const CSSM_OID_PTR oid, - char *strBuf) -{ - char *fullOidStr = NULL; - char *ourEntry = NULL; - char *nextEntry = NULL; - char *descStart = NULL; - char *cp; - unsigned i; - CSSM_BOOL brtn; - char *nextCr; // next CR if any - char *nextNl; // next NL if any - char *eol; // end of line - int len; - - if(configData == NULL) { - return CSSM_FALSE; - } - - /* cook up a full OID string, with tag and length */ - fullOidStr = (char *)malloc((3 * oid->Length) + - // 2 chars plus space per byte - strlen(OID_ENTRY_START) + // "OID = " - 6 + // 06 xx - tag and length - 1); // NULL - if(fullOidStr == NULL) { - return CSSM_FALSE; - } - /* subsequent errors to errOut: */ - - sprintf(fullOidStr, "OID = 06 %02X", (unsigned)oid->Length); - cp = fullOidStr + strlen(fullOidStr); - for(i=0; iLength; i++) { - /* move cp to current end of string */ - cp += strlen(cp); - /* add one byte */ - sprintf(cp, " %02X", oid->Data[i]); - } - - /* - * Let's play it loose and assume that there are no embedded NULLs - * in the config file. Thus we can use the spiffy string functions - * in stdlib. - */ - ourEntry = strstr((char *)configData->Data, fullOidStr); - if(ourEntry == NULL) { - brtn = CSSM_FALSE; - goto errOut; - } - - /* get position of NEXT full entry - may be NULL (end of file) */ - nextEntry = strstr(ourEntry+1, OID_ENTRY_START); - - /* get position of our entry's description line */ - descStart = strstr(ourEntry+1, OID_DESCR_START); - - /* handle not found/overflow */ - if( (descStart == NULL) || // no more description lines - ( (descStart > nextEntry) && // no description in THIS entry - (nextEntry != NULL) ) ) { // make sure this is valid - brtn = CSSM_FALSE; - goto errOut; - } - - /* set descStart to after the leader */ - descStart += strlen(OID_DESCR_START); - - /* - * descStart points to the text we're interested in. - * First find end of line, any style. - */ - nextNl = strchr(descStart, '\n'); - nextCr = strchr(descStart, '\r'); - if((nextNl == NULL) && (nextCr == NULL)) { - /* no line terminator, go to eof */ - eol = (char *)configData->Data + configData->Length; - } - else if(nextCr == NULL) { - eol = nextNl; - } - else if(nextNl == NULL) { - eol = nextCr; - } - else if(nextNl < nextCr) { - /* both present, take first one */ - eol = nextNl; - } - else { - eol = nextCr; - } - - /* caller's string buf = remainder of description line */ - len = (int)(eol - descStart); - if(len > (OID_PARSER_STRING_SIZE - 1)) { - /* fixed-length output buf, avoid overflow */ - len = OID_PARSER_STRING_SIZE - 1; - } - memcpy(strBuf, descStart, len); - strBuf[len] = '\0'; - brtn = CSSM_TRUE; -errOut: - if(fullOidStr != NULL) { - free(fullOidStr); - } - return brtn; -} - -/*** OidParser class ***/ -OidParser::OidParser(bool noConfig) -{ - if(noConfig) { - configData = NULL; - } - else { - configData = readConfig(); - } -} - -OidParser::~OidParser() -{ - if(configData == NULL) { - return; - } - if(configData->Data != NULL) { - free(configData->Data); - } - free(configData); -} - -/* - * Parse an Intel-style OID, generating a C string in caller-supplied buffer. - */ -void OidParser::oidParse( - const unsigned char *oidp, - unsigned oidLen, - char *strBuf) -{ - unsigned i; - CSSM_OID oid; - - oid.Data = (uint8 *)oidp; - oid.Length = oidLen; - - if((oidLen == 0) || (oidp == NULL)) { - strcpy(strBuf, "EMPTY"); - return; - } - if(parseOidWithConfig(configData, &oid, strBuf) == CSSM_FALSE) { - /* no config file, just dump the bytes */ - char cbuf[8]; - - sprintf(strBuf, "OID : < 06 %02X ", (unsigned)oid.Length); - for(i=0; i"); - } -} - - diff --git a/OSX/include/security_cdsa_utils/cuOidParser.h b/OSX/include/security_cdsa_utils/cuOidParser.h deleted file mode 100644 index 229688cf..00000000 --- a/OSX/include/security_cdsa_utils/cuOidParser.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2002-2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * cuOidParser.cpp - parse an Intel-style OID, with the assistance of - * dumpasn1.cfg. - * - * The config file is looked for in the following locations: - * - * current working directory (.) - * parent directory (..) - * The directory specified by the environment variable LOCAL_BUILD_DIR - * - * OidParser will still work if the config file is not found, but OIDs - * will be dispayed in raw hex format. - */ - -#ifndef _OID_PARSER_H_ -#define _OID_PARSER_H_ - -#include - -/* - * Generated strings go into a client-allocated char array of - * this size. - */ -#define OID_PARSER_STRING_SIZE 120 - -class OidParser -{ -private: - CSSM_DATA_PTR configData; // contents of dumpasn1.cfg -public: - /* costruct with noConfig true - skip reading config file */ - OidParser(bool noConfig=false); - ~OidParser(); - - /* - * Parse an Intel-style OID, generating a C string in - * caller-supplied buffer. - */ - void oidParse( - const unsigned char *oidp, - unsigned oidLen, - char *strBuf); - -}; - -#endif /* _OID_PARSER_H_ */ diff --git a/OSX/include/security_cdsa_utils/cuPem.cpp b/OSX/include/security_cdsa_utils/cuPem.cpp deleted file mode 100644 index cbf87203..00000000 --- a/OSX/include/security_cdsa_utils/cuPem.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2003,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuPem.h - - Description: PEM encode/decode routines - - Author: dmitch - -*/ - -#include "cuPem.h" -#include -#include -#include -#include -#include "cuEnc64.h" - -#define PEM_SCAN_LEN 8192 - -/* - * Determine if specified blob appears to be PEM format. - * Returns 1 if so, 0 if not. - */ -int isPem( - const unsigned char *inData, - unsigned inDataLen) -{ - /* - * 1. The entire blob must be printable ASCII. - */ - const unsigned char *cp = inData; - for(unsigned dex=0; dex PEM_SCAN_LEN) { - len = PEM_SCAN_LEN; - } - memcpy(buf, inData, len); - buf[len] = '\0'; - const char *p = strstr((const char *)buf, "-----BEGIN "); - if(p == NULL) { - return 0; - } - - /* - * Now the last PEM_SCAN_LEN chars or inDataLen, whichever is less. - */ - if(inDataLen > PEM_SCAN_LEN) { - memcpy(buf, inData + inDataLen - PEM_SCAN_LEN, PEM_SCAN_LEN); - buf[PEM_SCAN_LEN] = '\0'; - } - /* else we already have whole blob in buf[] */ - p = strstr((const char *)buf, "-----END "); - if(p == NULL) { - return 0; - } - /* success */ - return 1; -} - -int pemEncode( - const unsigned char *inData, - unsigned inDataLen, - unsigned char **outData, - unsigned *outDataLen, - const char *headerString) -{ - unsigned char *enc; - unsigned encLen; - - /* First base64 encode */ - enc = cuEnc64WithLines(inData, inDataLen, 64, &encLen); - if(enc == NULL) { - /* malloc error is actually the only known failure */ - printf("***pemEncode: Error encoding file. Aborting.\n"); - return -1; - } - - /* estimate outsize - just be sloppy, way conservative */ - size_t outSize = encLen + (2 * strlen(headerString)) + 200; - *outData = (unsigned char *)malloc(outSize); - sprintf((char *)*outData, "-----BEGIN %s-----\n%s-----END %s-----\n", - headerString, (char *)enc, headerString); - *outDataLen = (unsigned int)strlen((char *)*outData); - - if((*outData)[*outDataLen - 1] == '\0') { - (*outDataLen)--; - } - free(enc); - return 0; -} - -int pemDecode( - const unsigned char *inData, - unsigned inDataLen, - unsigned char **outData, - unsigned *outDataLen) -{ - char *cp; - char *curr1, *curr2; - char *startPem = NULL; - char *endPem = NULL; - unsigned char *out; - unsigned outLen; - int ourRtn = 0; - char *freeCp = NULL; - - /* make the whole thing a NULL-terminated string */ - if(inData[inDataLen - 1] != '\0') { - cp = freeCp = (char *)malloc(inDataLen + 1); - memmove(cp, inData, inDataLen); - cp[inDataLen] = '\0'; - inDataLen++; - } - else { - /* already is */ - cp = (char *)inData; - } - - /* cp is start of NULL-terminated buffer, size inDataLen */ - /* skip over everything until "-----" */ - curr1 = strstr(cp, "-----"); - if(curr1 == NULL) { - printf("***pemDecode: no terminator found\n"); - ourRtn = -1; - goto abort; - } - - /* find end of separator line, handling both flavors of terminator */ - cp = curr1; - curr1 = strchr(cp, '\n'); - curr2 = strchr(cp, '\r'); - if((curr1 == NULL) & (curr2 == NULL)) { - printf("***pemDecode: Bad PEM format (1)\n"); - ourRtn = -1; - goto abort; - } - if(curr1 == NULL) { - startPem = curr2; - } - else { - startPem = curr1; - } - - /* startPem points to end of separator line */ - /* locate ending terminator and lop it off */ - curr1 = strstr(startPem, "-----"); - if(curr1 == NULL) { - printf("***pemDecode: Bad PEM format (2)\n"); - ourRtn = -1; - goto abort; - } - endPem = curr1; - /* endPem points to last PEM data plus one */ - - out = cuDec64((unsigned char *)startPem, (unsigned int)(endPem-startPem), &outLen); - if(out == NULL) { - printf("Bad PEM format (3)\n"); - ourRtn = -1; - goto abort; - } - *outData = out; - *outDataLen = outLen; -abort: - if(freeCp) { - free(freeCp); - } - return ourRtn; -} - diff --git a/OSX/include/security_cdsa_utils/cuPem.h b/OSX/include/security_cdsa_utils/cuPem.h deleted file mode 100644 index a7ef5d90..00000000 --- a/OSX/include/security_cdsa_utils/cuPem.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please - * obtain a copy of the License at http://www.apple.com/publicsource and - * read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - */ - -/* - File: cuPem.h - - Description: PEM encode/decode routines - - Author: dmitch -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -int isPem( - const unsigned char *inData, - unsigned inDataLen); - -int pemEncode( - const unsigned char *inData, - unsigned inFileLen, - unsigned char **outData, - unsigned *outDataLen, - const char *headerString); - -int pemDecode( - const unsigned char *inData, - unsigned inFileLen, - unsigned char **outData, - unsigned *outDataLen); - -#ifdef __cplusplus -} -#endif diff --git a/OSX/include/security_cdsa_utils/cuPrintCert.cpp b/OSX/include/security_cdsa_utils/cuPrintCert.cpp deleted file mode 100644 index 5f0281ba..00000000 --- a/OSX/include/security_cdsa_utils/cuPrintCert.cpp +++ /dev/null @@ -1,1504 +0,0 @@ -/* - * Copyright (c) 2002,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - -/* - * cuPrintCert.cpp - Parse a cert or CRL, dump contents. - */ -#include "cuCdsaUtils.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "cuPrintCert.h" -#include "cuOidParser.h" -#include "cuTimeStr.h" -#include -#include -#include - -static const char *months[] = { - "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" -}; - -static void printTimeStr(const CSSM_DATA *cssmTime) -{ - struct tm tm; - - /* ignore cssmTime->timeType for now */ - if(cuTimeStringToTm((char *)cssmTime->Data, (unsigned int)cssmTime->Length, &tm)) { - printf("***Bad time string format***\n"); - return; - } - if(tm.tm_mon > 11) { - printf("***Bad time string format***\n"); - return; - } - printf("%02d:%02d:%02d %s %d, %04d\n", - tm.tm_hour, tm.tm_min, tm.tm_sec, - months[tm.tm_mon], tm.tm_mday, tm.tm_year + 1900); - -} - - -static void printTime(const CSSM_X509_TIME *cssmTime) -{ - /* ignore cssmTime->timeType for now */ - printTimeStr(&cssmTime->time); -} - -static void printDataAsHex( - const CSSM_DATA *d, - unsigned maxToPrint = 0) // optional, 0 means print it all -{ - unsigned i; - bool more = false; - uint32 len = (uint32)d->Length; - uint8 *cp = d->Data; - - if((maxToPrint != 0) && (len > maxToPrint)) { - len = maxToPrint; - more = true; - } - for(i=0; iLength - * Tag is implied - */ -static void printOid(OidParser &parser, const CSSM_DATA *oid) -{ - char strBuf[OID_PARSER_STRING_SIZE]; - - if(oid == NULL) { - printf("NULL\n"); - return; - } - if((oid->Length == 0) || (oid->Data == NULL)) { - printf("EMPTY\n"); - return; - } - parser.oidParse(oid->Data, (unsigned int)oid->Length, strBuf); - printf("%s\n", strBuf); -} - -/* - * Used to print generic blobs which we don't really understand. - * The bytesToPrint argument is usually thing->Length; it's here because snacc - * peports lengths of bit strings in BITS. Caller knows this and - * modifies bytesToPrint accordingly. In any case, bytesToPrint is the - * max number of valid bytes in *thing->Data. - */ -#define BLOB_LENGTH_PRINT 3 - -static void printBlobBytes( - const char *blobType, - const char *quanta, // e.g., "bytes', "bits" - uint32 bytesToPrint, - const CSSM_DATA *thing) -{ - uint32 dex; - uint32 toPrint = bytesToPrint; - - if(toPrint > BLOB_LENGTH_PRINT) { - toPrint = BLOB_LENGTH_PRINT; - } - printf("%s; Length %u %s; data = ", - blobType, (unsigned)thing->Length, quanta); - for(dex=0; dexData[dex]); - if(dex == (toPrint - 1)) { - break; - } - } - if(dex < bytesToPrint) { - printf(" ...\n"); - } - else { - printf("\n"); - } -} - -/* - * Print an IA5String or Printable string. Null terminator is not assumed. - * Trailing newline is printed. - */ -static void printString( - const CSSM_DATA *str) -{ - unsigned i; - char *cp = (char *)str->Data; - for(i=0; iLength; i++) { - printf("%c", *cp++); - } - printf("\n"); -} - -static void printDerThing( - CSSM_BER_TAG tagType, - const CSSM_DATA *thing, - OidParser &parser) -{ - switch(tagType) { - case BER_TAG_INTEGER: - printf("%d\n", cuDER_ToInt(thing)); - return; - case BER_TAG_BOOLEAN: - if(thing->Length != 1) { - printf("***malformed BER_TAG_BOOLEAN: length %u data ", - (unsigned)thing->Length); - } - printf("%u\n", cuDER_ToInt(thing)); - return; - case BER_TAG_PRINTABLE_STRING: - case BER_TAG_IA5_STRING: - case BER_TAG_T61_STRING: - case BER_TAG_PKIX_UTF8_STRING: // mostly printable.... - printString(thing); - return; - case BER_TAG_OCTET_STRING: - printBlobBytes("Byte string", "bytes", (uint32)thing->Length, thing); - return; - case BER_TAG_BIT_STRING: - printBlobBytes("Bit string", "bits", (uint32)(thing->Length + 7) / 8, thing); - return; - case BER_TAG_SEQUENCE: - printBlobBytes("Sequence", "bytes", (uint32)thing->Length, thing); - return; - case BER_TAG_SET: - printBlobBytes("Set", "bytes", (uint32)thing->Length, thing); - return; - case BER_TAG_OID: - printf("OID = "); - printOid(parser, thing); - break; - default: - printf("not displayed (tagType = %s; length %u)\n", - tagTypeString(tagType), (unsigned)thing->Length); - break; - - } -} - -/* compare two OIDs, return CSSM_TRUE if identical */ -static CSSM_BOOL compareOids( - const CSSM_OID *oid1, - const CSSM_OID *oid2) -{ - if((oid1 == NULL) || (oid2 == NULL)) { - return CSSM_FALSE; - } - if(oid1->Length != oid2->Length) { - return CSSM_FALSE; - } - if(memcmp(oid1->Data, oid2->Data, oid1->Length)) { - return CSSM_FALSE; - } - else { - return CSSM_TRUE; - } -} - -/* - * Following a CSSMOID_ECDSA_WithSpecified algorithm is another encoded - * CSSM_X509_ALGORITHM_IDENTIFIER containing the digest algorithm OID. - * Decode and print the OID. - */ -static void printECDSA_SigAlgParams( - const CSSM_DATA *params, - OidParser &parser) -{ - SecAsn1CoderRef coder = NULL; - if(SecAsn1CoderCreate(&coder)) { - printf("***Error in SecAsn1CoderCreate()\n"); - return; - } - CSSM_X509_ALGORITHM_IDENTIFIER algParams; - memset(&algParams, 0, sizeof(algParams)); - if(SecAsn1DecodeData(coder, params, kSecAsn1AlgorithmIDTemplate, - &algParams)) { - printf("***Error decoding CSSM_X509_ALGORITHM_IDENTIFIER\n"); - goto errOut; - } - printOid(parser, &algParams.algorithm); -errOut: - SecAsn1CoderRelease(coder); -} - -static void printSigAlg( - const CSSM_X509_ALGORITHM_IDENTIFIER *sigAlg, - OidParser &parser) -{ - printOid(parser, &sigAlg->algorithm); - if(sigAlg->parameters.Data != NULL) { - printf(" alg params : "); - if(compareOids(&sigAlg->algorithm, &CSSMOID_ecPublicKey) && - (sigAlg->parameters.Data[0] == BER_TAG_OID) && - (sigAlg->parameters.Length > 2)) { - /* - * An OID accompanying an ECDSA public key. The OID is an ECDSA curve. - * Do a quickie DER-decode of the OID - it's here in encoded form - * because this field is an ASN_ANY - and print the resulting OID. - */ - CSSM_OID curveOid = {sigAlg->parameters.Length-2, sigAlg->parameters.Data+2}; - printOid(parser, &curveOid); - } - else if(compareOids(&sigAlg->algorithm, &CSSMOID_ECDSA_WithSpecified)) { - /* - * The accompanying params specify the digest algorithm. - */ - printECDSA_SigAlgParams(&sigAlg->parameters, parser); - } - else { - /* All others - ASN_ANY - punt */ - printDataAsHex(&sigAlg->parameters, 8); - } - } -} - -static void printRdn( - const CSSM_X509_RDN *rdnp, - OidParser &parser) -{ - CSSM_X509_TYPE_VALUE_PAIR *ptvp; - unsigned pairDex; - const char *fieldName; - - for(pairDex=0; pairDexnumberOfPairs; pairDex++) { - ptvp = &rdnp->AttributeTypeAndValue[pairDex]; - if(compareOids(&ptvp->type, &CSSMOID_CountryName)) { - fieldName = "Country "; - } - else if(compareOids(&ptvp->type, &CSSMOID_OrganizationName)) { - fieldName = "Org "; - } - else if(compareOids(&ptvp->type, &CSSMOID_LocalityName)) { - fieldName = "Locality "; - } - else if(compareOids(&ptvp->type, &CSSMOID_OrganizationalUnitName)) { - fieldName = "OrgUnit "; - } - else if(compareOids(&ptvp->type, &CSSMOID_CommonName)) { - fieldName = "Common Name "; - } - else if(compareOids(&ptvp->type, &CSSMOID_Surname)) { - fieldName = "Surname "; - } - else if(compareOids(&ptvp->type, &CSSMOID_Title)) { - fieldName = "Title "; - } - else if(compareOids(&ptvp->type, &CSSMOID_Surname)) { - fieldName = "Surname "; - } - else if(compareOids(&ptvp->type, &CSSMOID_StateProvinceName)) { - fieldName = "State "; - } - else if(compareOids(&ptvp->type, &CSSMOID_CollectiveStateProvinceName)) { - fieldName = "Coll. State "; - } - else if(compareOids(&ptvp->type, &CSSMOID_EmailAddress)) { - /* deprecated, used by Thawte */ - fieldName = "Email addrs "; - } - else if(compareOids(&ptvp->type, &CSSMOID_Description)) { - fieldName = "Description "; - } - else { - fieldName = "Other name "; - } - printf(" %s : ", fieldName); - printDerThing(ptvp->valueType, &ptvp->value, parser); - } /* for each type/value pair */ -} - -static CSSM_RETURN printName( - const CSSM_X509_NAME *x509Name, - OidParser &parser) -{ - CSSM_X509_RDN_PTR rdnp; - unsigned rdnDex; - - for(rdnDex=0; rdnDexnumberOfRDNs; rdnDex++) { - rdnp = &x509Name->RelativeDistinguishedName[rdnDex]; - printRdn(rdnp, parser); - } - - return CSSM_OK; -} - -static void printKeyHeader( - const CSSM_KEYHEADER &hdr) -{ - printf(" Algorithm : "); - switch(hdr.AlgorithmId) { - case CSSM_ALGID_RSA: - printf("RSA\n"); - break; - case CSSM_ALGID_DSA: - printf("DSA\n"); - break; - case CSSM_ALGID_FEE: - printf("FEE\n"); - break; - case CSSM_ALGID_DH: - printf("Diffie-Hellman\n"); - break; - case CSSM_ALGID_ECDSA: - printf("ECDSA\n"); - break; - default: - printf("Unknown(%u(d), 0x%x)\n", (unsigned)hdr.AlgorithmId, - (unsigned)hdr.AlgorithmId); - } - printf(" Key Size : %u bits\n", (unsigned)hdr.LogicalKeySizeInBits); - printf(" Key Use : "); - CSSM_KEYUSE usage = hdr.KeyUsage; - if(usage & CSSM_KEYUSE_ANY) { - printf("CSSM_KEYUSE_ANY "); - } - if(usage & CSSM_KEYUSE_ENCRYPT) { - printf("CSSM_KEYUSE_ENCRYPT "); - } - if(usage & CSSM_KEYUSE_DECRYPT) { - printf("CSSM_KEYUSE_DECRYPT "); - } - if(usage & CSSM_KEYUSE_SIGN) { - printf("CSSM_KEYUSE_SIGN "); - } - if(usage & CSSM_KEYUSE_VERIFY) { - printf("CSSM_KEYUSE_VERIFY "); - } - if(usage & CSSM_KEYUSE_SIGN_RECOVER) { - printf("CSSM_KEYUSE_SIGN_RECOVER "); - } - if(usage & CSSM_KEYUSE_VERIFY_RECOVER) { - printf("CSSM_KEYUSE_VERIFY_RECOVER "); - } - if(usage & CSSM_KEYUSE_WRAP) { - printf("CSSM_KEYUSE_WRAP "); - } - if(usage & CSSM_KEYUSE_UNWRAP) { - printf("CSSM_KEYUSE_UNWRAP "); - } - if(usage & CSSM_KEYUSE_DERIVE) { - printf("CSSM_KEYUSE_DERIVE "); - } - printf("\n"); - -} - -/* - * Print contents of a CE_GeneralName as best we can. - */ -static void printGeneralName( - const CE_GeneralName *name, - OidParser &parser) -{ - switch(name->nameType) { - case GNT_RFC822Name: - printf(" RFC822Name : "); - printString(&name->name); - break; - case GNT_DNSName: - printf(" DNSName : "); - printString(&name->name); - break; - case GNT_URI: - printf(" URI : "); - printString(&name->name); - break; - case GNT_IPAddress: - printf(" IP Address : "); - for(unsigned i=0; iname.Length; i++) { - printf("%d", name->name.Data[i]); - if(i < (name->name.Length - 1)) { - printf("."); - } - } - printf("\n"); - break; - case GNT_RegisteredID: - printf(" RegisteredID : "); - printOid(parser, &name->name); - break; - case GNT_X400Address: - /* ORAddress, a very complicated struct - punt */ - printf(" X400Address : "); - printBlobBytes("Sequence", "bytes", (uint32)name->name.Length, &name->name); - break; - case GNT_DirectoryName: - if(!name->berEncoded) { - /* CL parsed it for us into an CSSM_X509_NAME */ - if(name->name.Length != sizeof(CSSM_X509_NAME)) { - printf("***MALFORMED GNT_DirectoryName\n"); - break; - } - const CSSM_X509_NAME *x509Name = - (const CSSM_X509_NAME *)name->name.Data; - printf(" Dir Name :\n"); - printName(x509Name, parser); - } - else { - /* encoded Name (i.e. CSSM_X509_NAME) */ - printf(" Dir Name : "); - printBlobBytes("Byte string", "bytes", - (uint32)name->name.Length, &name->name); - } - break; - case GNT_EdiPartyName: - /* sequence EDIPartyName */ - printf(" EdiPartyName : "); - printBlobBytes("Sequence", "bytes", (uint32)name->name.Length, &name->name); - break; - case GNT_OtherName: - { - printf(" OtherName :\n"); - if(name->name.Length != sizeof(CE_OtherName)) { - printf("***Malformed CE_OtherName\n"); - break; - } - CE_OtherName *other = (CE_OtherName *)name->name.Data; - printf(" typeID : "); - printOid(parser, &other->typeId); - printf(" value : "); - printDataAsHex(&other->value, 0); - break; - } - } -} - - -/* - * Print contents of a CE_GeneralNames as best we can. - */ -static void printGeneralNames( - const CE_GeneralNames *generalNames, - OidParser &parser) -{ - unsigned i; - CE_GeneralName *name; - - for(i=0; inumNames; i++) { - name = &generalNames->generalName[i]; - printGeneralName(name, parser); - } -} - -static int printCdsaExtensionCommon( - const CSSM_X509_EXTENSION *cssmExt, - OidParser &parser, - bool expectParsed, - CSSM_BOOL verbose, - bool extraIndent = false) -{ - if(extraIndent) { - printf(" Extension : "); printOid(parser, &cssmExt->extnId); - printf(" Critical : %s\n", cssmExt->critical ? "TRUE" : "FALSE"); - } - else { - printf("Extension struct : "); printOid(parser, &cssmExt->extnId); - printf(" Critical : %s\n", cssmExt->critical ? "TRUE" : "FALSE"); - } - - /* currently (since Radar 3593624), these are both always valid */ - #if 0 - /* this prevents printing pre-encoded extensions in clxutils/extenTest */ - if((cssmExt->BERvalue.Data == NULL) || - (cssmExt->value.parsedValue == NULL)) { /* actually, one of three variants */ - printf("***Malformed CSSM_X509_EXTENSION (1)\n"); - return 1; - } - #endif - switch(cssmExt->format) { - case CSSM_X509_DATAFORMAT_ENCODED: - if(expectParsed) { - printf("Bad CSSM_X509_EXTENSION; expected FORMAT_PARSED\n"); - return 1; - } - break; - case CSSM_X509_DATAFORMAT_PARSED: - if(!expectParsed) { - printf("Bad CSSM_X509_EXTENSION; expected FORMAT_ENCODED\n"); - return 1; - } - break; - case CSSM_X509_DATAFORMAT_PAIR: - /* unsupported */ - printf("Bad CSSM_X509_EXTENSION format:FORMAT_PAIR\n"); - return 1; - default: - printf("***Unknown CSSM_X509_EXTENSION.format\n"); - return 1; - } - return 0; -} - -static int printExtensionCommon( - const CSSM_DATA &value, - OidParser &parser, - CSSM_BOOL verbose, - bool expectParsed = true) -{ - if(value.Length != sizeof(CSSM_X509_EXTENSION)) { - printf("***malformed CSSM_FIELD (1)\n"); - return 1; - } - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - return printCdsaExtensionCommon(cssmExt, parser, expectParsed, verbose); -} - - -static void printKeyUsage( - const CSSM_DATA &value) -{ - CE_KeyUsage usage; - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - - usage = *((CE_KeyUsage *)cssmExt->value.parsedValue); - printf(" usage : "); - if(usage & CE_KU_DigitalSignature) { - printf("DigitalSignature "); - } - if(usage & CE_KU_NonRepudiation) { - printf("NonRepudiation "); - } - if(usage & CE_KU_KeyEncipherment) { - printf("KeyEncipherment "); - } - if(usage & CE_KU_DataEncipherment) { - printf("DataEncipherment "); - } - if(usage & CE_KU_KeyAgreement) { - printf("KeyAgreement "); - } - if(usage & CE_KU_KeyCertSign) { - printf("KeyCertSign "); - } - if(usage & CE_KU_CRLSign) { - printf("CRLSign "); - } - if(usage & CE_KU_EncipherOnly) { - printf("EncipherOnly "); - } - if(usage & CE_KU_DecipherOnly) { - printf("DecipherOnly "); - } - printf("\n"); - -} - -static void printBasicConstraints( - const CSSM_DATA &value) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_BasicConstraints *bc = (CE_BasicConstraints *)cssmExt->value.parsedValue; - printf(" CA : %s\n", bc->cA ? "TRUE" : "FALSE"); - if(bc->pathLenConstraintPresent) { - printf(" pathLenConstr : %u\n", (unsigned)bc->pathLenConstraint); - } -} - -static void printExtKeyUsage( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_ExtendedKeyUsage *eku = (CE_ExtendedKeyUsage *)cssmExt->value.parsedValue; - unsigned oidDex; - for(oidDex=0; oidDexnumPurposes; oidDex++) { - printf(" purpose %2d : ", oidDex); - printOid(parser, &eku->purposes[oidDex]); - } -} - -static void printCssmAuthorityKeyId( - const CE_AuthorityKeyID *akid, - OidParser &parser) -{ - if(akid->keyIdentifierPresent) { - printf(" Auth KeyID : "); - printDataAsHex(&akid->keyIdentifier, -8); - } - if(akid->generalNamesPresent) { - printGeneralNames(akid->generalNames, parser); - } - if(akid->serialNumberPresent) { - printf(" serialNumber : "); - printDataAsHex(&akid->serialNumber, 8); - } -} - -static void printAuthorityKeyId( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_AuthorityKeyID *akid = (CE_AuthorityKeyID *)cssmExt->value.parsedValue; - printCssmAuthorityKeyId(akid, parser); -} - -static void printSubjectIssuerAltName( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_GeneralNames *san = (CE_GeneralNames *)cssmExt->value.parsedValue; - printGeneralNames(san, parser); -} - -static void printDistPointName( - const CE_DistributionPointName *dpn, - OidParser &parser) -{ - switch(dpn->nameType) { - case CE_CDNT_FullName: - printGeneralNames(dpn->dpn.fullName, parser); - break; - case CE_CDNT_NameRelativeToCrlIssuer: - printRdn(dpn->dpn.rdn, parser); - break; - default: - printf("***BOGUS CE_DistributionPointName.nameType\n"); - break; - } -} - -static void printDistPoint( - const CE_CRLDistributionPoint *dp, - OidParser &parser) -{ - if(dp->distPointName) { - printf(" Dist pt Name :\n"); - printDistPointName(dp->distPointName, parser); - } - printf(" reasonsPresent : %s\n", dp->reasonsPresent ? "TRUE" : "FALSE"); - if(dp->reasonsPresent) { - /* FIXME - parse */ - printf(" reasons : 0x%X\n", dp->reasons); - } - if(dp->crlIssuer) { - printf(" CRLIssuer :\n"); - printGeneralNames(dp->crlIssuer, parser); - } -} - -static void printDistributionPoints( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_CRLDistPointsSyntax *dps = (CE_CRLDistPointsSyntax *)cssmExt->value.parsedValue; - - for(unsigned dex=0; dexnumDistPoints; dex++) { - printf(" Dist pt %d :\n", dex); - printDistPoint(&dps->distPoints[dex], parser); - } -} - -static void printValueOrNotPresent( - CSSM_BOOL present, - CSSM_BOOL value) -{ - if(!present) { - printf("\n"); - } - else if(value) { - printf("TRUE\n"); - } - else { - printf("FALSE"); - } -} - -static void printIssuingDistributionPoint( - const CE_IssuingDistributionPoint *idp, - OidParser &parser) -{ - if(idp->distPointName) { - printf(" Dist pt :\n"); - printDistPointName(idp->distPointName, parser); - } - printf(" Only user certs : "); - printValueOrNotPresent(idp->onlyUserCertsPresent, idp->onlyUserCerts); - printf(" Only CA certs : "); - printValueOrNotPresent(idp->onlyCACertsPresent, idp->onlyCACerts); - printf(" Only some reason: "); - printValueOrNotPresent(idp->onlySomeReasonsPresent, idp->onlySomeReasons); - printf(" Indirectl CRL : "); - printValueOrNotPresent(idp->indirectCrlPresent, idp->indirectCrl); -} - -static void printCertPolicies( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_CertPolicies *cdsaObj = (CE_CertPolicies *)cssmExt->value.parsedValue; - for(unsigned polDex=0; polDexnumPolicies; polDex++) { - CE_PolicyInformation *cPolInfo = &cdsaObj->policies[polDex]; - printf(" Policy %2d : ID ", polDex); - printOid(parser, &cPolInfo->certPolicyId); - for(unsigned qualDex=0; qualDexnumPolicyQualifiers; qualDex++) { - CE_PolicyQualifierInfo *cQualInfo = &cPolInfo->policyQualifiers[qualDex]; - printf(" Qual %2d : ID ", qualDex); - printOid(parser, &cQualInfo->policyQualifierId); - if(cuCompareCssmData(&cQualInfo->policyQualifierId, - &CSSMOID_QT_CPS)) { - printf(" CPS : "); - printString(&cQualInfo->qualifier); - } - else { - printf(" unparsed : "); - printDataAsHex(&cQualInfo->qualifier, 8); - } - } - } -} - -static void printNetscapeCertType( - const CSSM_DATA &value) -{ - CE_NetscapeCertType certType; - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - - certType = *((CE_NetscapeCertType *)cssmExt->value.parsedValue); - printf(" certType : "); - if(certType & CE_NCT_SSL_Client) { - printf("SSL_Client "); - } - if(certType & CE_NCT_SSL_Server) { - printf("SSL_Server "); - } - if(certType & CE_NCT_SMIME) { - printf("S/MIME "); - } - if(certType & CE_NCT_ObjSign) { - printf("ObjectSign "); - } - if(certType & CE_NCT_Reserved) { - printf("Reserved "); - } - if(certType & CE_NCT_SSL_CA) { - printf("SSL_CA "); - } - if(certType & CE_NCT_SMIME_CA) { - printf("SMIME_CA "); - } - if(certType & CE_NCT_ObjSignCA) { - printf("ObjSignCA "); - } - printf("\n"); -} - -static void printAuthorityInfoAccess( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_AuthorityInfoAccess *info = (CE_AuthorityInfoAccess *)cssmExt->value.parsedValue; - - printf(" numDescriptions : %lu\n", (unsigned long)info->numAccessDescriptions); - for(unsigned dex=0; dexnumAccessDescriptions; dex++) { - printf(" description %u : \n", dex); - printf(" accessMethod : "); - CE_AccessDescription *descr = &info->accessDescriptions[dex]; - printOid(parser, &descr->accessMethod); - printGeneralName(&descr->accessLocation, parser); - } -} - -static void printQualCertStatements( - const CSSM_DATA &value, - OidParser &parser) -{ - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)value.Data; - CE_QC_Statements *qcss = (CE_QC_Statements *)cssmExt->value.parsedValue; - - printf(" numQCStatements : %lu\n", (unsigned long)qcss->numQCStatements); - for(unsigned dex=0; dexnumQCStatements; dex++) { - CE_QC_Statement *qcs = &qcss->qcStatements[dex]; - - printf(" statement %u : \n", dex); - printf(" statementId : "); - printOid(parser, &qcs->statementId); - if(qcs->semanticsInfo) { - printf(" semanticsInfo :\n"); - CE_SemanticsInformation *si = qcs->semanticsInfo; - if(si->semanticsIdentifier) { - printf(" semanticsId : "); - printOid(parser, si->semanticsIdentifier); - } - if(si->nameRegistrationAuthorities) { - printf(" nameRegAuth :\n"); - printGeneralNames(si->nameRegistrationAuthorities, parser); - } - } - if(qcs->otherInfo) { - printf(" otherInfo : "); printDataAsHex(qcs->otherInfo, 8); - } - } -} - -/* print one field */ -void printCertField( - const CSSM_FIELD &field, - OidParser &parser, - CSSM_BOOL verbose) -{ - const CSSM_DATA *thisData = &field.FieldValue; - const CSSM_OID *thisOid = &field.FieldOid; - - if(cuCompareCssmData(thisOid, &CSSMOID_X509V1Version)) { - if(verbose) { - printf("Version : %u\n", cuDER_ToInt(thisData)); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SerialNumber)) { - printf("Serial Number : "); printDataAsHex(thisData, 0); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1IssuerNameCStruct)) { - printf("Issuer Name :\n"); - CSSM_X509_NAME_PTR name = (CSSM_X509_NAME_PTR)thisData->Data; - if((name == NULL) || (thisData->Length != sizeof(CSSM_X509_NAME))) { - printf(" ***malformed CSSM_X509_NAME\n"); - } - else { - printName(name, parser); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SubjectNameCStruct)) { - printf("Subject Name :\n"); - CSSM_X509_NAME_PTR name = (CSSM_X509_NAME_PTR)thisData->Data; - if((name == NULL) || (thisData->Length != sizeof(CSSM_X509_NAME))) { - printf(" ***malformed CSSM_X509_NAME\n"); - } - else { - printName(name, parser); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1ValidityNotBefore)) { - CSSM_X509_TIME *cssmTime = (CSSM_X509_TIME *)thisData->Data; - if((cssmTime == NULL) || (thisData->Length != sizeof(CSSM_X509_TIME))) { - printf(" ***malformed CSSM_X509_TIME\n"); - } - else if(verbose) { - printf("Not Before : "); printString(&cssmTime->time); - printf(" : "); - printTime(cssmTime); - } - else { - printf("Not Before : "); - printTime(cssmTime); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1ValidityNotAfter)) { - CSSM_X509_TIME *cssmTime = (CSSM_X509_TIME *)thisData->Data; - if((cssmTime == NULL) || (thisData->Length != sizeof(CSSM_X509_TIME))) { - printf(" ***malformed CSSM_X509_TIME\n"); - } - else if(verbose) { - printf("Not After : "); printString(&cssmTime->time); - printf(" : "); - printTime(cssmTime); - } - else { - printf("Not After : "); - printTime(cssmTime); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SignatureAlgorithmTBS)) { - if(verbose) { - /* normally skip, it's the same as TBS sig alg */ - printf("TBS Sig Algorithm : "); - CSSM_X509_ALGORITHM_IDENTIFIER *algId = - (CSSM_X509_ALGORITHM_IDENTIFIER *)thisData->Data; - if((algId == NULL) || - (thisData->Length != sizeof(CSSM_X509_ALGORITHM_IDENTIFIER))) { - printf(" ***malformed CSSM_X509_ALGORITHM_IDENTIFIER\n"); - } - else { - printSigAlg(algId, parser); - } - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SignatureAlgorithm)) { - printf("Cert Sig Algorithm : "); - CSSM_X509_ALGORITHM_IDENTIFIER *algId = - (CSSM_X509_ALGORITHM_IDENTIFIER *)thisData->Data; - if((algId == NULL) || - (thisData->Length != sizeof(CSSM_X509_ALGORITHM_IDENTIFIER))) { - printf(" ***malformed CSSM_X509_ALGORITHM_IDENTIFIER\n"); - } - else { - printSigAlg(algId, parser); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1CertificateIssuerUniqueId)) { - if(verbose) { - printf("Issuer UniqueId : "); - printDerThing(BER_TAG_BIT_STRING, thisData, parser); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1CertificateSubjectUniqueId)) { - if(verbose) { - printf("Subject UniqueId : "); - printDerThing(BER_TAG_BIT_STRING, thisData, parser); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SubjectPublicKeyCStruct)) { - CSSM_X509_SUBJECT_PUBLIC_KEY_INFO *pubKeyInfo = - (CSSM_X509_SUBJECT_PUBLIC_KEY_INFO *)thisData->Data; - printf("Pub Key Algorithm : "); - if((pubKeyInfo == NULL) || - (thisData->Length != sizeof(CSSM_X509_SUBJECT_PUBLIC_KEY_INFO))) { - printf(" ***malformed CSSM_X509_SUBJECT_PUBLIC_KEY_INFO\n"); - } - else { - printSigAlg(&pubKeyInfo->algorithm, parser); - printf("Pub key Bytes : Length %u bytes : ", - (unsigned)pubKeyInfo->subjectPublicKey.Length); - printDataAsHex(&pubKeyInfo->subjectPublicKey, 8); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_CSSMKeyStruct)) { - CSSM_KEY_PTR cssmKey = (CSSM_KEY_PTR)thisData->Data; - printf("CSSM Key :\n"); - if((cssmKey == NULL) || - (thisData->Length != sizeof(CSSM_KEY))) { - printf(" ***malformed CSSM_KEY\n"); - } - else { - printKeyHeader(cssmKey->KeyHeader); - if(verbose) { - printf(" Key Blob : "); - printDataAsHex(&cssmKey->KeyData, 8); - } - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1Signature)) { - printf("Signature : %u bytes : ", (unsigned)thisData->Length); - printDataAsHex(thisData, 8); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V3CertificateExtensionCStruct)) { - if(printExtensionCommon(*thisData, parser, verbose, false)) { - return; - } - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)thisData->Data; - printf(" Unparsed data : "); printDataAsHex(&cssmExt->BERvalue, 8); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_KeyUsage)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printKeyUsage(*thisData); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_BasicConstraints)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printBasicConstraints(*thisData); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_ExtendedKeyUsage)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printExtKeyUsage(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_SubjectKeyIdentifier)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)thisData->Data; - CSSM_DATA_PTR cdata = (CSSM_DATA_PTR)cssmExt->value.parsedValue; - if((cdata == NULL) || (cdata->Data == NULL)) { - printf("****Malformed extension (no parsedValue)\n"); - } - else { - printf(" Subject KeyID : "); printDataAsHex(cdata, 8); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_AuthorityKeyIdentifier)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printAuthorityKeyId(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_SubjectAltName)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printSubjectIssuerAltName(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_IssuerAltName)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printSubjectIssuerAltName(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_CertificatePolicies)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printCertPolicies(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_NetscapeCertType)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printNetscapeCertType(*thisData); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_CrlDistributionPoints)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printDistributionPoints(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_AuthorityInfoAccess)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printAuthorityInfoAccess(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_SubjectInfoAccess)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printAuthorityInfoAccess(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_QC_Statements)) { - if(printExtensionCommon(*thisData, parser, verbose)) { - return; - } - printQualCertStatements(*thisData, parser); - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1IssuerName)) { - if(verbose) { - printf("Normalized Issuer : "); - printDataAsHex(thisData, 8); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SubjectName)) { - if(verbose) { - printf("Normalized Subject : "); - printDataAsHex(thisData, 8); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1IssuerNameStd)) { - if(verbose) { - printf("DER-encoded issuer : "); - printDataAsHex(thisData, 8); - } - } - else if(cuCompareCssmData(thisOid, &CSSMOID_X509V1SubjectNameStd)) { - if(verbose) { - printf("DER-encoded subject: "); - printDataAsHex(thisData, 8); - } - } - else { - printf("Other field: : "); printOid(parser, thisOid); - } -} - -static -void printCrlExten( - const CSSM_X509_EXTENSION *exten, - CSSM_BOOL verbose, - OidParser &parser) -{ - const CSSM_OID *oid = &exten->extnId; - const void *thisData = exten->value.parsedValue; - - if(exten->format == CSSM_X509_DATAFORMAT_ENCODED) { - if(printCdsaExtensionCommon(exten, parser, false, verbose)) { - return; - } - printf(" Unparsed data : "); printDataAsHex(&exten->BERvalue, 8); - } - else if(exten->format != CSSM_X509_DATAFORMAT_PARSED) { - printf("***Badly formatted CSSM_X509_EXTENSION\n"); - return; - } - else if(cuCompareCssmData(oid, &CSSMOID_AuthorityKeyIdentifier)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose)) { - return; - } - printCssmAuthorityKeyId((CE_AuthorityKeyID *)thisData, parser); - } - else if(cuCompareCssmData(oid, &CSSMOID_IssuerAltName)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose)) { - return; - } - printGeneralNames((CE_GeneralNames *)thisData, parser); - } - else if(cuCompareCssmData(oid, &CSSMOID_CrlNumber)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose)) { - return; - } - printf(" CRL Number : %u\n", *((unsigned *)thisData)); - } - else if(cuCompareCssmData(oid, &CSSMOID_DeltaCrlIndicator)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose)) { - return; - } - printf(" Delta CRL Base : %u\n", *((unsigned *)thisData)); - } - else if(cuCompareCssmData(oid, &CSSMOID_IssuingDistributionPoint)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose)) { - return; - } - printIssuingDistributionPoint((CE_IssuingDistributionPoint *)thisData, - parser); - } - else { - /* should never happen - we're out of sync with the CL */ - printf("UNKNOWN EXTENSION : "); printOid(parser, oid); - } -} - - -static -void printCrlEntryExten( - const CSSM_X509_EXTENSION *exten, - CSSM_BOOL verbose, - OidParser &parser) -{ - const CSSM_OID *oid = &exten->extnId; - const void *thisData = exten->value.parsedValue; - - if(exten->format == CSSM_X509_DATAFORMAT_ENCODED) { - if(printCdsaExtensionCommon(exten, parser, false, verbose, true)) { - return; - } - printf(" Unparsed data: "); printDataAsHex(&exten->BERvalue, 8); - } - else if(exten->format != CSSM_X509_DATAFORMAT_PARSED) { - printf("***Badly formatted CSSM_X509_EXTENSION\n"); - return; - } - else if(cuCompareCssmData(oid, &CSSMOID_CrlReason)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose, true)) { - return; - } - CE_CrlReason *cr = (CE_CrlReason *)thisData; - const char *reason = "UNKNOWN"; - switch(*cr) { - case CE_CR_Unspecified: - reason = "CE_CR_Unspecified"; break; - case CE_CR_KeyCompromise: - reason = "CE_CR_KeyCompromise"; break; - case CE_CR_CACompromise: - reason = "CE_CR_CACompromise"; break; - case CE_CR_AffiliationChanged: - reason = "CE_CR_AffiliationChanged"; break; - case CE_CR_Superseded: - reason = "CE_CR_Superseded"; break; - case CE_CR_CessationOfOperation: - reason = "CE_CR_CessationOfOperation"; break; - case CE_CR_CertificateHold: - reason = "CE_CR_CertificateHold"; break; - case CE_CR_RemoveFromCRL: - reason = "CE_CR_RemoveFromCRL"; break; - default: - break; - } - printf(" CRL Reason : %s\n", reason); - } - else if(cuCompareCssmData(oid, &CSSMOID_HoldInstructionCode)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose, true)) { - return; - } - printf(" Hold Instr : "); - printOid(parser, (CSSM_OID_PTR)thisData); - } - else if(cuCompareCssmData(oid, &CSSMOID_InvalidityDate)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose, true)) { - return; - } - printf(" Invalid Date : "); - printTimeStr((CSSM_DATA_PTR)thisData); - } - else if(cuCompareCssmData(oid, &CSSMOID_CertIssuer)) { - if(printCdsaExtensionCommon(exten, parser, true, verbose, true)) { - return; - } - printGeneralNames((CE_GeneralNames *)thisData, parser); - } - else { - /* should never happen - we're out of sync with the CL */ - printf("UNKNOWN EXTENSION : "); printOid(parser, oid); - } -} - -static -void printCrlFields( - const CSSM_X509_SIGNED_CRL *signedCrl, - CSSM_BOOL verbose, - OidParser &parser) -{ - unsigned i; - const CSSM_X509_TBS_CERTLIST *tbsCrl = &signedCrl->tbsCertList; - - if(tbsCrl->version.Data) { - printf("Version : %d\n", cuDER_ToInt(&tbsCrl->version)); - } - - printf("TBS Sig Algorithm : "); - const CSSM_X509_ALGORITHM_IDENTIFIER *algId = &tbsCrl->signature; - printSigAlg(algId, parser); - - printf("Issuer Name :\n"); - printName(&tbsCrl->issuer, parser); - - printf("This Update : "); - printTime(&tbsCrl->thisUpdate); - printf("Next Update : "); - if(tbsCrl->nextUpdate.time.Data) { - printTime(&tbsCrl->nextUpdate); - } - else { - printf("\n"); - } - - CSSM_X509_REVOKED_CERT_LIST_PTR certList = tbsCrl->revokedCertificates; - if(certList) { - if(verbose) { - printf("Num Revoked Certs : %d\n", - (int)certList->numberOfRevokedCertEntries); - for(i=0; inumberOfRevokedCertEntries; i++) { - CSSM_X509_REVOKED_CERT_ENTRY_PTR entry; - entry = &certList->revokedCertEntry[i]; - printf("Revoked Cert %d :\n", (int)i); - printf(" Serial number : "); - printDataAsHex(&entry->certificateSerialNumber, 0); - printf(" Revocation time : "); - printTime(&entry->revocationDate); - const CSSM_X509_EXTENSIONS *cssmExtens = &entry->extensions; - uint32 numExtens = cssmExtens->numberOfExtensions; - if(numExtens == 0) { - continue; - } - printf(" Num Extensions : %u\n", (unsigned)numExtens); - for(unsigned dex=0; dexextensions[dex], verbose, - parser); - } - } - } - else { - printf("Num Revoked Certs : %d (use verbose option to see)\n", - (int)certList->numberOfRevokedCertEntries); - } - } - - const CSSM_X509_EXTENSIONS *crlExtens = &tbsCrl->extensions; - if(crlExtens->numberOfExtensions) { - printf("Num CRL Extensions : %d\n", - (int)crlExtens->numberOfExtensions); - for(i=0; inumberOfExtensions; i++) { - printCrlExten(&crlExtens->extensions[i], verbose, parser); - } - } - - const CSSM_X509_SIGNATURE *sig = &signedCrl->signature; - if(sig->encrypted.Data) { - printf("Signature : %u bytes : ", (unsigned)sig->encrypted.Length); - printDataAsHex(&sig->encrypted, 8); - } -} - - -/* connect to CSSM/CL lazily, once */ -static CSSM_CL_HANDLE clHand = 0; - -int printCert( - const unsigned char *certData, - unsigned certLen, - CSSM_BOOL verbose) -{ - CSSM_FIELD_PTR fieldPtr; // mallocd by CL - uint32 i; - uint32 numFields; - OidParser parser; - CSSM_DATA cert; - - if(clHand == 0) { - clHand = cuClStartup(); - if(clHand == 0) { - printf("***Error connecting to CSSM cert module; aborting cert " - "display\n"); - return 0; - } - } - cert.Data = (uint8 *)certData; - cert.Length = certLen; - - CSSM_RETURN crtn = CSSM_CL_CertGetAllFields(clHand, - &cert, - &numFields, - &fieldPtr); - if(crtn) { - cuPrintError("CSSM_CL_CertGetAllFields", crtn); - return crtn; - } - - for(i=0; iData == NULL) || - (value->Length != sizeof(CSSM_X509_SIGNED_CRL))) { - printf("***CSSM_CL_CrlGetFirstFieldValue: value error (2)\n"); - return 1; - } - const CSSM_X509_SIGNED_CRL *signedCrl = - (const CSSM_X509_SIGNED_CRL *)value->Data; - printCrlFields(signedCrl, verbose, parser); - - crtn = CSSM_CL_FreeFieldValue(clHand, - &CSSMOID_X509V2CRLSignedCrlCStruct, - value); - if(crtn) { - cuPrintError("CSSM_CL_FreeFieldValue", crtn); - return crtn; - } - return 0; -} - - -void printCertShutdown() -{ - if(clHand != 0) { - CSSM_ModuleDetach(clHand); - } -} diff --git a/OSX/include/security_cdsa_utils/cuPrintCert.h b/OSX/include/security_cdsa_utils/cuPrintCert.h deleted file mode 100644 index 2ff3c150..00000000 --- a/OSX/include/security_cdsa_utils/cuPrintCert.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2002,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. - * Please obtain a copy of the License at http://www.apple.com/publicsource - * and read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights - * and limitations under the License. - */ - -/* - * cuPrintCert.h - text-based cert/CRL parser using CL - */ - -#ifndef _PRINT_CERT_H_ -#define _PRINT_CERT_H_ - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* print one field */ -void printCertField( - const CSSM_FIELD &field, - OidParser &parser, - CSSM_BOOL verbose); - -/* parse cert & print it */ -int printCert( - const unsigned char *certData, - unsigned certLen, - CSSM_BOOL verbose); - -/* print parsed CRL */ -void printCrlFields( - const CSSM_X509_SIGNED_CRL *signedCrl, - OidParser &parser); - -/* parse CRL & print it */ -int printCrl( - const unsigned char *crlData, - unsigned crlLen, - CSSM_BOOL verbose); - - -void printCertShutdown(); - -#ifdef __cplusplus -} -#endif - -#endif /* _PRINT_CERT_H_ */ diff --git a/OSX/include/security_cdsa_utils/cuTimeStr.cpp b/OSX/include/security_cdsa_utils/cuTimeStr.cpp deleted file mode 100644 index fe246994..00000000 --- a/OSX/include/security_cdsa_utils/cuTimeStr.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (c) 2002,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - -/* - * cuTimeStr.cpp - time string routines - */ -#include "cuTimeStr.h" -#include "cuCdsaUtils.h" -#include -#include -#include -#include -#include - -/* - * Given a string containing either a UTC-style or "generalized time" - * time string, convert to a struct tm (in GMT/UTC). Returns nonzero on - * error. - */ -int cuTimeStringToTm( - const char *str, - unsigned len, - struct tm *tmp) -{ - char szTemp[5]; - unsigned isUtc = 0; - unsigned noSeconds = 0; - int x; - unsigned i; - char *cp; - - if((str == NULL) || (len == 0) || (tmp == NULL)) { - return 1; - } - - /* tolerate NULL terminated or not */ - if(str[len - 1] == '\0') { - len--; - } - switch(len) { - case UTC_TIME_NOSEC_LEN: // 2-digit year, no seconds, not y2K compliant - isUtc = 1; - noSeconds = 1; - break; - case UTC_TIME_STRLEN: // 2-digit year, not Y2K compliant - isUtc = 1; - break; - case GENERALIZED_TIME_STRLEN: // 4-digit year - break; - default: // unknown format - return 1; - } - - cp = (char *)str; - - /* check that all characters except last are digits */ - for(i=0; i<(len - 1); i++) { - if ( !(isdigit(cp[i])) ) { - return 1; - } - } - - /* check last character is a 'Z' */ - if(cp[len - 1] != 'Z' ) { - return 1; - } - - /* YEAR */ - szTemp[0] = *cp++; - szTemp[1] = *cp++; - if(!isUtc) { - /* two more digits */ - szTemp[2] = *cp++; - szTemp[3] = *cp++; - szTemp[4] = '\0'; - } - else { - szTemp[2] = '\0'; - } - x = atoi( szTemp ); - if(isUtc) { - /* - * 2-digit year. - * 0 <= year < 50 : assume century 21 - * 50 <= year < 70 : illegal per PKIX, though we tolerate - * 70 < year <= 99 : assume century 20 - */ - if(x < 50) { - x += 2000; - } - /* - else if(x < 70) { - return 1; - } - */ - else { - /* century 20 */ - x += 1900; - } - } - /* by definition - tm_year is year - 1900 */ - tmp->tm_year = x - 1900; - - /* MONTH */ - szTemp[0] = *cp++; - szTemp[1] = *cp++; - szTemp[2] = '\0'; - x = atoi( szTemp ); - /* in the string, months are from 1 to 12 */ - if((x > 12) || (x <= 0)) { - return 1; - } - /* in a tm, 0 to 11 */ - tmp->tm_mon = x - 1; - - /* DAY */ - szTemp[0] = *cp++; - szTemp[1] = *cp++; - szTemp[2] = '\0'; - x = atoi( szTemp ); - /* 1..31 in both formats */ - if((x > 31) || (x <= 0)) { - return 1; - } - tmp->tm_mday = x; - - /* HOUR */ - szTemp[0] = *cp++; - szTemp[1] = *cp++; - szTemp[2] = '\0'; - x = atoi( szTemp ); - if((x > 23) || (x < 0)) { - return 1; - } - tmp->tm_hour = x; - - /* MINUTE */ - szTemp[0] = *cp++; - szTemp[1] = *cp++; - szTemp[2] = '\0'; - x = atoi( szTemp ); - if((x > 59) || (x < 0)) { - return 1; - } - tmp->tm_min = x; - - /* SECOND */ - if(noSeconds) { - tmp->tm_sec = 0; - } - else { - szTemp[0] = *cp++; - szTemp[1] = *cp++; - szTemp[2] = '\0'; - x = atoi( szTemp ); - if((x > 59) || (x < 0)) { - return 1; - } - tmp->tm_sec = x; - } - return 0; -} - -#define MAX_TIME_STR_LEN 30 - -/* protects time(), gmtime() */ -static pthread_mutex_t timeMutex = PTHREAD_MUTEX_INITIALIZER; - -char *cuTimeAtNowPlus(int secFromNow, - timeSpec spec) -{ - struct tm utc; - char *outStr; - time_t baseTime; - - pthread_mutex_lock(&timeMutex); - baseTime = time(NULL); - baseTime += (time_t)secFromNow; - utc = *gmtime(&baseTime); - pthread_mutex_unlock(&timeMutex); - - outStr = (char *)APP_MALLOC(MAX_TIME_STR_LEN); - - switch(spec) { - case TIME_UTC: - /* UTC - 2 year digits - code which parses this assumes that - * (2-digit) years between 0 and 49 are in century 21 */ - if(utc.tm_year >= 100) { - utc.tm_year -= 100; - } - sprintf(outStr, "%02d%02d%02d%02d%02d%02dZ", - utc.tm_year /* + 1900 */, utc.tm_mon + 1, - utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec); - break; - case TIME_GEN: - sprintf(outStr, "%04d%02d%02d%02d%02d%02dZ", - /* note year is relative to 1900, hopefully it'll - * have four valid digits! */ - utc.tm_year + 1900, utc.tm_mon + 1, - utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec); - break; - case TIME_CSSM: - sprintf(outStr, "%04d%02d%02d%02d%02d%02d", - /* note year is relative to 1900, hopefully it'll have - * four valid digits! */ - utc.tm_year + 1900, utc.tm_mon + 1, - utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec); - break; - } - return outStr; -} - -/* - * Convert a CSSM_X509_TIME, which can be in any of three forms (UTC, - * generalized, or CSSM_TIMESTRING) into a CSSM_TIMESTRING. Caller - * must free() the result. Returns NULL if x509time is badly formed. - */ -char *cuX509TimeToCssmTimestring( - const CSSM_X509_TIME *x509Time, - unsigned *rtnLen) // for caller's convenience -{ - int len = (int)x509Time->time.Length; - const char *inStr = (char *)x509Time->time.Data; - // not NULL terminated! - char *rtn; - - *rtnLen = 0; - if((len == 0) || (inStr == NULL)) { - return NULL; - } - rtn = (char *)malloc(CSSM_TIME_STRLEN + 1); - rtn[0] = '\0'; - switch(len) { - case UTC_TIME_STRLEN: - { - /* infer century and prepend to output */ - char tmp[3]; - int year; - tmp[0] = inStr[0]; - tmp[1] = inStr[1]; - tmp[2] = '\0'; - year = atoi(tmp); - - /* - * 0 <= year < 50 : assume century 21 - * 50 <= year < 70 : illegal per PKIX - * 70 < year <= 99 : assume century 20 - */ - if(year < 50) { - /* century 21 */ - strcpy(rtn, "20"); - } - else if(year < 70) { - free(rtn); - return NULL; - } - else { - /* century 20 */ - strcpy(rtn, "19"); - } - memmove(rtn + 2, inStr, len - 1); // don't copy the Z - break; - } - case CSSM_TIME_STRLEN: - memmove(rtn, inStr, len); // trivial case - break; - case GENERALIZED_TIME_STRLEN: - memmove(rtn, inStr, len - 1); // don't copy the Z - break; - - default: - free(rtn); - return NULL; - } - rtn[CSSM_TIME_STRLEN] = '\0'; - *rtnLen = CSSM_TIME_STRLEN; - return rtn; -} - diff --git a/OSX/include/security_cdsa_utils/cuTimeStr.h b/OSX/include/security_cdsa_utils/cuTimeStr.h deleted file mode 100644 index 0eefc56e..00000000 --- a/OSX/include/security_cdsa_utils/cuTimeStr.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2002,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. - * Please obtain a copy of the License at http://www.apple.com/publicsource - * and read it before using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights - * and limitations under the License. - */ - -/* - * cuTimeStr.h = Time string utilities. - */ - -#ifndef _TIME_STR_H_ -#define _TIME_STR_H_ - -#include -#include - -#define UTC_TIME_NOSEC_LEN 11 -#define UTC_TIME_STRLEN 13 -#define CSSM_TIME_STRLEN 14 /* no trailing 'Z' */ -#define GENERALIZED_TIME_STRLEN 15 - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Given a string containing either a UTC-style or "generalized time" - * time string, convert to a struct tm (in GMT/UTC). Returns nonzero on - * error. - */ -int cuTimeStringToTm( - const char *str, - unsigned len, - struct tm *tmp); - -typedef enum { - TIME_UTC, - TIME_CSSM, - TIME_GEN -} timeSpec; - -/* - * Return an APP_MALLOCd time string, specified format and time relative - * to 'now' in seconds. - */ -char *cuTimeAtNowPlus( - int secFromNow, - timeSpec spec); - -/* - * Convert a CSSM_X509_TIME, which can be in any of three forms (UTC, - * generalized, or CSSM_TIMESTRING) into a CSSM_TIMESTRING. Caller - * must free() the result. Returns NULL if x509time is badly formed. - */ -char *cuX509TimeToCssmTimestring( - const CSSM_X509_TIME *x509Time, - unsigned *rtnLen); // for caller's convenience - -#ifdef __cplusplus -} -#endif - -#endif /* _TIME_STR_H_ */ diff --git a/OSX/include/security_codesigning b/OSX/include/security_codesigning new file mode 120000 index 00000000..7c67092b --- /dev/null +++ b/OSX/include/security_codesigning @@ -0,0 +1 @@ +./libsecurity_codesigning/lib \ No newline at end of file diff --git a/OSX/include/security_codesigning/CSCommon.h b/OSX/include/security_codesigning/CSCommon.h deleted file mode 100644 index 70058cf1..00000000 --- a/OSX/include/security_codesigning/CSCommon.h +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header CSCommon - CSCommon is the common header of all Code Signing API headers. - It defines types, constants, and error codes. -*/ -#ifndef _H_CSCOMMON -#define _H_CSCOMMON - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -CF_ASSUME_NONNULL_BEGIN - -/* - Code Signing specific OSStatus codes. - [Assigned range 0xFFFE_FAxx]. -*/ -CF_ENUM(OSStatus) { - errSecCSUnimplemented = -67072, /* unimplemented code signing feature */ - errSecCSInvalidObjectRef = -67071, /* invalid API object reference */ - errSecCSInvalidFlags = -67070, /* invalid or inappropriate API flag(s) specified */ - errSecCSObjectRequired = -67069, /* a required pointer argument was NULL */ - errSecCSStaticCodeNotFound = -67068, /* cannot find code object on disk */ - errSecCSUnsupportedGuestAttributes = -67067, /* cannot locate guests using this attribute set */ - errSecCSInvalidAttributeValues = -67066, /* given attribute values are invalid */ - errSecCSNoSuchCode = -67065, /* host has no guest with the requested attributes */ - errSecCSMultipleGuests = -67064, /* ambiguous guest specification (host has multiple guests with these attribute values) */ - errSecCSGuestInvalid = -67063, /* code identity has been invalidated */ - errSecCSUnsigned = -67062, /* code object is not signed at all */ - errSecCSSignatureFailed = -67061, /* invalid signature (code or signature have been modified) */ - errSecCSSignatureNotVerifiable = -67060, /* the code cannot be read by the verifier (file system permissions etc.) */ - errSecCSSignatureUnsupported = -67059, /* unsupported type or version of signature */ - errSecCSBadDictionaryFormat = -67058, /* a required plist file or resource is malformed */ - errSecCSResourcesNotSealed = -67057, /* resources are present but not sealed by signature */ - errSecCSResourcesNotFound = -67056, /* code has no resources but signature indicates they must be present */ - errSecCSResourcesInvalid = -67055, /* the sealed resource directory is invalid */ - errSecCSBadResource = -67054, /* a sealed resource is missing or invalid */ - errSecCSResourceRulesInvalid = -67053, /* invalid resource specification rule(s) */ - errSecCSReqInvalid = -67052, /* invalid or corrupted code requirement(s) */ - errSecCSReqUnsupported = -67051, /* unsupported type or version of code requirement(s) */ - errSecCSReqFailed = -67050, /* code failed to satisfy specified code requirement(s) */ - errSecCSBadObjectFormat = -67049, /* object file format unrecognized, invalid, or unsuitable */ - errSecCSInternalError = -67048, /* internal error in Code Signing subsystem */ - errSecCSHostReject = -67047, /* code rejected its host */ - errSecCSNotAHost = -67046, /* attempt to specify guest of code that is not a host */ - errSecCSSignatureInvalid = -67045, /* invalid or unsupported format for signature */ - errSecCSHostProtocolRelativePath = -67044, /* host protocol violation - absolute guest path required */ - errSecCSHostProtocolContradiction = -67043, /* host protocol violation - contradictory hosting modes */ - errSecCSHostProtocolDedicationError = -67042, /* host protocol violation - operation not allowed with/for a dedicated guest */ - errSecCSHostProtocolNotProxy = -67041, /* host protocol violation - proxy hosting not engaged */ - errSecCSHostProtocolStateError = -67040, /* host protocol violation - invalid guest state change request */ - errSecCSHostProtocolUnrelated = -67039, /* host protocol violation - the given guest is not a guest of the given host */ - /* -67038 obsolete (no longer issued) */ - errSecCSNotSupported = -67037, /* operation inapplicable or not supported for this type of code */ - errSecCSCMSTooLarge = -67036, /* signature too large to embed (size limitation of on-disk representation) */ - errSecCSHostProtocolInvalidHash = -67035, /* host protocol violation - invalid guest hash */ - errSecCSStaticCodeChanged = -67034, /* the code on disk does not match what is running */ - errSecCSDBDenied = -67033, /* permission to use a database denied */ - errSecCSDBAccess = -67032, /* cannot access a database */ - errSecCSSigDBDenied = errSecCSDBDenied, - errSecCSSigDBAccess = errSecCSDBAccess, - errSecCSHostProtocolInvalidAttribute = -67031, /* host returned invalid or inconsistent guest attributes */ - errSecCSInfoPlistFailed = -67030, /* invalid Info.plist (plist or signature have been modified) */ - errSecCSNoMainExecutable = -67029, /* the code has no main executable file */ - errSecCSBadBundleFormat = -67028, /* bundle format unrecognized, invalid, or unsuitable */ - errSecCSNoMatches = -67027, /* no matches for search or update operation */ - errSecCSFileHardQuarantined = -67026, /* File created by an AppSandbox, exec/open not allowed */ - errSecCSOutdated = -67025, /* presented data is out of date */ - errSecCSDbCorrupt = -67024, /* a system database or file is corrupt */ - errSecCSResourceDirectoryFailed = -67023, /* invalid resource directory (directory or signature have been modified) */ - errSecCSUnsignedNestedCode = -67022, /* nested code is unsigned */ - errSecCSBadNestedCode = -67021, /* nested code is modified or invalid */ - errSecCSBadCallbackValue = -67020, /* monitor callback returned invalid value */ - errSecCSHelperFailed = -67019, /* the codesign_allocate helper tool cannot be found or used */ - errSecCSVetoed = -67018, - errSecCSBadLVArch = -67017, /* library validation flag cannot be used with an i386 binary */ - errSecCSResourceNotSupported = -67016, /* unsupported resource found (something not a directory, file or symlink) */ - errSecCSRegularFile = -67015, /* the main executable or Info.plist must be a regular file (no symlinks, etc.) */ - errSecCSUnsealedAppRoot = -67014, /* unsealed contents present in the bundle root */ - errSecCSWeakResourceRules = -67013, /* resource envelope is obsolete (custom omit rules) */ - errSecCSDSStoreSymlink = -67012, /* .DS_Store files cannot be a symlink */ - errSecCSAmbiguousBundleFormat = -67011, /* bundle format is ambiguous (could be app or framework) */ - errSecCSBadMainExecutable = -67010, /* main executable failed strict validation */ - errSecCSBadFrameworkVersion = -67009, /* embedded framework contains modified or invalid version */ - errSecCSUnsealedFrameworkRoot = -67008, /* unsealed contents present in the root directory of an embedded framework */ - errSecCSWeakResourceEnvelope = -67007, /* resource envelope is obsolete (version 1 signature) */ - errSecCSCancelled = -67006, /* operation was terminated by explicit cancellation */ - errSecCSInvalidPlatform = -67005, /* invalid platform identifier or platform mismatch */ - errSecCSTooBig = -67004, /* code is too big for current signing format */ - errSecCSInvalidSymlink = -67003, /* invalid destination for symbolic link in bundle */ -}; - -/* - * Code Signing specific CFError "user info" keys. - * In calls that can return CFErrorRef indications, if a CFErrorRef is actually - * returned, its "user info" dictionary may contain some of the following keys - * to more closely describe the circumstances of the failure. - * Do not rely on the presence of any particular key to categorize a problem; - * always use the primary OSStatus return for that. The data contained under - * these keys is always supplemental and optional. - */ -extern const CFStringRef kSecCFErrorArchitecture; /* CFStringRef: name of architecture causing the problem */ -extern const CFStringRef kSecCFErrorPattern; /* CFStringRef: invalid resource selection pattern encountered */ -extern const CFStringRef kSecCFErrorResourceSeal; /* CFTypeRef: invalid component in resource seal (CodeResources) */ -extern const CFStringRef kSecCFErrorResourceAdded; /* CFURLRef: unsealed resource found */ -extern const CFStringRef kSecCFErrorResourceAltered; /* CFURLRef: modified resource found */ -extern const CFStringRef kSecCFErrorResourceMissing; /* CFURLRef: sealed (non-optional) resource missing */ -extern const CFStringRef kSecCFErrorInfoPlist; /* CFTypeRef: Info.plist dictionary or component thereof found invalid */ -extern const CFStringRef kSecCFErrorGuestAttributes; /* CFTypeRef: Guest attribute set of element not accepted */ -extern const CFStringRef kSecCFErrorRequirementSyntax; /* CFStringRef: compilation error for Requirement source */ -extern const CFStringRef kSecCFErrorPath; /* CFURLRef: subcomponent containing the error */ - -/*! - @typedef SecCodeRef - This is the type of a reference to running code. - - In many (but not all) calls, this can be passed to a SecStaticCodeRef - argument, which performs an implicit SecCodeCopyStaticCode call and - operates on the result. -*/ -typedef struct CF_BRIDGED_TYPE(id) __SecCode *SecCodeRef; /* running code */ - -/*! - @typedef SecStaticCodeRef - This is the type of a reference to static code on disk. -*/ -typedef struct CF_BRIDGED_TYPE(id) __SecCode const *SecStaticCodeRef; /* code on disk */ - -/*! - @typedef SecRequirementRef - This is the type of a reference to a code requirement. -*/ -typedef struct CF_BRIDGED_TYPE(id) __SecRequirement *SecRequirementRef; /* code requirement */ - - -/*! - @typedef SecGuestRef - An abstract handle to identify a particular Guest in the context of its Host. - - Guest handles are assigned by the host at will, with kSecNoGuest (zero) being - reserved as the null value. They can be reused for new children if desired. -*/ -typedef u_int32_t SecGuestRef; - -CF_ENUM(SecGuestRef) { - kSecNoGuest = 0, /* not a valid SecGuestRef */ -}; - - -/*! - @typedef SecCSFlags - This is the type of flags arguments to Code Signing API calls. - It provides a bit mask of request and option flags. All of the bits in these - masks are reserved to Apple; if you set any bits not defined in these headers, - the behavior is generally undefined. - - This list describes the flags that are shared among several Code Signing API calls. - Flags that only apply to one call are defined and documented with that call. - Global flags are assigned from high order down (31 -> 0); call-specific flags - are assigned from the bottom up (0 -> 31). - - @constant kSecCSDefaultFlags - When passed to a flags argument throughout, indicates that default behavior - is desired. Do not mix with other flags values. - @constant kSecCSConsiderExpiration - When passed to a call that performs code validation, requests that code signatures - made by expired certificates be rejected. By default, expiration of participating - certificates is not automatic grounds for rejection. -*/ -typedef CF_OPTIONS(uint32_t, SecCSFlags) { - kSecCSDefaultFlags = 0, /* no particular flags (default behavior) */ - - kSecCSConsiderExpiration = 1 << 31, /* consider expired certificates invalid */ - kSecCSEnforceRevocationChecks = 1 << 30, /* force revocation checks regardless of preference settings */ - kSecCSNoNetworkAccess = 1 << 29, /* do not use the network, cancels "kSecCSEnforceRevocationChecks" */ - kSecCSReportProgress = 1 << 28, /* make progress report call-backs when configured */ - kSecCSCheckTrustedAnchors = 1 << 27, /* build certificate chain to system trust anchors, not to any self-signed certificate */ -}; - - -/*! - @typedef SecCodeSignatureFlags - This is the type of option flags that can be embedded in a code signature - during signing, and that govern the use of the signature thereafter. - Some of these flags can be set through the codesign(1) command's --options - argument; some are set implicitly based on signing circumstances; and all - can be set with the kSecCodeSignerFlags item of a signing information dictionary. - - @constant kSecCodeSignatureHost - Indicates that the code may act as a host that controls and supervises guest - code. If this flag is not set in a code signature, the code is never considered - eligible to be a host, and any attempt to act like one will be ignored or rejected. - @constant kSecCodeSignatureAdhoc - The code has been sealed without a signing identity. No identity may be retrieved - from it, and any code requirement placing restrictions on the signing identity - will fail. This flag is set by the code signing API and cannot be set explicitly. - @constant kSecCodeSignatureForceHard - Implicitly set the "hard" status bit for the code when it starts running. - This bit indicates that the code prefers to be denied access to a resource - if gaining such access would cause its invalidation. Since the hard bit is - sticky, setting this option bit guarantees that the code will always have - it set. - @constant kSecCodeSignatureForceKill - Implicitly set the "kill" status bit for the code when it starts running. - This bit indicates that the code wishes to be terminated with prejudice if - it is ever invalidated. Since the kill bit is sticky, setting this option bit - guarantees that the code will always be dynamically valid, since it will die - immediately if it becomes invalid. - @constant kSecCodeSignatureForceExpiration - Forces the kSecCSConsiderExpiration flag on all validations of the code. - */ -typedef CF_OPTIONS(uint32_t, SecCodeSignatureFlags) { - kSecCodeSignatureHost = 0x0001, /* may host guest code */ - kSecCodeSignatureAdhoc = 0x0002, /* must be used without signer */ - kSecCodeSignatureForceHard = 0x0100, /* always set HARD mode on launch */ - kSecCodeSignatureForceKill = 0x0200, /* always set KILL mode on launch */ - kSecCodeSignatureForceExpiration = 0x0400, /* force certificate expiration checks */ - kSecCodeSignatureRestrict = 0x0800, /* restrict dyld loading */ - kSecCodeSignatureEnforcement = 0x1000, /* enforce code signing */ - kSecCodeSignatureLibraryValidation = 0x2000, /* library validation required */ -}; - - -/*! - @typedef SecCodeStatus - The code signing system attaches a set of status flags to each running code. - These flags are maintained by the code's host, and can be read by anyone. - A code may change its own flags, a host may change its guests' flags, - and root may change anyone's flags. However, these flags are sticky in that - each can change in only one direction (and never back, for the lifetime of the code). - Not even root can violate this restriction. - - There are other flags in SecCodeStatus that are not publicly documented. - Do not rely on them, and do not ever attempt to explicitly set them. - - @constant kSecCodeStatusValid - Indicates that the code is dynamically valid, i.e. it started correctly - and has not been invalidated since then. The valid bit can only be cleared. - - Warning: This bit is not your one-stop shortcut to determining the validity of code. - It represents the dynamic component of the full validity function; if this - bit is unset, the code is definitely invalid, but the converse is not always true. - In fact, code hosts may represent the outcome of some delayed static validation work in this bit, - and thus it strictly represents a blend of (all of) dynamic and (some of) static validity, - depending on the implementation of the particular host managing the code. You can (only) - rely that (1) dynamic invalidation will clear this bit; and (2) the combination - of static validation and dynamic validity (as performed by the SecCodeCheckValidity* APIs) - will give a correct answer. - - @constant kSecCodeStatusHard - Indicates that the code prefers to be denied access to resources if gaining access - would invalidate it. This bit can only be set. - It is undefined whether code that is marked hard and is already invalid will still - be denied access to a resource that would invalidate it if it were still valid. That is, - the code may or may not get access to such a resource while being invalid, and that choice - may appear random. - - @constant kSecCodeStatusKill - Indicates that the code wants to be killed (terminated) if it ever loses its validity. - This bit can only be set. Code that has the kill flag set will never be dynamically invalid - (and live). Note however that a change in static validity does not necessarily trigger instant - death. -*/ -typedef CF_OPTIONS(uint32_t, SecCodeStatus) { - kSecCodeStatusValid = 0x0001, - kSecCodeStatusHard = 0x0100, - kSecCodeStatusKill = 0x0200, -}; - - -/*! - @typedef SecRequirementType - An enumeration indicating different types of internal requirements for code. - */ -typedef CF_ENUM(uint32_t, SecRequirementType) { - kSecHostRequirementType = 1, /* what hosts may run us */ - kSecGuestRequirementType = 2, /* what guests we may run */ - kSecDesignatedRequirementType = 3, /* designated requirement */ - kSecLibraryRequirementType = 4, /* what libraries we may link against */ - kSecPluginRequirementType = 5, /* what plug-ins we may load */ - kSecInvalidRequirementType, /* invalid type of Requirement (must be last) */ - kSecRequirementTypeCount = kSecInvalidRequirementType /* number of valid requirement types */ -}; - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif //_H_CSCOMMON diff --git a/OSX/include/security_codesigning/CSCommonPriv.h b/OSX/include/security_codesigning/CSCommonPriv.h deleted file mode 100644 index a03ac61d..00000000 --- a/OSX/include/security_codesigning/CSCommonPriv.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header CSCommonPriv - SecStaticCodePriv is the private counter-part to CSCommon. Its contents are not - official API, and are subject to change without notice. -*/ -#ifndef _H_CSCOMMONPRIV -#define _H_CSCOMMONPRIV - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/*! - @typedef SecCodeDirectoryFlagTable - This constant array can be used to translate between names and values - of CodeDirectory flag bits. The table ends with an entry with NULL name. - The elements are in no particular order. - @field name The official text name of the flag. - @field value The binary value of the flag. - @field signable True if the flag can be specified during signing. False if it is set - internally and can only be read from a signature. - */ -typedef struct { - const char *name; - uint32_t value; - bool signable; -} SecCodeDirectoryFlagTable; - -extern const SecCodeDirectoryFlagTable kSecCodeDirectoryFlagTable[]; - - -/*! - Blob types (magic numbers) for blobs used by Code Signing. - - @constant kSecCodeMagicRequirement Magic number for individual code requirements. - @constant kSecCodeMagicRequirementSet Magic number for a collection of - individual code requirements, indexed by requirement type. This is used - for internal requirement sets. - @constant kSecCodeMagicCodeDirectory Magic number for a CodeDirectory. - @constant kSecCodeMagicEmbeddedSignature Magic number for a SuperBlob - containing all the signing components that are usually embedded within - a main executable. - @constant kSecCodeMagicDetachedSignature Magic number for a SuperBlob that - contains all the data for all architectures of a signature, including any - data that is usually written to separate files. This is the format of - detached signatures if the program is capable of having multiple architectures. - @constant kSecCodeMagicEntitlement Magic number for a standard entitlement blob. - @constant kSecCodeMagicByte The first byte (in NBO) shared by all these magic - numbers. This is not a valid ASCII character; test for this to distinguish - between text and binary data if you expect a code signing-related binary blob. - */ - -enum { - kSecCodeMagicRequirement = 0xfade0c00, /* single requirement */ - kSecCodeMagicRequirementSet = 0xfade0c01, /* requirement set */ - kSecCodeMagicCodeDirectory = 0xfade0c02, /* CodeDirectory */ - kSecCodeMagicEmbeddedSignature = 0xfade0cc0, /* single-architecture embedded signature */ - kSecCodeMagicDetachedSignature = 0xfade0cc1, /* detached multi-architecture signature */ - kSecCodeMagicEntitlement = 0xfade7171, /* entitlement blob */ - - kSecCodeMagicByte = 0xfa /* shared first byte */ -}; - - -/*! - Types of cryptographic digests (hashes) used to hold code signatures - together. - - Each combination of type, length, and other parameters is a separate - hash type; we don't understand "families" here. - - These type codes govern the digest links that connect a CodeDirectory - to its subordinate data structures (code pages, resources, etc.) - They do not directly control other uses of hashes (such as the - hash-of-CodeDirectory identifiers used in requirements). - */ -enum { - kSecCodeSignatureNoHash = 0, /* null value */ - kSecCodeSignatureHashSHA1 = 1, /* SHA-1 */ - kSecCodeSignatureHashSHA256 = 2, /* SHA-256 */ - kSecCodeSignatureHashSHA256Truncated = 3, /* SHA-256 truncated to first 20 bytes */ - - kSecCodeSignatureDefaultDigestAlgorithm = kSecCodeSignatureHashSHA1 -}; - - -/* - The current (fixed) size of a cdhash in the system. - */ -enum { - kSecCodeCDHashLength = 20 -}; - - -/*! - A callback block type for monitoring certain code signing operations - */ -typedef CFTypeRef (^SecCodeCallback)(SecStaticCodeRef code, CFStringRef stage, CFDictionaryRef info); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_CSCOMMON diff --git a/OSX/include/security_codesigning/Code.cpp b/OSX/include/security_codesigning/Code.cpp deleted file mode 100644 index 643c4f58..00000000 --- a/OSX/include/security_codesigning/Code.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Code - SecCode API objects -// -#include "Code.h" -#include "StaticCode.h" -#include -#include "cskernel.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// Construction -// -SecCode::SecCode(SecCode *host) - : mHost(host), mIdentified(false) -{ - CODESIGN_DYNAMIC_CREATE(this, host); -} - - -// -// Clean up a SecCode object -// -SecCode::~SecCode() throw() -try { -} catch (...) { - return; -} - - -// -// CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed, -// and falls back on comparing canonical paths if (both are) not. -// -bool SecCode::equal(SecCFObject &secOther) -{ - SecCode *other = static_cast(&secOther); - CFDataRef mine = this->cdHash(); - CFDataRef his = other->cdHash(); - if (mine || his) - return mine && his && CFEqual(mine, his); - else - return this->staticCode()->equal(*other->staticCode()); -} - -CFHashCode SecCode::hash() -{ - if (CFDataRef h = this->cdHash()) - return CFHash(h); - else - return this->staticCode()->hash(); -} - - -// -// Yield the host Code -// -SecCode *SecCode::host() const -{ - return mHost; -} - - -// -// Yield the static code. This is cached. -// The caller does not own the object returned; it lives (at least) as long -// as the SecCode it was derived from. -// -SecStaticCode *SecCode::staticCode() -{ - if (!mIdentified) { - this->identify(); - mIdentified = true; - } - assert(mStaticCode); - return mStaticCode; -} - - -// -// Yield the CodeDirectory hash as presented by our host. -// This usually is the same as the hash of staticCode().codeDirectory(), but might not -// if files are changing on disk while code is running. -// -CFDataRef SecCode::cdHash() -{ - if (!mIdentified) { - this->identify(); - mIdentified = true; - } - return mCDHash; // can be NULL (host has no dynamic identity for guest) -} - - -// -// Retrieve current dynamic status. -// -SecCodeStatus SecCode::status() -{ - if (this->isRoot()) - return kSecCodeStatusValid; // root of trust, presumed valid - else - return this->host()->getGuestStatus(this); -} - -void SecCode::status(SecCodeStatusOperation operation, CFDictionaryRef arguments) -{ - if (this->isRoot()) - MacOSError::throwMe(errSecCSHostProtocolStateError); - else - this->host()->changeGuestStatus(this, operation, arguments); -} - - -// -// By default, we have no guests -// -SecCode *SecCode::locateGuest(CFDictionaryRef) -{ - return NULL; -} - - -// -// By default, we self-identify by asking our host to identify us. -// (This is currently only overridden in the root-of-trust (kernel) implementation.) -// -void SecCode::identify() -{ - mStaticCode.take(host()->identifyGuest(this, &mCDHash.aref())); -} - - -// -// The default implementation cannot map guests to disk -// -SecStaticCode *SecCode::identifyGuest(SecCode *, CFDataRef *) -{ - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -// -// Master validation function. -// -// This is the most important function in all of Code Signing. It performs -// dynamic validation on running code. Despite its simple structure, it does -// everything that's needed to establish whether a Code is currently valid... -// with a little help from StaticCode, format drivers, type drivers, and so on. -// -// This function validates internal requirements in the hosting chain. It does -// not validate external requirements - the caller needs to do that with a separate call. -// -void SecCode::checkValidity(SecCSFlags flags) -{ - if (this->isRoot()) { - // the root-of-trust is valid by definition - CODESIGN_EVAL_DYNAMIC_ROOT(this); - return; - } - DTRACK(CODESIGN_EVAL_DYNAMIC, this, (char*)this->staticCode()->mainExecutablePath().c_str()); - - // - // Do not reorder the operations below without thorough cogitation. There are - // interesting dependencies and significant performance issues. There is also - // client code that relies on errors being noticed in a particular order. - // - // For the most part, failure of (reliable) identity will cause exceptions to be - // thrown, and success is indicated by survival. If you make it to the end, - // you have won the validity race. (Good rat.) - // - - // check my host first, recursively - this->host()->checkValidity(flags); - - SecStaticCode *myDisk = this->staticCode(); - myDisk->setValidationFlags(flags); - SecStaticCode *hostDisk = this->host()->staticCode(); - - // check my static state - myDisk->validateDirectory(); - - // check my own dynamic state - if (!(this->host()->getGuestStatus(this) & kSecCodeStatusValid)) - MacOSError::throwMe(errSecCSGuestInvalid); - - // check that static and dynamic views are consistent - if (this->cdHash() && !CFEqual(this->cdHash(), myDisk->cdHash())) - MacOSError::throwMe(errSecCSStaticCodeChanged); - - // check host/guest constraints - if (!this->host()->isRoot()) { // not hosted by root of trust - myDisk->validateRequirements(kSecHostRequirementType, hostDisk, errSecCSHostReject); - hostDisk->validateRequirements(kSecGuestRequirementType, myDisk); - } -} - - -// -// By default, we track no validity for guests (we don't have any) -// -uint32_t SecCode::getGuestStatus(SecCode *guest) -{ - MacOSError::throwMe(errSecCSNoSuchCode); -} - -void SecCode::changeGuestStatus(SecCode *guest, SecCodeStatusOperation operation, CFDictionaryRef arguments) -{ - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -// -// Given a bag of attribute values, automagically come up with a SecCode -// without any other information. -// This is meant to be the "just do what makes sense" generic call, for callers -// who don't want to engage in the fascinating dance of manual guest enumeration. -// -// Note that we expect the logic embedded here to change over time (in backward -// compatible fashion, one hopes), and that it's all right to use heuristics here -// as long as it's done sensibly. -// -// Be warned that the present logic is quite a bit ad-hoc, and will likely not -// handle arbitrary combinations of proxy hosting, dynamic hosting, and dedicated -// hosting all that well. -// -SecCode *SecCode::autoLocateGuest(CFDictionaryRef attributes, SecCSFlags flags) -{ - // special case: with no attributes at all, return the root of trust - if (CFDictionaryGetCount(attributes) == 0) - return KernelCode::active()->retain(); - - // main logic: we need a pid, and we'll take a canonical guest id as an option - int pid = 0; - if (!cfscan(attributes, "{%O=%d}", kSecGuestAttributePid, &pid)) - CSError::throwMe(errSecCSUnsupportedGuestAttributes, kSecCFErrorGuestAttributes, attributes); - if (SecCode *process = - KernelCode::active()->locateGuest(attributes)) { - SecPointer code; - code.take(process); // locateGuest gave us a retained object - if (code->staticCode()->flag(kSecCodeSignatureHost)) { - // might be a code host. Let's find out - CFRef rest = makeCFMutableDictionary(attributes); - CFDictionaryRemoveValue(rest, kSecGuestAttributePid); - if (SecCode *guest = code->locateGuest(rest)) - return guest; - } - if (!CFDictionaryGetValue(attributes, kSecGuestAttributeCanonical)) { - // only "soft" attributes, and no hosting is happening. Return the (non-)host itself - return code.yield(); - } - } - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/Code.h b/OSX/include/security_codesigning/Code.h deleted file mode 100644 index aa5942c9..00000000 --- a/OSX/include/security_codesigning/Code.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Code - SecCode API objects -// -#ifndef _H_CODE -#define _H_CODE - -#include "cs.h" -#include "Requirements.h" -#include - -namespace Security { -namespace CodeSigning { - - -class SecStaticCode; - - -// -// A SecCode object represents running code in the system. It must be subclassed -// to implement a particular notion of code. -// -class SecCode : public SecCFObject { - NOCOPY(SecCode) - friend class KernelCode; // overrides identify() to set mStaticCode/mCDHash -public: - SECCFFUNCTIONS(SecCode, SecCodeRef, errSecCSInvalidObjectRef, gCFObjects().Code) - - SecCode(SecCode *host); - virtual ~SecCode() throw(); - - bool equal(SecCFObject &other); - CFHashCode hash(); - - SecCode *host() const; - bool isRoot() const { return host() == NULL; } - SecStaticCode *staticCode(); // cached. Result lives as long as this SecCode - CFDataRef cdHash(); - - SecCodeStatus status(); // dynamic status - void status(SecCodeStatusOperation operation, CFDictionaryRef arguments); - - // primary virtual drivers. Caller owns the result - virtual void identify(); - virtual SecCode *locateGuest(CFDictionaryRef attributes); - virtual SecStaticCode *identifyGuest(SecCode *guest, CFDataRef *cdhash); - - void checkValidity(SecCSFlags flags); - virtual SecCodeStatus getGuestStatus(SecCode *guest); - virtual void changeGuestStatus(SecCode *guest, SecCodeStatusOperation operation, CFDictionaryRef arguments); - -public: - // perform "autolocation" (root-based heuristic). Caller owns the result - static SecCode *autoLocateGuest(CFDictionaryRef attributes, SecCSFlags flags); - -private: - SecPointer mHost; - bool mIdentified; // called identify(), mStaticCode & mCDHash are valid - SecPointer mStaticCode; // (static) code origin - CFRef mCDHash; // (dynamic) CodeDirectory hash as per host -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CODE diff --git a/OSX/include/security_codesigning/CodeSigner.cpp b/OSX/include/security_codesigning/CodeSigner.cpp deleted file mode 100644 index 3d80482c..00000000 --- a/OSX/include/security_codesigning/CodeSigner.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// CodeSigner - SecCodeSigner API objects -// -#include "CodeSigner.h" -#include "signer.h" -#include "csdatabase.h" -#include "drmaker.h" -#include "csutilities.h" -#include -#include -#include -#include -#include - -namespace Security { - -__SEC_CFTYPE(SecIdentity) - -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// A helper for parsing out a CFDictionary signing-data specification -// -class SecCodeSigner::Parser : CFDictionary { -public: - Parser(SecCodeSigner &signer, CFDictionaryRef parameters); - - bool getBool(CFStringRef key) const - { - if (CFBooleanRef flag = get(key)) - return flag == kCFBooleanTrue; - else - return false; - } -}; - - -// -// Construct a SecCodeSigner -// -SecCodeSigner::SecCodeSigner(SecCSFlags flags) - : mOpFlags(flags), mDigestAlgorithm(kSecCodeSignatureDefaultDigestAlgorithm), mLimitedAsync(NULL) -{ -} - - -// -// Clean up a SecCodeSigner -// -SecCodeSigner::~SecCodeSigner() throw() -try { - delete mLimitedAsync; -} catch (...) { - return; -} - - -// -// Parse an input parameter dictionary and set ready-to-use parameters -// -void SecCodeSigner::parameters(CFDictionaryRef paramDict) -{ - Parser(*this, paramDict); - if (!valid()) - MacOSError::throwMe(errSecCSInvalidObjectRef); -} - -// -// Retrieve the team ID from the signing certificate if and only if -// it is an apple developer signing cert -// -std::string SecCodeSigner::getTeamIDFromSigner(CFArrayRef certs) -{ - if (mSigner && mSigner != SecIdentityRef(kCFNull)) { - CFRef signerCert; - MacOSError::check(SecIdentityCopyCertificate(mSigner, &signerCert.aref())); - - /* Make sure the certificate looks like an Apple certificate, because we do not - extract the team ID from a non Apple certificate */ - if (SecStaticCode::isAppleDeveloperCert(certs)) { - CFRef teamIDFromCert; - - MacOSError::check(SecCertificateCopySubjectComponent(signerCert.get(), &CSSMOID_OrganizationalUnitName, &teamIDFromCert.aref())); - - if (teamIDFromCert) - return cfString(teamIDFromCert); - } - } - - return ""; -} - -// -// Roughly check for validity. -// This isn't thorough; it just sees if if looks like we've set up the object appropriately. -// -bool SecCodeSigner::valid() const -{ - if (mOpFlags & kSecCSRemoveSignature) - return true; - return mSigner; -} - - -// -// Sign code -// -void SecCodeSigner::sign(SecStaticCode *code, SecCSFlags flags) -{ - code->setValidationFlags(flags); - if (code->isSigned() && (flags & kSecCSSignPreserveSignature)) - return; - Signer operation(*this, code); - if ((flags | mOpFlags) & kSecCSRemoveSignature) { - secdebug("signer", "%p will remove signature from %p", this, code); - operation.remove(flags); - } else { - if (!valid()) - MacOSError::throwMe(errSecCSInvalidObjectRef); - secdebug("signer", "%p will sign %p (flags 0x%x)", this, code, flags); - operation.sign(flags); - } - code->resetValidity(); -} - - -// -// ReturnDetachedSignature is called by writers or editors that try to return -// detached signature data (rather than annotate the target). -// -void SecCodeSigner::returnDetachedSignature(BlobCore *blob, Signer &signer) -{ - assert(mDetached); - if (CFGetTypeID(mDetached) == CFURLGetTypeID()) { - // URL to destination file - AutoFileDesc fd(cfString(CFURLRef(mDetached.get())), O_WRONLY | O_CREAT | O_TRUNC); - fd.writeAll(*blob); - } else if (CFGetTypeID(mDetached) == CFDataGetTypeID()) { - CFDataAppendBytes(CFMutableDataRef(mDetached.get()), - (const UInt8 *)blob, blob->length()); - } else if (CFGetTypeID(mDetached) == CFNullGetTypeID()) { - SignatureDatabaseWriter db; - db.storeCode(blob, signer.path().c_str()); - } else - assert(false); -} - - -// -// Our DiskRep::signingContext methods communicate with the signing subsystem -// in terms those callers can easily understand. -// -string SecCodeSigner::sdkPath(const std::string &path) const -{ - assert(path[0] == '/'); // need absolute path here - if (mSDKRoot) - return cfString(mSDKRoot) + path; - else - return path; -} - -bool SecCodeSigner::isAdhoc() const -{ - return mSigner == SecIdentityRef(kCFNull); -} - -SecCSFlags SecCodeSigner::signingFlags() const -{ - return mOpFlags; -} - - -// -// The actual parsing operation is done in the Parser class. -// -// Note that we need to copy or retain all incoming data. The caller has no requirement -// to keep the parameters dictionary around. -// -SecCodeSigner::Parser::Parser(SecCodeSigner &state, CFDictionaryRef parameters) - : CFDictionary(parameters, errSecCSBadDictionaryFormat) -{ - // the signer may be an identity or null - state.mSigner = SecIdentityRef(get(kSecCodeSignerIdentity)); - if (state.mSigner) - if (CFGetTypeID(state.mSigner) != SecIdentityGetTypeID() && !CFEqual(state.mSigner, kCFNull)) - MacOSError::throwMe(errSecCSInvalidObjectRef); - - // the flags need some augmentation - if (CFNumberRef flags = get(kSecCodeSignerFlags)) { - state.mCdFlagsGiven = true; - state.mCdFlags = cfNumber(flags); - } else - state.mCdFlagsGiven = false; - - // digest algorithms are specified as a numeric code - if (CFNumberRef digestAlgorithm = get(kSecCodeSignerDigestAlgorithm)) - state.mDigestAlgorithm = cfNumber(digestAlgorithm); - - if (CFNumberRef cmsSize = get(CFSTR("cmssize"))) - state.mCMSSize = cfNumber(cmsSize); - else - state.mCMSSize = 9000; // likely big enough - - // metadata preservation options - if (CFNumberRef preserve = get(kSecCodeSignerPreserveMetadata)) { - state.mPreserveMetadata = cfNumber(preserve); - } else - state.mPreserveMetadata = 0; - - // signing time can be a CFDateRef or null - if (CFTypeRef time = get(kSecCodeSignerSigningTime)) { - if (CFGetTypeID(time) == CFDateGetTypeID() || time == kCFNull) - state.mSigningTime = CFDateRef(time); - else - MacOSError::throwMe(errSecCSInvalidObjectRef); - } - - if (CFStringRef ident = get(kSecCodeSignerIdentifier)) - state.mIdentifier = cfString(ident); - - if (CFStringRef teamid = get(kSecCodeSignerTeamIdentifier)) - state.mTeamID = cfString(teamid); - - if (CFNumberRef platform = get(kSecCodeSignerPlatformIdentifier)) { - int64_t ident = cfNumber(platform); - if (ident < 0 || ident > maxPlatform) // overflow - MacOSError::throwMe(errSecCSInvalidPlatform); - state.mPlatform = ident; - } - - if (CFStringRef prefix = get(kSecCodeSignerIdentifierPrefix)) - state.mIdentifierPrefix = cfString(prefix); - - // Requirements can be binary or string (to be compiled). - // We must pass them along to the signer for possible text substitution - if (CFTypeRef reqs = get(kSecCodeSignerRequirements)) { - if (CFGetTypeID(reqs) == CFDataGetTypeID() || CFGetTypeID(reqs) == CFStringGetTypeID()) - state.mRequirements = reqs; - else - MacOSError::throwMe(errSecCSInvalidObjectRef); - } else - state.mRequirements = NULL; - - state.mNoMachO = getBool(CFSTR("no-macho")); - - state.mPageSize = get(kSecCodeSignerPageSize); - - // detached can be (destination) file URL or (mutable) Data to be appended-to - if ((state.mDetached = get(kSecCodeSignerDetached))) { - CFTypeID type = CFGetTypeID(state.mDetached); - if (type != CFURLGetTypeID() && type != CFDataGetTypeID() && type != CFNullGetTypeID()) - MacOSError::throwMe(errSecCSInvalidObjectRef); - } - - state.mDryRun = getBool(kSecCodeSignerDryRun); - - state.mResourceRules = get(kSecCodeSignerResourceRules); - - state.mApplicationData = get(kSecCodeSignerApplicationData); - state.mEntitlementData = get(kSecCodeSignerEntitlements); - - state.mSDKRoot = get(kSecCodeSignerSDKRoot); - - if (CFBooleanRef timestampRequest = get(kSecCodeSignerRequireTimestamp)) { - state.mWantTimeStamp = timestampRequest == kCFBooleanTrue; - } else { // pick default - state.mWantTimeStamp = false; - if (state.mSigner && state.mSigner != SecIdentityRef(kCFNull)) { - CFRef signerCert; - MacOSError::check(SecIdentityCopyCertificate(state.mSigner, &signerCert.aref())); - if (certificateHasField(signerCert, devIdLeafMarkerOID)) - state.mWantTimeStamp = true; - } - } - state.mTimestampAuthentication = get(kSecCodeSignerTimestampAuthentication); - state.mTimestampService = get(kSecCodeSignerTimestampServer); - state.mNoTimeStampCerts = getBool(kSecCodeSignerTimestampOmitCertificates); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/CodeSigner.h b/OSX/include/security_codesigning/CodeSigner.h deleted file mode 100644 index c17c5801..00000000 --- a/OSX/include/security_codesigning/CodeSigner.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// CodeSigner - SecCodeSigner API objects -// -#ifndef _H_CODESIGNER -#define _H_CODESIGNER - -#include "cs.h" -#include "StaticCode.h" -#include "cdbuilder.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// A SecCode object represents running code in the system. It must be subclassed -// to implement a particular notion of code. -// -class SecCodeSigner : public SecCFObject, public DiskRep::SigningContext { - NOCOPY(SecCodeSigner) -public: - class Parser; - class Signer; - -public: - SECCFFUNCTIONS(SecCodeSigner, SecCodeSignerRef, errSecCSInvalidObjectRef, gCFObjects().CodeSigner) - - SecCodeSigner(SecCSFlags flags); - virtual ~SecCodeSigner() throw(); - - void parameters(CFDictionaryRef args); // parse and set parameters - bool valid() const; - - std::string getTeamIDFromSigner(CFArrayRef certs); - - void sign(SecStaticCode *code, SecCSFlags flags); - void remove(SecStaticCode *code, SecCSFlags flags); - - void returnDetachedSignature(BlobCore *blob, Signer &signer); - -protected: - std::string sdkPath(const std::string &path) const; - bool isAdhoc() const; - SecCSFlags signingFlags() const; - -private: - // parsed parameter set - SecCSFlags mOpFlags; // operation flags - CFRef mSigner; // signing identity - CFRef mDetached; // detached-signing information (NULL => attached) - CFRef mResourceRules; // explicit resource collection rules (override) - CFRef mSigningTime; // signing time desired (kCFNull for none) - CFRef mApplicationData; // contents of application slot - CFRef mEntitlementData; // entitlement configuration data - CFRef mSDKRoot; // substitute filesystem root for sub-component lookup - CFRef mRequirements; // internal code requirements - size_t mCMSSize; // size estimate for CMS blob - uint32_t mCdFlags; // CodeDirectory flags - uint32_t mPreserveMetadata; // metadata preservation options - bool mCdFlagsGiven; // CodeDirectory flags were specified - CodeDirectory::HashAlgorithm mDigestAlgorithm; // interior digest (hash) algorithm - std::string mIdentifier; // unique identifier override - std::string mIdentifierPrefix; // prefix for un-dotted default identifiers - std::string mTeamID; // teamID - PlatformIdentifier mPlatform; // platform identifier (zero if not platform binary) - bool mNoMachO; // override to perform non-Mach-O signing - bool mDryRun; // dry run (do not change target) - CFRef mPageSize; // main executable page size - CFRef mTimestampAuthentication; // identity for client-side authentication to the Timestamp server - CFRef mTimestampService; // URL for Timestamp server - bool mWantTimeStamp; // use a Timestamp server - bool mNoTimeStampCerts; // don't request certificates with timestamping request - LimitedAsync *mLimitedAsync; // limited async workers for verification - -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CODESIGNER diff --git a/OSX/include/security_codesigning/CodeSigning.h b/OSX/include/security_codesigning/CodeSigning.h deleted file mode 100644 index 138801b2..00000000 --- a/OSX/include/security_codesigning/CodeSigning.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_CODESIGNING -#define _H_CODESIGNING - - -/*! - @header CodeSigning - This header file includes all the headers that are needed to use - the client interface to Code Signing. - It does not include headers for the other Code Signing related interfaces. - */ -#include -#include -#include - -#endif //_H_CODESIGNING diff --git a/OSX/include/security_codesigning/RequirementKeywords.h b/OSX/include/security_codesigning/RequirementKeywords.h deleted file mode 100644 index dde80999..00000000 --- a/OSX/include/security_codesigning/RequirementKeywords.h +++ /dev/null @@ -1,25 +0,0 @@ - "guest", - "host", - "designated", - "library", - "plugin", - "or", - "and", - "always", - "true", - "never", - "false", - "identifier", - "cdhash", - "platform", - "anchor", - "apple", - "generic", - "certificate", - "cert", - "trusted", - "info", - "entitlement", - "exists", - "leaf", - "root", diff --git a/OSX/include/security_codesigning/RequirementLexer.cpp b/OSX/include/security_codesigning/RequirementLexer.cpp deleted file mode 100644 index 5ed5abea..00000000 --- a/OSX/include/security_codesigning/RequirementLexer.cpp +++ /dev/null @@ -1,1269 +0,0 @@ -/* $ANTLR 2.7.7 (20121221): "requirements.grammar" -> "RequirementLexer.cpp"$ */ -#include "RequirementLexer.hpp" -#include -#include -#include -#include -#include -#include -#include - - -#include "requirement.h" -#include "reqmaker.h" -#include "csutilities.h" -#include -#include -#include // OID coding -using namespace CodeSigning; -typedef Requirement::Maker Maker; - -ANTLR_BEGIN_NAMESPACE(Security_CodeSigning) -RequirementLexer::RequirementLexer(std::istream& in) - : antlr::CharScanner(new antlr::CharBuffer(in),true) -{ - initLiterals(); -} - -RequirementLexer::RequirementLexer(antlr::InputBuffer& ib) - : antlr::CharScanner(ib,true) -{ - initLiterals(); -} - -RequirementLexer::RequirementLexer(const antlr::LexerSharedInputState& state) - : antlr::CharScanner(state,true) -{ - initLiterals(); -} - -void RequirementLexer::initLiterals() -{ - literals["certificate"] = 25; - literals["always"] = 15; - literals["host"] = 6; - literals["guest"] = 5; - literals["cdhash"] = 20; - literals["entitlement"] = 29; - literals["library"] = 8; - literals["never"] = 17; - literals["cert"] = 26; - literals["plugin"] = 9; - literals["or"] = 10; - literals["leaf"] = 42; - literals["info"] = 28; - literals["designated"] = 7; - literals["apple"] = 23; - literals["trusted"] = 27; - literals["true"] = 16; - literals["and"] = 11; - literals["root"] = 43; - literals["platform"] = 21; - literals["anchor"] = 22; - literals["false"] = 18; - literals["generic"] = 24; - literals["identifier"] = 19; - literals["exists"] = 30; -} - -antlr::RefToken RequirementLexer::nextToken() -{ - antlr::RefToken theRetToken; - for (;;) { - antlr::RefToken theRetToken; - int _ttype = antlr::Token::INVALID_TYPE; - resetText(); - try { // for lexical and char stream error handling - switch ( LA(1)) { - case 0x22 /* '\"' */ : - { - mSTRING(true); - theRetToken=_returnToken; - break; - } - case 0x3b /* ';' */ : - { - mSEMI(true); - theRetToken=_returnToken; - break; - } - case 0x28 /* '(' */ : - { - mLPAREN(true); - theRetToken=_returnToken; - break; - } - case 0x29 /* ')' */ : - { - mRPAREN(true); - theRetToken=_returnToken; - break; - } - case 0x5b /* '[' */ : - { - mLBRACK(true); - theRetToken=_returnToken; - break; - } - case 0x5d /* ']' */ : - { - mRBRACK(true); - theRetToken=_returnToken; - break; - } - case 0x2c /* ',' */ : - { - mCOMMA(true); - theRetToken=_returnToken; - break; - } - case 0x7e /* '~' */ : - { - mSUBS(true); - theRetToken=_returnToken; - break; - } - case 0x2d /* '-' */ : - { - mNEG(true); - theRetToken=_returnToken; - break; - } - case 0x21 /* '!' */ : - { - mNOT(true); - theRetToken=_returnToken; - break; - } - case 0x2a /* '*' */ : - { - mSTAR(true); - theRetToken=_returnToken; - break; - } - case 0x9 /* '\t' */ : - case 0xa /* '\n' */ : - case 0x20 /* ' ' */ : - { - mWS(true); - theRetToken=_returnToken; - break; - } - case 0x23 /* '#' */ : - { - mSHELLCOMMENT(true); - theRetToken=_returnToken; - break; - } - default: - if ((LA(1) == 0x2f /* '/' */ ) && (_tokenSet_0.member(LA(2)))) { - mPATHNAME(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x48 /* 'H' */ ) && (LA(2) == 0x22 /* '\"' */ )) { - mHASHCONSTANT(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x30 /* '0' */ ) && (LA(2) == 0x78 /* 'x' */ )) { - mHEXCONSTANT(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3d /* '=' */ ) && (LA(2) == 0x3e /* '>' */ )) { - mARROW(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3c /* '<' */ ) && (LA(2) == 0x3d /* '=' */ )) { - mLE(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3e /* '>' */ ) && (LA(2) == 0x3d /* '=' */ )) { - mGE(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3d /* '=' */ ) && (LA(2) == 0x3d /* '=' */ )) { - mEQQL(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x2f /* '/' */ ) && (LA(2) == 0x2a /* '*' */ )) { - mC_COMMENT(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x2f /* '/' */ ) && (LA(2) == 0x2f /* '/' */ )) { - mCPP_COMMENT(true); - theRetToken=_returnToken; - } - else if ((_tokenSet_0.member(LA(1))) && (true)) { - mDOTKEY(true); - theRetToken=_returnToken; - } - else if (((LA(1) >= 0x30 /* '0' */ && LA(1) <= 0x39 /* '9' */ )) && (true)) { - mINTEGER(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3c /* '<' */ ) && (true)) { - mLESS(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3e /* '>' */ ) && (true)) { - mGT(true); - theRetToken=_returnToken; - } - else if ((LA(1) == 0x3d /* '=' */ ) && (true)) { - mEQL(true); - theRetToken=_returnToken; - } - else { - if (LA(1)==EOF_CHAR) - { - uponEOF(); - _returnToken = makeToken(antlr::Token::EOF_TYPE); - } - else {throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn());} - } - } - if ( !_returnToken ) - goto tryAgain; // found SKIP token - - _ttype = _returnToken->getType(); - _returnToken->setType(_ttype); - return _returnToken; - } - catch (antlr::RecognitionException& e) { - throw antlr::TokenStreamRecognitionException(e); - } - catch (antlr::CharStreamIOException& csie) { - throw antlr::TokenStreamIOException(csie.io); - } - catch (antlr::CharStreamException& cse) { - throw antlr::TokenStreamException(cse.getMessage()); - } -tryAgain:; - } -} - -void RequirementLexer::mIDENT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = IDENT; - std::string::size_type _saveIndex; - - { - switch ( LA(1)) { - case 0x41 /* 'A' */ : - case 0x42 /* 'B' */ : - case 0x43 /* 'C' */ : - case 0x44 /* 'D' */ : - case 0x45 /* 'E' */ : - case 0x46 /* 'F' */ : - case 0x47 /* 'G' */ : - case 0x48 /* 'H' */ : - case 0x49 /* 'I' */ : - case 0x4a /* 'J' */ : - case 0x4b /* 'K' */ : - case 0x4c /* 'L' */ : - case 0x4d /* 'M' */ : - case 0x4e /* 'N' */ : - case 0x4f /* 'O' */ : - case 0x50 /* 'P' */ : - case 0x51 /* 'Q' */ : - case 0x52 /* 'R' */ : - case 0x53 /* 'S' */ : - case 0x54 /* 'T' */ : - case 0x55 /* 'U' */ : - case 0x56 /* 'V' */ : - case 0x57 /* 'W' */ : - case 0x58 /* 'X' */ : - case 0x59 /* 'Y' */ : - case 0x5a /* 'Z' */ : - { - matchRange('A','Z'); - break; - } - case 0x61 /* 'a' */ : - case 0x62 /* 'b' */ : - case 0x63 /* 'c' */ : - case 0x64 /* 'd' */ : - case 0x65 /* 'e' */ : - case 0x66 /* 'f' */ : - case 0x67 /* 'g' */ : - case 0x68 /* 'h' */ : - case 0x69 /* 'i' */ : - case 0x6a /* 'j' */ : - case 0x6b /* 'k' */ : - case 0x6c /* 'l' */ : - case 0x6d /* 'm' */ : - case 0x6e /* 'n' */ : - case 0x6f /* 'o' */ : - case 0x70 /* 'p' */ : - case 0x71 /* 'q' */ : - case 0x72 /* 'r' */ : - case 0x73 /* 's' */ : - case 0x74 /* 't' */ : - case 0x75 /* 'u' */ : - case 0x76 /* 'v' */ : - case 0x77 /* 'w' */ : - case 0x78 /* 'x' */ : - case 0x79 /* 'y' */ : - case 0x7a /* 'z' */ : - { - matchRange('a','z'); - break; - } - default: - { - throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn()); - } - } - } - { // ( ... )* - for (;;) { - switch ( LA(1)) { - case 0x41 /* 'A' */ : - case 0x42 /* 'B' */ : - case 0x43 /* 'C' */ : - case 0x44 /* 'D' */ : - case 0x45 /* 'E' */ : - case 0x46 /* 'F' */ : - case 0x47 /* 'G' */ : - case 0x48 /* 'H' */ : - case 0x49 /* 'I' */ : - case 0x4a /* 'J' */ : - case 0x4b /* 'K' */ : - case 0x4c /* 'L' */ : - case 0x4d /* 'M' */ : - case 0x4e /* 'N' */ : - case 0x4f /* 'O' */ : - case 0x50 /* 'P' */ : - case 0x51 /* 'Q' */ : - case 0x52 /* 'R' */ : - case 0x53 /* 'S' */ : - case 0x54 /* 'T' */ : - case 0x55 /* 'U' */ : - case 0x56 /* 'V' */ : - case 0x57 /* 'W' */ : - case 0x58 /* 'X' */ : - case 0x59 /* 'Y' */ : - case 0x5a /* 'Z' */ : - { - matchRange('A','Z'); - break; - } - case 0x61 /* 'a' */ : - case 0x62 /* 'b' */ : - case 0x63 /* 'c' */ : - case 0x64 /* 'd' */ : - case 0x65 /* 'e' */ : - case 0x66 /* 'f' */ : - case 0x67 /* 'g' */ : - case 0x68 /* 'h' */ : - case 0x69 /* 'i' */ : - case 0x6a /* 'j' */ : - case 0x6b /* 'k' */ : - case 0x6c /* 'l' */ : - case 0x6d /* 'm' */ : - case 0x6e /* 'n' */ : - case 0x6f /* 'o' */ : - case 0x70 /* 'p' */ : - case 0x71 /* 'q' */ : - case 0x72 /* 'r' */ : - case 0x73 /* 's' */ : - case 0x74 /* 't' */ : - case 0x75 /* 'u' */ : - case 0x76 /* 'v' */ : - case 0x77 /* 'w' */ : - case 0x78 /* 'x' */ : - case 0x79 /* 'y' */ : - case 0x7a /* 'z' */ : - { - matchRange('a','z'); - break; - } - case 0x30 /* '0' */ : - case 0x31 /* '1' */ : - case 0x32 /* '2' */ : - case 0x33 /* '3' */ : - case 0x34 /* '4' */ : - case 0x35 /* '5' */ : - case 0x36 /* '6' */ : - case 0x37 /* '7' */ : - case 0x38 /* '8' */ : - case 0x39 /* '9' */ : - { - matchRange('0','9'); - break; - } - default: - { - goto _loop47; - } - } - } - _loop47:; - } // ( ... )* - _ttype = testLiteralsTable(text.substr(_begin, text.length()-_begin),_ttype); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mDOTKEY(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = DOTKEY; - std::string::size_type _saveIndex; - - mIDENT(false); - { // ( ... )* - for (;;) { - if ((LA(1) == 0x2e /* '.' */ )) { - match("."); - { - switch ( LA(1)) { - case 0x41 /* 'A' */ : - case 0x42 /* 'B' */ : - case 0x43 /* 'C' */ : - case 0x44 /* 'D' */ : - case 0x45 /* 'E' */ : - case 0x46 /* 'F' */ : - case 0x47 /* 'G' */ : - case 0x48 /* 'H' */ : - case 0x49 /* 'I' */ : - case 0x4a /* 'J' */ : - case 0x4b /* 'K' */ : - case 0x4c /* 'L' */ : - case 0x4d /* 'M' */ : - case 0x4e /* 'N' */ : - case 0x4f /* 'O' */ : - case 0x50 /* 'P' */ : - case 0x51 /* 'Q' */ : - case 0x52 /* 'R' */ : - case 0x53 /* 'S' */ : - case 0x54 /* 'T' */ : - case 0x55 /* 'U' */ : - case 0x56 /* 'V' */ : - case 0x57 /* 'W' */ : - case 0x58 /* 'X' */ : - case 0x59 /* 'Y' */ : - case 0x5a /* 'Z' */ : - case 0x61 /* 'a' */ : - case 0x62 /* 'b' */ : - case 0x63 /* 'c' */ : - case 0x64 /* 'd' */ : - case 0x65 /* 'e' */ : - case 0x66 /* 'f' */ : - case 0x67 /* 'g' */ : - case 0x68 /* 'h' */ : - case 0x69 /* 'i' */ : - case 0x6a /* 'j' */ : - case 0x6b /* 'k' */ : - case 0x6c /* 'l' */ : - case 0x6d /* 'm' */ : - case 0x6e /* 'n' */ : - case 0x6f /* 'o' */ : - case 0x70 /* 'p' */ : - case 0x71 /* 'q' */ : - case 0x72 /* 'r' */ : - case 0x73 /* 's' */ : - case 0x74 /* 't' */ : - case 0x75 /* 'u' */ : - case 0x76 /* 'v' */ : - case 0x77 /* 'w' */ : - case 0x78 /* 'x' */ : - case 0x79 /* 'y' */ : - case 0x7a /* 'z' */ : - { - mIDENT(false); - break; - } - case 0x30 /* '0' */ : - case 0x31 /* '1' */ : - case 0x32 /* '2' */ : - case 0x33 /* '3' */ : - case 0x34 /* '4' */ : - case 0x35 /* '5' */ : - case 0x36 /* '6' */ : - case 0x37 /* '7' */ : - case 0x38 /* '8' */ : - case 0x39 /* '9' */ : - { - mINTEGER(false); - break; - } - default: - { - throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn()); - } - } - } - } - else { - goto _loop51; - } - - } - _loop51:; - } // ( ... )* - _ttype = testLiteralsTable(_ttype); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mINTEGER(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = INTEGER; - std::string::size_type _saveIndex; - - { // ( ... )+ - int _cnt69=0; - for (;;) { - if (((LA(1) >= 0x30 /* '0' */ && LA(1) <= 0x39 /* '9' */ ))) { - matchRange('0','9'); - } - else { - if ( _cnt69>=1 ) { goto _loop69; } else {throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn());} - } - - _cnt69++; - } - _loop69:; - } // ( ... )+ - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mPATHNAME(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = PATHNAME; - std::string::size_type _saveIndex; - - match("/"); - mIDENT(false); - { // ( ... )+ - int _cnt54=0; - for (;;) { - if ((LA(1) == 0x2f /* '/' */ )) { - match("/"); - mIDENT(false); - } - else { - if ( _cnt54>=1 ) { goto _loop54; } else {throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn());} - } - - _cnt54++; - } - _loop54:; - } // ( ... )+ - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mHASHCONSTANT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = HASHCONSTANT; - std::string::size_type _saveIndex; - - _saveIndex = text.length(); - match('H' /* charlit */ ); - text.erase(_saveIndex); - _saveIndex = text.length(); - match('\"' /* charlit */ ); - text.erase(_saveIndex); - { // ( ... )+ - int _cnt57=0; - for (;;) { - if ((_tokenSet_1.member(LA(1)))) { - mHEX(false); - } - else { - if ( _cnt57>=1 ) { goto _loop57; } else {throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn());} - } - - _cnt57++; - } - _loop57:; - } // ( ... )+ - _saveIndex = text.length(); - match('\"' /* charlit */ ); - text.erase(_saveIndex); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mHEX(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = HEX; - std::string::size_type _saveIndex; - - switch ( LA(1)) { - case 0x30 /* '0' */ : - case 0x31 /* '1' */ : - case 0x32 /* '2' */ : - case 0x33 /* '3' */ : - case 0x34 /* '4' */ : - case 0x35 /* '5' */ : - case 0x36 /* '6' */ : - case 0x37 /* '7' */ : - case 0x38 /* '8' */ : - case 0x39 /* '9' */ : - { - matchRange('0','9'); - break; - } - case 0x61 /* 'a' */ : - case 0x62 /* 'b' */ : - case 0x63 /* 'c' */ : - case 0x64 /* 'd' */ : - case 0x65 /* 'e' */ : - case 0x66 /* 'f' */ : - { - matchRange('a','f'); - break; - } - case 0x41 /* 'A' */ : - case 0x42 /* 'B' */ : - case 0x43 /* 'C' */ : - case 0x44 /* 'D' */ : - case 0x45 /* 'E' */ : - case 0x46 /* 'F' */ : - { - matchRange('A','F'); - break; - } - default: - { - throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn()); - } - } - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mHEXCONSTANT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = HEXCONSTANT; - std::string::size_type _saveIndex; - - _saveIndex = text.length(); - match('0' /* charlit */ ); - text.erase(_saveIndex); - _saveIndex = text.length(); - match('x' /* charlit */ ); - text.erase(_saveIndex); - { // ( ... )+ - int _cnt60=0; - for (;;) { - if ((_tokenSet_1.member(LA(1)))) { - mHEX(false); - } - else { - if ( _cnt60>=1 ) { goto _loop60; } else {throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn());} - } - - _cnt60++; - } - _loop60:; - } // ( ... )+ - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mSTRING(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = STRING; - std::string::size_type _saveIndex; - - _saveIndex = text.length(); - match('\"' /* charlit */ ); - text.erase(_saveIndex); - { // ( ... )* - for (;;) { - switch ( LA(1)) { - case 0x5c /* '\\' */ : - { - { - _saveIndex = text.length(); - match('\\' /* charlit */ ); - text.erase(_saveIndex); - match('\"' /* charlit */ ); - } - break; - } - case 0x0 /* '\0' */ : - case 0x1 /* '\1' */ : - case 0x2 /* '\2' */ : - case 0x3 /* '\3' */ : - case 0x4 /* '\4' */ : - case 0x5 /* '\5' */ : - case 0x6 /* '\6' */ : - case 0x7 /* '\7' */ : - case 0x8 /* '\10' */ : - case 0x9 /* '\t' */ : - case 0xa /* '\n' */ : - case 0xb /* '\13' */ : - case 0xc /* '\14' */ : - case 0xd /* '\r' */ : - case 0xe /* '\16' */ : - case 0xf /* '\17' */ : - case 0x10 /* '\20' */ : - case 0x11 /* '\21' */ : - case 0x12 /* '\22' */ : - case 0x13 /* '\23' */ : - case 0x14 /* '\24' */ : - case 0x15 /* '\25' */ : - case 0x16 /* '\26' */ : - case 0x17 /* '\27' */ : - case 0x18 /* '\30' */ : - case 0x19 /* '\31' */ : - case 0x1a /* '\32' */ : - case 0x1b /* '\33' */ : - case 0x1c /* '\34' */ : - case 0x1d /* '\35' */ : - case 0x1e /* '\36' */ : - case 0x1f /* '\37' */ : - case 0x20 /* ' ' */ : - case 0x21 /* '!' */ : - case 0x23 /* '#' */ : - case 0x24 /* '$' */ : - case 0x25 /* '%' */ : - case 0x26 /* '&' */ : - case 0x27 /* '\'' */ : - case 0x28 /* '(' */ : - case 0x29 /* ')' */ : - case 0x2a /* '*' */ : - case 0x2b /* '+' */ : - case 0x2c /* ',' */ : - case 0x2d /* '-' */ : - case 0x2e /* '.' */ : - case 0x2f /* '/' */ : - case 0x30 /* '0' */ : - case 0x31 /* '1' */ : - case 0x32 /* '2' */ : - case 0x33 /* '3' */ : - case 0x34 /* '4' */ : - case 0x35 /* '5' */ : - case 0x36 /* '6' */ : - case 0x37 /* '7' */ : - case 0x38 /* '8' */ : - case 0x39 /* '9' */ : - case 0x3a /* ':' */ : - case 0x3b /* ';' */ : - case 0x3c /* '<' */ : - case 0x3d /* '=' */ : - case 0x3e /* '>' */ : - case 0x3f /* '?' */ : - case 0x40 /* '@' */ : - case 0x41 /* 'A' */ : - case 0x42 /* 'B' */ : - case 0x43 /* 'C' */ : - case 0x44 /* 'D' */ : - case 0x45 /* 'E' */ : - case 0x46 /* 'F' */ : - case 0x47 /* 'G' */ : - case 0x48 /* 'H' */ : - case 0x49 /* 'I' */ : - case 0x4a /* 'J' */ : - case 0x4b /* 'K' */ : - case 0x4c /* 'L' */ : - case 0x4d /* 'M' */ : - case 0x4e /* 'N' */ : - case 0x4f /* 'O' */ : - case 0x50 /* 'P' */ : - case 0x51 /* 'Q' */ : - case 0x52 /* 'R' */ : - case 0x53 /* 'S' */ : - case 0x54 /* 'T' */ : - case 0x55 /* 'U' */ : - case 0x56 /* 'V' */ : - case 0x57 /* 'W' */ : - case 0x58 /* 'X' */ : - case 0x59 /* 'Y' */ : - case 0x5a /* 'Z' */ : - case 0x5b /* '[' */ : - case 0x5d /* ']' */ : - case 0x5e /* '^' */ : - case 0x5f /* '_' */ : - case 0x60 /* '`' */ : - case 0x61 /* 'a' */ : - case 0x62 /* 'b' */ : - case 0x63 /* 'c' */ : - case 0x64 /* 'd' */ : - case 0x65 /* 'e' */ : - case 0x66 /* 'f' */ : - case 0x67 /* 'g' */ : - case 0x68 /* 'h' */ : - case 0x69 /* 'i' */ : - case 0x6a /* 'j' */ : - case 0x6b /* 'k' */ : - case 0x6c /* 'l' */ : - case 0x6d /* 'm' */ : - case 0x6e /* 'n' */ : - case 0x6f /* 'o' */ : - case 0x70 /* 'p' */ : - case 0x71 /* 'q' */ : - case 0x72 /* 'r' */ : - case 0x73 /* 's' */ : - case 0x74 /* 't' */ : - case 0x75 /* 'u' */ : - case 0x76 /* 'v' */ : - case 0x77 /* 'w' */ : - case 0x78 /* 'x' */ : - case 0x79 /* 'y' */ : - case 0x7a /* 'z' */ : - case 0x7b /* '{' */ : - case 0x7c /* '|' */ : - case 0x7d /* '}' */ : - case 0x7e /* '~' */ : - case 0x7f: - { - { - { - match(_tokenSet_2); - } - } - break; - } - default: - { - goto _loop66; - } - } - } - _loop66:; - } // ( ... )* - _saveIndex = text.length(); - match('\"' /* charlit */ ); - text.erase(_saveIndex); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mARROW(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = ARROW; - std::string::size_type _saveIndex; - - match("=>"); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mSEMI(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = SEMI; - std::string::size_type _saveIndex; - - match(';' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mLPAREN(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = LPAREN; - std::string::size_type _saveIndex; - - match('(' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mRPAREN(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = RPAREN; - std::string::size_type _saveIndex; - - match(')' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mLBRACK(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = LBRACK; - std::string::size_type _saveIndex; - - match('[' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mRBRACK(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = RBRACK; - std::string::size_type _saveIndex; - - match(']' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mLESS(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = LESS; - std::string::size_type _saveIndex; - - match('<' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mGT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = GT; - std::string::size_type _saveIndex; - - match('>' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mLE(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = LE; - std::string::size_type _saveIndex; - - match("<="); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mGE(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = GE; - std::string::size_type _saveIndex; - - match(">="); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mCOMMA(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = COMMA; - std::string::size_type _saveIndex; - - match(',' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mEQL(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = EQL; - std::string::size_type _saveIndex; - - match('=' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mEQQL(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = EQQL; - std::string::size_type _saveIndex; - - match("=="); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mSUBS(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = SUBS; - std::string::size_type _saveIndex; - - match('~' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mNEG(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = NEG; - std::string::size_type _saveIndex; - - match('-' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mNOT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = NOT; - std::string::size_type _saveIndex; - - match('!' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mSTAR(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = STAR; - std::string::size_type _saveIndex; - - match('*' /* charlit */ ); - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mWS(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = WS; - std::string::size_type _saveIndex; - - { // ( ... )+ - int _cnt90=0; - for (;;) { - switch ( LA(1)) { - case 0x20 /* ' ' */ : - { - match(' ' /* charlit */ ); - break; - } - case 0xa /* '\n' */ : - { - match('\n' /* charlit */ ); - newline(); - break; - } - case 0x9 /* '\t' */ : - { - match('\t' /* charlit */ ); - break; - } - default: - { - if ( _cnt90>=1 ) { goto _loop90; } else {throw antlr::NoViableAltForCharException(LA(1), getFilename(), getLine(), getColumn());} - } - } - _cnt90++; - } - _loop90:; - } // ( ... )+ - _ttype = antlr::Token::SKIP; - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mSHELLCOMMENT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = SHELLCOMMENT; - std::string::size_type _saveIndex; - - match('#' /* charlit */ ); - { // ( ... )* - for (;;) { - if ((_tokenSet_3.member(LA(1)))) { - matchNot('\n' /* charlit */ ); - } - else { - goto _loop93; - } - - } - _loop93:; - } // ( ... )* - _ttype = antlr::Token::SKIP; - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mC_COMMENT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = C_COMMENT; - std::string::size_type _saveIndex; - - match("/*"); - { // ( ... )* - for (;;) { - if ((LA(1) == 0x2a /* '*' */ ) && (_tokenSet_4.member(LA(2)))) { - { - match('*' /* charlit */ ); - { - matchNot('/' /* charlit */ ); - } - } - } - else if ((_tokenSet_5.member(LA(1)))) { - { - matchNot('*' /* charlit */ ); - } - } - else { - goto _loop99; - } - - } - _loop99:; - } // ( ... )* - match("*/"); - _ttype = antlr::Token::SKIP; - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - -void RequirementLexer::mCPP_COMMENT(bool _createToken) { - int _ttype; antlr::RefToken _token; std::string::size_type _begin = text.length(); - _ttype = CPP_COMMENT; - std::string::size_type _saveIndex; - - match("//"); - { // ( ... )* - for (;;) { - if ((_tokenSet_3.member(LA(1)))) { - matchNot('\n' /* charlit */ ); - } - else { - goto _loop102; - } - - } - _loop102:; - } // ( ... )* - _ttype = antlr::Token::SKIP; - if ( _createToken && _token==antlr::nullToken && _ttype!=antlr::Token::SKIP ) { - _token = makeToken(_ttype); - _token->setText(text.substr(_begin, text.length()-_begin)); - } - _returnToken = _token; - _saveIndex=0; -} - - -const unsigned long RequirementLexer::_tokenSet_0_data_[] = { 0UL, 0UL, 134217726UL, 134217726UL, 0UL, 0UL, 0UL, 0UL }; -const antlr::BitSet RequirementLexer::_tokenSet_0(_tokenSet_0_data_,8); -const unsigned long RequirementLexer::_tokenSet_1_data_[] = { 0UL, 67043328UL, 126UL, 126UL, 0UL, 0UL, 0UL, 0UL }; -// 0 1 2 3 4 5 6 7 8 9 -const antlr::BitSet RequirementLexer::_tokenSet_1(_tokenSet_1_data_,8); -const unsigned long RequirementLexer::_tokenSet_2_data_[] = { 4294967295UL, 4294967291UL, 4026531839UL, 4294967295UL, 0UL, 0UL, 0UL, 0UL }; -// 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 -// 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e -// 0x1f ! # $ % & \' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 -const antlr::BitSet RequirementLexer::_tokenSet_2(_tokenSet_2_data_,8); -const unsigned long RequirementLexer::_tokenSet_3_data_[] = { 4294966271UL, 4294967295UL, 4294967295UL, 4294967295UL, 0UL, 0UL, 0UL, 0UL }; -// 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xb 0xc 0xd 0xe 0xf 0x10 0x11 -// 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e 0x1f -// ! \" # $ % & \' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 -const antlr::BitSet RequirementLexer::_tokenSet_3(_tokenSet_3_data_,8); -const unsigned long RequirementLexer::_tokenSet_4_data_[] = { 4294967295UL, 4294934527UL, 4294967295UL, 4294967295UL, 0UL, 0UL, 0UL, 0UL }; -// 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 -// 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e -// 0x1f ! \" # $ % & \' ( ) * + , - . 0 1 2 3 4 5 6 7 8 9 -const antlr::BitSet RequirementLexer::_tokenSet_4(_tokenSet_4_data_,8); -const unsigned long RequirementLexer::_tokenSet_5_data_[] = { 4294967295UL, 4294966271UL, 4294967295UL, 4294967295UL, 0UL, 0UL, 0UL, 0UL }; -// 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 -// 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1a 0x1b 0x1c 0x1d 0x1e -// 0x1f ! \" # $ % & \' ( ) + , - . / 0 1 2 3 4 5 6 7 8 9 -const antlr::BitSet RequirementLexer::_tokenSet_5(_tokenSet_5_data_,8); - -ANTLR_END_NAMESPACE diff --git a/OSX/include/security_codesigning/RequirementLexer.hpp b/OSX/include/security_codesigning/RequirementLexer.hpp deleted file mode 100644 index ef27c4c3..00000000 --- a/OSX/include/security_codesigning/RequirementLexer.hpp +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef INC_RequirementLexer_hpp_ -#define INC_RequirementLexer_hpp_ - -#include -/* $ANTLR 2.7.7 (20121221): "requirements.grammar" -> "RequirementLexer.hpp"$ */ -#include -#include -#include -#include "RequirementParserTokenTypes.hpp" -#include - -#include "requirement.h" -using namespace CodeSigning; -typedef Requirement::Maker Maker; - -ANTLR_BEGIN_NAMESPACE(Security_CodeSigning) -class CUSTOM_API RequirementLexer : public antlr::CharScanner, public RequirementParserTokenTypes -{ -private: - void initLiterals(); -public: - bool getCaseSensitiveLiterals() const - { - return true; - } -public: - RequirementLexer(std::istream& in); - RequirementLexer(antlr::InputBuffer& ib); - RequirementLexer(const antlr::LexerSharedInputState& state); - antlr::RefToken nextToken(); - protected: void mIDENT(bool _createToken); - public: void mDOTKEY(bool _createToken); - public: void mINTEGER(bool _createToken); - public: void mPATHNAME(bool _createToken); - public: void mHASHCONSTANT(bool _createToken); - protected: void mHEX(bool _createToken); - public: void mHEXCONSTANT(bool _createToken); - public: void mSTRING(bool _createToken); - public: void mARROW(bool _createToken); - public: void mSEMI(bool _createToken); - public: void mLPAREN(bool _createToken); - public: void mRPAREN(bool _createToken); - public: void mLBRACK(bool _createToken); - public: void mRBRACK(bool _createToken); - public: void mLESS(bool _createToken); - public: void mGT(bool _createToken); - public: void mLE(bool _createToken); - public: void mGE(bool _createToken); - public: void mCOMMA(bool _createToken); - public: void mEQL(bool _createToken); - public: void mEQQL(bool _createToken); - public: void mSUBS(bool _createToken); - public: void mNEG(bool _createToken); - public: void mNOT(bool _createToken); - public: void mSTAR(bool _createToken); - public: void mWS(bool _createToken); - public: void mSHELLCOMMENT(bool _createToken); - public: void mC_COMMENT(bool _createToken); - public: void mCPP_COMMENT(bool _createToken); -private: - - static const unsigned long _tokenSet_0_data_[]; - static const antlr::BitSet _tokenSet_0; - static const unsigned long _tokenSet_1_data_[]; - static const antlr::BitSet _tokenSet_1; - static const unsigned long _tokenSet_2_data_[]; - static const antlr::BitSet _tokenSet_2; - static const unsigned long _tokenSet_3_data_[]; - static const antlr::BitSet _tokenSet_3; - static const unsigned long _tokenSet_4_data_[]; - static const antlr::BitSet _tokenSet_4; - static const unsigned long _tokenSet_5_data_[]; - static const antlr::BitSet _tokenSet_5; -}; - -ANTLR_END_NAMESPACE -#endif /*INC_RequirementLexer_hpp_*/ diff --git a/OSX/include/security_codesigning/RequirementParser.cpp b/OSX/include/security_codesigning/RequirementParser.cpp deleted file mode 100644 index dfaa3450..00000000 --- a/OSX/include/security_codesigning/RequirementParser.cpp +++ /dev/null @@ -1,1331 +0,0 @@ -/* $ANTLR 2.7.7 (20121221): "requirements.grammar" -> "RequirementParser.cpp"$ */ -#include "RequirementParser.hpp" -#include -#include -#include - -#include "requirement.h" -#include "reqmaker.h" -#include "csutilities.h" -#include -#include -#include // OID coding -using namespace CodeSigning; -typedef Requirement::Maker Maker; - -ANTLR_BEGIN_NAMESPACE(Security_CodeSigning) - - // - // Collect error messages. - // Note that the immediate caller takes the absence of collected error messages - // to indicate compilation success. - // - void RequirementParser::reportError(const antlr::RecognitionException &ex) - { - errors += ex.toString() + "\n"; - } - - void RequirementParser::reportError(const std::string &s) - { - errors += s + "\n"; - } - - - // - // Parser helper functions - // - string RequirementParser::hexString(const string &s) - { - if (s.size() % 2) - throw antlr::SemanticException("odd number of digits"); - const char *p = s.data(); - string result; - for (unsigned n = 0; n < s.length(); n += 2) { - char c; - sscanf(p+n, "%2hhx", &c); - result.push_back(c); - } - return result; - } - - void RequirementParser::hashString(const string &s, SHA1::Digest hash) - { - if (s.size() != 2 * SHA1::digestLength) - throw antlr::SemanticException("invalid hash length"); - memcpy(hash, hexString(s).data(), SHA1::digestLength); - } - - static const char *matchPrefix(const string &key, const char *prefix) - { - size_t pLength = strlen(prefix); - if (!key.compare(0, pLength, prefix, 0, pLength)) - return key.c_str() + pLength; - else - return NULL; - } - - void RequirementParser::certMatchOperation(Maker &maker, int32_t slot, string key) - { - if (matchPrefix(key, "subject.")) { - maker.put(opCertField); - maker.put(slot); - maker.put(key); - } else if (const char *oids = matchPrefix(key, "field.")) { - maker.put(opCertGeneric); - maker.put(slot); - CssmAutoData oid(Allocator::standard()); oid.fromOid(oids); - maker.putData(oid.data(), oid.length()); - } else if (const char *oids = matchPrefix(key, "extension.")) { - maker.put(opCertGeneric); - maker.put(slot); - CssmAutoData oid(Allocator::standard()); oid.fromOid(oids); - maker.putData(oid.data(), oid.length()); - } else if (const char *oids = matchPrefix(key, "policy.")) { - maker.put(opCertPolicy); - maker.put(slot); - CssmAutoData oid(Allocator::standard()); oid.fromOid(oids); - maker.putData(oid.data(), oid.length()); - } else { - throw antlr::SemanticException(key + ": unrecognized certificate field"); - } - } - -RequirementParser::RequirementParser(antlr::TokenBuffer& tokenBuf, int k) -: antlr::LLkParser(tokenBuf,k) -{ -} - -RequirementParser::RequirementParser(antlr::TokenBuffer& tokenBuf) -: antlr::LLkParser(tokenBuf,2) -{ -} - -RequirementParser::RequirementParser(antlr::TokenStream& lexer, int k) -: antlr::LLkParser(lexer,k) -{ -} - -RequirementParser::RequirementParser(antlr::TokenStream& lexer) -: antlr::LLkParser(lexer,2) -{ -} - -RequirementParser::RequirementParser(const antlr::ParserSharedInputState& state) -: antlr::LLkParser(state,2) -{ -} - -BlobCore * RequirementParser::autosense() { - BlobCore *result = NULL; - - try { // for error handling - switch ( LA(1)) { - case LPAREN: - case NOT: - case LITERAL_always: - case LITERAL_true: - case LITERAL_never: - case LITERAL_false: - case LITERAL_identifier: - case LITERAL_cdhash: - case LITERAL_platform: - case LITERAL_anchor: - case LITERAL_certificate: - case LITERAL_cert: - case LITERAL_info: - case LITERAL_entitlement: - { - result=requirement(); - break; - } - case LITERAL_guest: - case LITERAL_host: - case LITERAL_designated: - case LITERAL_library: - case LITERAL_plugin: - case INTEGER: - { - result=requirementSet(); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_0); - } - return result; -} - -Requirement * RequirementParser::requirement() { - Requirement *result = NULL; - - try { // for error handling - result=requirementElement(); - match(antlr::Token::EOF_TYPE); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_0); - } - return result; -} - -Requirements * RequirementParser::requirementSet() { - Requirements *result = NULL; - Requirements::Maker maker; - - try { // for error handling - { // ( ... )+ - int _cnt4=0; - for (;;) { - if ((_tokenSet_1.member(LA(1)))) { - uint32_t t; Requirement *req; - t=requirementType(); - match(ARROW); - req=requirementElement(); - maker.add(t, req); - } - else { - if ( _cnt4>=1 ) { goto _loop4; } else {throw antlr::NoViableAltException(LT(1), getFilename());} - } - - _cnt4++; - } - _loop4:; - } // ( ... )+ - result = errors.empty() ? maker() : NULL; - match(antlr::Token::EOF_TYPE); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_0); - } - return result; -} - -uint32_t RequirementParser::requirementType() { - uint32_t type = kSecInvalidRequirementType; - - try { // for error handling - switch ( LA(1)) { - case LITERAL_guest: - { - match(LITERAL_guest); - type = kSecGuestRequirementType; - break; - } - case LITERAL_host: - { - match(LITERAL_host); - type = kSecHostRequirementType; - break; - } - case LITERAL_designated: - { - match(LITERAL_designated); - type = kSecDesignatedRequirementType; - break; - } - case LITERAL_library: - { - match(LITERAL_library); - type = kSecLibraryRequirementType; - break; - } - case LITERAL_plugin: - { - match(LITERAL_plugin); - type = kSecPluginRequirementType; - break; - } - case INTEGER: - { - type=integer(); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_2); - } - return type; -} - -Requirement * RequirementParser::requirementElement() { - Requirement *result = NULL; - Requirement::Maker maker; - - try { // for error handling - expr(maker); - result = maker(); - { // ( ... )* - for (;;) { - if ((LA(1) == SEMI)) { - fluff(); - } - else { - goto _loop9; - } - - } - _loop9:; - } // ( ... )* - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_3); - } - return result; -} - -int32_t RequirementParser::integer() { - int32_t result; - antlr::RefToken s = antlr::nullToken; - - try { // for error handling - s = LT(1); - match(INTEGER); - result = int32_t(atol(s->getText().c_str())); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_4); - } - return result; -} - -void RequirementParser::expr( - Maker &maker -) { - Maker::Label label(maker); - - try { // for error handling - term(maker); - { // ( ... )* - for (;;) { - if ((LA(1) == LITERAL_or)) { - match(LITERAL_or); - maker.insert(label) = opOr; - term(maker); - } - else { - goto _loop12; - } - - } - _loop12:; - } // ( ... )* - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_5); - } -} - -void RequirementParser::fluff() { - - try { // for error handling - match(SEMI); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_6); - } -} - -void RequirementParser::term( - Maker &maker -) { - Maker::Label label(maker); - - try { // for error handling - primary(maker); - { // ( ... )* - for (;;) { - if ((LA(1) == LITERAL_and)) { - match(LITERAL_and); - maker.insert(label) = opAnd; - primary(maker); - } - else { - goto _loop15; - } - - } - _loop15:; - } // ( ... )* - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_7); - } -} - -void RequirementParser::primary( - Maker &maker -) { - - try { // for error handling - switch ( LA(1)) { - case NOT: - { - match(NOT); - maker.put(opNot); - primary(maker); - break; - } - case LITERAL_always: - case LITERAL_true: - { - { - switch ( LA(1)) { - case LITERAL_always: - { - match(LITERAL_always); - break; - } - case LITERAL_true: - { - match(LITERAL_true); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - maker.put(opTrue); - break; - } - case LITERAL_never: - case LITERAL_false: - { - { - switch ( LA(1)) { - case LITERAL_never: - { - match(LITERAL_never); - break; - } - case LITERAL_false: - { - match(LITERAL_false); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - maker.put(opFalse); - break; - } - case LITERAL_anchor: - case LITERAL_certificate: - case LITERAL_cert: - { - certspec(maker); - break; - } - case LITERAL_info: - { - infospec(maker); - break; - } - case LITERAL_entitlement: - { - entitlementspec(maker); - break; - } - case LITERAL_identifier: - { - match(LITERAL_identifier); - string code; - eql(); - code=identifierString(); - maker.ident(code); - break; - } - case LITERAL_cdhash: - { - match(LITERAL_cdhash); - SHA1::Digest digest; - eql(); - hash(digest); - maker.cdhash(digest); - break; - } - case LITERAL_platform: - { - match(LITERAL_platform); - int32_t ident; - eql(); - ident=integer(); - maker.platform(ident); - break; - } - default: - if ((LA(1) == LPAREN) && (_tokenSet_8.member(LA(2)))) { - match(LPAREN); - expr(maker); - match(RPAREN); - } - else if ((LA(1) == LPAREN) && (LA(2) == DOTKEY || LA(2) == STRING)) { - match(LPAREN); - string name; - name=identifierString(); - match(RPAREN); - maker.put(opNamedCode); maker.put(name); - } - else { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -void RequirementParser::certspec( - Maker &maker -) { - - try { // for error handling - if ((LA(1) == LITERAL_anchor) && (LA(2) == LITERAL_apple)) { - match(LITERAL_anchor); - match(LITERAL_apple); - appleanchor(maker); - } - else if ((LA(1) == LITERAL_anchor) && (LA(2) == LITERAL_generic)) { - match(LITERAL_anchor); - match(LITERAL_generic); - match(LITERAL_apple); - maker.put(opAppleGenericAnchor); - } - else if ((LA(1) == LITERAL_anchor || LA(1) == LITERAL_certificate || LA(1) == LITERAL_cert) && (LA(2) == LITERAL_trusted)) { - { - switch ( LA(1)) { - case LITERAL_certificate: - { - match(LITERAL_certificate); - break; - } - case LITERAL_cert: - { - match(LITERAL_cert); - break; - } - case LITERAL_anchor: - { - match(LITERAL_anchor); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - match(LITERAL_trusted); - maker.trustedAnchor(); - } - else if ((LA(1) == LITERAL_certificate || LA(1) == LITERAL_cert) && (_tokenSet_10.member(LA(2)))) { - { - switch ( LA(1)) { - case LITERAL_certificate: - { - match(LITERAL_certificate); - break; - } - case LITERAL_cert: - { - match(LITERAL_cert); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - int32_t slot; - slot=certSlot(); - { - switch ( LA(1)) { - case EQL: - case EQQL: - case LBRACK: - case HASHCONSTANT: - case DOTKEY: - case STRING: - case PATHNAME: - { - certslotspec(maker, slot); - break; - } - case LITERAL_trusted: - { - match(LITERAL_trusted); - maker.trustedAnchor(slot); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - } - else if ((LA(1) == LITERAL_anchor) && (_tokenSet_11.member(LA(2)))) { - match(LITERAL_anchor); - certslotspec(maker, Requirement::anchorCert); - } - else { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -void RequirementParser::infospec( - Maker &maker -) { - string key; - - try { // for error handling - match(LITERAL_info); - key=bracketKey(); - maker.put(opInfoKeyField); maker.put(key); - match_suffix(maker); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -void RequirementParser::entitlementspec( - Maker &maker -) { - string key; - - try { // for error handling - match(LITERAL_entitlement); - key=bracketKey(); - maker.put(opEntitlementField); maker.put(key); - match_suffix(maker); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -void RequirementParser::eql() { - - try { // for error handling - switch ( LA(1)) { - case EQL: - { - match(EQL); - break; - } - case EQQL: - { - match(EQQL); - break; - } - case HASHCONSTANT: - case DOTKEY: - case STRING: - case PATHNAME: - case INTEGER: - { - empty(); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_12); - } -} - -string RequirementParser::identifierString() { - string result; - antlr::RefToken dk = antlr::nullToken; - antlr::RefToken s = antlr::nullToken; - - try { // for error handling - switch ( LA(1)) { - case DOTKEY: - { - dk = LT(1); - match(DOTKEY); - result = dk->getText(); - break; - } - case STRING: - { - s = LT(1); - match(STRING); - result = s->getText(); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } - return result; -} - -void RequirementParser::hash( - SHA1::Digest digest -) { - antlr::RefToken hash = antlr::nullToken; - - try { // for error handling - hash = LT(1); - match(HASHCONSTANT); - hashString(hash->getText(), digest); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -void RequirementParser::appleanchor( - Maker &maker -) { - - try { // for error handling - switch ( LA(1)) { - case antlr::Token::EOF_TYPE: - case LITERAL_guest: - case LITERAL_host: - case LITERAL_designated: - case LITERAL_library: - case LITERAL_plugin: - case LITERAL_or: - case LITERAL_and: - case RPAREN: - case INTEGER: - case SEMI: - { - empty(); - maker.put(opAppleAnchor); - break; - } - case LITERAL_generic: - { - match(LITERAL_generic); - maker.put(opAppleGenericAnchor); - break; - } - case DOTKEY: - case STRING: - { - string name; - name=identifierString(); - maker.put(opNamedAnchor); maker.put(name); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -int32_t RequirementParser::certSlot() { - int32_t slot = 0; - - try { // for error handling - switch ( LA(1)) { - case INTEGER: - { - slot=integer(); - break; - } - case NEG: - { - match(NEG); - slot=integer(); - slot = -slot; - break; - } - case LITERAL_leaf: - { - match(LITERAL_leaf); - slot = Requirement::leafCert; - break; - } - case LITERAL_root: - { - match(LITERAL_root); - slot = Requirement::anchorCert; - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_13); - } - return slot; -} - -void RequirementParser::certslotspec( - Maker &maker, int32_t slot -) { - string key; - - try { // for error handling - switch ( LA(1)) { - case EQL: - case EQQL: - case HASHCONSTANT: - case DOTKEY: - case STRING: - case PATHNAME: - { - eql(); - SHA1::Digest digest; - certificateDigest(digest); - maker.anchor(slot, digest); - break; - } - case LBRACK: - { - key=bracketKey(); - certMatchOperation(maker, slot, key); - match_suffix(maker); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -void RequirementParser::empty() { - - try { // for error handling - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_14); - } -} - -void RequirementParser::certificateDigest( - SHA1::Digest digest -) { - - try { // for error handling - switch ( LA(1)) { - case HASHCONSTANT: - { - hash(digest); - break; - } - case DOTKEY: - case STRING: - case PATHNAME: - { - string path; - path=pathstring(); - if (CFRef certData = cfLoadFile(path)) - hashOfCertificate(CFDataGetBytePtr(certData), CFDataGetLength(certData), digest); - else - throw antlr::SemanticException(path + ": not found"); - - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -string RequirementParser::bracketKey() { - string key; - - try { // for error handling - match(LBRACK); - key=stringvalue(); - match(RBRACK); - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_15); - } - return key; -} - -void RequirementParser::match_suffix( - Maker &maker -) { - - try { // for error handling - switch ( LA(1)) { - case antlr::Token::EOF_TYPE: - case LITERAL_guest: - case LITERAL_host: - case LITERAL_designated: - case LITERAL_library: - case LITERAL_plugin: - case LITERAL_or: - case LITERAL_and: - case RPAREN: - case LITERAL_exists: - case INTEGER: - case SEMI: - { - empty(); - { - switch ( LA(1)) { - case LITERAL_exists: - { - match(LITERAL_exists); - break; - } - case antlr::Token::EOF_TYPE: - case LITERAL_guest: - case LITERAL_host: - case LITERAL_designated: - case LITERAL_library: - case LITERAL_plugin: - case LITERAL_or: - case LITERAL_and: - case RPAREN: - case INTEGER: - case SEMI: - { - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - maker.put(matchExists); - break; - } - case EQL: - case EQQL: - { - { - switch ( LA(1)) { - case EQL: - { - match(EQL); - break; - } - case EQQL: - { - match(EQQL); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - MatchOperation mop = matchEqual; string value; - { - switch ( LA(1)) { - case STAR: - { - match(STAR); - mop = matchEndsWith; - break; - } - case HEXCONSTANT: - case DOTKEY: - case STRING: - { - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - value=datavalue(); - { - switch ( LA(1)) { - case STAR: - { - match(STAR); - mop = (mop == matchEndsWith) ? matchContains : matchBeginsWith; - break; - } - case antlr::Token::EOF_TYPE: - case LITERAL_guest: - case LITERAL_host: - case LITERAL_designated: - case LITERAL_library: - case LITERAL_plugin: - case LITERAL_or: - case LITERAL_and: - case RPAREN: - case INTEGER: - case SEMI: - { - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - maker.put(mop); maker.put(value); - break; - } - case SUBS: - { - match(SUBS); - string value; - value=datavalue(); - maker.put(matchContains); maker.put(value); - break; - } - case LESS: - { - match(LESS); - string value; - value=datavalue(); - maker.put(matchLessThan); maker.put(value); - break; - } - case GT: - { - match(GT); - string value; - value=datavalue(); - maker.put(matchGreaterThan); maker.put(value); - break; - } - case LE: - { - match(LE); - string value; - value=datavalue(); - maker.put(matchLessEqual); maker.put(value); - break; - } - case GE: - { - match(GE); - string value; - value=datavalue(); - maker.put(matchGreaterEqual); maker.put(value); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } -} - -string RequirementParser::datavalue() { - string result; - antlr::RefToken hex = antlr::nullToken; - - try { // for error handling - switch ( LA(1)) { - case DOTKEY: - case STRING: - { - result=stringvalue(); - break; - } - case HEXCONSTANT: - { - hex = LT(1); - match(HEXCONSTANT); - result = hexString(hex->getText()); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_16); - } - return result; -} - -string RequirementParser::stringvalue() { - string result; - antlr::RefToken dk = antlr::nullToken; - antlr::RefToken s = antlr::nullToken; - - try { // for error handling - switch ( LA(1)) { - case DOTKEY: - { - dk = LT(1); - match(DOTKEY); - result = dk->getText(); - break; - } - case STRING: - { - s = LT(1); - match(STRING); - result = s->getText(); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_17); - } - return result; -} - -string RequirementParser::pathstring() { - string result; - antlr::RefToken dk = antlr::nullToken; - antlr::RefToken s = antlr::nullToken; - antlr::RefToken pn = antlr::nullToken; - - try { // for error handling - switch ( LA(1)) { - case DOTKEY: - { - dk = LT(1); - match(DOTKEY); - result = dk->getText(); - break; - } - case STRING: - { - s = LT(1); - match(STRING); - result = s->getText(); - break; - } - case PATHNAME: - { - pn = LT(1); - match(PATHNAME); - result = pn->getText(); - break; - } - default: - { - throw antlr::NoViableAltException(LT(1), getFilename()); - } - } - } - catch (antlr::RecognitionException& ex) { - reportError(ex); - recover(ex,_tokenSet_9); - } - return result; -} - -void RequirementParser::initializeASTFactory( antlr::ASTFactory& ) -{ -} -const char* RequirementParser::tokenNames[] = { - "<0>", - "EOF", - "<2>", - "NULL_TREE_LOOKAHEAD", - "ARROW", - "\"guest\"", - "\"host\"", - "\"designated\"", - "\"library\"", - "\"plugin\"", - "\"or\"", - "\"and\"", - "LPAREN", - "RPAREN", - "NOT", - "\"always\"", - "\"true\"", - "\"never\"", - "\"false\"", - "\"identifier\"", - "\"cdhash\"", - "\"platform\"", - "\"anchor\"", - "\"apple\"", - "\"generic\"", - "\"certificate\"", - "\"cert\"", - "\"trusted\"", - "\"info\"", - "\"entitlement\"", - "\"exists\"", - "EQL", - "EQQL", - "STAR", - "SUBS", - "LESS", - "GT", - "LE", - "GE", - "LBRACK", - "RBRACK", - "NEG", - "\"leaf\"", - "\"root\"", - "HASHCONSTANT", - "HEXCONSTANT", - "DOTKEY", - "STRING", - "PATHNAME", - "INTEGER", - "SEMI", - "IDENT", - "HEX", - "COMMA", - "WS", - "SHELLCOMMENT", - "C_COMMENT", - "CPP_COMMENT", - 0 -}; - -const unsigned long RequirementParser::_tokenSet_0_data_[] = { 2UL, 0UL, 0UL, 0UL }; -// EOF -const antlr::BitSet RequirementParser::_tokenSet_0(_tokenSet_0_data_,4); -const unsigned long RequirementParser::_tokenSet_1_data_[] = { 992UL, 131072UL, 0UL, 0UL }; -// "guest" "host" "designated" "library" "plugin" INTEGER -const antlr::BitSet RequirementParser::_tokenSet_1(_tokenSet_1_data_,4); -const unsigned long RequirementParser::_tokenSet_2_data_[] = { 16UL, 0UL, 0UL, 0UL }; -// ARROW -const antlr::BitSet RequirementParser::_tokenSet_2(_tokenSet_2_data_,4); -const unsigned long RequirementParser::_tokenSet_3_data_[] = { 994UL, 131072UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" INTEGER -const antlr::BitSet RequirementParser::_tokenSet_3(_tokenSet_3_data_,4); -const unsigned long RequirementParser::_tokenSet_4_data_[] = { 2281713650UL, 512129UL, 0UL, 0UL }; -// EOF ARROW "guest" "host" "designated" "library" "plugin" "or" "and" -// RPAREN "trusted" EQL EQQL LBRACK HASHCONSTANT DOTKEY STRING PATHNAME -// INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_4(_tokenSet_4_data_,4); -const unsigned long RequirementParser::_tokenSet_5_data_[] = { 9186UL, 393216UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" RPAREN INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_5(_tokenSet_5_data_,4); -const unsigned long RequirementParser::_tokenSet_6_data_[] = { 994UL, 393216UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_6(_tokenSet_6_data_,4); -const unsigned long RequirementParser::_tokenSet_7_data_[] = { 10210UL, 393216UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" "or" RPAREN INTEGER -// SEMI -const antlr::BitSet RequirementParser::_tokenSet_7(_tokenSet_7_data_,4); -const unsigned long RequirementParser::_tokenSet_8_data_[] = { 914345984UL, 0UL, 0UL, 0UL }; -// LPAREN NOT "always" "true" "never" "false" "identifier" "cdhash" "platform" -// "anchor" "certificate" "cert" "info" "entitlement" -const antlr::BitSet RequirementParser::_tokenSet_8(_tokenSet_8_data_,4); -const unsigned long RequirementParser::_tokenSet_9_data_[] = { 12258UL, 393216UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" "or" "and" RPAREN -// INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_9(_tokenSet_9_data_,4); -const unsigned long RequirementParser::_tokenSet_10_data_[] = { 0UL, 134656UL, 0UL, 0UL }; -// NEG "leaf" "root" INTEGER -const antlr::BitSet RequirementParser::_tokenSet_10(_tokenSet_10_data_,4); -const unsigned long RequirementParser::_tokenSet_11_data_[] = { 2147483648UL, 118913UL, 0UL, 0UL }; -// EQL EQQL LBRACK HASHCONSTANT DOTKEY STRING PATHNAME -const antlr::BitSet RequirementParser::_tokenSet_11(_tokenSet_11_data_,4); -const unsigned long RequirementParser::_tokenSet_12_data_[] = { 0UL, 249856UL, 0UL, 0UL }; -// HASHCONSTANT DOTKEY STRING PATHNAME INTEGER -const antlr::BitSet RequirementParser::_tokenSet_12(_tokenSet_12_data_,4); -const unsigned long RequirementParser::_tokenSet_13_data_[] = { 2281701376UL, 118913UL, 0UL, 0UL }; -// "trusted" EQL EQQL LBRACK HASHCONSTANT DOTKEY STRING PATHNAME -const antlr::BitSet RequirementParser::_tokenSet_13(_tokenSet_13_data_,4); -const unsigned long RequirementParser::_tokenSet_14_data_[] = { 1073754082UL, 512000UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" "or" "and" RPAREN -// "exists" HASHCONSTANT DOTKEY STRING PATHNAME INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_14(_tokenSet_14_data_,4); -const unsigned long RequirementParser::_tokenSet_15_data_[] = { 3221237730UL, 393341UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" "or" "and" RPAREN -// "exists" EQL EQQL SUBS LESS GT LE GE INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_15(_tokenSet_15_data_,4); -const unsigned long RequirementParser::_tokenSet_16_data_[] = { 12258UL, 393218UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" "or" "and" RPAREN -// STAR INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_16(_tokenSet_16_data_,4); -const unsigned long RequirementParser::_tokenSet_17_data_[] = { 12258UL, 393474UL, 0UL, 0UL }; -// EOF "guest" "host" "designated" "library" "plugin" "or" "and" RPAREN -// STAR RBRACK INTEGER SEMI -const antlr::BitSet RequirementParser::_tokenSet_17(_tokenSet_17_data_,4); - - -ANTLR_END_NAMESPACE diff --git a/OSX/include/security_codesigning/RequirementParser.hpp b/OSX/include/security_codesigning/RequirementParser.hpp deleted file mode 100644 index 81857c65..00000000 --- a/OSX/include/security_codesigning/RequirementParser.hpp +++ /dev/null @@ -1,158 +0,0 @@ -#ifndef INC_RequirementParser_hpp_ -#define INC_RequirementParser_hpp_ - -#include -/* $ANTLR 2.7.7 (20121221): "requirements.grammar" -> "RequirementParser.hpp"$ */ -#include -#include -#include "RequirementParserTokenTypes.hpp" -#include - - -#include "requirement.h" -using namespace CodeSigning; -typedef Requirement::Maker Maker; - -ANTLR_BEGIN_NAMESPACE(Security_CodeSigning) -class CUSTOM_API RequirementParser : public antlr::LLkParser, public RequirementParserTokenTypes -{ - -public: - std::string errors; - void reportError(const antlr::RecognitionException &ex); - void reportError(const std::string &s); - -private: - static string hexString(const string &s); - static void hashString(const string &s, SHA1::Digest hash); - void certMatchOperation(Maker &maker, int32_t slot, string key); -public: - void initializeASTFactory( antlr::ASTFactory& factory ); -protected: - RequirementParser(antlr::TokenBuffer& tokenBuf, int k); -public: - RequirementParser(antlr::TokenBuffer& tokenBuf); -protected: - RequirementParser(antlr::TokenStream& lexer, int k); -public: - RequirementParser(antlr::TokenStream& lexer); - RequirementParser(const antlr::ParserSharedInputState& state); - int getNumTokens() const - { - return RequirementParser::NUM_TOKENS; - } - const char* getTokenName( int type ) const - { - if( type > getNumTokens() ) return 0; - return RequirementParser::tokenNames[type]; - } - const char* const* getTokenNames() const - { - return RequirementParser::tokenNames; - } - public: BlobCore * autosense(); - public: Requirement * requirement(); - public: Requirements * requirementSet(); - public: uint32_t requirementType(); - public: Requirement * requirementElement(); - public: int32_t integer(); - public: void expr( - Maker &maker - ); - public: void fluff(); - public: void term( - Maker &maker - ); - public: void primary( - Maker &maker - ); - public: void certspec( - Maker &maker - ); - public: void infospec( - Maker &maker - ); - public: void entitlementspec( - Maker &maker - ); - public: void eql(); - public: string identifierString(); - public: void hash( - SHA1::Digest digest - ); - public: void appleanchor( - Maker &maker - ); - public: int32_t certSlot(); - public: void certslotspec( - Maker &maker, int32_t slot - ); - public: void empty(); - public: void certificateDigest( - SHA1::Digest digest - ); - public: string bracketKey(); - public: void match_suffix( - Maker &maker - ); - public: string datavalue(); - public: string stringvalue(); - public: string pathstring(); -public: - antlr::RefAST getAST() - { - return returnAST; - } - -protected: - antlr::RefAST returnAST; -private: - static const char* tokenNames[]; -#ifndef NO_STATIC_CONSTS - static const int NUM_TOKENS = 58; -#else - enum { - NUM_TOKENS = 58 - }; -#endif - - static const unsigned long _tokenSet_0_data_[]; - static const antlr::BitSet _tokenSet_0; - static const unsigned long _tokenSet_1_data_[]; - static const antlr::BitSet _tokenSet_1; - static const unsigned long _tokenSet_2_data_[]; - static const antlr::BitSet _tokenSet_2; - static const unsigned long _tokenSet_3_data_[]; - static const antlr::BitSet _tokenSet_3; - static const unsigned long _tokenSet_4_data_[]; - static const antlr::BitSet _tokenSet_4; - static const unsigned long _tokenSet_5_data_[]; - static const antlr::BitSet _tokenSet_5; - static const unsigned long _tokenSet_6_data_[]; - static const antlr::BitSet _tokenSet_6; - static const unsigned long _tokenSet_7_data_[]; - static const antlr::BitSet _tokenSet_7; - static const unsigned long _tokenSet_8_data_[]; - static const antlr::BitSet _tokenSet_8; - static const unsigned long _tokenSet_9_data_[]; - static const antlr::BitSet _tokenSet_9; - static const unsigned long _tokenSet_10_data_[]; - static const antlr::BitSet _tokenSet_10; - static const unsigned long _tokenSet_11_data_[]; - static const antlr::BitSet _tokenSet_11; - static const unsigned long _tokenSet_12_data_[]; - static const antlr::BitSet _tokenSet_12; - static const unsigned long _tokenSet_13_data_[]; - static const antlr::BitSet _tokenSet_13; - static const unsigned long _tokenSet_14_data_[]; - static const antlr::BitSet _tokenSet_14; - static const unsigned long _tokenSet_15_data_[]; - static const antlr::BitSet _tokenSet_15; - static const unsigned long _tokenSet_16_data_[]; - static const antlr::BitSet _tokenSet_16; - static const unsigned long _tokenSet_17_data_[]; - static const antlr::BitSet _tokenSet_17; -}; - -ANTLR_END_NAMESPACE -#endif /*INC_RequirementParser_hpp_*/ diff --git a/OSX/include/security_codesigning/RequirementParserTokenTypes.hpp b/OSX/include/security_codesigning/RequirementParserTokenTypes.hpp deleted file mode 100644 index 3654840c..00000000 --- a/OSX/include/security_codesigning/RequirementParserTokenTypes.hpp +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef INC_RequirementParserTokenTypes_hpp_ -#define INC_RequirementParserTokenTypes_hpp_ - -ANTLR_BEGIN_NAMESPACE(Security_CodeSigning) -/* $ANTLR 2.7.7 (20121221): "requirements.grammar" -> "RequirementParserTokenTypes.hpp"$ */ - -#ifndef CUSTOM_API -# define CUSTOM_API -#endif - -#ifdef __cplusplus -struct CUSTOM_API RequirementParserTokenTypes { -#endif - enum { - EOF_ = 1, - ARROW = 4, - LITERAL_guest = 5, - LITERAL_host = 6, - LITERAL_designated = 7, - LITERAL_library = 8, - LITERAL_plugin = 9, - LITERAL_or = 10, - LITERAL_and = 11, - LPAREN = 12, - RPAREN = 13, - NOT = 14, - LITERAL_always = 15, - LITERAL_true = 16, - LITERAL_never = 17, - LITERAL_false = 18, - LITERAL_identifier = 19, - LITERAL_cdhash = 20, - LITERAL_platform = 21, - LITERAL_anchor = 22, - LITERAL_apple = 23, - LITERAL_generic = 24, - LITERAL_certificate = 25, - LITERAL_cert = 26, - LITERAL_trusted = 27, - LITERAL_info = 28, - LITERAL_entitlement = 29, - LITERAL_exists = 30, - EQL = 31, - EQQL = 32, - STAR = 33, - SUBS = 34, - LESS = 35, - GT = 36, - LE = 37, - GE = 38, - LBRACK = 39, - RBRACK = 40, - NEG = 41, - LITERAL_leaf = 42, - LITERAL_root = 43, - HASHCONSTANT = 44, - HEXCONSTANT = 45, - DOTKEY = 46, - STRING = 47, - PATHNAME = 48, - INTEGER = 49, - SEMI = 50, - IDENT = 51, - HEX = 52, - COMMA = 53, - WS = 54, - SHELLCOMMENT = 55, - C_COMMENT = 56, - CPP_COMMENT = 57, - NULL_TREE_LOOKAHEAD = 3 - }; -#ifdef __cplusplus -}; -#endif -ANTLR_END_NAMESPACE -#endif /*INC_RequirementParserTokenTypes_hpp_*/ diff --git a/OSX/include/security_codesigning/RequirementParserTokenTypes.txt b/OSX/include/security_codesigning/RequirementParserTokenTypes.txt deleted file mode 100644 index 781f4f52..00000000 --- a/OSX/include/security_codesigning/RequirementParserTokenTypes.txt +++ /dev/null @@ -1,56 +0,0 @@ -// $ANTLR 2.7.7 (20121221): requirements.grammar -> RequirementParserTokenTypes.txt$ -RequirementParser // output token vocab name -ARROW=4 -LITERAL_guest="guest"=5 -LITERAL_host="host"=6 -LITERAL_designated="designated"=7 -LITERAL_library="library"=8 -LITERAL_plugin="plugin"=9 -LITERAL_or="or"=10 -LITERAL_and="and"=11 -LPAREN=12 -RPAREN=13 -NOT=14 -LITERAL_always="always"=15 -LITERAL_true="true"=16 -LITERAL_never="never"=17 -LITERAL_false="false"=18 -LITERAL_identifier="identifier"=19 -LITERAL_cdhash="cdhash"=20 -LITERAL_platform="platform"=21 -LITERAL_anchor="anchor"=22 -LITERAL_apple="apple"=23 -LITERAL_generic="generic"=24 -LITERAL_certificate="certificate"=25 -LITERAL_cert="cert"=26 -LITERAL_trusted="trusted"=27 -LITERAL_info="info"=28 -LITERAL_entitlement="entitlement"=29 -LITERAL_exists="exists"=30 -EQL=31 -EQQL=32 -STAR=33 -SUBS=34 -LESS=35 -GT=36 -LE=37 -GE=38 -LBRACK=39 -RBRACK=40 -NEG=41 -LITERAL_leaf="leaf"=42 -LITERAL_root="root"=43 -HASHCONSTANT=44 -HEXCONSTANT=45 -DOTKEY=46 -STRING=47 -PATHNAME=48 -INTEGER=49 -SEMI=50 -IDENT=51 -HEX=52 -COMMA=53 -WS=54 -SHELLCOMMENT=55 -C_COMMENT=56 -CPP_COMMENT=57 diff --git a/OSX/include/security_codesigning/Requirements.cpp b/OSX/include/security_codesigning/Requirements.cpp deleted file mode 100644 index d2fb04fe..00000000 --- a/OSX/include/security_codesigning/Requirements.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Requirements - SecRequirement API objects -// -#include "Requirements.h" - -namespace Security { -namespace CodeSigning { - - -// -// Create from a Requirement blob in memory -// -SecRequirement::SecRequirement(const void *data, size_t length) - : mReq(NULL) -{ - const Requirement *req = (const Requirement *)data; - if (!req->validateBlob(length)) - MacOSError::throwMe(errSecCSReqInvalid); - mReq = req->clone(); -} - - -// -// Create from a genuine Requirement object -// -SecRequirement::SecRequirement(const Requirement *req, bool transferOwnership) - : mReq(NULL) -{ - if (!req->validateBlob()) - MacOSError::throwMe(errSecCSReqInvalid); - - if (transferOwnership) - mReq = req; - else - mReq = req->clone(); -} - - -// -// Clean up a SecRequirement object -// -SecRequirement::~SecRequirement() throw() -try { - ::free((void *)mReq); -} catch (...) { - return; -} - - -// -// CF-level comparison of SecRequirement objects compares the entire requirement -// structure for equality. This means that two requirement programs are recognized -// as equal if they're written identically (modulo comments and syntactic sugar). -// Obviously, equality of outcome is not in the cards. :-) -// -bool SecRequirement::equal(SecCFObject &secOther) -{ - SecRequirement *other = static_cast(&secOther); - return !memcmp(this->requirement(), other->requirement(), this->requirement()->length()); -} - -CFHashCode SecRequirement::hash() -{ - return CFHash(CFTempDataWrap(*this->requirement())); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/Requirements.h b/OSX/include/security_codesigning/Requirements.h deleted file mode 100644 index 8a266f1c..00000000 --- a/OSX/include/security_codesigning/Requirements.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Requirements - SecRequirement API objects -// -#ifndef _H_REQUIREMENTS -#define _H_REQUIREMENTS - -#include "cs.h" -#include "requirement.h" - -namespace Security { -namespace CodeSigning { - - -// -// A SecRequirement object acts as the API representation for a code -// requirement. All its semantics are within the Requirement object it holds. -// The SecRequirement just manages the API appearances. -// -class SecRequirement : public SecCFObject { - NOCOPY(SecRequirement) -public: - SECCFFUNCTIONS(SecRequirement, SecRequirementRef, errSecCSInvalidObjectRef, gCFObjects().Requirement) - - SecRequirement(const void *data, size_t length); - SecRequirement(const Requirement *req, bool transferOwnership = false); - virtual ~SecRequirement() throw(); - - bool equal(SecCFObject &other); - CFHashCode hash(); - - const Requirement *requirement() const { return mReq; } - -private: - const Requirement *mReq; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_REQUIREMENTS diff --git a/OSX/include/security_codesigning/SecAssessment.cpp b/OSX/include/security_codesigning/SecAssessment.cpp deleted file mode 100644 index c6129c79..00000000 --- a/OSX/include/security_codesigning/SecAssessment.cpp +++ /dev/null @@ -1,544 +0,0 @@ -/* - * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "cs.h" -#include "SecAssessment.h" -#include "policydb.h" -#include "policyengine.h" -#include "xpcengine.h" -#include "csutilities.h" -#include -#include -#include -#include -#include -#include - -using namespace CodeSigning; - - -static void esp_do_check(const char *op, CFDictionaryRef dict) -{ - OSStatus result = __esp_check_ns(op, (void *)(CFDictionaryRef)dict); - if (result != noErr) - MacOSError::throwMe(result); -} - -// -// CF Objects -// -struct _SecAssessment : private CFRuntimeBase { -public: - _SecAssessment(CFURLRef p, AuthorityType typ, CFDictionaryRef r) : path(p), type(typ), result(r) { } - - CFCopyRef path; - AuthorityType type; - CFRef result; - -public: - static _SecAssessment &ref(SecAssessmentRef r) - { return *(_SecAssessment *)r; } - - // CF Boiler-plate - void *operator new (size_t size) - { - return (void *)_CFRuntimeCreateInstance(NULL, SecAssessmentGetTypeID(), - sizeof(_SecAssessment) - sizeof(CFRuntimeBase), NULL); - } - - static void finalize(CFTypeRef obj) - { ((_SecAssessment *)obj)->~_SecAssessment(); } -}; - -typedef _SecAssessment SecAssessment; - - -static const CFRuntimeClass assessmentClass = { - 0, // version - "SecAssessment", // name - NULL, // init - NULL, // copy - SecAssessment::finalize, // finalize - NULL, // equal - NULL, // hash - NULL, // formatting - NULL // debug string -}; - - -static dispatch_once_t assessmentOnce; -CFTypeID assessmentType = _kCFRuntimeNotATypeID; - -CFTypeID SecAssessmentGetTypeID() -{ - dispatch_once(&assessmentOnce, ^void() { - if ((assessmentType = _CFRuntimeRegisterClass(&assessmentClass)) == _kCFRuntimeNotATypeID) - abort(); - }); - return assessmentType; -} - - -// -// Common dictionary constants -// -CFStringRef kSecAssessmentContextKeyOperation = CFSTR("operation"); -CFStringRef kSecAssessmentOperationTypeExecute = CFSTR("operation:execute"); -CFStringRef kSecAssessmentOperationTypeInstall = CFSTR("operation:install"); -CFStringRef kSecAssessmentOperationTypeOpenDocument = CFSTR("operation:lsopen"); - - -// -// Read-only in-process access to the policy database -// -class ReadPolicy : public PolicyDatabase { -public: - ReadPolicy() : PolicyDatabase(defaultDatabase) { } -}; -ModuleNexus gDatabase; - - -// -// An on-demand instance of the policy engine -// -ModuleNexus gEngine; - - -// -// Policy evaluation ("assessment") operations -// -CFStringRef kSecAssessmentContextKeyFeedback = CFSTR("context:feedback"); -CFStringRef kSecAssessmentFeedbackProgress = CFSTR("feedback:progress"); -CFStringRef kSecAssessmentFeedbackInfoCurrent = CFSTR("current"); -CFStringRef kSecAssessmentFeedbackInfoTotal = CFSTR("total"); - -CFStringRef kSecAssessmentAssessmentVerdict = CFSTR("assessment:verdict"); -CFStringRef kSecAssessmentAssessmentOriginator = CFSTR("assessment:originator"); -CFStringRef kSecAssessmentAssessmentAuthority = CFSTR("assessment:authority"); -CFStringRef kSecAssessmentAssessmentSource = CFSTR("assessment:authority:source"); -CFStringRef kSecAssessmentAssessmentAuthorityRow = CFSTR("assessment:authority:row"); -CFStringRef kSecAssessmentAssessmentAuthorityOverride = CFSTR("assessment:authority:override"); -CFStringRef kSecAssessmentAssessmentAuthorityOriginalVerdict = CFSTR("assessment:authority:verdict"); -CFStringRef kSecAssessmentAssessmentFromCache = CFSTR("assessment:authority:cached"); -CFStringRef kSecAssessmentAssessmentWeakSignature = CFSTR("assessment:authority:weak"); -CFStringRef kSecAssessmentAssessmentCodeSigningError = CFSTR("assessment:cserror"); - -CFStringRef kDisabledOverride = CFSTR("security disabled"); - -SecAssessmentRef SecAssessmentCreate(CFURLRef path, - SecAssessmentFlags flags, - CFDictionaryRef context, - CFErrorRef *errors) -{ - BEGIN_CSAPI - - if (flags & kSecAssessmentFlagAsynchronous) - MacOSError::throwMe(errSecCSUnimplemented); - - AuthorityType type = typeFor(context, kAuthorityExecute); - CFRef result = makeCFMutableDictionary(); - - SYSPOLICY_ASSESS_API(cfString(path).c_str(), int(type), flags); - - try { - if (__esp_enabled() && (flags & kSecAssessmentFlagDirect)) { - CFTemp dict("{path=%O, flags=%d, context=%O, override=%d}", path, flags, context, overrideAssessment()); - esp_do_check("cs-assessment-evaluate", dict); - } - - if (flags & kSecAssessmentFlagDirect) { - // ask the engine right here to do its thing - SYSPOLICY_ASSESS_LOCAL(); - gEngine().evaluate(path, type, flags, context, result); - } else { - // relay the question to our daemon for consideration - SYSPOLICY_ASSESS_REMOTE(); - xpcEngineAssess(path, flags, context, result); - } - } catch (CommonError &error) { - switch (error.osStatus()) { - case CSSMERR_TP_CERT_REVOKED: - throw; - default: - if (!overrideAssessment(flags)) - throw; // let it go as an error - break; - } - // record the error we would have returned - cfadd(result, "{%O=#F,'assessment:error'=%d}}", kSecAssessmentAssessmentVerdict, error.osStatus()); - } catch (...) { - // catch stray errors not conforming to the CommonError scheme - if (!overrideAssessment(flags)) - throw; // let it go as an error - cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); - } - - if (__esp_enabled() && (flags & kSecAssessmentFlagDirect)) { - CFTemp dict("{path=%O, flags=%d, context=%O, override=%d, result=%O}", path, flags, context, overrideAssessment(), (CFDictionaryRef)result); - __esp_notify_ns("cs-assessment-evaluate", (void *)(CFDictionaryRef)dict); - } - - return new SecAssessment(path, type, result.yield()); - - END_CSAPI_ERRORS1(NULL) -} - - -static void traceResult(CFURLRef target, MessageTrace &trace, std::string &sanitized) -{ - static const char *interestingBundles[] = { - "UNBUNDLED", - "com.apple.", - "com.install4j.", - "com.MindVision.", - "com.yourcompany.", - - "com.adobe.flashplayer.installmanager", - "com.adobe.Installers.Setup", - "com.adobe.PDApp.setup", - "com.bittorrent.uTorrent", - "com.divx.divx6formacinstaller", - "com.getdropbox.dropbox", - "com.google.Chrome", - "com.Google.GoogleEarthPlugin.plugin", - "com.Google.GoogleEarthPlus", - "com.hp.Installer", - "com.macpaw.CleanMyMac", - "com.microsoft.SilverlightInstaller", - "com.paragon-software.filesystems.NTFS.pkg", - "com.RealNetworks.RealPlayer", - "com.skype.skype", - "it.alfanet.squared5.MPEGStreamclip", - "org.mozilla.firefox", - "org.videolan.vlc", - - NULL // sentinel - }; - - string identifier = "UNBUNDLED"; - string version = "UNKNOWN"; - if (CFRef bundle = CFBundleCreate(NULL, target)) { - if (CFStringRef ident = CFBundleGetIdentifier(bundle)) - identifier = cfString(ident); - if (CFStringRef vers = CFStringRef(CFBundleGetValueForInfoDictionaryKey(bundle, CFSTR("CFBundleShortVersionString")))) - version = cfString(vers); - } - - CFRef url = CFURLCopyAbsoluteURL(target); - sanitized = cfString(url); - string::size_type rslash = sanitized.rfind('/'); - if (rslash != string::npos) - sanitized = sanitized.substr(rslash+1); - bool keepFilename = false; - for (const char **pfx = interestingBundles; *pfx; pfx++) { - size_t pfxlen = strlen(*pfx); - if (identifier.compare(0, pfxlen, *pfx, pfxlen) == 0) - if (pfxlen == identifier.size() || (*pfx)[pfxlen-1] == '.') { - keepFilename = true; - break; - } - } - if (!keepFilename) { - string::size_type dot = sanitized.rfind('.'); - if (dot != string::npos) - sanitized = sanitized.substr(dot); - else - sanitized = "(none)"; - } - - trace.add("signature2", "bundle:%s", identifier.c_str()); - trace.add("signature3", "%s", sanitized.c_str()); - trace.add("signature5", "%s", version.c_str()); -} - -static void traceAssessment(SecAssessment &assessment, AuthorityType type, CFDictionaryRef result) -{ - if (CFDictionaryGetValue(result, CFSTR("assessment:remote"))) - return; // just traced in syspolicyd - - string authority = "UNSPECIFIED"; - bool overridden = false; - bool old_overridden = false; - if (CFDictionaryRef authdict = CFDictionaryRef(CFDictionaryGetValue(result, kSecAssessmentAssessmentAuthority))) { - if (CFStringRef auth = CFStringRef(CFDictionaryGetValue(authdict, kSecAssessmentAssessmentSource))) - authority = cfString(auth); - else - authority = "no authority"; - if (CFTypeRef override = CFDictionaryGetValue(authdict, kSecAssessmentAssessmentAuthorityOverride)) - if (CFEqual(override, kDisabledOverride)) { - old_overridden = true; - if (CFDictionaryGetValue(authdict, kSecAssessmentAssessmentAuthorityOriginalVerdict) == kCFBooleanFalse) - overridden = true; - } - } - - MessageTrace trace("com.apple.security.assessment.outcome2", NULL); - std::string sanitized; - traceResult(assessment.path, trace, sanitized); - trace.add("signature4", "%d", type); - - if (CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict) == kCFBooleanFalse) { - trace.add("signature", "denied:%s", authority.c_str()); - trace.send("assessment denied for %s", sanitized.c_str()); - } else if (overridden) { // would have failed except for override - trace.add("signature", "defeated:%s", authority.c_str()); - trace.send("assessment denied for %s but overridden", sanitized.c_str()); - } else if (old_overridden) { // would have succeeded even without override - trace.add("signature", "override:%s", authority.c_str()); - trace.send("assessment granted for %s and overridden", sanitized.c_str()); - } else { - trace.add("signature", "granted:%s", authority.c_str()); - trace.send("assessment granted for %s by %s", sanitized.c_str(), authority.c_str()); - } -} - -static void traceUpdate(CFTypeRef target, CFDictionaryRef context, CFDictionaryRef result) -{ - // only trace add operations on URL targets - if (target == NULL || CFGetTypeID(target) != CFURLGetTypeID()) - return; - CFStringRef edit = CFStringRef(CFDictionaryGetValue(context, kSecAssessmentContextKeyUpdate)); - if (!CFEqual(edit, kSecAssessmentUpdateOperationAdd)) - return; - MessageTrace trace("com.apple.security.assessment.update", NULL); - std::string sanitized; - traceResult(CFURLRef(target), trace, sanitized); - trace.send("added rule for %s", sanitized.c_str()); -} - - -// -// At present, CopyResult simply retrieves the result already formed by Create. -// In the future, this will be more lazy. -// -CFDictionaryRef SecAssessmentCopyResult(SecAssessmentRef assessmentRef, - SecAssessmentFlags flags, - CFErrorRef *errors) -{ - BEGIN_CSAPI - - SecAssessment &assessment = SecAssessment::ref(assessmentRef); - CFCopyRef result = assessment.result; - if (overrideAssessment(flags)) { - // turn rejections into approvals, but note that we did that - CFTypeRef verdict = CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict); - if (verdict == kCFBooleanFalse) { - CFRef adulterated = makeCFMutableDictionary(result.get()); - CFDictionarySetValue(adulterated, kSecAssessmentAssessmentVerdict, kCFBooleanTrue); - if (CFDictionaryRef authority = CFDictionaryRef(CFDictionaryGetValue(adulterated, kSecAssessmentAssessmentAuthority))) { - CFRef authority2 = makeCFMutableDictionary(authority); - CFDictionarySetValue(authority2, kSecAssessmentAssessmentAuthorityOverride, kDisabledOverride); - CFDictionarySetValue(authority2, kSecAssessmentAssessmentAuthorityOriginalVerdict, verdict); - CFDictionarySetValue(adulterated, kSecAssessmentAssessmentAuthority, authority2); - } else { - cfadd(adulterated, "{%O={%O=%O}}", - kSecAssessmentAssessmentAuthority, kSecAssessmentAssessmentAuthorityOverride, kDisabledOverride); - } - result = adulterated.get(); - } - } - traceAssessment(assessment, assessment.type, result); - return result.yield(); - - END_CSAPI_ERRORS1(NULL) -} - - -// -// Policy editing operations. -// These all make permanent changes to the system-wide authority records. -// -CFStringRef kSecAssessmentContextKeyUpdate = CFSTR("update"); -CFStringRef kSecAssessmentUpdateOperationAdd = CFSTR("update:add"); -CFStringRef kSecAssessmentUpdateOperationRemove = CFSTR("update:remove"); -CFStringRef kSecAssessmentUpdateOperationEnable = CFSTR("update:enable"); -CFStringRef kSecAssessmentUpdateOperationDisable = CFSTR("update:disable"); -CFStringRef kSecAssessmentUpdateOperationFind = CFSTR("update:find"); - -CFStringRef kSecAssessmentUpdateKeyAuthorization = CFSTR("update:authorization"); -CFStringRef kSecAssessmentUpdateKeyPriority = CFSTR("update:priority"); -CFStringRef kSecAssessmentUpdateKeyLabel = CFSTR("update:label"); -CFStringRef kSecAssessmentUpdateKeyExpires = CFSTR("update:expires"); -CFStringRef kSecAssessmentUpdateKeyAllow = CFSTR("update:allow"); -CFStringRef kSecAssessmentUpdateKeyRemarks = CFSTR("update:remarks"); - -CFStringRef kSecAssessmentUpdateKeyRow = CFSTR("update:row"); -CFStringRef kSecAssessmentUpdateKeyCount = CFSTR("update:count"); -CFStringRef kSecAssessmentUpdateKeyFound = CFSTR("update:found"); - -CFStringRef kSecAssessmentRuleKeyID = CFSTR("rule:id"); -CFStringRef kSecAssessmentRuleKeyPriority = CFSTR("rule:priority"); -CFStringRef kSecAssessmentRuleKeyAllow = CFSTR("rule:allow"); -CFStringRef kSecAssessmentRuleKeyLabel = CFSTR("rule:label"); -CFStringRef kSecAssessmentRuleKeyRemarks = CFSTR("rule:remarks"); -CFStringRef kSecAssessmentRuleKeyRequirement = CFSTR("rule:requirement"); -CFStringRef kSecAssessmentRuleKeyType = CFSTR("rule:type"); -CFStringRef kSecAssessmentRuleKeyExpires = CFSTR("rule:expires"); -CFStringRef kSecAssessmentRuleKeyDisabled = CFSTR("rule:disabled"); -CFStringRef kSecAssessmentRuleKeyBookmark = CFSTR("rule:bookmark"); - - -Boolean SecAssessmentUpdate(CFTypeRef target, - SecAssessmentFlags flags, - CFDictionaryRef context, - CFErrorRef *errors) -{ - if (CFDictionaryRef outcome = SecAssessmentCopyUpdate(target, flags, context, errors)) { - CFRelease(outcome); - return true; - } else { - return false; - } -} - -CFDictionaryRef SecAssessmentCopyUpdate(CFTypeRef target, - SecAssessmentFlags flags, - CFDictionaryRef context, - CFErrorRef *errors) -{ - BEGIN_CSAPI - - CFDictionary ctx(context, errSecCSInvalidAttributeValues); - CFRef result; - - // make context exist and writable - CFMutableDictionaryRef mcontext; - if (context == NULL) { - mcontext = makeCFMutableDictionary(); - } else { - mcontext = makeCFMutableDictionary(context); - } - - if (CFDictionaryGetValue(mcontext, kSecAssessmentUpdateKeyAuthorization) == NULL) { - // no authorization passed in. Make an empty one in this context - AuthorizationRef authorization; - MacOSError::check(AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &authorization)); - AuthorizationExternalForm extform; - MacOSError::check(AuthorizationMakeExternalForm(authorization, &extform)); - CFDictionaryAddValue(mcontext, kSecAssessmentUpdateKeyAuthorization, CFTempData(&extform, sizeof(extform))); - if (!(flags & kSecAssessmentFlagDirect)) - AuthorizationFree(authorization, kAuthorizationFlagDefaults); - } - - if (flags & kSecAssessmentFlagDirect) { - if (__esp_enabled()) { - CFTemp dict("{target=%O, flags=%d, context=%O}", target, flags, context); - OSStatus esp_result = __esp_check_ns("cs-assessment-update", (void *)(CFDictionaryRef)dict); - if (esp_result != noErr) - return NULL; - } - - // ask the engine right here to do its thing - result = gEngine().update(target, flags, ctx); - } else { - // relay the question to our daemon for consideration - result = xpcEngineUpdate(target, flags, ctx); - } - - if (__esp_enabled() && (flags & kSecAssessmentFlagDirect)) { - CFTemp dict("{target=%O, flags=%d, context=%O, outcome=%O}", target, flags, context, (CFDictionaryRef)result); - __esp_notify_ns("cs-assessment-update", (void *)(CFDictionaryRef)dict); - } - - traceUpdate(target, context, result); - return result.yield(); - - END_CSAPI_ERRORS1(false) -} - - -// -// The fcntl of System Policies. -// For those very special requests. -// -Boolean SecAssessmentControl(CFStringRef control, void *arguments, CFErrorRef *errors) -{ - BEGIN_CSAPI - - CFTemp dict("{control=%O}", control); - esp_do_check("cs-assessment-control", dict); - - if (CFEqual(control, CFSTR("ui-enable"))) { - setAssessment(true); - MessageTrace trace("com.apple.security.assessment.state", "enable"); - trace.send("enable assessment outcomes"); - return true; - } else if (CFEqual(control, CFSTR("ui-disable"))) { - setAssessment(false); - MessageTrace trace("com.apple.security.assessment.state", "disable"); - trace.send("disable assessment outcomes"); - return true; - } else if (CFEqual(control, CFSTR("ui-status"))) { - CFBooleanRef &result = *(CFBooleanRef*)(arguments); - if (overrideAssessment()) - result = kCFBooleanFalse; - else - result = kCFBooleanTrue; - return true; - } else if (CFEqual(control, CFSTR("ui-enable-devid"))) { - CFTemp ctx("{%O=%s}", kSecAssessmentUpdateKeyLabel, "Developer ID"); - if (CFDictionaryRef result = gEngine().enable(NULL, kAuthorityInvalid, kSecCSDefaultFlags, ctx, false)) - CFRelease(result); - MessageTrace trace("com.apple.security.assessment.state", "enable-devid"); - trace.send("enable Developer ID approval"); - return true; - } else if (CFEqual(control, CFSTR("ui-disable-devid"))) { - CFTemp ctx("{%O=%s}", kSecAssessmentUpdateKeyLabel, "Developer ID"); - if (CFDictionaryRef result = gEngine().disable(NULL, kAuthorityInvalid, kSecCSDefaultFlags, ctx, false)) - CFRelease(result); - MessageTrace trace("com.apple.security.assessment.state", "disable-devid"); - trace.send("disable Developer ID approval"); - return true; - } else if (CFEqual(control, CFSTR("ui-get-devid"))) { - CFBooleanRef &result = *(CFBooleanRef*)(arguments); - if (gEngine().value("SELECT disabled FROM authority WHERE label = 'Developer ID';", true)) - result = kCFBooleanFalse; - else - result = kCFBooleanTrue; - return true; - } else if (CFEqual(control, CFSTR("ui-record-reject"))) { - // send this through syspolicyd for update validation - xpcEngineRecord(CFDictionaryRef(arguments)); - return true; - } else if (CFEqual(control, CFSTR("ui-record-reject-local"))) { - // perform the local operation (requires root) - gEngine().recordFailure(CFDictionaryRef(arguments)); - return true; - } else if (CFEqual(control, CFSTR("ui-recall-reject"))) { - // no special privileges required for this, so read directly - CFDictionaryRef &result = *(CFDictionaryRef*)(arguments); - CFRef infoData = cfLoadFile(lastRejectFile); - if (infoData) - result = makeCFDictionaryFrom(infoData); - else - result = NULL; - return true; - } else if (CFEqual(control, CFSTR("rearm-status"))) { - CFTimeInterval &result = *(CFTimeInterval*)(arguments); - if (!queryRearmTimer(result)) - result = 0; - return true; - } else - MacOSError::throwMe(errSecCSInvalidAttributeValues); - - END_CSAPI_ERRORS1(false) -} diff --git a/OSX/include/security_codesigning/SecAssessment.h b/OSX/include/security_codesigning/SecAssessment.h deleted file mode 100644 index 78d96832..00000000 --- a/OSX/include/security_codesigning/SecAssessment.h +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_SECASSESSMENT -#define _H_SECASSESSMENT - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/*! - * @type SecAccessmentRef An assessment being performed. - */ -typedef struct _SecAssessment *SecAssessmentRef; - - -/*! - * CF-standard type function - */ -CFTypeID SecAssessmentGetTypeID(); - - -/* - * Notifications sent when the policy authority database changes. - * (Should move to /usr/include/notify_keys.h eventually.) - */ -#define kNotifySecAssessmentMasterSwitch "com.apple.security.assessment.masterswitch" -#define kNotifySecAssessmentUpdate "com.apple.security.assessment.update" -#define kNotifySecAssessmentRecordingChange "com.apple.security.assessment.UIRecordRejectDidChangeNotification" - - -/*! - * Primary operation types. These are operations the system policy can express - * opinions on. They are not operations *on* the system configuration itself. - * (For those, see SecAssessmentUpdate below.) - * - * @constant kSecAssessmentContextKeyOperation Context key describing the type of operation - * being contemplated. The default varies depending on the API call used. - * @constant kSecAssessmentOperationTypeExecute Value denoting the operation of running or executing - * code on the system. - * @constant kSecAssessmentOperationTypeInstall Value denoting the operation of installing - * software into the system. - * @constant kSecAssessmentOperationTypeOpenDocument Value denoting the operation of opening - * (in the LaunchServices sense) of documents. - */ -extern CFStringRef kSecAssessmentContextKeyOperation; // proposed operation -extern CFStringRef kSecAssessmentOperationTypeExecute; // .. execute code -extern CFStringRef kSecAssessmentOperationTypeInstall; // .. install software -extern CFStringRef kSecAssessmentOperationTypeOpenDocument; // .. LaunchServices-level document open - - -/*! - Operational flags for SecAssessment calls - - @type SecAssessmentFlags A mask of flag bits passed to SecAssessment calls to influence their - operation. - - @constant kSecAssessmentDefaultFlags Pass this to indicate that default behavior is desired. - @constant kSecAssessmentFlagIgnoreCache Do not use cached information; always perform a full - evaluation of system policy. This may be substantially slower. - @constant kSecAssessmentFlagNoCache Do not save any evaluation outcome in the system caches. - Any content already there is left undisturbed. Independent of kSecAssessmentFlagIgnoreCache. - @constant kSecAssessmentFlagEnforce Perform normal operations even if assessments have been - globally bypassed (which would usually approve anything). - @constant kSecAssessmentAllowWeak Allow signatures that contain known weaknesses, such as an - insecure resource envelope. - @constant kSecAssessmentIgnoreWhitelist Do not search the weak signature whitelist. - @constant kSecAssessmentFlagDequarantine Set the ASSESSMENT_OK flag if successful. - @constant kSecAssessmentFlagIgnoreActiveAssessments Permit parallel re-assessment of the same target. - @constant kSecAssessmentFlagLowPriority Run the assessment in low priority. - - Flags common to multiple calls are assigned from high-bit down. Flags for particular calls - are assigned low-bit up, and are documented with that call. - */ -typedef uint64_t SecAssessmentFlags; -enum { - kSecAssessmentDefaultFlags = 0, // default behavior - - kSecAssessmentFlagDirect = 1 << 30, // in-process evaluation - kSecAssessmentFlagAsynchronous = 1 << 29, // request asynchronous operation - kSecAssessmentFlagIgnoreCache = 1 << 28, // do not search cache - kSecAssessmentFlagNoCache = 1 << 27, // do not populate cache - kSecAssessmentFlagEnforce = 1 << 26, // force on (disable bypass switches) - kSecAssessmentFlagAllowWeak = 1 << 25, // allow weak signatures - kSecAssessmentFlagIgnoreWhitelist = 1 << 24, // do not search weak signature whitelist - kSecAssessmentFlagDequarantine = 1 << 23, // set the ASSESSMENT_OK flag if successful - kSecAssessmentFlagIgnoreActiveAssessments = 1 << 22, // permit parallel re-assessment of the same target - kSecAssessmentFlagLowPriority = 1 << 21, // run the assessment in low priority -}; - - -/*! - @function SecAssessmentCreate - Ask the system for its assessment of a proposed operation. - - @param path CFURL describing the file central to the operation - the program - to be executed, archive to be installed, plugin to be loaded, etc. - @param flags Operation flags and options. Pass kSecAssessmentDefaultFlags for default - behavior. - @param context Optional CFDictionaryRef containing additional information bearing - on the requested assessment. - @param errors Standard CFError argument for reporting errors. Note that declining to permit - the proposed operation is not an error. Inability to arrive at a judgment is. - @result On success, a SecAssessment object that can be queried for its outcome. - On error, NULL (with *errors set). - - Option flags: - - @constant kSecAssessmentFlagRequestOrigin Request additional work to produce information on - the originator (signer) of the object being discussed. - - Context keys: - - @constant kSecAssessmentContextKeyOperation Type of operation (see overview above). This defaults - to the kSecAssessmentOperationTypeExecute. - */ -extern CFStringRef kSecAssessmentContextKeyFeedback; // feedback reporting block -typedef Boolean (^SecAssessmentFeedback)(CFStringRef type, CFDictionaryRef information); -extern CFStringRef kSecAssessmentFeedbackProgress; // progress reporting feedback -extern CFStringRef kSecAssessmentFeedbackInfoCurrent; // info key: current work progress -extern CFStringRef kSecAssessmentFeedbackInfoTotal; // info key: total expected work - -extern CFStringRef kSecAssessmentAssessmentVerdict; // CFBooleanRef: master result - allow or deny -extern CFStringRef kSecAssessmentAssessmentOriginator; // CFStringRef: describing the signature originator -extern CFStringRef kSecAssessmentAssessmentAuthority; // CFDictionaryRef: authority used to arrive at result -extern CFStringRef kSecAssessmentAssessmentSource; // CFStringRef: primary source of authority -extern CFStringRef kSecAssessmentAssessmentFromCache; // present if result is from cache -extern CFStringRef kSecAssessmentAssessmentWeakSignature; // present if result attributable to signature weakness -extern CFStringRef kSecAssessmentAssessmentCodeSigningError; // error code returned by code signing API -extern CFStringRef kSecAssessmentAssessmentAuthorityRow; // (internal) -extern CFStringRef kSecAssessmentAssessmentAuthorityOverride; // (internal) -extern CFStringRef kSecAssessmentAssessmentAuthorityOriginalVerdict; // (internal) - -extern CFStringRef kDisabledOverride; // AuthorityOverride value for "Gatekeeper is disabled" - -enum { - kSecAssessmentFlagRequestOrigin = 1 << 0, // request origin information (slower) -}; - -SecAssessmentRef SecAssessmentCreate(CFURLRef path, - SecAssessmentFlags flags, - CFDictionaryRef context, - CFErrorRef *errors); - - -/*! - @function SecAssessmentCopyResult - - Extract results from a completed assessment and return them as a CFDictionary. - - @param assessment A SecAssessmentRef created with SecAssessmentCreate. - @param flags Operation flags and options. Pass kSecAssessmentDefaultFlags for default - behavior. - @errors Standard CFError argument for reporting errors. Note that declining to permit - the proposed operation is not an error. Inability to form a judgment is. - @result On success, a CFDictionary describing the outcome and various corroborating - data as requested by flags. The caller owns this dictionary and should release it - when done with it. On error, NULL (with *errors set). - - Assessment result keys (dictionary keys returned on success): - - @constant kSecAssessmentAssessmentVerdict A CFBoolean value indicating whether the system policy - allows (kCFBooleanTrue) or denies (kCFBooleanFalse) the proposed operation. - @constant kSecAssessmentAssessmentAuthority A CFDictionary describing what sources of authority - were used to arrive at this result. - @constant kSecAssessmentAssessmentOriginator A human-readable CFString describing the originator - of the signature securing the subject of the verdict. Requires kSecAssessmentFlagRequireOrigin. - May be missing anyway if no reliable source of origin can be determined. - */ -CFDictionaryRef SecAssessmentCopyResult(SecAssessmentRef assessment, - SecAssessmentFlags flags, - CFErrorRef *errors); - - -/*! - @function SecAssessmentCopyUpdate - Make changes to the system policy configuration. - - @param path CFTypeRef describing the subject of the operation. Depending on the operation, - this may be a CFURL denoting a (single) file or bundle; a SecRequirement describing - a group of files; a CFNumber denoting an existing rule by rule number, or NULL to perform - global changes. - @param flags Operation flags and options. Pass kSecAssessmentDefaultFlags for default - behavior. - @param context Required CFDictionaryRef containing information bearing - on the requested assessment. Must at least contain the kSecAssessmentContextKeyEdit key. - @param errors Standard CFError argument for reporting errors. Note that declining to permit - the proposed operation is not an error. Inability to form a judgment is. - @result Returns On success, a CFDictionary containing information pertaining to the completed operation. - Caller must CFRelease it when done. On failure, NULL, with *errors set if provided. - - Note: The SecAssessmentUpdate variant does not return data. It returns True on success, or False on error. - - Context keys and values: - - @constant kSecAssessmentContextKeyEdit Required context key describing the kind of change - requested to the system policy configuration. Currently understood values: - @constant kSecAssessmentUpdateOperationAdd Add a new rule to the assessment rule database. - @constant kSecAssessmentUpdateOperationRemove Remove rules from the rule database. - @constant kSecAssessmentUpdateOperationEnable (Re)enable rules in the rule database. - @constant kSecAssessmentUpdateOperationDisable Disable rules in the rule database. - @constant kSecAssessmentUpdateOperationFind Locate and return rules from the rule database. - This operation does not change the database, and does not require authorization or privileges. - - @constant kSecAssessmentUpdateKeyAuthorization A CFData containing the external form of a - system AuthorizationRef used to authorize the change. The call will automatically generate - a suitable authorization if this is missing; however, if the request is on behalf of - another client, an AuthorizationRef should be created there and passed along here. - @constant kSecAssessmentUpdateKeyPriority CFNumber denoting a (floating point) priority - for the rule(s) being processed. - @constant kSecAssessmentUpdateKeyLabel CFString denoting a label string applied to the rule(s) - being processed. - @constant kSecAssessmentUpdateKeyExpires CFDate denoting an (absolute, future) expiration date - for rule(s) being processed. - @constant kSecAssessmentUpdateKeyAllow CFBoolean denoting whether a new rule allows or denies - assessment. The default is to allow; set to kCFBooleanFalse to create a negative (denial) rule. - @constant kSecAssessmentUpdateKeyRemarks CFString containing a colloquial description or comment - about a newly created rule. This is mean to be human readable and is not used when evaluating rules. - - Keys returned as the result of a successful kSecAssessmentUpdateOperationFind operation: - - @constant kSecAssessmentRuleKeyID A CFNumber uniquely identifying a rule. - @constant kSecAssessmentRuleKeyPriority A CFNumber indicating the rule's priority. - This is a floating point number. Higher values indicate higher priority. - @constant kSecAssessmentRuleKeyAllow A CFBoolean indicating whether the rule allows (true) or denies (false) the operation. - @constant kSecAssessmentRuleKeyLabel An optional CFString labeling the rule. Multiple rules may have the same label; - this can be used to group rules. Labels are not presented to the user. The label has no effect on evaluation. - @constant kSecAssessmentRuleKeyRemarks An optional CFString containing user-readable text characterizing the rule's meaning. - The remark has no effect on the evaluation. - @constant kSecAssessmentRuleKeyRequirement A CFString containing the (text form of) the code requirement governing the rule's match. - @constant kSecAssessmentRuleKeyType A CFString denoting the type of operation governed by the rule. - One of the kSecAssessmentOperationType* constants. - @constant kSecAssessmentRuleKeyExpires A CFDate indicating when the rule expires. Absent if the rule does not expire. Expired rules are never returned. - @constant kSecAssessmentRuleKeyDisabled A CFNumber; non zero if temporarily disabled. Optional. - @constant kSecAssessmentRuleKeyBookmark A CFData with the bookmark to the rule. Optional. - */ -extern CFStringRef kSecAssessmentContextKeyUpdate; // proposed operation -extern CFStringRef kSecAssessmentUpdateOperationAdd; // add rule to policy database -extern CFStringRef kSecAssessmentUpdateOperationRemove; // remove rule from policy database -extern CFStringRef kSecAssessmentUpdateOperationEnable; // enable rule(s) in policy database -extern CFStringRef kSecAssessmentUpdateOperationDisable; // disable rule(s) in policy database -extern CFStringRef kSecAssessmentUpdateOperationFind; // extract rule(s) from the policy database - -extern CFStringRef kSecAssessmentUpdateKeyAuthorization; // [CFData] external form of governing authorization - -extern CFStringRef kSecAssessmentUpdateKeyPriority; // rule priority -extern CFStringRef kSecAssessmentUpdateKeyLabel; // rule label -extern CFStringRef kSecAssessmentUpdateKeyExpires; // rule expiration -extern CFStringRef kSecAssessmentUpdateKeyAllow; // rule outcome (allow/deny) -extern CFStringRef kSecAssessmentUpdateKeyRemarks; // rule remarks (human readable) - -extern CFStringRef kSecAssessmentUpdateKeyRow; // rule identifier (CFNumber; add only) -extern CFStringRef kSecAssessmentUpdateKeyCount; // count of changed rules (CFNumber) -extern CFStringRef kSecAssessmentUpdateKeyFound; // set of found rules (CFArray of CFDictionaries) - -extern CFStringRef kSecAssessmentRuleKeyID; // rule content returned: rule ID -extern CFStringRef kSecAssessmentRuleKeyPriority; // rule content returned: rule priority (floating point) -extern CFStringRef kSecAssessmentRuleKeyAllow; // rule content returned: rule allows (boolean) -extern CFStringRef kSecAssessmentRuleKeyLabel; // rule content returned: rule label (string; optional) -extern CFStringRef kSecAssessmentRuleKeyRemarks; // rule content returned: rule remarks (string; optional) -extern CFStringRef kSecAssessmentRuleKeyRequirement; // rule content returned: rule code requirement (string) -extern CFStringRef kSecAssessmentRuleKeyType; // rule content returned: rule type (string) -extern CFStringRef kSecAssessmentRuleKeyExpires; // rule content returned: rule expiration (CFDate; optional) -extern CFStringRef kSecAssessmentRuleKeyDisabled; // rule content returned: rule disabled (CFNumber; nonzero means temporarily disabled) -extern CFStringRef kSecAssessmentRuleKeyBookmark; // rule content returned: bookmark data (CFBookmark; optional) - -CFDictionaryRef SecAssessmentCopyUpdate(CFTypeRef target, - SecAssessmentFlags flags, - CFDictionaryRef context, - CFErrorRef *errors); - -Boolean SecAssessmentUpdate(CFTypeRef target, - SecAssessmentFlags flags, - CFDictionaryRef context, - CFErrorRef *errors); - - -/*! - @function SecAssessmentControl - Miscellaneous system policy operations. - - @param control A CFString indicating which operation is requested. - @param arguments Arguments to the operation as documented for control. - @param errors Standard CFErrorRef * argument to report errors. - @result Returns True on success. Returns False on failure (and sets *errors). - */ -Boolean SecAssessmentControl(CFStringRef control, void *arguments, CFErrorRef *errors); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECASSESSMENT diff --git a/OSX/include/security_codesigning/SecCode.cpp b/OSX/include/security_codesigning/SecCode.cpp deleted file mode 100644 index 2544d654..00000000 --- a/OSX/include/security_codesigning/SecCode.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2006-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecCode - API frame for SecCode objects. -// -// Note that some SecCode* functions take SecStaticCodeRef arguments in order to -// accept either static or dynamic code references, operating on the respective -// StaticCode. Those functions are in SecStaticCode.cpp, not here, despite their name. -// -#include "cs.h" -#include "Code.h" -#include "cskernel.h" -#include -#include - -using namespace CodeSigning; - - -// -// CFError user info keys -// -const CFStringRef kSecCFErrorArchitecture = CFSTR("SecCSArchitecture"); -const CFStringRef kSecCFErrorPattern = CFSTR("SecCSPattern"); -const CFStringRef kSecCFErrorResourceSeal = CFSTR("SecCSResourceSeal"); -const CFStringRef kSecCFErrorResourceAdded = CFSTR("SecCSResourceAdded"); -const CFStringRef kSecCFErrorResourceAltered = CFSTR("SecCSResourceAltered"); -const CFStringRef kSecCFErrorResourceMissing = CFSTR("SecCSResourceMissing"); -const CFStringRef kSecCFErrorInfoPlist = CFSTR("SecCSInfoPlist"); -const CFStringRef kSecCFErrorGuestAttributes = CFSTR("SecCSGuestAttributes"); -const CFStringRef kSecCFErrorRequirementSyntax = CFSTR("SecRequirementSyntax"); -const CFStringRef kSecCFErrorPath = CFSTR("SecComponentPath"); - - -// -// CF-standard type code functions -// -CFTypeID SecCodeGetTypeID(void) -{ - BEGIN_CSAPI - return gCFObjects().Code.typeID; - END_CSAPI1(_kCFRuntimeNotATypeID) -} - - -// -// Get a reference to the calling code. -// -OSStatus SecCodeCopySelf(SecCSFlags flags, SecCodeRef *selfRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - CFRef attributes = makeCFMutableDictionary(1, - kSecGuestAttributePid, CFTempNumber(getpid()).get()); - CodeSigning::Required(selfRef) = SecCode::autoLocateGuest(attributes, flags)->handle(false); - - END_CSAPI -} - - -// -// Get the dynamic status of a code. -// -OSStatus SecCodeGetStatus(SecCodeRef codeRef, SecCSFlags flags, SecCodeStatus *status) -{ - BEGIN_CSAPI - - checkFlags(flags); - CodeSigning::Required(status) = SecCode::required(codeRef)->status(); - - END_CSAPI -} - - -// -// Change the dynamic status of a code -// -OSStatus SecCodeSetStatus(SecCodeRef codeRef, SecCodeStatusOperation operation, - CFDictionaryRef arguments, SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecCode::required(codeRef)->status(operation, arguments); - - END_CSAPI -} - - -// -// Get the StaticCode for an Code -// -OSStatus SecCodeCopyStaticCode(SecCodeRef codeRef, SecCSFlags flags, SecStaticCodeRef *staticCodeRef) -{ - BEGIN_CSAPI - - checkFlags(flags, kSecCSUseAllArchitectures); - SecPointer staticCode = SecCode::required(codeRef)->staticCode(); - if (flags & kSecCSUseAllArchitectures) - if (Universal* macho = staticCode->diskRep()->mainExecutableImage()) // Mach-O main executable - if (macho->narrowed()) { - // create a new StaticCode comprising the whole fat file - RefPointer rep = DiskRep::bestGuess(staticCode->diskRep()->mainExecutablePath()); - staticCode = new SecStaticCode(rep); - } - CodeSigning::Required(staticCodeRef) = staticCode ? staticCode->handle() : NULL; - - END_CSAPI -} - - -// -// Get the host for an Code -// -OSStatus SecCodeCopyHost(SecCodeRef guestRef, SecCSFlags flags, SecCodeRef *hostRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecPointer host = SecCode::required(guestRef)->host(); - CodeSigning::Required(hostRef) = host ? host->handle() : NULL; - - END_CSAPI -} - - -// -// Find a guest by attribute(s) -// -const CFStringRef kSecGuestAttributeCanonical = CFSTR("canonical"); -const CFStringRef kSecGuestAttributeHash = CFSTR("codedirectory-hash"); -const CFStringRef kSecGuestAttributeMachPort = CFSTR("mach-port"); -const CFStringRef kSecGuestAttributePid = CFSTR("pid"); -const CFStringRef kSecGuestAttributeDynamicCode = CFSTR("dynamicCode"); -const CFStringRef kSecGuestAttributeDynamicCodeInfoPlist = CFSTR("dynamicCodeInfoPlist"); -const CFStringRef kSecGuestAttributeArchitecture = CFSTR("architecture"); -const CFStringRef kSecGuestAttributeSubarchitecture = CFSTR("subarchitecture"); - -OSStatus SecCodeCopyGuestWithAttributes(SecCodeRef hostRef, - CFDictionaryRef attributes, SecCSFlags flags, SecCodeRef *guestRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - if (hostRef) { - if (SecCode *guest = SecCode::required(hostRef)->locateGuest(attributes)) - CodeSigning::Required(guestRef) = guest->handle(false); - else - return errSecCSNoSuchCode; - } else - CodeSigning::Required(guestRef) = SecCode::autoLocateGuest(attributes, flags)->handle(false); - - END_CSAPI -} - - -// -// Shorthand for getting the SecCodeRef for a UNIX process -// -OSStatus SecCodeCreateWithPID(pid_t pid, SecCSFlags flags, SecCodeRef *processRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - if (SecCode *guest = KernelCode::active()->locateGuest(CFTemp("{%O=%d}", kSecGuestAttributePid, pid))) - CodeSigning::Required(processRef) = guest->handle(false); - else - return errSecCSNoSuchCode; - - END_CSAPI -} - - -// -// Check validity of an Code -// -OSStatus SecCodeCheckValidity(SecCodeRef codeRef, SecCSFlags flags, - SecRequirementRef requirementRef) -{ - return SecCodeCheckValidityWithErrors(codeRef, flags, requirementRef, NULL); -} - -OSStatus SecCodeCheckValidityWithErrors(SecCodeRef codeRef, SecCSFlags flags, - SecRequirementRef requirementRef, CFErrorRef *errors) -{ -#if !SECTRUST_OSX - BEGIN_CSAPI - - checkFlags(flags, - kSecCSConsiderExpiration - | kSecCSEnforceRevocationChecks); - SecPointer code = SecCode::required(codeRef); - code->checkValidity(flags); - if (const SecRequirement *req = SecRequirement::optional(requirementRef)) - code->staticCode()->validateRequirement(req->requirement(), errSecCSReqFailed); - - END_CSAPI_ERRORS -#else -#warning resolve before enabling SECTRUST_OSX: - OSStatus result = errSecSuccess; - const char *func = "SecCodeCheckValidity"; - CFErrorRef localErrors = NULL; - if (!errors) { errors = &localErrors; } - try { - checkFlags(flags, - kSecCSConsiderExpiration - | kSecCSEnforceRevocationChecks); - SecPointer code = SecCode::required(codeRef); - code->checkValidity(flags); - if (const SecRequirement *req = SecRequirement::optional(requirementRef)) - code->staticCode()->validateRequirement(req->requirement(), errSecCSReqFailed); - } - catch (...) { - // the actual error being thrown is not being caught by any of the - // type-specific blocks contained in the END_CSAPI_ERRORS macro, - // so we only have the catch-all block here for now. - result = errSecCSInternalError; - } - - if (errors && *errors) { - CFShow(errors); - CFRelease(errors); - *errors = NULL; - } - if (result == errSecCSInternalError) { - #if !NDEBUG - Security::Syslog::error("WARNING: %s ignored error %d", func, (int)result); - #endif - result = errSecSuccess; - } - return result; -#endif -} - - -// -// Collect suitably laundered information about the code signature of a SecStaticCode -// and return it as a CFDictionary. -// -// This API contracts to return a few pieces of information even for unsigned -// code. This means that a SecStaticCodeRef is usable as a basic indentifier -// (i.e. handle) for any code out there. -// -const CFStringRef kSecCodeInfoCertificates = CFSTR("certificates"); -const CFStringRef kSecCodeInfoChangedFiles = CFSTR("changed-files"); -const CFStringRef kSecCodeInfoCMS = CFSTR("cms"); -const CFStringRef kSecCodeInfoDesignatedRequirement = CFSTR("designated-requirement"); -const CFStringRef kSecCodeInfoEntitlements = CFSTR("entitlements"); -const CFStringRef kSecCodeInfoEntitlementsDict = CFSTR("entitlements-dict"); -const CFStringRef kSecCodeInfoFlags = CFSTR("flags"); -const CFStringRef kSecCodeInfoFormat = CFSTR("format"); -const CFStringRef kSecCodeInfoDigestAlgorithm = CFSTR("digest-algorithm"); -const CFStringRef kSecCodeInfoPlatformIdentifier = CFSTR("platform-identifier"); -const CFStringRef kSecCodeInfoIdentifier = CFSTR("identifier"); -const CFStringRef kSecCodeInfoImplicitDesignatedRequirement = CFSTR("implicit-requirement"); -const CFStringRef kSecCodeInfoMainExecutable = CFSTR("main-executable"); -const CFStringRef kSecCodeInfoPList = CFSTR("info-plist"); -const CFStringRef kSecCodeInfoRequirements = CFSTR("requirements"); -const CFStringRef kSecCodeInfoRequirementData = CFSTR("requirement-data"); -const CFStringRef kSecCodeInfoSource = CFSTR("source"); -const CFStringRef kSecCodeInfoStatus = CFSTR("status"); -const CFStringRef kSecCodeInfoTeamIdentifier = CFSTR("teamid"); -const CFStringRef kSecCodeInfoTime = CFSTR("signing-time"); -const CFStringRef kSecCodeInfoTimestamp = CFSTR("signing-timestamp"); -const CFStringRef kSecCodeInfoTrust = CFSTR("trust"); -const CFStringRef kSecCodeInfoUnique = CFSTR("unique"); - -const CFStringRef kSecCodeInfoCodeDirectory = CFSTR("CodeDirectory"); -const CFStringRef kSecCodeInfoCodeOffset = CFSTR("CodeOffset"); -const CFStringRef kSecCodeInfoResourceDirectory = CFSTR("ResourceDirectory"); - - -OSStatus SecCodeCopySigningInformation(SecStaticCodeRef codeRef, SecCSFlags flags, - CFDictionaryRef *infoRef) -{ - BEGIN_CSAPI - - checkFlags(flags, - kSecCSInternalInformation - | kSecCSSigningInformation - | kSecCSRequirementInformation - | kSecCSDynamicInformation - | kSecCSContentInformation); - - SecPointer code = SecStaticCode::requiredStatic(codeRef); - CFRef info = code->signingInformation(flags); - - if (flags & kSecCSDynamicInformation) - if (SecPointer dcode = SecStaticCode::optionalDynamic(codeRef)) - info.take(cfmake("{+%O,%O=%u}", info.get(), kSecCodeInfoStatus, dcode->status())); - - CodeSigning::Required(infoRef) = info.yield(); - - END_CSAPI -} diff --git a/OSX/include/security_codesigning/SecCode.h b/OSX/include/security_codesigning/SecCode.h deleted file mode 100644 index 415506b4..00000000 --- a/OSX/include/security_codesigning/SecCode.h +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCode - SecCode represents separately indentified running code in the system. - In addition to UNIX processes, this can also include (with suitable support) - scripts, applets, widgets, etc. -*/ -#ifndef _H_SECCODE -#define _H_SECCODE - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -/*! - @function SecCodeGetTypeID - Returns the type identifier of all SecCode instances. -*/ -CFTypeID SecCodeGetTypeID(void); - - -/*! - @function SecCodeCopySelf - Obtains a SecCode object for the code making the call. - The calling code is determined in a way that is subject to modification over - time, but obeys the following rules. If it is a UNIX process, its process id (pid) - is always used. If it is an active code host that has a dedicated guest, such a guest - is always preferred. If it is a host that has called SecHostSelectGuest, such selection - is considered until revoked. - - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param self Upon successful return, contains a SecCodeRef representing the caller. - - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - */ -OSStatus SecCodeCopySelf(SecCSFlags flags, SecCodeRef * __nonnull CF_RETURNS_RETAINED self); - - -/*! - @function SecCodeCopyStaticCode - Given a SecCode object, locate its origin in the file system and return - a SecStaticCode object representing it. - - The link established by this call is generally reliable but is NOT guaranteed - to be secure. - - Many API functions taking SecStaticCodeRef arguments will also directly - accept a SecCodeRef and apply this translation implicitly, operating on - its result or returning its error code if any. Each of these functions - calls out that behavior in its documentation. - - If the code was obtained from a universal (aka "fat") program file, - the resulting SecStaticCodeRef will refer only to the architecture actually - being used. This means that multiple running codes started from the same file - may conceivably result in different static code references if they ended up - using different execution architectures. (This is unusual but possible.) - - @param code A valid SecCode object reference representing code running - on the system. - - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @constant kSecCSUseAllArchitectures - If code refers to a single architecture of a universal binary, return a SecStaticCodeRef - that refers to the entire universal code with all its architectures. By default, the - returned static reference identifies only the actual architecture of the running program. - - @param staticCode On successful return, a SecStaticCode object reference representing - the file system origin of the given SecCode. On error, unchanged. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -CF_ENUM(uint32_t) { - kSecCSUseAllArchitectures = 1 << 0, -}; - -OSStatus SecCodeCopyStaticCode(SecCodeRef code, SecCSFlags flags, SecStaticCodeRef * __nonnull CF_RETURNS_RETAINED staticCode); - - -/*! - @function SecCodeCopyHost - Given a SecCode object, identify the (different) SecCode object that acts - as its host. A SecCode's host acts as a supervisor and controller, - and is the ultimate authority on the its dynamic validity and status. - The host relationship is securely established (absent reported errors). - - @param code A valid SecCode object reference representing code running - on the system. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param host On successful return, a SecCode object reference identifying - the code's host. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeCopyHost(SecCodeRef guest, SecCSFlags flags, SecCodeRef * __nonnull CF_RETURNS_RETAINED host); - -/*! - @function SecCodeCopyGuestWithAttributes - This is the omnibus API function for obtaining dynamic code references. - In general, it asks a particular code acting as a code host to locate - and return a guest with given attributes. Different hosts support - different combinations of attributes and values for guest selection. - - Asking the NULL host invokes system default procedures for obtaining - any running code in the system with the attributes given. The returned - code may be anywhere in the system. - - The methods a host uses to identify, separate, and control its guests - are specific to each type of host. This call provides a generic abstraction layer - that allows uniform interrogation of all hosts. A SecCode that does not - act as a host will always return errSecCSNoSuchCode. A SecCode that does - support hosting may return itself to signify that the attribute refers to - itself rather than one of its hosts. - - @param host A valid SecCode object reference representing code running - on the system that acts as a Code Signing host. As a special case, passing - NULL indicates that the Code Signing root of trust should be used as a starting - point. Currently, that is the system kernel. - @param attributes A CFDictionary containing zero or more attribute selector - values. Each selector has a CFString key and associated CFTypeRef value. - The key name identifies the attribute being specified; the associated value, - whose type depends on the the key name, selects a particular value or other - constraint on that attribute. Each host only supports particular combinations - of keys and values, and errors will be returned if any unsupported set is requested. - As a special case, NULL is taken to mean an empty attribute set. - Note that some hosts that support hosting chains (guests being hosts) - may return sub-guests in this call. In other words, do not assume that - a SecCodeRef returned by this call is a direct guest of the queried host - (though it will be a proximate guest, i.e. a guest's guest some way down). - Asking the NULL host for NULL attributes returns a code reference for the system root - of trust (at present, the running Darwin kernel). - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param guest On successful return, a SecCode object reference identifying - the particular guest of the host that owns the attribute value(s) specified. - This argument will not be changed if the call fails (does not return errSecSuccess). - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. In particular: - @error errSecCSUnsupportedGuestAttributes The host does not support the attribute - type given by attributeType. - @error errSecCSInvalidAttributeValues The type of value given for a guest - attribute is not supported by the host. - @error errSecCSNoSuchCode The host has no guest with the attribute value given - by attributeValue, even though the value is of a supported type. This may also - be returned if the host code does not currently act as a Code Signing host. - @error errSecCSNotAHost The specified host cannot, in fact, act as a code - host. (It is missing the kSecCodeSignatureHost option flag in its code - signature.) - @error errSecCSMultipleGuests The attributes specified do not uniquely identify - a guest (the specification is ambiguous). -*/ -extern const CFStringRef kSecGuestAttributeCanonical; -extern const CFStringRef kSecGuestAttributeHash; -extern const CFStringRef kSecGuestAttributeMachPort; -extern const CFStringRef kSecGuestAttributePid; -extern const CFStringRef kSecGuestAttributeDynamicCode; -extern const CFStringRef kSecGuestAttributeDynamicCodeInfoPlist; -extern const CFStringRef kSecGuestAttributeArchitecture; -extern const CFStringRef kSecGuestAttributeSubarchitecture; - -OSStatus SecCodeCopyGuestWithAttributes(SecCodeRef __nullable host, - CFDictionaryRef __nullable attributes, SecCSFlags flags, SecCodeRef * __nonnull CF_RETURNS_RETAINED guest); - - -/*! - @function SecCodeCheckValidity - Performs dynamic validation of the given SecCode object. The call obtains and - verifies the signature on the code object. It checks the validity of only those - sealed components required to establish identity. It checks the SecCode's - dynamic validity status as reported by its host. It ensures that the SecCode's - host is in turn valid. Finally, it validates the code against a SecRequirement - if one is given. The call succeeds if all these conditions are satisfactory. - It fails otherwise. - - This call is secure against attempts to modify the file system source of the - SecCode. - - @param code The code object to be validated. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement An optional code requirement specifying additional conditions - the code object must satisfy to be considered valid. If NULL, no additional - requirements are imposed. - @param errors An optional pointer to a CFErrorRef variable. If the call fails - (and something other than errSecSuccess is returned), and this argument is non-NULL, - a CFErrorRef is stored there further describing the nature and circumstances - of the failure. The caller must CFRelease() this error object when done with it. - @result If validation passes, errSecSuccess. If validation fails, an OSStatus value - documented in CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeCheckValidity(SecCodeRef code, SecCSFlags flags, - SecRequirementRef __nullable requirement); - -OSStatus SecCodeCheckValidityWithErrors(SecCodeRef code, SecCSFlags flags, - SecRequirementRef __nullable requirement, CFErrorRef *errors); - - -/*! - @function SecCodeCopyPath - For a given Code or StaticCode object, returns a URL to a location on disk where the - code object can be found. For single files, the URL points to that file. - For bundles, it points to the directory containing the entire bundle. - - This returns the same URL as the kSecCodeInfoMainExecutable key returned - by SecCodeCopySigningInformation. - - @param code The Code or StaticCode object to be located. For a Code - argument, its StaticCode is processed as per SecCodeCopyStaticCode. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param path On successful return, contains a CFURL identifying the location - on disk of the staticCode object. - @result On success, errSecSuccess. On error, an OSStatus value - documented in CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeCopyPath(SecStaticCodeRef staticCode, SecCSFlags flags, - CFURLRef * __nonnull CF_RETURNS_RETAINED path); - - -/*! - @function SecCodeCopyDesignatedRequirement - For a given Code or StaticCode object, determines its Designated Code Requirement. - The Designated Requirement is the SecRequirement that the code believes - should be used to properly identify it in the future. - - If the SecCode contains an explicit Designated Requirement, a copy of that - is returned. If it does not, a SecRequirement is implicitly constructed from - its signing authority and its embedded unique identifier. No Designated - Requirement can be obtained from code that is unsigned. Code that is modified - after signature, improperly signed, or has become invalid, may or may not yield - a Designated Requirement. This call does not validate the SecStaticCode argument. - - @param code The Code or StaticCode object to be interrogated. For a Code - argument, its StaticCode is processed as per SecCodeCopyStaticCode. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement On successful return, contains a copy of a SecRequirement - object representing the code's Designated Requirement. On error, unchanged. - @result On success, errSecSuccess. On error, an OSStatus value - documented in CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeCopyDesignatedRequirement(SecStaticCodeRef code, SecCSFlags flags, - SecRequirementRef * __nonnull CF_RETURNS_RETAINED requirement); - - -/* - @function SecCodeCopySigningInformation - For a given Code or StaticCode object, extract various pieces of information - from its code signature and return them in the form of a CFDictionary. The amount - and detail level of the data is controlled by the flags passed to the call. - - If the code exists but is not signed at all, this call will succeed and return - a dictionary that does NOT contain the kSecCodeInfoIdentifier key. This is the - recommended way to check quickly whether a code is signed. - - If the signing data for the code is corrupt or invalid, this call may fail or it - may return partial data. To ensure that only valid data is returned (and errors - are raised for invalid data), you must successfully call one of the CheckValidity - functions on the code before calling CopySigningInformation. - - @param code The Code or StaticCode object to be interrogated. For a Code - argument, its StaticCode is processed as per SecCodeCopyStaticCode. - Note that dynamic information (kSecCSDynamicInformation) cannot be obtained - for a StaticCode argument. - @param flags Optional flags. Use any or all of the kSecCS*Information flags - to select what information to return. A generic set of entries is returned - regardless; you may specify kSecCSDefaultFlags for just those. - @param information A CFDictionary containing information about the code is stored - here on successful completion. The contents of the dictionary depend on - the flags passed. Regardless of flags, the kSecCodeInfoIdentifier key is - always present if the code is signed, and always absent if the code is - unsigned. - Note that some of the objects returned are (retained) "live" API objects - used by the code signing infrastructure. Making changes to these objects - is unsupported and may cause subsequent code signing operations on the - affected code to behave in undefined ways. - @result On success, errSecSuccess. On error, an OSStatus value - documented in CSCommon.h or certain other Security framework headers. - - Flags: - - @constant kSecCSSigningInformation Return cryptographic signing information, - including the certificate chain and CMS data (if any). For ad-hoc signed - code, there are no certificates and the CMS data is empty. - @constant kSecCSRequirementInformation Return information about internal code - requirements embedded in the code. This includes the Designated Requirement. - @constant kSecCSInternalInformation Return internal code signing information. - This information is for use by Apple, and is subject to change without notice. - It will not be further documented here. - @constant kSecCSDynamicInformation Return dynamic validity information about - the Code. The subject code must be a SecCodeRef (not a SecStaticCodeRef). - @constant kSecCSContentInformation Return more information about the file system - contents making up the signed code on disk. It is not generally advisable to - make use of this information, but some utilities (such as software-update - tools) may find it useful. - - Dictionary keys: - - @constant kSecCodeInfoCertificates A CFArray of SecCertificates identifying the - certificate chain of the signing certificate as seen by the system. Absent - for ad-hoc signed code. May be partial or absent in error cases. - @constant kSecCodeInfoChangedFiles A CFArray of CFURLs identifying all files in - the code that may have been modified by the process of signing it. (In other - words, files not in this list will not have been touched by the signing operation.) - @constant kSecCodeInfoCMS A CFData containing the CMS cryptographic object that - secures the code signature. Empty for ad-hoc signed code. - @constant kSecCodeInfoDesignatedRequirement A SecRequirement describing the - actual Designated Requirement of the code. - @constant kSecCodeInfoEntitlements A CFData containing the embedded entitlement - blob of the code, if any. - @constant kSecCodeInfoEntitlementsDict A CFDictionary containing the embedded entitlements - of the code if it has entitlements and they are in standard dictionary form. - Absent if the code has no entitlements, or they are in a different format (in which - case, see kSecCodeInfoEntitlements). - @constant kSecCodeInfoFlags A CFNumber with the static (on-disk) state of the object. - Contants are defined by the type SecCodeSignatureFlags. - @constant kSecCodeInfoFormat A CFString characterizing the type and format of - the code. Suitable for display to a (knowledeable) user. - @constant kSecCodeInfoDigestAlgorithm A CFNumber indicating the kind of cryptographic - hash function used within the signature to seal its pieces together. - @constant kSecCodeInfoPlatformIdentifier If this code was signed as part of an operating - system release, this value identifies that release. - @constant kSecCodeInfoIdentifier A CFString with the actual signing identifier - sealed into the signature. Absent for unsigned code. - @constant kSecCodeInfoImplicitDesignatedRequirement A SecRequirement describing - the designated requirement that the system did generate, or would have generated, - for the code. If the Designated Requirement was implicitly generated, this is - the same object as kSecCodeInfoDesignatedRequirement; this can be used to test - for an explicit Designated Requirement. - @constant kSecCodeInfoMainExecutable A CFURL identifying the main executable file - of the code. For single files, that is the file itself. For bundles, it is the - main executable as identified by its Info.plist. - @constant kSecCodeInfoPList A retained CFDictionary referring to the secured Info.plist - as seen by code signing. Absent if no Info.plist is known to the code signing - subsystem. Note that this is not the same dictionary as the one CFBundle would - give you (CFBundle is free to add entries to the on-disk plist). - @constant kSecCodeInfoRequirements A CFString describing the internal requirements - of the code in canonical syntax. - @constant kSecCodeInfoRequirementsData A CFData containing the internal requirements - of the code as a binary blob. - @constant kSecCodeInfoSource A CFString describing the source of the code signature - used for the code object. The values are meant to be shown in informational - displays; do not rely on the precise value returned. - @constant kSecCodeInfoStatus A CFNumber containing the dynamic status word of the - (running) code. This is a snapshot at the time the API is executed and may be - out of date by the time you examine it. Do note however that most of the bits - are sticky and thus some values are permanently reliable. Be careful. - @constant kSecCodeInfoTime A CFDate describing the signing date (securely) embedded - in the code signature. Note that a signer is able to omit this date or pre-date - it. Nobody certifies that this was really the date the code was signed; however, - you do know that this is the date the signer wanted you to see. - Ad-hoc signatures have no CMS and thus never have secured signing dates. - @constant kSecCodeInfoTimestamp A CFDate describing the signing date as (securely) - certified by a timestamp authority service. This time cannot be falsified by the - signer; you trust the timestamp authority's word on this. - Ad-hoc signatures have no CMS and thus never have secured signing dates. - @constant kSecCodeInfoTrust The (retained) SecTrust object the system uses to - evaluate the validity of the code's signature. You may use the SecTrust API - to extract detailed information, particularly for reasons why certificate - validation may have failed. This object may continue to be used for further - evaluations of this code; if you make any changes to it, behavior is undefined. - @constant kSecCodeInfoUnique A CFData binary identifier that uniquely identifies - the static code in question. It can be used to recognize this particular code - (and none other) now or in the future. Compare to kSecCodeInfoIdentifier, which - remains stable across (developer-approved) updates. - The algorithm used may change from time to time. However, for any existing signature, - the value is stable. - */ -CF_ENUM(uint32_t) { - kSecCSInternalInformation = 1 << 0, - kSecCSSigningInformation = 1 << 1, - kSecCSRequirementInformation = 1 << 2, - kSecCSDynamicInformation = 1 << 3, - kSecCSContentInformation = 1 << 4 -}; - /* flag required to get this value */ -extern const CFStringRef kSecCodeInfoCertificates; /* Signing */ -extern const CFStringRef kSecCodeInfoChangedFiles; /* Content */ -extern const CFStringRef kSecCodeInfoCMS; /* Signing */ -extern const CFStringRef kSecCodeInfoDesignatedRequirement; /* Requirement */ -extern const CFStringRef kSecCodeInfoEntitlements; /* Requirement */ -extern const CFStringRef kSecCodeInfoEntitlementsDict; /* Requirement */ -extern const CFStringRef kSecCodeInfoFlags; /* generic */ -extern const CFStringRef kSecCodeInfoFormat; /* generic */ -extern const CFStringRef kSecCodeInfoDigestAlgorithm; /* generic */ -extern const CFStringRef kSecCodeInfoPlatformIdentifier; /* generic */ -extern const CFStringRef kSecCodeInfoIdentifier; /* generic */ -extern const CFStringRef kSecCodeInfoImplicitDesignatedRequirement; /* Requirement */ -extern const CFStringRef kSecCodeInfoMainExecutable; /* generic */ -extern const CFStringRef kSecCodeInfoPList; /* generic */ -extern const CFStringRef kSecCodeInfoRequirements; /* Requirement */ -extern const CFStringRef kSecCodeInfoRequirementData; /* Requirement */ -extern const CFStringRef kSecCodeInfoSource; /* generic */ -extern const CFStringRef kSecCodeInfoStatus; /* Dynamic */ -extern const CFStringRef kSecCodeInfoTeamIdentifier; /* Signing */ -extern const CFStringRef kSecCodeInfoTime; /* Signing */ -extern const CFStringRef kSecCodeInfoTimestamp; /* Signing */ -extern const CFStringRef kSecCodeInfoTrust; /* Signing */ -extern const CFStringRef kSecCodeInfoUnique; /* generic */ - -OSStatus SecCodeCopySigningInformation(SecStaticCodeRef code, SecCSFlags flags, - CFDictionaryRef * __nonnull CF_RETURNS_RETAINED information); - - -/* - @function SecCodeMapMemory - For a given Code or StaticCode object, ask the kernel to accept the signing information - currently attached to it in the caller and use it to validate memory page-ins against it, - updating dynamic validity state accordingly. This change affects all processes that have - the main executable of this code mapped. - - @param code A Code or StaticCode object representing the signed code whose main executable - should be subject to page-in validation. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - */ -OSStatus SecCodeMapMemory(SecStaticCodeRef code, SecCSFlags flags); - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECCODE diff --git a/OSX/include/security_codesigning/SecCodeHost.cpp b/OSX/include/security_codesigning/SecCodeHost.cpp deleted file mode 100644 index 7de4bf90..00000000 --- a/OSX/include/security_codesigning/SecCodeHost.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecCodeHost - Host Code API -// -#include "cs.h" -#include "SecCodeHost.h" -#include -#include -#include - -using namespace CodeSigning; - - -// -// Munge a CFDictionary into a CssmData representing its plist -// -class DictData : public CFRef { -public: - DictData(CFDictionaryRef dict) : CFRef(makeCFData(dict)) { } - - operator CssmData() const - { - if (*this) - return CssmData::wrap(CFDataGetBytePtr(*this), CFDataGetLength(*this)); - else - return CssmData(); - } -}; - - -OSStatus SecHostCreateGuest(SecGuestRef host, - uint32_t status, CFURLRef path, CFDictionaryRef attributes, - SecCSFlags flags, SecGuestRef *newGuest) -{ - BEGIN_CSAPI - - checkFlags(flags, kSecCSDedicatedHost | kSecCSGenerateGuestHash); - CodeSigning::Required(newGuest) = SecurityServer::ClientSession().createGuest(host, - status, cfString(path).c_str(), CssmData(), DictData(attributes), flags); - - END_CSAPI -} - -OSStatus SecHostRemoveGuest(SecGuestRef host, SecGuestRef guest, SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecurityServer::ClientSession().removeGuest(host, guest); - - END_CSAPI -} - -OSStatus SecHostSelectGuest(SecGuestRef guestRef, SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecurityServer::ClientSession().selectGuest(guestRef); - - END_CSAPI -} - - -OSStatus SecHostSelectedGuest(SecCSFlags flags, SecGuestRef *guestRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - CodeSigning::Required(guestRef) = SecurityServer::ClientSession().selectedGuest(); - - END_CSAPI -} - -OSStatus SecHostSetGuestStatus(SecGuestRef guestRef, - uint32_t status, CFDictionaryRef attributes, - SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecurityServer::ClientSession().setGuestStatus(guestRef, status, DictData(attributes)); - - END_CSAPI -} - -OSStatus SecHostSetHostingPort(mach_port_t hostingPort, SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecurityServer::ClientSession().registerHosting(hostingPort, flags); - - END_CSAPI -} diff --git a/OSX/include/security_codesigning/SecCodeHost.h b/OSX/include/security_codesigning/SecCodeHost.h deleted file mode 100644 index 7e462af4..00000000 --- a/OSX/include/security_codesigning/SecCodeHost.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCodeHost - This header provides the hosting API for Code Signing. These are calls - that are (only) made by code that is hosting guests. - In the context of Code Signing, a Host is code that creates and manages other - codes from which it defends its own integrity. As part of that duty, it maintains - state for each of its children, and answers questions about them. - - A Host is externally represented by a SecCodeRef (it is a SecCode object). - So is a Guest. There is no specific API object to represent Hosts or Guests. - Within the Hosting API, guests are identified by simple numeric handles that - are unique and valid only in the context of their specific host. - - The functions in this API always apply to the Host making the API calls. - They cannot be used to (directly) interrogate another host. -*/ -#ifndef _H_SECCODEHOST -#define _H_SECCODEHOST - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -/*! - @header SecCodeHost - This header describes the Code Signing Hosting API. These are calls made - by code that wishes to become a Host in the Code Signing Host/Guest infrastructure. - Hosting allows the caller to establish separate, independent code identities - (SecCodeRefs) for parts of itself, usually because it is loading and managing - code in the form of scripts, plugins, etc. - - The Hosting API does not directly connect to the Code Signing Client APIs. - Certain calls in the client API will cause internal queries to hosts about their - guests. The Host side of these queries is managed through this API. The results - will eventually be delivered to client API callers in appropriate form. - - If code never calls any of the Hosting API functions, it is deemed to not have - guests and not act as a Host. This is the default and requires no action. - - Hosting operates in one of two modes, dynamic or proxy. Whichever mode is first - engaged prevails for the lifetime of the caller. There is no way to switch between - the two, and calling an API belonging to the opposite mode will fail. - - In dynamic hosting mode, the caller provides a Mach port that receives direct - queries about its guests. Dynamic mode is engaged by calling SecHostSetHostingPort. - - In proxy hosting mode, the caller provides information about its guests as - guests are created, removed, or change status. The system caches this information - and answers queries about guests from this pool of information. The caller is not - directly involved in answering such queries, and has no way to intervene. -*/ - - -/*! - @function SecHostCreateGuest - Create a new Guest and describe its initial properties. - - This call activates Hosting Proxy Mode. From here on, the system will record - guest information provided through SecHostCreateGuest, SecHostSetGuestStatus, and - SecHostRemoveGuest, and report hosting status to callers directly. This mode - is incompatible with dynamic host mode as established by a call to SecHostSetHostingPort. - - @param host Pass kSecNoGuest to create a guest of the process itself. - To create a guest of another guest (extending the hosting chain), pass the SecGuestRef - of the guest to act as the new guest's host. If host has a dedicated guest, - it will be deemed to be be the actual host, recursively. - @param status The Code Signing status word for the new guest. These are combinations - of the kSecCodeStatus* flags in . Note that the proxy will enforce - the rules for the stickiness of these bits. In particular, if you don't pass the - kSecCodeStatusValid bit during creation, your new guest will be born invalid and will - never have a valid identity. - @param path The canonical path to the guest's code on disk. This is the path you would - pass to SecStaticCodeCreateWithPath to make a static code object reference. You must - use an absolute path. - @param attributes An optional CFDictionaryRef containing attributes that can be used - to locate this particular guest among all of the caller's guests. The "canonical" - attribute is automatically added for the value of guestRef. If you pass NULL, - no other attributes are established for the guest. - While any key can be used in the attributes dictionary, the kSecGuestAttribute* constants - (in SecCode.h) are conventionally used here. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior, or - a combination of the flags defined below for special features. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - @param newGuest Upon successful creation of the new guest, the new SecGuestRef - that should be used to identify the new guest from here on. - - @constant kSecCSDedicatedHost Declares dedicated hosting for the given host. - In dedicated hosting, the host has exactly one guest (the one this call is - introducing), and the host will spend all of its time from here on running - that guest (or on its behalf). This declaration is irreversable for the lifetime - of the host. Note that this is a declaration about the given host, and is not - binding upon other hosts on either side of the hosting chain, though they in turn - may declare dedicated hosting if desired. - It is invalid to declare dedicated hosting if other guests have already been - introduced for this host, and it is invalid to introduce additional guests - for this host after this call. - @constant kSecCSGenerateGuestHash Ask the proxy to generate the binary identifier - (hash of CodeDirectory) from the copy on disk at the path given. This is not optimal - since an attacker with write access may be able to substitute a different copy just - in time, but it is convenient. For optimal security, the host should calculate the - hash from the loaded in-memory signature of its guest and pass the result as an - attribute with key kSecGuestAttributeHash. -*/ -CF_ENUM(uint32_t) { - kSecCSDedicatedHost = 1 << 0, - kSecCSGenerateGuestHash = 1 << 1, -}; - -OSStatus SecHostCreateGuest(SecGuestRef host, - uint32_t status, CFURLRef path, CFDictionaryRef __nullable attributes, - SecCSFlags flags, SecGuestRef * __nonnull newGuest); - - -/*! - @function SecHostRemoveGuest - Announce that the guest with the given guestRef has permanently disappeared. - It removes all memory of the guest from the hosting system. You cannot remove - a dedicated guest. - - @param host The SecGuestRef that was used to create guest. You cannot specify - a proximate host (host of a host) here. However, the substitution for dedicated - guests described for SecHostCreateGuest also takes place here. - @param guest The handle for a Guest previously created with SecHostCreateGuest - that has not previously been destroyed. This guest is to be destroyed now. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecHostRemoveGuest(SecGuestRef host, SecGuestRef guest, SecCSFlags flags); - - -/*! - @function SecHostSelectGuest - Tell the Code Signing host subsystem that the calling thread will now act - on behalf of the given Guest. This must be a valid Guest previously created - with SecHostCreateGuest. - - @param guestRef The handle for a Guest previously created with SecHostCreateGuest - on whose behalf this thread will act from now on. This setting will be remembered - until it is changed (or the thread terminates). - To indicate that the thread will act on behalf of the Host itself (rather than - any Guest), pass kSecNoGuest. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecHostSelectGuest(SecGuestRef guestRef, SecCSFlags flags); - - -/*! - @function SecHostSelectedGuest - Retrieve the handle for the Guest currently selected for the calling thread. - - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param guestRef Will be assigned the SecGuestRef currently in effect for - the calling thread. If no Guest is active on this thread (i.e. the thread - is acting for the Host), the return value is kSecNoGuest. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecHostSelectedGuest(SecCSFlags flags, SecGuestRef * __nonnull guestRef); - - -/*! - @function SecHostSetGuestStatus - Updates the status of a particular guest. - - @param guestRef The handle for a Guest previously created with SecHostCreateGuest - on whose behalf this thread will act from now on. This setting will be remembered - until it is changed (or the thread terminates). - @param status The new Code Signing status word for the guest. The proxy enforces - the restrictions on changes to guest status; in particular, the kSecCodeStatusValid bit can only - be cleared, and the kSecCodeStatusHard and kSecCodeStatusKill flags can only be set. Pass the previous - guest status to indicate that no change is desired. - @param attributes An optional dictionary containing attributes to be used to distinguish - this guest from all guests of the caller. If given, it completely replaces the attributes - specified earlier. If NULL, previously established attributes are retained. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - */ -OSStatus SecHostSetGuestStatus(SecGuestRef guestRef, - uint32_t status, CFDictionaryRef __nullable attributes, - SecCSFlags flags); - - -/*! - @function SecHostSetHostingPort - Tells the Code Signing Hosting subsystem that the calling code will directly respond - to hosting inquiries over the given port. - - This API should be the first hosting API call made. With it, the calling code takes - direct responsibility for answering questions about its guests using the hosting IPC - services. The SecHostCreateGuest, SecHostDestroyGuest and SecHostSetGuestStatus calls - are not valid after this. The SecHostSelectGuest and SecHostSelectedGuest calls will - still work, and will use whatever SecGuestRefs the caller has assigned in its internal - data structures. - - This call cannot be undone; once it is made, record-and-forward facilities are - disabled for the lifetime of the calling code. - - @param hostingPort A Mach message port with send rights. This port will be recorded - and handed to parties interested in querying the host about its children. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - */ -OSStatus SecHostSetHostingPort(mach_port_t hostingPort, SecCSFlags flags); - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECCODEHOST diff --git a/OSX/include/security_codesigning/SecCodeHostLib.c b/OSX/include/security_codesigning/SecCodeHostLib.c deleted file mode 100644 index 44774523..00000000 --- a/OSX/include/security_codesigning/SecCodeHostLib.c +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "SecCodeHost.h" -#include "SecCodeHostLib.h" -#include -#include -#include -#include - - -// -// Global state -// -mach_port_t gServerPort; -SecCSFlags gInitFlags; - - -// -// Framing macros and facilities -// -#define UCSP_ARGS gServerPort, mig_get_reply_port(), &securitydCreds, &rcode -#define ATTRDATA(attr) (void *)(attr), (attr) ? strlen((attr)) : 0 - -#define CALL(func) \ - security_token_t securitydCreds; \ - CSSM_RETURN rcode; \ - if (KERN_SUCCESS != func) \ - return errSecCSInternalError; \ - if (securitydCreds.val[0] != 0) \ - return CSSM_ERRCODE_VERIFICATION_FAILURE; \ - return rcode - - - -// -// Mandatory initialization call -// -OSStatus SecHostLibInit(SecCSFlags flags) -{ - if (gServerPort != MACH_PORT_NULL) // re-initialization attempt - return errSecCSInternalError; - - mach_port_t bootstrapPort; - if (KERN_SUCCESS != task_get_bootstrap_port(mach_task_self(), &bootstrapPort)) - return errSecCSInternalError; - static char serverName[BOOTSTRAP_MAX_NAME_LEN] = SECURITYSERVER_BOOTSTRAP_NAME; - if (KERN_SUCCESS != bootstrap_look_up(bootstrapPort, serverName, &gServerPort)) - return errSecCSInternalError; - - ClientSetupInfo info = { 0x1234, SSPROTOVERSION }; - CALL(ucsp_client_setup(UCSP_ARGS, mach_task_self(), info, "?:unspecified")); -} - - -// -// Guest creation. -// At this time, this ONLY supports the creation of (one) dedicated guest. -// -OSStatus SecHostLibCreateGuest(SecGuestRef host, - uint32_t status, const char *path, const char *attributeXML, - SecCSFlags flags, SecGuestRef *newGuest) -{ - return SecHostLibCreateGuest2(host, status, path, "", 0, attributeXML, flags, newGuest); -} - -OSStatus SecHostLibCreateGuest2(SecGuestRef host, - uint32_t status, const char *path, const void *cdhash, size_t cdhashLength, const char *attributeXML, - SecCSFlags flags, SecGuestRef *newGuest) -{ - if (flags != kSecCSDedicatedHost) - return errSecCSInvalidFlags; - - CALL(ucsp_client_createGuest(UCSP_ARGS, host, status, path, - (void *)cdhash, cdhashLength, ATTRDATA(attributeXML), flags, newGuest)); -} - - -// -// Update the status of a guest. -// -OSStatus SecHostLibSetGuestStatus(SecGuestRef guestRef, - uint32_t status, const char *attributeXML, - SecCSFlags flags) -{ - CALL(ucsp_client_setGuestStatus(UCSP_ARGS, guestRef, status, ATTRDATA(attributeXML))); -} - - -// -// Enable dynamic hosting mode. -// -OSStatus SecHostSetHostingPort(mach_port_t hostingPort, SecCSFlags flags) -{ - CALL(ucsp_client_registerHosting(UCSP_ARGS, hostingPort, flags)); -} - - -// -// Helper for checked incorporation of code. -// -OSStatus SecHostLibCheckLoad(const char *path, SecRequirementType type) -{ - CALL(ucsp_client_helpCheckLoad(UCSP_ARGS, path, type)); -} diff --git a/OSX/include/security_codesigning/SecCodeHostLib.h b/OSX/include/security_codesigning/SecCodeHostLib.h deleted file mode 100644 index 3cceb306..00000000 --- a/OSX/include/security_codesigning/SecCodeHostLib.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCodeHostLib - This header provides a subset of the hosting API for Code Signing. - This subset functionality is implemented as a static library written - entirely in C, and depends on nothing except the system library and the - C runtime. It is thus suitable to be used by low-level libraries and - other such system facilities. On the other hand, it does not provide the - full functionality of . - - This file is documented as a delta to , which - you should consult as a baseline. -*/ -#ifndef _H_SECCODEHOSTLIB -#define _H_SECCODEHOSTLIB - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/*! - @function SecHostLibInit - This function must be called first to use the SecCodeHostLib facility. - */ -OSStatus SecHostLibInit(SecCSFlags flags); - - -/*! - @function SecHostLibCreateGuest - This function declares a code host, engages hosting proxy services for it, - and creates a guest with given attributes and state. - - NOTE: This version of the function currently only supports dedicated hosting. - If you do not pass the kSecCSDedicatedHost flag, the call will fail. - */ -OSStatus SecHostLibCreateGuest(SecGuestRef host, - uint32_t status, const char *path, const char *attributeXML, - SecCSFlags flags, SecGuestRef *newGuest) DEPRECATED_ATTRIBUTE; - -OSStatus SecHostLibCreateGuest2(SecGuestRef host, - uint32_t status, const char *path, const void *cdhash, size_t cdhashLength, const char *attributeXML, - SecCSFlags flags, SecGuestRef *newGuest); - - -/*! - @function SecHostLibSetGuestStatus - This function can change the state or attributes (or both) of a given guest. - It performs all the work of SecHostSetGuestStatus. - */ -OSStatus SecHostLibSetGuestStatus(SecGuestRef guestRef, - uint32_t status, const char *attributeXML, - SecCSFlags flags); - - -/*! - @function SecHostLibSetHostingPort - Register a Mach port to receive hosting queries on. This enables (and locks) - dynamic hosting mode, and is incompatible with all proxy-mode calls. - You still must call SecHostLibInit first. - */ -OSStatus SecHostSetHostingPort(mach_port_t hostingPort, SecCSFlags flags); - - -/* - Functionality from SecCodeHost.h that is genuinely missing here: - -OSStatus SecHostRemoveGuest(SecGuestRef host, SecGuestRef guest, SecCSFlags flags); - -OSStatus SecHostSelectGuest(SecGuestRef guestRef, SecCSFlags flags); - -OSStatus SecHostSelectedGuest(SecCSFlags flags, SecGuestRef *guestRef); - -*/ - - -/*! - */ -OSStatus SecHostLibCheckLoad(const char *path, SecRequirementType type); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECCODEHOSTLIB diff --git a/OSX/include/security_codesigning/SecCodePriv.h b/OSX/include/security_codesigning/SecCodePriv.h deleted file mode 100644 index 158121a9..00000000 --- a/OSX/include/security_codesigning/SecCodePriv.h +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCodePriv - SecCodePriv is the private counter-part to SecCode. Its contents are not - official API, and are subject to change without notice. -*/ -#ifndef _H_SECCODEPRIV -#define _H_SECCODEPRIV - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/* - * Private constants for SecCodeCopySigningInformation. - * These are returned with the - */ -extern const CFStringRef kSecCodeInfoCodeDirectory; /* Internal */ -extern const CFStringRef kSecCodeInfoCodeOffset; /* Internal */ -extern const CFStringRef kSecCodeInfoResourceDirectory; /* Internal */ - - -/*! - @function SecCodeGetStatus - Retrieves the dynamic status for a SecCodeRef. - - The dynamic status of a code can change at any time; the value returned is a snapshot - in time that is inherently stale by the time it is received by the caller. However, - since the status bits can only change in certain ways, some information is indefinitely - valid. For example, an indication of invalidity (kSecCodeStatusValid bit off) is permanent - since the valid bit cannot be set once clear, while an indication of validity (bit set) - may already be out of date. - Use this call with caution; it is usually wiser to call the validation API functions - and let then consider the status as part of their holistic computation. However, - SecCodeGetStatus is useful at times to capture persistent (sticky) status configurations. - - @param code A valid SecCode object reference representing code running - on the system. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param status Upon successful return, contains the dynamic status of code as - determined by its host. - - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - */ -OSStatus SecCodeGetStatus(SecCodeRef code, SecCSFlags flags, SecCodeStatus *status); - - -/*! - @function SecCodeSetStatus - Change the dynamic status of a SecCodeRef. - - @param code A valid SecCode object reference representing code running - on the system. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param status Upon successful return, contains the dynamic status of code as - determined by its host. - - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - */ -typedef uint32_t SecCodeStatusOperation; -enum { - kSecCodeOperationNull = 0, - kSecCodeOperationInvalidate = 1, - kSecCodeOperationSetHard = 2, - kSecCodeOperationSetKill = 3, -}; - -OSStatus SecCodeSetStatus(SecCodeRef code, SecCodeStatusOperation operation, - CFDictionaryRef arguments, SecCSFlags flags); - - -/*! - @function SecCodeCopyInternalRequirement - For a given Code or StaticCode object, retrieves a particular kind of internal - requirement that was sealed during signing. - - This function will always fail for unsigned code. Requesting a type of internal - requirement that was not given during signing is not an error. - - Specifying a type of kSecDesignatedRequirementType is not the same as calling - SecCodeCopyDesignatedRequirement. This function will only return an explicit - Designated Requirement if one was specified during signing. SecCodeCopyDesignatedRequirement - will synthesize a suitable Designated Requirement if one was not given explicitly. - - @param code The Code or StaticCode object to be interrogated. For a Code - argument, its StaticCode is processed as per SecCodeCopyStaticCode. - @param type A SecRequirementType specifying which internal requirement is being - requested. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement On successful return, contains a copy of the internal requirement - of the given type included in the given code. If the code has no such internal - requirement, this argument is set to NULL (with no error). - @result On success, errSecSuccess. On error, an OSStatus value - documented in CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeCopyInternalRequirement(SecStaticCodeRef code, SecRequirementType type, - SecCSFlags flags, SecRequirementRef *requirement); - - -/*! - @function SecCodeCreateWithPID - Asks the kernel to return a SecCode object for a process identified - by a UNIX process id (pid). This is a shorthand for asking SecGetRootCode() - for a guest whose "pid" attribute has the given pid value. - - This is a deprecated convenience function. - Call SecCodeCopyGuestWithAttributes instead. - - @param pid A process id for an existing UNIX process on the system. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param process On successful return, a SecCode object reference identifying - the requesteed process. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeCreateWithPID(pid_t pid, SecCSFlags flags, SecCodeRef *process) - AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_6; - - -/* - @function SecCodeSetDetachedSignature - For a given Code or StaticCode object, explicitly specify the detached signature - data used to verify it. - This call unconditionally overrides any signature embedded in the Code and any - previously specified detached signature; only the signature data specified here - will be used from now on for this Code object. If NULL data is specified, the - code object is returned to its natural signing state (before a detached - signature was first attached to it). - Any call to this function voids all cached validations for the Code object. - Validations will be performed again as needed in the future. This call does not, - by itself, perform or trigger any validations. - Please note that it is possible to have multiple Code objects for the same static - or dynamic code entity in the system. This function only attaches signature data - to the particular SecStaticCodeRef involved. It is your responsibility to understand - the object graph and pick the right one(s). - - @param code A Code or StaticCode object whose signature information is to be changed. - @param signature A CFDataRef containing the signature data to be used for validating - the given Code. This must be exactly the data previously generated as a detached - signature by the SecCodeSignerAddSignature API or the codesign(1) command with - the -D/--detached option. - If signature is NULL, discards any previously set signature data and reverts - to using the embedded signature, if any. If not NULL, the data is retained and used - for future validation operations. - The data may be retained or copied. Behavior is undefined if this object - is modified after this call before it is replaced through another call to this - function). - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - */ -OSStatus SecCodeSetDetachedSignature(SecStaticCodeRef code, CFDataRef signature, - SecCSFlags flags); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECCODE diff --git a/OSX/include/security_codesigning/SecCodeSigner.cpp b/OSX/include/security_codesigning/SecCodeSigner.cpp deleted file mode 100644 index e9965556..00000000 --- a/OSX/include/security_codesigning/SecCodeSigner.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecCode - API frame for SecCode objects. -// -// Note that some SecCode* functions take SecStaticCodeRef arguments in order to -// accept either static or dynamic code references, operating on the respective -// StaticCode. Those functions are in SecStaticCode.cpp, not here, despite their name. -// -#include "cs.h" -#include "CodeSigner.h" -#include "cskernel.h" - -using namespace CodeSigning; - - -// -// Parameter keys -// -const CFStringRef kSecCodeSignerApplicationData = CFSTR("application-specific"); -const CFStringRef kSecCodeSignerDetached = CFSTR("detached"); -const CFStringRef kSecCodeSignerDigestAlgorithm = CFSTR("digest-algorithm"); -const CFStringRef kSecCodeSignerDryRun = CFSTR("dryrun"); -const CFStringRef kSecCodeSignerEntitlements = CFSTR("entitlements"); -const CFStringRef kSecCodeSignerFlags = CFSTR("flags"); -const CFStringRef kSecCodeSignerIdentifier = CFSTR("identifier"); -const CFStringRef kSecCodeSignerIdentifierPrefix = CFSTR("identifier-prefix"); -const CFStringRef kSecCodeSignerIdentity = CFSTR("signer"); -const CFStringRef kSecCodeSignerPageSize = CFSTR("pagesize"); -const CFStringRef kSecCodeSignerRequirements = CFSTR("requirements"); -const CFStringRef kSecCodeSignerResourceRules = CFSTR("resource-rules"); -const CFStringRef kSecCodeSignerSDKRoot = CFSTR("sdkroot"); -const CFStringRef kSecCodeSignerSigningTime = CFSTR("signing-time"); -const CFStringRef kSecCodeSignerRequireTimestamp = CFSTR("timestamp-required"); -const CFStringRef kSecCodeSignerTimestampServer = CFSTR("timestamp-url"); -const CFStringRef kSecCodeSignerTimestampAuthentication = CFSTR("timestamp-authentication"); -const CFStringRef kSecCodeSignerTimestampOmitCertificates = CFSTR("timestamp-omit-certificates"); -const CFStringRef kSecCodeSignerPreserveMetadata = CFSTR("preserve-metadata"); -const CFStringRef kSecCodeSignerTeamIdentifier = CFSTR("teamidentifier"); -const CFStringRef kSecCodeSignerPlatformIdentifier = CFSTR("platform-identifier"); - -// temporary add-back to bridge B&I build dependencies -- remove soon -const CFStringRef kSecCodeSignerTSAUse = CFSTR("timestamp-required"); -const CFStringRef kSecCodeSignerTSAURL = CFSTR("timestamp-url"); -const CFStringRef kSecCodeSignerTSAClientAuth = CFSTR("timestamp-authentication"); -const CFStringRef kSecCodeSignerTSANoCerts = CFSTR("timestamp-omit-certificates"); - - -// -// CF-standard type code functions -// -CFTypeID SecCodeSignerGetTypeID(void) -{ - BEGIN_CSAPI - return gCFObjects().CodeSigner.typeID; - END_CSAPI1(_kCFRuntimeNotATypeID) -} - - -// -// Create a signer object -// -OSStatus SecCodeSignerCreate(CFDictionaryRef parameters, SecCSFlags flags, - SecCodeSignerRef *signerRef) -{ - BEGIN_CSAPI - - checkFlags(flags, - kSecCSRemoveSignature - | kSecCSSignPreserveSignature - | kSecCSSignNestedCode - | kSecCSSignOpaque - | kSecCSSignV1 - | kSecCSSignNoV1 - | kSecCSSignBundleRoot - | kSecCSSignStrictPreflight); - SecPointer signer = new SecCodeSigner(flags); - signer->parameters(parameters); - CodeSigning::Required(signerRef) = signer->handle(); - - END_CSAPI -} - - -// -// Generate a signature -// -OSStatus SecCodeSignerAddSignature(SecCodeSignerRef signerRef, - SecStaticCodeRef codeRef, SecCSFlags flags) -{ - return SecCodeSignerAddSignatureWithErrors(signerRef, codeRef, flags, NULL); -} - -OSStatus SecCodeSignerAddSignatureWithErrors(SecCodeSignerRef signerRef, - SecStaticCodeRef codeRef, SecCSFlags flags, CFErrorRef *errors) -{ - BEGIN_CSAPI - checkFlags(flags, - kSecCSReportProgress - ); - SecCodeSigner::required(signerRef)->sign(SecStaticCode::required(codeRef), flags); - END_CSAPI_ERRORS -} diff --git a/OSX/include/security_codesigning/SecCodeSigner.h b/OSX/include/security_codesigning/SecCodeSigner.h deleted file mode 100644 index 4dead60d..00000000 --- a/OSX/include/security_codesigning/SecCodeSigner.h +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCodeSigner - SecCodeSigner represents an object that can sign code. -*/ -#ifndef _H_SECCODESIGNER -#define _H_SECCODESIGNER - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/*! - @typedef SecCodeSignerRef - This is the type of a reference to a code requirement. -*/ -typedef struct __SecCodeSigner *SecCodeSignerRef; /* code signing object */ - - -/*! - @function SecCodeGetTypeID - Returns the type identifier of all SecCodeSigner instances. -*/ -CFTypeID SecCodeSignerGetTypeID(void); - - -/*! - The following CFString constants can be used as keys in the parameters argument - of SecCodeSignerCreate to specify various modes and options of the signing operation. - Passing any keys not specified here may lead to undefined behavior and is not supported. - The same applies to passing objects of types not explicitly allowed here. - - @constant kSecCodeSignerDetached Determines where the signature is written. - If this key is absent, the code being signed is modified to contain the signature, - replacing any signature already embedded there. - If the value is kCFNull, the signature is written to the system-wide detached - signature database. (You must have root privileges to write there.) - If the value of this key is a CFURL, the signature is written to a file at that location, - replacing any data there. - If the value is a CFMutableData, the signature is appended to that data. - @constant kSecCodeSignerDryRun A boolean value. If present and true, the actual writing - of the signature is inhibited, and the code is not modified, but all operations - leading up to this are performed normally, including the cryptographic access to - the signing identity (if any). - @constant kSecCodeSignerFlags A CFNumber specifying which flags to set in the code signature. - Note that depending on circumstances, this value may be augmented or modified - as part of the signing operation. - @constant kSecCodeSignerIdentifier If present, a CFString that explicitly specifies - the unique identifier string sealed into the code signature. If absent, the identifier - is derived implicitly from the code being signed. - @constant kSecCodeSignerIdentifierPrefix If the unique identifier string of the code signature - is implicitly generated, and the resulting string does not contain any "." (dot) - characters, then the (string) value of this parameter is prepended to the identifier. - By convention, the prefix is usually of the form "com.yourcompany.", but any value - is acceptable. If the kSecCodeSignerIdentifier parameter is specified, this parameter - is ineffective (but still allowed). - @constant kSecCodeSignerIdentity A SecIdentityRef describing the signing identity - to use for signing code. This is a mandatory parameter for signing operations. - Its value must be either a SecIdentityRef specifying a cryptographic identity - valid for Code Signing, or the special value kCFNull to indicate ad-hoc signing. - @constant kSecCodeSignerOperation The type of operation to be performed. Valid values - are kSecCodeSignerOperationSign to sign code, and kSecCodeSignerOperationRemove - to remove any existing signature from code. The default operation is to sign code. - @constant kSecCodeSignerPageSize An integer value explicitly specifying the page size - used to sign the main executable. This must be a power of two. A value of zero indicates - infinite size (no paging). - Only certain page sizes are allowed in most circumstances, and specifying an inappropriate - size will lead to spurious verification failures. This is for expert use only. - @constant kSecCodeSignerRequirements Specifies the internal requirements to be sealed into - the code signature. Must be either a CFData containing the binary (compiled) form of - a requirements set (SuperBlob), or a CFString containing a valid text form to be - compiled into binary form. Default requirements are automatically generated if this - parameter is omitted, and defaults may be applied to particular requirement types - that are not specified; but any requirement type you specify is sealed exactly as - specified. - @constant kSecCodeSignerResourceRules A CFDictionary containing resource scanning rules - determining what resource files are sealed into the signature (and in what way). - A situation-dependent default is applied if this parameter is not specified. - @constant kSecCodeSignerSDKRoot A CFURLRef indicating an alterate directory root - where signing operations should find subcomponents (libraries, frameworks, modules, etc.). - The default is the host system root "/". - @constant kSecCodeSignerSigningTime Specifies what date and time is sealed into the - code signature's CMS data. Can be either a CFDate object specifying a date, or - the value kCFNull indicating that no date should be included in the signature. - If not specified, the current date is chosen and sealed. - Since an ad-hoc signature has no CMS data, this argument is ineffective - for ad-hoc signing operations. - @constant kSecCodeSignerRequireTimestamp A CFBoolean indicating (if kCFBooleanTrue) that - the code signature should be certified by a timestamp authority service. This option - requires access to a timestamp server (usually over the Internet). If requested and - the timestamp server cannot be contacted or refuses service, the signing operation fails. - The timestamp value is not under the caller's control. - If the value is kCFBooleanFalse, no timestamp service is contacted and the resulting signature - has no certified timestamp. - If this key is omitted, a default is used that may vary from release to release. - Note that when signing multi-architectural ("fat") programs, each architecture will - be signed separately, and thus each architecture will have a slightly different timestamp. - @constant kSecCodeSignerTimestampServer A CFURL specifying which timestamp authority service - to contact for timestamping if requested by the kSecCodeSignerRequireTimestamp argument. - If omitted (and timestamping is performed), a system-defined default value is used, referring - to an Apple-operated timestamp service. Note that this service may not freely serve all requests. - @constant kSecCodeSignerTimestampAuthentication A SecIdentityRef describing the identity - used to authenticate to the timestamp authority server, if the server requires client-side - (SSL/TLS) authentication. This will not generally be the identity used to sign the actual - code, depending on the requirements of the timestamp authority service used. - If omitted, the timestamp server is contacted using unauthenticated HTTP requests. - @constant kSecCodeSignerTimestampOmitCertificates A CFBoolean indicating (if kCFBooleanTrue) - that the timestamp embedded in the signature, if requested, not contain the full certificate chain - of the timestamp service used. This will make for a marginally smaller signature, but may not - verify correctly unless all such certificates are available (through the keychain system) - on the verifying system. - The default is to embed enough certificates to ensure proper verification of Apple-generated - timestamp signatures. - */ -extern const CFStringRef kSecCodeSignerApplicationData; -extern const CFStringRef kSecCodeSignerDetached; -extern const CFStringRef kSecCodeSignerDigestAlgorithm; -extern const CFStringRef kSecCodeSignerDryRun; -extern const CFStringRef kSecCodeSignerEntitlements; -extern const CFStringRef kSecCodeSignerFlags; -extern const CFStringRef kSecCodeSignerIdentifier; -extern const CFStringRef kSecCodeSignerIdentifierPrefix; -extern const CFStringRef kSecCodeSignerIdentity; -extern const CFStringRef kSecCodeSignerPageSize; -extern const CFStringRef kSecCodeSignerRequirements; -extern const CFStringRef kSecCodeSignerResourceRules; -extern const CFStringRef kSecCodeSignerSDKRoot; -extern const CFStringRef kSecCodeSignerSigningTime; -extern const CFStringRef kSecCodeSignerTimestampAuthentication; -extern const CFStringRef kSecCodeSignerRequireTimestamp; -extern const CFStringRef kSecCodeSignerTimestampServer; -extern const CFStringRef kSecCodeSignerTimestampOmitCertificates; -extern const CFStringRef kSecCodeSignerPreserveMetadata; -extern const CFStringRef kSecCodeSignerTeamIdentifier; -extern const CFStringRef kSecCodeSignerPlatformIdentifier; - -enum { - kSecCodeSignerPreserveIdentifier = 1 << 0, // preserve signing identifier - kSecCodeSignerPreserveRequirements = 1 << 1, // preserve internal requirements (including DR) - kSecCodeSignerPreserveEntitlements = 1 << 2, // preserve entitlements - kSecCodeSignerPreserveResourceRules = 1 << 3, // preserve resource rules (and thus resources) - kSecCodeSignerPreserveFlags = 1 << 4, // preserve signing flags - kSecCodeSignerPreserveTeamIdentifier = 1 << 5, // preserve team identifier flags -}; - - -/*! - @function SecCodeSignerCreate - Create a (new) SecCodeSigner object to be used for signing code. - - @param parameters An optional CFDictionary containing parameters that influence - signing operations with the newly created SecCodeSigner. If NULL, defaults - are applied to all parameters; note however that some parameters do not have - useful defaults, and will need to be set before signing is attempted. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - The kSecCSRemoveSignature flag requests that any existing signature be stripped - from the target code instead of signing. - @param staticCode On successful return, a SecStaticCode object reference representing - the file system origin of the given SecCode. On error, unchanged. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -enum { - kSecCSRemoveSignature = 1 << 0, // strip existing signature - kSecCSSignPreserveSignature = 1 << 1, // do not (re)sign if an embedded signature is already present - kSecCSSignNestedCode = 1 << 2, // recursive (deep) signing - kSecCSSignOpaque = 1 << 3, // treat all files as resources (no nest scan, no flexibility) - kSecCSSignV1 = 1 << 4, // sign ONLY in V1 form - kSecCSSignNoV1 = 1 << 5, // do not include V1 form - kSecCSSignBundleRoot = 1 << 6, // include files in bundle root - kSecCSSignStrictPreflight = 1 << 7, // fail signing operation if signature would fail strict validation -}; - - -OSStatus SecCodeSignerCreate(CFDictionaryRef parameters, SecCSFlags flags, - SecCodeSignerRef *signer); - - -/*! - @function SecCodeSignerAddSignature - Create a code signature and add it to the StaticCode object being signed. - - @param signer A SecCodeSigner object containing all the information required - to sign code. - @param code A valid SecStaticCode object reference representing code files - on disk. This code will be signed, and will ordinarily be modified to contain - the resulting signature data. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param errors An optional pointer to a CFErrorRef variable. If the call fails - (and something other than errSecSuccess is returned), and this argument is non-NULL, - a CFErrorRef is stored there further describing the nature and circumstances - of the failure. The caller must CFRelease() this error object when done with it. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecCodeSignerAddSignature(SecCodeSignerRef signer, - SecStaticCodeRef code, SecCSFlags flags); - -OSStatus SecCodeSignerAddSignatureWithErrors(SecCodeSignerRef signer, - SecStaticCodeRef code, SecCSFlags flags, CFErrorRef *errors); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECCODESIGNER diff --git a/OSX/include/security_codesigning/SecIntegrity.cpp b/OSX/include/security_codesigning/SecIntegrity.cpp deleted file mode 100644 index dc266a02..00000000 --- a/OSX/include/security_codesigning/SecIntegrity.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include -#include "SecIntegrity.h" - - diff --git a/OSX/include/security_codesigning/SecIntegrity.h b/OSX/include/security_codesigning/SecIntegrity.h deleted file mode 100644 index 4c92f44e..00000000 --- a/OSX/include/security_codesigning/SecIntegrity.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecIntegrity - This header provides functionality that allows a program to use its own - code signature to extend trust to parts of its bundle that it covers. - - This file does not help you verify code signatures themselves; use SecCode.h - for that. It is reasonable to use SecCode.h and SecIntegrity.h together. -*/ -#ifndef _H_SECINTEGRITY -#define _H_SECINTEGRITY - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - - - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECINTEGRITY diff --git a/OSX/include/security_codesigning/SecIntegrityLib.c b/OSX/include/security_codesigning/SecIntegrityLib.c deleted file mode 100644 index 17b1825a..00000000 --- a/OSX/include/security_codesigning/SecIntegrityLib.c +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "SecIntegrityLib.h" diff --git a/OSX/include/security_codesigning/SecIntegrityLib.h b/OSX/include/security_codesigning/SecIntegrityLib.h deleted file mode 100644 index 0a0a0c51..00000000 --- a/OSX/include/security_codesigning/SecIntegrityLib.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecIntegrityLib - This header provides a subset of the code-integrity API for Code Signing. - This subset functionality is implemented as a static library written - entirely in C, and depends on nothing except the system library and the - C runtime. It is thus suitable to be used by low-level libraries and - other such system facilities. On the other hand, it does not provide the - full functionality of . - - This file is documented as a delta to , which - you should consult as a baseline. -*/ -#ifndef _H_SECINTEGRITYLIB -#define _H_SECINTEGRITYLIB - -#include "SecIntegrity.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -/* - This file is not yet published. - */ - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECINTEGRITYLIB diff --git a/OSX/include/security_codesigning/SecRequirement.cpp b/OSX/include/security_codesigning/SecRequirement.cpp deleted file mode 100644 index eab15a41..00000000 --- a/OSX/include/security_codesigning/SecRequirement.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright (c) 2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecRequirement - API frame for SecRequirement objects -// -#include "cs.h" -#include "Requirements.h" -#include "reqparser.h" -#include "reqmaker.h" -#include "reqdumper.h" -#include -#include - -using namespace CodeSigning; - - -// -// CF-standard type code function -// -CFTypeID SecRequirementGetTypeID(void) -{ - BEGIN_CSAPI - return gCFObjects().Requirement.typeID; - END_CSAPI1(_kCFRuntimeNotATypeID) -} - - -// -// Create a Requirement from data -// -OSStatus SecRequirementCreateWithData(CFDataRef data, SecCSFlags flags, - SecRequirementRef *requirementRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - CodeSigning::Required(requirementRef) = (new SecRequirement(CFDataGetBytePtr(data), CFDataGetLength(data)))->handle(); - - END_CSAPI -} - - -// -// Create a Requirement from data in a file -// -OSStatus SecRequirementCreateWithResource(CFURLRef resource, SecCSFlags flags, - SecRequirementRef *requirementRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - CFRef data = cfLoadFile(resource); - CodeSigning::Required(requirementRef) = - (new SecRequirement(CFDataGetBytePtr(data), CFDataGetLength(data)))->handle(); - - END_CSAPI -} - - -// -// Create a Requirement from source text (compiling it) -// -OSStatus SecRequirementCreateWithString(CFStringRef text, SecCSFlags flags, - SecRequirementRef *requirementRef) -{ - return SecRequirementCreateWithStringAndErrors(text, flags, NULL, requirementRef); -} - -OSStatus SecRequirementCreateWithStringAndErrors(CFStringRef text, SecCSFlags flags, - CFErrorRef *errors, SecRequirementRef *requirementRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - CodeSigning::Required(requirementRef) = (new SecRequirement(parseRequirement(cfString(text)), true))->handle(); - - END_CSAPI_ERRORS -} - - -// -// Create a Requirement group. -// This is the canonical point where "application group" is defined. -// -OSStatus SecRequirementCreateGroup(CFStringRef groupName, SecCertificateRef anchorRef, - SecCSFlags flags, SecRequirementRef *requirementRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - Requirement::Maker maker; - maker.put(opAnd); // both of... - maker.infoKey("Application-Group", cfString(groupName)); - if (anchorRef) { - CSSM_DATA certData; - MacOSError::check(SecCertificateGetData(anchorRef, &certData)); - maker.anchor(0, certData.Data, certData.Length); - } else { - maker.anchor(); // canonical Apple anchor - } - CodeSigning::Required(requirementRef) = (new SecRequirement(maker.make(), true))->handle(); - - END_CSAPI -} - - -// -// Extract the stable binary from from a SecRequirementRef -// -OSStatus SecRequirementCopyData(SecRequirementRef requirementRef, SecCSFlags flags, - CFDataRef *data) -{ - BEGIN_CSAPI - - const Requirement *req = SecRequirement::required(requirementRef)->requirement(); - checkFlags(flags); - CodeSigning::Required(data); - *data = makeCFData(*req); - - END_CSAPI -} - - -// -// Generate source form for a SecRequirement (decompile/disassemble) -// -OSStatus SecRequirementCopyString(SecRequirementRef requirementRef, SecCSFlags flags, - CFStringRef *text) -{ - BEGIN_CSAPI - - const Requirement *req = SecRequirement::required(requirementRef)->requirement(); - checkFlags(flags); - CodeSigning::Required(text); - *text = makeCFString(Dumper::dump(req)); - - END_CSAPI -} - - -// -CFStringRef kSecRequirementKeyInfoPlist = CFSTR("requirement:eval:info"); -CFStringRef kSecRequirementKeyEntitlements = CFSTR("requirement:eval:entitlements"); -CFStringRef kSecRequirementKeyIdentifier = CFSTR("requirement:eval:identifier"); - -OSStatus SecRequirementEvaluate(SecRequirementRef requirementRef, - CFArrayRef certificateChain, CFDictionaryRef context, - SecCSFlags flags) -{ - BEGIN_CSAPI - - const Requirement *req = SecRequirement::required(requirementRef)->requirement(); - checkFlags(flags); - CodeSigning::Required(certificateChain); - - Requirement::Context ctx(certificateChain, // mandatory - context ? CFDictionaryRef(CFDictionaryGetValue(context, kSecRequirementKeyInfoPlist)) : NULL, - context ? CFDictionaryRef(CFDictionaryGetValue(context, kSecRequirementKeyEntitlements)) : NULL, - (context && CFDictionaryGetValue(context, kSecRequirementKeyIdentifier)) ? - cfString(CFStringRef(CFDictionaryGetValue(context, kSecRequirementKeyIdentifier))) : "", - NULL // can't specify a CodeDirectory here - ); - req->validate(ctx); - - END_CSAPI -} - - -// -// Assemble a requirement set (as a CFData) from a dictionary of requirement objects. -// An empty set is allowed. -// -OSStatus SecRequirementsCreateFromRequirements(CFDictionaryRef requirements, SecCSFlags flags, - CFDataRef *requirementSet) -{ - BEGIN_CSAPI - - checkFlags(flags); - if (requirements == NULL) - return errSecCSObjectRequired; - CFIndex count = CFDictionaryGetCount(requirements); - CFNumberRef keys[count]; - SecRequirementRef reqs[count]; - CFDictionaryGetKeysAndValues(requirements, (const void **)keys, (const void **)reqs); - Requirements::Maker maker; - for (CFIndex n = 0; n < count; n++) { - const Requirement *req = SecRequirement::required(reqs[n])->requirement(); - maker.add(cfNumber(keys[n]), req->clone()); - } - Requirements *reqset = maker.make(); // malloc'ed - CodeSigning::Required(requirementSet) = makeCFDataMalloc(*reqset); // takes ownership of reqs - - END_CSAPI -} - - -// -// Break a requirement set (given as a CFData) into its constituent requirements -// and return it as a CFDictionary. -// -OSStatus SecRequirementsCopyRequirements(CFDataRef requirementSet, SecCSFlags flags, - CFDictionaryRef *requirements) -{ - BEGIN_CSAPI - - checkFlags(flags); - if (requirementSet == NULL) - return errSecCSObjectRequired; - const Requirements *reqs = (const Requirements *)CFDataGetBytePtr(requirementSet); - if (!reqs->validateBlob()) - MacOSError::throwMe(errSecCSReqInvalid); - CFRef dict = makeCFMutableDictionary(); - unsigned count = reqs->count(); - for (unsigned n = 0; n < count; n++) { - CFRef req = (new SecRequirement(reqs->blob(n)))->handle(); - CFDictionaryAddValue(dict, CFTempNumber(reqs->type(n)), req); - } - CodeSigning::Required(requirements) = dict.yield(); - - END_CSAPI -} - - -// -// Generically parse a string as some kind of requirement-related source form. -// If properly recognized, return the result as a CF object: -// SecRequirementRef for a single requirement -// CFDataRef for a requirement set -// -OSStatus SecRequirementsCreateWithString(CFStringRef text, SecCSFlags flags, - CFTypeRef *result, CFErrorRef *errors) -{ - BEGIN_CSAPI - - checkFlags(flags, kSecCSParseRequirement | kSecCSParseRequirementSet); - if (text == NULL || result == NULL) - return errSecCSObjectRequired; - std::string s = cfString(text); - switch (flags & (kSecCSParseRequirement | kSecCSParseRequirementSet)) { - case kSecCSParseRequirement: // single only - *result = (new SecRequirement(parseRequirement(s), true))->handle(); - break; - case kSecCSParseRequirementSet: // single only - { - const Requirements *reqs = parseRequirements(s); - *result = makeCFDataMalloc(*reqs); - break; - } - case 0: - case kSecCSParseRequirement | kSecCSParseRequirementSet: - { - const BlobCore *any = parseGeneric(s); - if (any->is()) - *result = (new SecRequirement(Requirement::specific(any), true))->handle(); - else - *result = makeCFDataMalloc(*any); - break; - } - } - - END_CSAPI_ERRORS -} - - -// -// Convert a SecRequirementRef or a CFDataRef containing a requirement set to text. -// Requirement sets will be formatted as multiple lines (one per requirement). They can be empty. -// A single requirement will return a single line that is NOT newline-terminated. -// -OSStatus SecRequirementsCopyString(CFTypeRef input, SecCSFlags flags, CFStringRef *text) -{ - BEGIN_CSAPI - - checkFlags(flags); - if (input == NULL) - return errSecCSObjectRequired; - if (CFGetTypeID(input) == SecRequirementGetTypeID()) { - return SecRequirementCopyString(SecRequirementRef(input), flags, text); - } else if (CFGetTypeID(input) == CFDataGetTypeID()) { - const Requirements *reqs = (const Requirements *)CFDataGetBytePtr(CFDataRef(input)); - if (!reqs->validateBlob(CFDataGetLength(CFDataRef(input)))) - return errSecCSReqInvalid; - CodeSigning::Required(text) = makeCFString(Dumper::dump(reqs, false)); - } else - return errSecCSInvalidObjectRef; - - END_CSAPI -} diff --git a/OSX/include/security_codesigning/SecRequirement.h b/OSX/include/security_codesigning/SecRequirement.h deleted file mode 100644 index 11cf0265..00000000 --- a/OSX/include/security_codesigning/SecRequirement.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecRequirement - SecRequirement represents a condition or constraint (a "Code Requirement") - that code must satisfy to be considered valid for some purpose. - SecRequirement itself does not understand or care WHY such a constraint - is appropriate or useful; it is purely a tool for formulating, recording, - and evaluating it. - - Code Requirements are usually stored and retrieved in the form of a variable-length - binary Blob that can be encapsulated as a CFDataRef and safely stored in various - data structures. They can be formulated in a text form that can be compiled - into binary form and decompiled back into text form without loss of functionality - (though comments and formatting are not preserved). -*/ -#ifndef _H_SECREQUIREMENT -#define _H_SECREQUIREMENT - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -/*! - @function SecRequirementGetTypeID - Returns the type identifier of all SecRequirement instances. -*/ -CFTypeID SecRequirementGetTypeID(void); - - -/*! - @function SecRequirementCreateWithData - Create a SecRequirement object from binary form. - This is the effective inverse of SecRequirementCopyData. - - @param data A binary blob obtained earlier from a valid SecRequirement object - using the SecRequirementCopyData call. This is the only publicly supported - way to get such a data blob. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement On successful return, contains a reference to a SecRequirement - object that behaves identically to the one the data blob was obtained from. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementCreateWithData(CFDataRef data, SecCSFlags flags, - SecRequirementRef * __nonnull CF_RETURNS_RETAINED requirement); - - -/*! - @function SecRequirementCreateWithString - Create a SecRequirement object by compiling a valid text representation - of a requirement. - - @param text A CFString containing the text form of a (single) Code Requirement. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement On successful return, contains a reference to a SecRequirement - object that implements the conditions described in text. - @param errors An optional pointer to a CFErrorRef variable. If the call fails - (and something other than errSecSuccess is returned), and this argument is non-NULL, - a CFErrorRef is stored there further describing the nature and circumstances - of the failure. The caller must CFRelease() this error object when done with it. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementCreateWithString(CFStringRef text, SecCSFlags flags, - SecRequirementRef * __nonnull CF_RETURNS_RETAINED requirement); - -OSStatus SecRequirementCreateWithStringAndErrors(CFStringRef text, SecCSFlags flags, - CFErrorRef *errors, SecRequirementRef * __nonnull CF_RETURNS_RETAINED requirement); - - -/*! - @function SecRequirementCopyData - Extracts a stable, persistent binary form of a SecRequirement. - This is the effective inverse of SecRequirementCreateWithData. - - @param requirement A valid SecRequirement object. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param data On successful return, contains a reference to a CFData object - containing a binary blob that can be fed to SecRequirementCreateWithData - to recreate a SecRequirement object with identical behavior. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementCopyData(SecRequirementRef requirement, SecCSFlags flags, - CFDataRef * __nonnull CF_RETURNS_RETAINED data); - - -/*! - @function SecRequirementCopyString - Converts a SecRequirement object into text form. - This is the effective inverse of SecRequirementCreateWithString. - - Repeated application of this function may produce text that differs in - formatting, may contain different source comments, and may perform its - validation functions in different order. However, it is guaranteed that - recompiling the text using SecRequirementCreateWithString will produce a - SecRequirement object that behaves identically to the one you start with. - - @param requirement A valid SecRequirement object. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param text On successful return, contains a reference to a CFString object - containing a text representation of the requirement. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementCopyString(SecRequirementRef requirement, SecCSFlags flags, - CFStringRef * __nonnull CF_RETURNS_RETAINED text); - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECREQUIREMENT diff --git a/OSX/include/security_codesigning/SecRequirementPriv.h b/OSX/include/security_codesigning/SecRequirementPriv.h deleted file mode 100644 index c7ad3683..00000000 --- a/OSX/include/security_codesigning/SecRequirementPriv.h +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecRequirement - SecRequirementPriv is the private counter-part to SecRequirement. Its contents are not - official API, and are subject to change without notice. -*/ -#ifndef _H_SECREQUIREMENTPRIV -#define _H_SECREQUIREMENTPRIV - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/*! - @function SecRequirementsCreateFromRequirements - Take a dictionary of requirement objects and package them up as a requirement set. - - @param requirements A dictionary of requirements to combine into a set. - Dictionary keys are CFNumbers representing the index keys. Values are SecRequirementRefs. - NULL requirements are not allowed in the dictionary. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirementSet Upon success, receives a CFData object - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementsCreateFromRequirements(CFDictionaryRef requirements, SecCSFlags flags, - CFDataRef *requirementSet); - - -/*! - @function SecRequirementsCopyRequirements - Create a SecRequirement object from binary form obtained from a file. - This call is functionally equivalent to reading the entire contents of a file - into a CFDataRef and then calling SecRequirementCreateWithData with that. - - @param requirementSet A CFData containing a requirement set. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirements Upon success, a dictionary containing each requirement contained - in requirementSet. The keys are CFNumbers indicating the requirement type. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementsCopyRequirements(CFDataRef requirementSet, SecCSFlags flags, - CFDictionaryRef *requirements); - - -/*! - @function SecRequirementsCreateWithString - Create a SecRequirement object or requirement set based on the string provided. - - @param text A CFString containing the text form of a (single) Code Requirement. - @param flags Optional flags. Pass kSecCSDefaultFlags to accept any supported input form. - Pass a combination of individual flags to select what forms to accept; other forms will result - in an error. - @param result Upon success, a CoreFoundation object of some kind representing - the result of parsing text. Depending on the input string and flags, the result - can be a SecRequirementRef (for a single requirement) or a CFDataRef for a requirement set. - @param errors An optional pointer to a CFErrorRef variable. If the call fails - (and something other than errSecSuccess is returned), and this argument is non-NULL, - a CFErrorRef is stored there further describing the nature and circumstances - of the failure. The caller must CFRelease() this error object when done with it. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -enum { - kSecCSParseRequirement = 0x0001, // accept single requirements - kSecCSParseRequirementSet = 0x0002, // accept requirement sets -}; - -OSStatus SecRequirementsCreateWithString(CFStringRef text, SecCSFlags flags, - CFTypeRef *result, CFErrorRef *errors); - - -/*! - @function SecRequirementsCopyString - Converts a requirement object of some kind into text form. - This is the effective inverse of SecRequirementsCreateWithString. - - This function can process individual requirements (SecRequirementRefs) - and requirement sets (represented as CFDataRefs). - - Repeated application of this function may produce text that differs in - formatting, may contain different source comments, and may perform its - validation functions in different order. However, it is guaranteed that - recompiling the text using SecRequirementCreateWithString will produce a - SecRequirement object that behaves identically to the one you start with. - - @param requirements A SecRequirementRef, or a CFDataRef containing a valid requirement set. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param text On successful return, contains a reference to a CFString object - containing a text representation of the requirement. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementsCopyString(CFTypeRef input, SecCSFlags flags, CFStringRef *text); - - -/*! - @function SecRequirementCreateWithResource - Create a SecRequirement object from binary form obtained from a file. - This call is functionally equivalent to reading the entire contents of a file - into a CFDataRef and then calling SecRequirementCreateWithData with that. - - @param resource A CFURL identifying a file containing a (binary) requirement blob. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement On successful return, contains a reference to a SecRequirement - object that behaves identically to the one the data blob was obtained from. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementCreateWithResource(CFURLRef resource, SecCSFlags flags, - SecRequirementRef *requirement); - - -/*! - @function SecRequirementCreateGroup - Create a SecRequirement object that represents membership in a developer-defined - application group. Group membership is defined by an entry in the code's - Info.plist, and sealed to a particular signing authority. - - This is not an API-track function. Don't call it if you don't already do. - - @param groupName A CFString containing the name of the desired application group. - @param anchor A reference to a digital certificate representing the signing - authority that asserts group membership. If NULL, indicates Apple's authority. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param requirement On successful return, contains a reference to a SecRequirement - object that requires group membership to pass validation. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. -*/ -OSStatus SecRequirementCreateGroup(CFStringRef groupName, SecCertificateRef anchor, - SecCSFlags flags, SecRequirementRef *requirement); - - - -/*! - @function SecRequirementEvaluate - Explicitly evaluate a SecRequirementRef against context provided in the call. - This allows evaluation of a code requirement outside the context of a code signature. - - @param requirement A valid SecRequirement object. - @param certificateChain A CFArray of SecCertificate objects describing the certificate - chain of the object being validated. This must be a full chain terminating in an anchor - certificate that is cryptographically valid. - @param context An optional CFDictionary containing additional context made available - to the requirement program's evaluation. NULL is equivalent to an empty dictionary. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @result Upon success, errSecSuccess. Failure to pass the check returns errSecCSReqFailed. - All other returns indicate errors as documented in CSCommon.h or certain other - Security framework headers. - - @constant kSecRequirementKeyInfoPlist A context key providing an CFDictionary denoting - an Info.plist. If this key is missing, all references to Info.plist contents will fail. - @constant kSecRequirementKeyEntitlements A context key providing an CFDictionary describing - an entitlement dictionary. If this key is missing, all references to entitlements will fail. - @constant kSecRequirementKeyIdentifier A context key providing the signing identifier as a CFString. -*/ -extern CFStringRef kSecRequirementKeyInfoPlist; -extern CFStringRef kSecRequirementKeyEntitlements; -extern CFStringRef kSecRequirementKeyIdentifier; - -OSStatus SecRequirementEvaluate(SecRequirementRef requirement, - CFArrayRef certificateChain, CFDictionaryRef context, - SecCSFlags flags); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECREQUIREMENTPRIV diff --git a/OSX/include/security_codesigning/SecStaticCode.cpp b/OSX/include/security_codesigning/SecStaticCode.cpp deleted file mode 100644 index 0d3ed8b1..00000000 --- a/OSX/include/security_codesigning/SecStaticCode.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecStaticCode - API frame for SecStaticCode objects -// -#include "cs.h" -#include "StaticCode.h" -#include -#include -#include -#include - -using namespace CodeSigning; - - -// -// CF-standard type code function -// -CFTypeID SecStaticCodeGetTypeID(void) -{ - BEGIN_CSAPI - return gCFObjects().StaticCode.typeID; - END_CSAPI1(_kCFRuntimeNotATypeID) -} - - -// -// Create an StaticCode directly from disk path. -// -OSStatus SecStaticCodeCreateWithPath(CFURLRef path, SecCSFlags flags, SecStaticCodeRef *staticCodeRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - CodeSigning::Required(staticCodeRef) = (new SecStaticCode(DiskRep::bestGuess(cfString(path).c_str())))->handle(); - - END_CSAPI -} - -const CFStringRef kSecCodeAttributeArchitecture = CFSTR("architecture"); -const CFStringRef kSecCodeAttributeSubarchitecture =CFSTR("subarchitecture"); -const CFStringRef kSecCodeAttributeBundleVersion = CFSTR("bundleversion"); -const CFStringRef kSecCodeAttributeUniversalFileOffset = CFSTR("UniversalFileOffset"); - -OSStatus SecStaticCodeCreateWithPathAndAttributes(CFURLRef path, SecCSFlags flags, CFDictionaryRef attributes, - SecStaticCodeRef *staticCodeRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - DiskRep::Context ctx; - std::string version; // holds memory placed into ctx - if (attributes) { - std::string archName; - int archNumber, subarchNumber, offset; - if (cfscan(attributes, "{%O=%d}", kSecCodeAttributeUniversalFileOffset, &offset)) { - ctx.offset = offset; - } else if (cfscan(attributes, "{%O=%s}", kSecCodeAttributeArchitecture, &archName)) { - ctx.arch = Architecture(archName.c_str()); - } else if (cfscan(attributes, "{%O=%d,%O=%d}", - kSecCodeAttributeArchitecture, &archNumber, kSecCodeAttributeSubarchitecture, &subarchNumber)) - ctx.arch = Architecture(archNumber, subarchNumber); - else if (cfscan(attributes, "{%O=%d}", kSecCodeAttributeArchitecture, &archNumber)) - ctx.arch = Architecture(archNumber); - if (cfscan(attributes, "{%O=%s}", kSecCodeAttributeBundleVersion, &version)) - ctx.version = version.c_str(); - } - - CodeSigning::Required(staticCodeRef) = (new SecStaticCode(DiskRep::bestGuess(cfString(path).c_str(), &ctx)))->handle(); - - END_CSAPI -} - - -// -// Check static validity of a StaticCode -// -OSStatus SecStaticCodeCheckValidity(SecStaticCodeRef staticCodeRef, SecCSFlags flags, - SecRequirementRef requirementRef) -{ - return SecStaticCodeCheckValidityWithErrors(staticCodeRef, flags, requirementRef, NULL); -} - -OSStatus SecStaticCodeCheckValidityWithErrors(SecStaticCodeRef staticCodeRef, SecCSFlags flags, - SecRequirementRef requirementRef, CFErrorRef *errors) -{ -#if !SECTRUST_OSX - BEGIN_CSAPI - - checkFlags(flags, - kSecCSReportProgress - | kSecCSCheckAllArchitectures - | kSecCSDoNotValidateExecutable - | kSecCSDoNotValidateResources - | kSecCSConsiderExpiration - | kSecCSEnforceRevocationChecks - | kSecCSNoNetworkAccess - | kSecCSCheckNestedCode - | kSecCSStrictValidate - | kSecCSCheckGatekeeperArchitectures - | kSecCSRestrictSymlinks - ); - - if (errors) - flags |= kSecCSFullReport; // internal-use flag - - SecPointer code = SecStaticCode::requiredStatic(staticCodeRef); - code->setValidationFlags(flags); - const SecRequirement *req = SecRequirement::optional(requirementRef); - DTRACK(CODESIGN_EVAL_STATIC, code, (char*)code->mainExecutablePath().c_str()); - code->staticValidate(flags, req); - - END_CSAPI_ERRORS -#else -#warning resolve before enabling SECTRUST_OSX: - OSStatus result = errSecSuccess; - const char *func = "SecStaticCodeCheckValidity"; - CFErrorRef localErrors = NULL; - if (!errors) { errors = &localErrors; } - try { - checkFlags(flags, - kSecCSReportProgress - | kSecCSCheckAllArchitectures - | kSecCSDoNotValidateExecutable - | kSecCSDoNotValidateResources - | kSecCSConsiderExpiration - | kSecCSEnforceRevocationChecks - | kSecCSNoNetworkAccess - | kSecCSCheckNestedCode - | kSecCSStrictValidate - | kSecCSCheckGatekeeperArchitectures - ); - - if (errors) - flags |= kSecCSFullReport; // internal-use flag - - SecPointer code = SecStaticCode::requiredStatic(staticCodeRef); - code->setValidationFlags(flags); - const SecRequirement *req = SecRequirement::optional(requirementRef); - DTRACK(CODESIGN_EVAL_STATIC, code, (char*)code->mainExecutablePath().c_str()); - code->staticValidate(flags, req); - } - catch (...) { - // the actual error being thrown is not being caught by any of the - // type-specific blocks contained in the END_CSAPI_ERRORS macro, - // so we only have the catch-all block here for now. - result = errSecCSInternalError; - } - - if (errors && *errors) { - CFShow(errors); - CFRelease(errors); - *errors = NULL; - } - if (result == errSecCSInternalError) { - #if !NDEBUG - Security::Syslog::error("WARNING: %s ignored error %d", func, (int)result); - #endif - result = errSecSuccess; - } - return result; - -#endif -} - - -// -// ==================================================================================== -// -// The following API functions are called SecCode* but accept both SecCodeRef and -// SecStaticCodeRef arguments, operating on the implied SecStaticCodeRef as appropriate. -// Hence they're here, rather than in SecCode.cpp. -// - - -// -// Retrieve location information for an StaticCode. -// -OSStatus SecCodeCopyPath(SecStaticCodeRef staticCodeRef, SecCSFlags flags, CFURLRef *path) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecPointer staticCode = SecStaticCode::requiredStatic(staticCodeRef); - CodeSigning::Required(path) = staticCode->copyCanonicalPath(); - - END_CSAPI -} - - -// -// Fetch or make up a designated requirement -// -OSStatus SecCodeCopyDesignatedRequirement(SecStaticCodeRef staticCodeRef, SecCSFlags flags, - SecRequirementRef *requirementRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - const Requirement *req = - SecStaticCode::requiredStatic(staticCodeRef)->designatedRequirement(); - CodeSigning::Required(requirementRef) = (new SecRequirement(req))->handle(); - - END_CSAPI -} - - -// -// Fetch a particular internal requirement, if present -// -OSStatus SecCodeCopyInternalRequirement(SecStaticCodeRef staticCodeRef, SecRequirementType type, - SecCSFlags flags, SecRequirementRef *requirementRef) -{ - BEGIN_CSAPI - - checkFlags(flags); - const Requirement *req = - SecStaticCode::requiredStatic(staticCodeRef)->internalRequirement(type); - CodeSigning::Required(requirementRef) = req ? (new SecRequirement(req))->handle() : NULL; - - END_CSAPI -} - - -// -// Record for future use a detached code signature. -// -OSStatus SecCodeSetDetachedSignature(SecStaticCodeRef codeRef, CFDataRef signature, - SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecPointer code = SecStaticCode::requiredStatic(codeRef); - - code->detachedSignature(signature); // ... and pass it to the code - code->resetValidity(); - - END_CSAPI -} - - -// -// Attach a code signature to a kernel memory mapping for page-in validation. -// -OSStatus SecCodeMapMemory(SecStaticCodeRef codeRef, SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecPointer code = SecStaticCode::requiredStatic(codeRef); - if (const CodeDirectory *cd = code->codeDirectory(false)) { - fsignatures args = { code->diskRep()->signingBase(), (void *)cd, cd->length() }; - UnixError::check(::fcntl(code->diskRep()->fd(), F_ADDSIGS, &args)); - } else - MacOSError::throwMe(errSecCSUnsigned); - - END_CSAPI -} - - -// -// Attach a callback block to a code object -// -OSStatus SecStaticCodeSetCallback(SecStaticCodeRef codeRef, SecCSFlags flags, SecCodeCallback *old, SecCodeCallback monitor) -{ - BEGIN_CSAPI - - checkFlags(flags); - SecStaticCode *code = SecStaticCode::requiredStatic(codeRef); - if (old) - *old = code->monitor(); - code->setMonitor(monitor); - - END_CSAPI -} - - -OSStatus SecStaticCodeSetValidationConditions(SecStaticCodeRef codeRef, CFDictionaryRef conditions) -{ - BEGIN_CSAPI - - checkFlags(0); - SecStaticCode *code = SecStaticCode::requiredStatic(codeRef); - code->setValidationModifiers(conditions); - - END_CSAPI -} - - -// -// Set cancellation flag on a static code object. -// -OSStatus SecStaticCodeCancelValidation(SecStaticCodeRef codeRef, SecCSFlags flags) -{ - BEGIN_CSAPI - - checkFlags(0); - SecStaticCode *code = SecStaticCode::requiredStatic(codeRef); - code->cancelValidation(); - - END_CSAPI -} diff --git a/OSX/include/security_codesigning/SecStaticCode.h b/OSX/include/security_codesigning/SecStaticCode.h deleted file mode 100644 index a5e17ebb..00000000 --- a/OSX/include/security_codesigning/SecStaticCode.h +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecStaticCode - SecStaticCode represents the Code Signing identity of code in the file system. - This includes applications, tools, frameworks, plugins, scripts, and so on. - Note that arbitrary files will be considered scripts of unknown provenance; - and thus it is possible to handle most files as if they were code, though that is - not necessarily a good idea. - - Normally, each SecCode has a specific SecStaticCode that holds its static signing - data. Informally, that is the SecStaticCode the SecCode "was made from" (by its host). - There is however no viable link in the other direction - given a SecStaticCode, - it is not possible to find, enumerate, or control any SecCode that originated from it. - There might not be any at a given point in time; or there might be many. -*/ -#ifndef _H_SECSTATICCODE -#define _H_SECSTATICCODE - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -/*! - @function SecStaticCodeGetTypeID - Returns the type identifier of all SecStaticCode instances. -*/ -CFTypeID SecStaticCodeGetTypeID(void); - - -/*! - @function SecStaticCodeCreateWithPath - Given a path to a file system object, create a SecStaticCode object representing - the code at that location, if possible. Such a SecStaticCode is not inherently - linked to running code in the system. - - It is possible to create a SecStaticCode object from an unsigned code object. - Most uses of such an object will return the errSecCSUnsigned error. However, - SecCodeCopyPath and SecCodeCopySigningInformation can be safely applied to such objects. - - @param path A path to a location in the file system. Only file:// URLs are - currently supported. For bundles, pass a URL to the root directory of the - bundle. For single files, pass a URL to the file. If you pass a URL to the - main executable of a bundle, the bundle as a whole will be generally recognized. - Caution: Paths containing embedded // or /../ within a bundle's directory - may cause the bundle to be misconstrued. If you expect to submit such paths, - first clean them with realpath(3) or equivalent. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param attributes A CFDictionary containing additional attributes of the code sought. - @param staticCode On successful return, contains a reference to the StaticCode object - representing the code at path. Unchanged on error. - @result Upon success, errSecSuccess. Upon error, an OSStatus value documented in - CSCommon.h or certain other Security framework headers. - - @constant kSecCodeAttributeArchitecture Specifies the Mach-O architecture of code desired. - This can be a CFString containing a canonical architecture name ("i386" etc.), or a CFNumber - specifying an architecture numerically (see mach/machine.h). This key is ignored if the code - is not in Mach-O binary form. If the code is Mach-O but not universal ("thin"), the architecture - specified must agree with the actual file contents. - @constant kSecCodeAttributeSubarchitecture If the architecture is specified numerically - (using the kSecCodeAttributeArchitecture key), specifies any sub-architecture by number. - This key is ignored if no main architecture is specified; if it is specified by name; or - if the code is not in Mach-O form. - @constant kSecCodeAttributeUniversalFileOffset The offset of a Mach-O specific slice of a universal Mach-O file. -*/ -extern const CFStringRef kSecCodeAttributeArchitecture; -extern const CFStringRef kSecCodeAttributeSubarchitecture; -extern const CFStringRef kSecCodeAttributeUniversalFileOffset; -extern const CFStringRef kSecCodeAttributeBundleVersion; - -OSStatus SecStaticCodeCreateWithPath(CFURLRef path, SecCSFlags flags, SecStaticCodeRef * __nonnull CF_RETURNS_RETAINED staticCode); - -OSStatus SecStaticCodeCreateWithPathAndAttributes(CFURLRef path, SecCSFlags flags, CFDictionaryRef attributes, - SecStaticCodeRef * __nonnull CF_RETURNS_RETAINED staticCode); - - -/*! - @function SecStaticCodeCheckValidity - Performs static validation on the given SecStaticCode object. The call obtains and - verifies the signature on the code object. It checks the validity of all - sealed components (including resources, if any). It validates the code against - a SecRequirement if one is given. The call succeeds if all these conditions - are satisfactory. It fails otherwise. - - This call is only secure if the code is not subject to concurrent modification, - and the outcome is only valid as long as the code is unmodified thereafter. - Consider this carefully if the underlying file system has dynamic characteristics, - such as a network file system, union mount, FUSE, etc. - - @param staticCode The code object to be validated. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - - @constant kSecCSCheckAllArchitectures - For multi-architecture (universal) Mach-O programs, validate all architectures - included. By default, only the native architecture is validated. - @constant kSecCSNoDnotValidateExecutable - Do not validate the contents of the main executable. This is normally done. - @constant kSecCSNoNotValidateResources - Do not validate the presence and contents of all bundle resources (if any). - By default, a mismatch in any bundle resource causes validation to fail. - @constant kSecCSCheckNestedCode - For code in bundle form, locate and recursively check embedded code. Only code - in standard locations is considered. - @constant kSecCSStrictValidate - For code in bundle form, perform additional checks to verify that the bundle - is not structured in a way that would allow tampering, and reject any resource - envelope that introduces weaknesses into the signature. - - @param requirement On optional code requirement specifying additional conditions - the staticCode object must satisfy to be considered valid. If NULL, no additional - requirements are imposed. - @param errors An optional pointer to a CFErrorRef variable. If the call fails - (something other than errSecSuccess is returned), and this argument is non-NULL, - a CFErrorRef is stored there further describing the nature and circumstances - of the failure. The caller must CFRelease() this error object when done with it. - @result If validation succeeds, errSecSuccess. If validation fails, an OSStatus value - documented in CSCommon.h or certain other Security framework headers. -*/ -CF_ENUM(uint32_t) { - kSecCSCheckAllArchitectures = 1 << 0, - kSecCSDoNotValidateExecutable = 1 << 1, - kSecCSDoNotValidateResources = 1 << 2, - kSecCSBasicValidateOnly = kSecCSDoNotValidateExecutable | kSecCSDoNotValidateResources, - kSecCSCheckNestedCode = 1 << 3, - kSecCSStrictValidate = 1 << 4, - kSecCSFullReport = 1 << 5, - kSecCSCheckGatekeeperArchitectures = (1 << 6) | kSecCSCheckAllArchitectures, - kSecCSRestrictSymlinks = 1 << 7, -}; - -OSStatus SecStaticCodeCheckValidity(SecStaticCodeRef staticCode, SecCSFlags flags, - SecRequirementRef __nullable requirement); - -OSStatus SecStaticCodeCheckValidityWithErrors(SecStaticCodeRef staticCode, SecCSFlags flags, - SecRequirementRef __nullable requirement, CFErrorRef *errors); - -CF_ASSUME_NONNULL_END - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECSTATICCODE diff --git a/OSX/include/security_codesigning/SecStaticCodePriv.h b/OSX/include/security_codesigning/SecStaticCodePriv.h deleted file mode 100644 index c534c0e5..00000000 --- a/OSX/include/security_codesigning/SecStaticCodePriv.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecStaticCode - SecStaticCodePriv is the private counter-part to SecStaticCode. Its contents are not - official API, and are subject to change without notice. -*/ -#ifndef _H_SECSTATICCODEPRIV -#define _H_SECSTATICCODEPRIV - -#include - -#ifdef __cplusplus -extern "C" { -#endif - - -/* - @function SecCodeSetCallback - For a given Code or StaticCode object, specify a block that is invoked at certain - stages of a validation operation. The block is only invoked for validations of this - particular object. Note that validation outcomes are cached in the API object, and - repeated validations will not generally result in the same set of callbacks. - Only one callback can be active for each API object. A new call to SecCodeSetCallback - replaces the previous callback. - - @param code A Code or StaticCode object whose validation should be monitored. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - @param old A pointer to a block pointer that receives any previously registered callback. - Pass NULL if you are not interested in any previous value. - @param callback A block to be synchronously invoked at certain stages of API operation. - Pass NULL to disable callbacks for this code object. The block must be available to - be invoked, possibly repeatedly, for as long as the code object exists or it is superseded - by another call to this API, whichever happens earlier. - From your block, return NULL to continue normal operation. Return a CFTypeRef object of - suitable value for the reported stage to intervene. - */ -OSStatus SecStaticCodeSetCallback(SecStaticCodeRef code, SecCSFlags flag, SecCodeCallback *olds, SecCodeCallback callback); - - -/* - @function SecStaticCodeSetValidationConditions - Set various parameters that modify the evaluation of a signature. - This is an internal affordance used by Gatekeeper to implement checkfix evaluation. - It is not meant to be a generally useful mechanism. - - @param code A Code or StaticCode object whose validation should be modified. - @param conditions A dictionary containing one or more validation conditions. Must not be NULL. - */ -OSStatus SecStaticCodeSetValidationConditions(SecStaticCodeRef code, CFDictionaryRef conditions); - - -/* - @function SecStaticCodeCancelValidation - Ask for an ongoing static validation using this (static) code object to be cancelled as soon as feasible. - if no validation is pending, this does nothing. - Since validation is synchronous, this call must be made from another thread. - This call will return immediately. If a validation operation is terminated due to it, - it will fail with the errSecCSVetoed error. - - @param code A Code or StaticCode object whose validation should be modified. - @param flags Optional flags. Pass kSecCSDefaultFlags for standard behavior. - */ -OSStatus SecStaticCodeCancelValidation(SecStaticCodeRef code, SecCSFlags flags); - - -#ifdef __cplusplus -} -#endif - -#endif //_H_SECSTATICCODEPRIV diff --git a/OSX/include/security_codesigning/SecTask.c b/OSX/include/security_codesigning/SecTask.c deleted file mode 100644 index c2b358e8..00000000 --- a/OSX/include/security_codesigning/SecTask.c +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2009-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "SecCode.h" -#include "SecCodePriv.h" -#include "SecRequirement.h" - -#include "SecTask.h" -#include "SecTaskPriv.h" - - -struct __SecTask { - CFRuntimeBase base; - - pid_t pid; - - audit_token_t *token; - audit_token_t token_storage; - - /* Track whether we've loaded entitlements independently since after the - * load, entitlements may legitimately be NULL */ - Boolean entitlementsLoaded; - CFDictionaryRef entitlements; -}; - -enum { - kSecCodeMagicEntitlement = 0xfade7171, /* entitlement blob */ -}; - - -CFTypeID _kSecTaskTypeID = _kCFRuntimeNotATypeID; - -static void SecTaskFinalize(CFTypeRef cfTask) -{ - SecTaskRef task = (SecTaskRef) cfTask; - - if (task->entitlements != NULL) { - CFRelease(task->entitlements); - task->entitlements = NULL; - } -} - - -// Define PRIdPID (proper printf format string for pid_t) -#define PRIdPID PRId32 - -static CFStringRef SecTaskCopyDebugDescription(CFTypeRef cfTask) -{ - SecTaskRef task = (SecTaskRef) cfTask; - const char *task_name; - int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, task->pid}; - struct kinfo_proc kp; - size_t len = sizeof(kp); - if (sysctl(mib, 4, &kp, &len, NULL, 0) == -1 || len == 0) - task_name = strerror(errno); - else - task_name = kp.kp_proc.p_comm; - - return CFStringCreateWithFormat(CFGetAllocator(task), NULL, CFSTR("%s[%" PRIdPID "]"), task_name, task->pid); -} - -static void SecTaskRegisterClass(void) -{ - static const CFRuntimeClass SecTaskClass = { - .version = 0, - .className = "SecTask", - .init = NULL, - .copy = NULL, - .finalize = SecTaskFinalize, - .equal = NULL, - .hash = NULL, - .copyFormattingDesc = NULL, - .copyDebugDesc = SecTaskCopyDebugDescription, - }; - - _kSecTaskTypeID = _CFRuntimeRegisterClass(&SecTaskClass); -} - -CFTypeID SecTaskGetTypeID(void) -{ - static pthread_once_t secTaskRegisterClassOnce = PTHREAD_ONCE_INIT; - - /* Register the class with the CF runtime the first time through */ - pthread_once(&secTaskRegisterClassOnce, SecTaskRegisterClass); - - return _kSecTaskTypeID; -} - -static SecTaskRef SecTaskCreateWithPID(CFAllocatorRef allocator, pid_t pid) -{ - CFIndex extra = sizeof(struct __SecTask) - sizeof(CFRuntimeBase); - SecTaskRef task = (SecTaskRef) _CFRuntimeCreateInstance(allocator, SecTaskGetTypeID(), extra, NULL); - if (task != NULL) { - task->pid = pid; - task->entitlementsLoaded = false; - task->entitlements = NULL; - } - - return task; -} - -SecTaskRef SecTaskCreateWithAuditToken(CFAllocatorRef allocator, audit_token_t token) -{ - SecTaskRef task; - - task = SecTaskCreateWithPID(allocator, audit_token_to_pid(token)); - if (task != NULL) { -#if 0 - task->token_storage = token; - task->token = &task->token_storage; -#endif - } - - return task; -} - -SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator) -{ - return SecTaskCreateWithPID(allocator, getpid()); -} - -/* - * Determine if the given task meets a specified requirement. - */ -OSStatus -SecTaskValidateForRequirement(SecTaskRef task, CFStringRef requirement) -{ - OSStatus status; - SecCodeRef code = NULL; - SecRequirementRef req = NULL; - pid_t pid = task->pid; - if (pid <= 0) { - return errSecParam; - } - status = SecCodeCreateWithPID(pid, kSecCSDefaultFlags, &code); - //syslog(LOG_NOTICE, "SecTaskValidateForRequirement: SecCodeCreateWithPID=%d", status); - if (!status) { - status = SecRequirementCreateWithString(requirement, - kSecCSDefaultFlags, &req); - //syslog(LOG_NOTICE, "SecTaskValidateForRequirement: SecRequirementCreateWithString=%d", status); - } - if (!status) { - status = SecCodeCheckValidity(code, kSecCSDefaultFlags, req); - //syslog(LOG_NOTICE, "SecTaskValidateForRequirement: SecCodeCheckValidity=%d", status); - } - if (req) - CFRelease(req); - if (code) - CFRelease(code); - - return status; -} - -static CFRange myMakeRange(CFIndex loc, CFIndex len) { - CFRange r = {.location = loc, .length = len }; - return r; -} -struct csheader { - uint32_t magic; - uint32_t length; -}; - -static int -csops_task(SecTaskRef task, int ops, void *blob, size_t size) -{ -#if 0 - if (task->token) - return csops_audittoken(task->pid, ops, blob, size, task->token); - else -#endif - return csops(task->pid, ops, blob, size); -} - -static int SecTaskLoadEntitlements(SecTaskRef task, CFErrorRef *error) -{ - CFMutableDataRef data = NULL; - struct csheader header; - uint32_t bufferlen; - int ret; - - ret = csops_task(task, CS_OPS_ENTITLEMENTS_BLOB, &header, sizeof(header)); - if (ret == 0) { - // we only gave a header's worth of buffer. If this succeeded, we have no entitlements - task->entitlementsLoaded = true; - return 0; - } - if (errno != ERANGE) { - // ERANGE means "your buffer is too small, it now tells you how much you need - // Everything else is a real error, so yell - syslog(LOG_NOTICE, "SecTaskLoadEntitlements failed error=%d", errno); // to ease diagnostics - // EINVAL is what the kernel says for unsigned code, so we'll have to let that pass - if (errno == EINVAL) { - task->entitlementsLoaded = true; - return 0; - } - ret = errno; - goto out; - } - // kernel told us the needed buffer size in header.length; proceed - - bufferlen = ntohl(header.length); - /* check for insane values */ - if (bufferlen > 1024 * 1024 || bufferlen < 8) { - ret = EINVAL; - goto out; - } - data = CFDataCreateMutable(NULL, bufferlen); - if (data == NULL) { - ret = ENOMEM; - goto out; - } - CFDataSetLength(data, bufferlen); - ret = csops_task(task, CS_OPS_ENTITLEMENTS_BLOB, CFDataGetMutableBytePtr(data), bufferlen); - if (ret) { - ret = errno; - goto out; - } - CFDataDeleteBytes(data, myMakeRange(0, 8)); - task->entitlements = CFPropertyListCreateWithData(NULL, data, 0, NULL, error); - task->entitlementsLoaded = true; - out: - if (data) - CFRelease(data); - if (ret && error) - *error = CFErrorCreate(NULL, kCFErrorDomainPOSIX, ret, NULL); - - return ret; -} - -CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error) -{ - /* Load entitlements if necessary */ - if (task->entitlementsLoaded == false) { - SecTaskLoadEntitlements(task, error); - } - - CFTypeRef value = NULL; - if (task->entitlements != NULL) { - value = CFDictionaryGetValue(task->entitlements, entitlement); - - /* Return something the caller must release */ - if (value != NULL) { - CFRetain(value); - } - } - - return value; -} - -CFDictionaryRef SecTaskCopyValuesForEntitlements(SecTaskRef task, CFArrayRef entitlements, CFErrorRef *error) -{ - /* Load entitlements if necessary */ - if (task->entitlementsLoaded == false) { - SecTaskLoadEntitlements(task, error); - } - - /* Iterate over the passed in entitlements, populating the dictionary - * If entitlements were loaded but none were present, return an empty - * dictionary */ - CFMutableDictionaryRef values = NULL; - if (task->entitlementsLoaded == true) { - - CFIndex i, count = CFArrayGetCount(entitlements); - values = CFDictionaryCreateMutable(CFGetAllocator(task), count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - if (task->entitlements != NULL) { - for (i = 0; i < count; i++) { - CFStringRef entitlement = CFArrayGetValueAtIndex(entitlements, i); - CFTypeRef value = CFDictionaryGetValue(task->entitlements, entitlement); - if (value != NULL) { - CFDictionarySetValue(values, entitlement, value); - } - } - } - } - - return values; -} - -Boolean SecTaskEntitlementsValidated(SecTaskRef task) { - // TODO: Cache the result - uint32_t csflags = 0; - const uint32_t mask = CS_VALID | CS_KILL | CS_ENTITLEMENTS_VALIDATED; - int rc = csops_task(task, CS_OPS_STATUS, &csflags, sizeof(csflags)); - return rc != -1 && ((csflags & mask) == mask); -} diff --git a/OSX/include/security_codesigning/SecTask.h b/OSX/include/security_codesigning/SecTask.h deleted file mode 100644 index 90674a35..00000000 --- a/OSX/include/security_codesigning/SecTask.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2008-2009,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#ifndef _SECURITY_SECTASK_H_ -#define _SECURITY_SECTASK_H_ - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN -CF_IMPLICIT_BRIDGING_ENABLED - -/*! - @typedef SecTaskRef - @abstract CFType used for representing a task -*/ -typedef struct CF_BRIDGED_TYPE(id) __SecTask *SecTaskRef; - -/*! - @function SecTaskGetTypeID - @abstract Returns the type ID for CF instances of SecTask. - @result A CFTypeID for SecTask -*/ -CFTypeID SecTaskGetTypeID(void); - -/*! - @function SecTaskCreateWithAuditToken - @abstract Create a SecTask object for the task that sent the mach message - represented by the audit token. - @param token The audit token of a mach message - @result The newly created SecTask object or NULL on error. The caller must - CFRelease the returned object. -*/ -__nullable -SecTaskRef SecTaskCreateWithAuditToken(CFAllocatorRef __nullable allocator, audit_token_t token); - -/*! - @function SecTaskCreateFromSelf - @abstract Create a SecTask object for the current task. - @result The newly created SecTask object or NULL on error. The caller must - CFRelease the returned object. -*/ -__nullable -SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef __nullable allocator); - -/*! - @function SecTaskCopyValueForEntitlement - @abstract Returns the value of a single entitlement for the represented - task. - @param task A previously created SecTask object - @param entitlement The name of the entitlement to be fetched - @param error On a NULL return, this may be contain a CFError describing - the problem. This argument may be NULL if the caller is not interested in - detailed errors. - @result The value of the specified entitlement for the process or NULL if - the entitlement value could not be retrieved. The type of the returned - value will depend on the entitlement specified. The caller must release - the returned object. - @discussion A NULL return may indicate an error, or it may indicate that - the entitlement is simply not present. In the latter case, no CFError is - returned. -*/ -__nullable -CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error); - -/*! - @function SecTaskCopyValuesForEntitlements - @abstract Returns the values of multiple entitlements for the represented - task. - @param task A previously created SecTask object - @param entitlements An array of entitlement names to be fetched - @param error On a NULL return, this will contain a CFError describing - the problem. This argument may be NULL if the caller is not interested in - detailed errors. If a requested entitlement is not present for the - returned dictionary, the entitlement is not set on the task. The caller - must CFRelease the returned value -*/ -__nullable -CFDictionaryRef SecTaskCopyValuesForEntitlements(SecTaskRef task, CFArrayRef entitlements, CFErrorRef *error); - -CF_IMPLICIT_BRIDGING_DISABLED -CF_ASSUME_NONNULL_END - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECTASK_H_ */ diff --git a/OSX/include/security_codesigning/SecTaskPriv.h b/OSX/include/security_codesigning/SecTaskPriv.h deleted file mode 100644 index 0190ee5b..00000000 --- a/OSX/include/security_codesigning/SecTaskPriv.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#ifndef _SECURITY_SECTASKPRIV_H_ -#define _SECURITY_SECTASKPRIV_H_ - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - @function SecTaskValidateForRequirement - @abstract Validate a SecTask instance for a specified requirement. - @param task The SecTask instance to validate. - @param requirement A requirement string to be validated. - @result An error code of type OSStatus. Returns errSecSuccess if the - task satisfies the requirement. -*/ -OSStatus SecTaskValidateForRequirement(SecTaskRef task, CFStringRef requirement); - -/*! - @function SecTaskEntitlementsValidated - @abstract Check whether entitlements can be trusted or not. If this returns - false the tasks entitlements must not be used for anything security sensetive. - @param task A previously created SecTask object -*/ -Boolean SecTaskEntitlementsValidated(SecTaskRef task); - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECTASKPRIV_H_ */ diff --git a/OSX/include/security_codesigning/StaticCode.cpp b/OSX/include/security_codesigning/StaticCode.cpp deleted file mode 100644 index 6bcfb500..00000000 --- a/OSX/include/security_codesigning/StaticCode.cpp +++ /dev/null @@ -1,1798 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// StaticCode - SecStaticCode API objects -// -#include "StaticCode.h" -#include "Code.h" -#include "reqmaker.h" -#include "drmaker.h" -#include "reqdumper.h" -#include "reqparser.h" -#include "sigblob.h" -#include "resources.h" -#include "detachedrep.h" -#include "csdatabase.h" -#include "dirscanner.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - -// A requirement representing a Mac or iOS dev cert, a Mac or iOS distribution cert, or a developer ID -static const char WWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.2] exists"; -static const char MACWWDRRequirement[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.12] exists"; -static const char developerID[] = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists" - " and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"; -static const char distributionCertificate[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.7] exists"; -static const char iPhoneDistributionCert[] = "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.4] exists"; - -// -// Map a component slot number to a suitable error code for a failure -// -static inline OSStatus errorForSlot(CodeDirectory::SpecialSlot slot) -{ - switch (slot) { - case cdInfoSlot: - return errSecCSInfoPlistFailed; - case cdResourceDirSlot: - return errSecCSResourceDirectoryFailed; - default: - return errSecCSSignatureFailed; - } -} - - -// -// Construct a SecStaticCode object given a disk representation object -// -SecStaticCode::SecStaticCode(DiskRep *rep) - : mRep(rep), - mValidated(false), mExecutableValidated(false), mResourcesValidated(false), mResourcesValidContext(NULL), - mProgressQueue("com.apple.security.validation-progress", false, DISPATCH_QUEUE_PRIORITY_DEFAULT), - mOuterScope(NULL), mResourceScope(NULL), - mDesignatedReq(NULL), mGotResourceBase(false), mMonitor(NULL), mLimitedAsync(NULL), mEvalDetails(NULL) -{ - CODESIGN_STATIC_CREATE(this, rep); - CFRef codeDirectory = rep->codeDirectory(); - if (codeDirectory && CFDataGetLength(codeDirectory) <= 0) - MacOSError::throwMe(errSecCSSignatureInvalid); - checkForSystemSignature(); -} - - -// -// Clean up a SecStaticCode object -// -SecStaticCode::~SecStaticCode() throw() -try { - ::free(const_cast(mDesignatedReq)); - delete mResourcesValidContext; - delete mLimitedAsync; -} catch (...) { - return; -} - -// -// Initialize a nested SecStaticCode object from its parent -// -void SecStaticCode::initializeFromParent(const SecStaticCode& parent) { - mOuterScope = &parent; - setMonitor(parent.monitor()); - if (parent.mLimitedAsync) - mLimitedAsync = new LimitedAsync(*parent.mLimitedAsync); -} - -// -// CF-level comparison of SecStaticCode objects compares CodeDirectory hashes if signed, -// and falls back on comparing canonical paths if (both are) not. -// -bool SecStaticCode::equal(SecCFObject &secOther) -{ - SecStaticCode *other = static_cast(&secOther); - CFDataRef mine = this->cdHash(); - CFDataRef his = other->cdHash(); - if (mine || his) - return mine && his && CFEqual(mine, his); - else - return CFEqual(CFRef(this->copyCanonicalPath()), CFRef(other->copyCanonicalPath())); -} - -CFHashCode SecStaticCode::hash() -{ - if (CFDataRef h = this->cdHash()) - return CFHash(h); - else - return CFHash(CFRef(this->copyCanonicalPath())); -} - - -// -// Invoke a stage monitor if registered -// -CFTypeRef SecStaticCode::reportEvent(CFStringRef stage, CFDictionaryRef info) -{ - if (mMonitor) - return mMonitor(this->handle(false), stage, info); - else - return NULL; -} - -void SecStaticCode::prepareProgress(unsigned int workload) -{ - dispatch_sync(mProgressQueue, ^{ - mCancelPending = false; // not cancelled - }); - if (mValidationFlags & kSecCSReportProgress) { - mCurrentWork = 0; // nothing done yet - mTotalWork = workload; // totally fake - we don't know how many files we'll get to chew - } -} - -void SecStaticCode::reportProgress(unsigned amount /* = 1 */) -{ - if (mMonitor && (mValidationFlags & kSecCSReportProgress)) { - // update progress and report - __block bool cancel = false; - dispatch_sync(mProgressQueue, ^{ - if (mCancelPending) - cancel = true; - mCurrentWork += amount; - mMonitor(this->handle(false), CFSTR("progress"), CFTemp("{current=%d,total=%d}", mCurrentWork, mTotalWork)); - }); - // if cancellation is pending, abort now - if (cancel) - MacOSError::throwMe(errSecCSCancelled); - } -} - - -// -// Set validation conditions for fine-tuning legacy tolerance -// -static void addError(CFTypeRef cfError, void* context) -{ - if (CFGetTypeID(cfError) == CFNumberGetTypeID()) { - int64_t error; - CFNumberGetValue(CFNumberRef(cfError), kCFNumberSInt64Type, (void*)&error); - MacOSErrorSet* errors = (MacOSErrorSet*)context; - errors->insert(OSStatus(error)); - } -} - -void SecStaticCode::setValidationModifiers(CFDictionaryRef conditions) -{ - if (conditions) { - CFDictionary source(conditions, errSecCSDbCorrupt); - mAllowOmissions = source.get("omissions"); - if (CFArrayRef errors = source.get("errors")) - CFArrayApplyFunction(errors, CFRangeMake(0, CFArrayGetCount(errors)), addError, &this->mTolerateErrors); - } -} - - -// -// Request cancellation of a validation in progress. -// We do this by posting an abort flag that is checked periodically. -// -void SecStaticCode::cancelValidation() -{ - if (!(mValidationFlags & kSecCSReportProgress)) // not using progress reporting; cancel won't make it through - MacOSError::throwMe(errSecCSInvalidFlags); - dispatch_assert_queue(mProgressQueue); - mCancelPending = true; -} - - -// -// Attach a detached signature. -// -void SecStaticCode::detachedSignature(CFDataRef sigData) -{ - if (sigData) { - mDetachedSig = sigData; - mRep = new DetachedRep(sigData, mRep->base(), "explicit detached"); - CODESIGN_STATIC_ATTACH_EXPLICIT(this, mRep); - } else { - mDetachedSig = NULL; - mRep = mRep->base(); - CODESIGN_STATIC_ATTACH_EXPLICIT(this, NULL); - } -} - - -// -// Consult the system detached signature database to see if it contains -// a detached signature for this StaticCode. If it does, fetch and attach it. -// We do this only if the code has no signature already attached. -// -void SecStaticCode::checkForSystemSignature() -{ - if (!this->isSigned()) { - SignatureDatabase db; - if (db.isOpen()) - try { - if (RefPointer dsig = db.findCode(mRep)) { - CODESIGN_STATIC_ATTACH_SYSTEM(this, dsig); - mRep = dsig; - } - } catch (...) { - } - } -} - - -// -// Return a descriptive string identifying the source of the code signature -// -string SecStaticCode::signatureSource() -{ - if (!isSigned()) - return "unsigned"; - if (DetachedRep *rep = dynamic_cast(mRep.get())) - return rep->source(); - return "embedded"; -} - - -// -// Do ::required, but convert incoming SecCodeRefs to their SecStaticCodeRefs -// (if possible). -// -SecStaticCode *SecStaticCode::requiredStatic(SecStaticCodeRef ref) -{ - SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef); - if (SecStaticCode *scode = dynamic_cast(object)) - return scode; - else if (SecCode *code = dynamic_cast(object)) - return code->staticCode(); - else // neither (a SecSomethingElse) - MacOSError::throwMe(errSecCSInvalidObjectRef); -} - -SecCode *SecStaticCode::optionalDynamic(SecStaticCodeRef ref) -{ - SecCFObject *object = SecCFObject::required(ref, errSecCSInvalidObjectRef); - if (dynamic_cast(object)) - return NULL; - else if (SecCode *code = dynamic_cast(object)) - return code; - else // neither (a SecSomethingElse) - MacOSError::throwMe(errSecCSInvalidObjectRef); -} - - -// -// Void all cached validity data. -// -// We also throw out cached components, because the new signature data may have -// a different idea of what components should be present. We could reconcile the -// cached data instead, if performance seems to be impacted. -// -void SecStaticCode::resetValidity() -{ - CODESIGN_EVAL_STATIC_RESET(this); - mValidated = false; - mExecutableValidated = mResourcesValidated = false; - if (mResourcesValidContext) { - delete mResourcesValidContext; - mResourcesValidContext = NULL; - } - mDir = NULL; - mSignature = NULL; - for (unsigned n = 0; n < cdSlotCount; n++) - mCache[n] = NULL; - mInfoDict = NULL; - mEntitlements = NULL; - mResourceDict = NULL; - mDesignatedReq = NULL; - mCDHash = NULL; - mGotResourceBase = false; - mTrust = NULL; - mCertChain = NULL; - mEvalDetails = NULL; - mRep->flush(); - - // we may just have updated the system database, so check again - checkForSystemSignature(); -} - - -// -// Retrieve a sealed component by special slot index. -// If the CodeDirectory has already been validated, validate against that. -// Otherwise, retrieve the component without validation (but cache it). Validation -// will go through the cache and validate all cached components. -// -CFDataRef SecStaticCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) -{ - assert(slot <= cdSlotMax); - - CFRef &cache = mCache[slot]; - if (!cache) { - if (CFRef data = mRep->component(slot)) { - if (validated()) { // if the directory has been validated... - if (!codeDirectory()->slotIsPresent(-slot)) - return NULL; - - if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), // ... and it's no good - CFDataGetLength(data), -slot)) - MacOSError::throwMe(errorForSlot(slot)); // ... then bail - } - cache = data; // it's okay, cache it - } else { // absent, mark so - if (validated()) // if directory has been validated... - if (codeDirectory()->slotIsPresent(-slot)) // ... and the slot is NOT missing - MacOSError::throwMe(errorForSlot(slot)); // was supposed to be there - cache = CFDataRef(kCFNull); // white lie - } - } - return (cache == CFDataRef(kCFNull)) ? NULL : cache.get(); -} - - -// -// Get the CodeDirectory. -// Throws (if check==true) or returns NULL (check==false) if there is none. -// Always throws if the CodeDirectory exists but is invalid. -// NEVER validates against the signature. -// -const CodeDirectory *SecStaticCode::codeDirectory(bool check /* = true */) -{ - if (!mDir) { - if (mDir.take(mRep->codeDirectory())) { - const CodeDirectory *dir = reinterpret_cast(CFDataGetBytePtr(mDir)); - if (!dir->validateBlob(CFDataGetLength(mDir))) - MacOSError::throwMe(errSecCSSignatureInvalid); - dir->checkIntegrity(); - } - } - if (mDir) - return reinterpret_cast(CFDataGetBytePtr(mDir)); - if (check) - MacOSError::throwMe(errSecCSUnsigned); - return NULL; -} - - -// -// Get the hash of the CodeDirectory. -// Returns NULL if there is none. -// -CFDataRef SecStaticCode::cdHash() -{ - if (!mCDHash) { - if (const CodeDirectory *cd = codeDirectory(false)) { - mCDHash.take(cd->cdhash()); - CODESIGN_STATIC_CDHASH(this, CFDataGetBytePtr(mCDHash), (unsigned int)CFDataGetLength(mCDHash)); - } - } - return mCDHash; -} - - -// -// Return the CMS signature blob; NULL if none found. -// -CFDataRef SecStaticCode::signature() -{ - if (!mSignature) - mSignature.take(mRep->signature()); - if (mSignature) - return mSignature; - MacOSError::throwMe(errSecCSUnsigned); -} - - -// -// Verify the signature on the CodeDirectory. -// If this succeeds (doesn't throw), the CodeDirectory is statically trustworthy. -// Any outcome (successful or not) is cached for the lifetime of the StaticCode. -// -void SecStaticCode::validateDirectory() -{ - // echo previous outcome, if any - // track revocation separately, as it may not have been checked - // during the initial validation - if (!validated() || ((mValidationFlags & kSecCSEnforceRevocationChecks) && !revocationChecked())) - try { - // perform validation (or die trying) - CODESIGN_EVAL_STATIC_DIRECTORY(this); - mValidationExpired = verifySignature(); - if (mValidationFlags & kSecCSEnforceRevocationChecks) - mRevocationChecked = true; - - for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot) - if (mCache[slot]) // if we already loaded that resource... - validateComponent(slot, errorForSlot(slot)); // ... then check it now - mValidated = true; // we've done the deed... - mValidationResult = errSecSuccess; // ... and it was good - } catch (const CommonError &err) { - mValidated = true; - mValidationResult = err.osStatus(); - throw; - } catch (...) { - secdebug("staticCode", "%p validation threw non-common exception", this); - mValidated = true; - mValidationResult = errSecCSInternalError; - throw; - } - assert(validated()); - if (mValidationResult == errSecSuccess) { - if (mValidationExpired) - if ((mValidationFlags & kSecCSConsiderExpiration) - || (codeDirectory()->flags & kSecCodeSignatureForceExpiration)) - MacOSError::throwMe(CSSMERR_TP_CERT_EXPIRED); - } else - MacOSError::throwMe(mValidationResult); -} - - -// -// Load and validate the CodeDirectory and all components *except* those related to the resource envelope. -// Those latter components are checked by validateResources(). -// -void SecStaticCode::validateNonResourceComponents() -{ - this->validateDirectory(); - for (CodeDirectory::SpecialSlot slot = codeDirectory()->maxSpecialSlot(); slot >= 1; --slot) - switch (slot) { - case cdResourceDirSlot: // validated by validateResources - break; - default: - this->component(slot); // loads and validates - break; - } -} - - -// -// Get the (signed) signing date from the code signature. -// Sadly, we need to validate the signature to get the date (as a side benefit). -// This means that you can't get the signing time for invalidly signed code. -// -// We could run the decoder "almost to" verification to avoid this, but there seems -// little practical point to such a duplication of effort. -// -CFAbsoluteTime SecStaticCode::signingTime() -{ - validateDirectory(); - return mSigningTime; -} - -CFAbsoluteTime SecStaticCode::signingTimestamp() -{ - validateDirectory(); - return mSigningTimestamp; -} - - -// -// Verify the CMS signature on the CodeDirectory. -// This performs the cryptographic tango. It returns if the signature is valid, -// or throws if it is not. As a side effect, a successful return sets up the -// cached certificate chain for future use. -// Returns true if the signature is expired (the X.509 sense), false if it's not. -// Expiration is fatal (throws) if a secure timestamp is included, but not otherwise. -// -bool SecStaticCode::verifySignature() -{ - // ad-hoc signed code is considered validly signed by definition - if (flag(kSecCodeSignatureAdhoc)) { - CODESIGN_EVAL_STATIC_SIGNATURE_ADHOC(this); - return false; - } - - DTRACK(CODESIGN_EVAL_STATIC_SIGNATURE, this, (char*)this->mainExecutablePath().c_str()); - - // decode CMS and extract SecTrust for verification - CFRef cms; - MacOSError::check(CMSDecoderCreate(&cms.aref())); // create decoder - CFDataRef sig = this->signature(); - MacOSError::check(CMSDecoderUpdateMessage(cms, CFDataGetBytePtr(sig), CFDataGetLength(sig))); - this->codeDirectory(); // load CodeDirectory (sets mDir) - MacOSError::check(CMSDecoderSetDetachedContent(cms, mDir)); - MacOSError::check(CMSDecoderFinalizeMessage(cms)); - MacOSError::check(CMSDecoderSetSearchKeychain(cms, cfEmptyArray())); - CFRef vf_policies = verificationPolicies(); - CFRef ts_policies = SecPolicyCreateAppleTimeStampingAndRevocationPolicies(vf_policies); - CMSSignerStatus status; - MacOSError::check(CMSDecoderCopySignerStatus(cms, 0, vf_policies, - false, &status, &mTrust.aref(), NULL)); - - if (status != kCMSSignerValid) { - const char *reason; - switch (status) { - case kCMSSignerUnsigned: reason="kCMSSignerUnsigned"; break; - case kCMSSignerNeedsDetachedContent: reason="kCMSSignerNeedsDetachedContent"; break; - case kCMSSignerInvalidSignature: reason="kCMSSignerInvalidSignature"; break; - case kCMSSignerInvalidCert: reason="kCMSSignerInvalidCert"; break; - case kCMSSignerInvalidIndex: reason="kCMSSignerInvalidIndex"; break; - default: reason="unknown"; break; - } - Security::Syslog::error("CMSDecoderCopySignerStatus failed with %s error (%d)", - reason, (int)status); - MacOSError::throwMe(errSecCSSignatureFailed); - } - - // internal signing time (as specified by the signer; optional) - mSigningTime = 0; // "not present" marker (nobody could code sign on Jan 1, 2001 :-) - switch (OSStatus rc = CMSDecoderCopySignerSigningTime(cms, 0, &mSigningTime)) { - case errSecSuccess: - case errSecSigningTimeMissing: - break; - default: - Security::Syslog::error("Could not get signing time (error %d)", (int)rc); - MacOSError::throwMe(rc); - } - - // certified signing time (as specified by a TSA; optional) - mSigningTimestamp = 0; - switch (OSStatus rc = CMSDecoderCopySignerTimestampWithPolicy(cms, ts_policies, 0, &mSigningTimestamp)) { - case errSecSuccess: - case errSecTimestampMissing: - break; - default: - Security::Syslog::error("Could not get timestamp (error %d)", (int)rc); - MacOSError::throwMe(rc); - } - - // set up the environment for SecTrust - if (mValidationFlags & kSecCSNoNetworkAccess) { - MacOSError::check(SecTrustSetNetworkFetchAllowed(mTrust,false)); // no network? - } - MacOSError::check(SecTrustSetKeychains(mTrust, cfEmptyArray())); // no keychains - - CSSM_APPLE_TP_ACTION_DATA actionData = { - CSSM_APPLE_TP_ACTION_VERSION, // version of data structure - 0 // action flags - }; - - if (!(mValidationFlags & kSecCSCheckTrustedAnchors)) { - /* no need to evaluate anchor trust when building cert chain */ - MacOSError::check(SecTrustSetAnchorCertificates(mTrust, cfEmptyArray())); // no anchors - actionData.ActionFlags |= CSSM_TP_ACTION_IMPLICIT_ANCHORS; // action flags - } - - for (;;) { // at most twice - MacOSError::check(SecTrustSetParameters(mTrust, - CSSM_TP_ACTION_DEFAULT, CFTempData(&actionData, sizeof(actionData)))); - - // evaluate trust and extract results - SecTrustResultType trustResult; - MacOSError::check(SecTrustEvaluate(mTrust, &trustResult)); - MacOSError::check(SecTrustGetResult(mTrust, &trustResult, &mCertChain.aref(), &mEvalDetails)); - - // if this is an Apple developer cert.... - if (teamID() && SecStaticCode::isAppleDeveloperCert(mCertChain)) { - CFRef teamIDFromCert; - if (CFArrayGetCount(mCertChain) > 0) { - /* Note that SecCertificateCopySubjectComponent sets the out parameter to NULL if there is no field present */ - MacOSError::check(SecCertificateCopySubjectComponent((SecCertificateRef)CFArrayGetValueAtIndex(mCertChain, Requirement::leafCert), - &CSSMOID_OrganizationalUnitName, - &teamIDFromCert.aref())); - - if (teamIDFromCert) { - CFRef teamIDFromCD = CFStringCreateWithCString(NULL, teamID(), kCFStringEncodingUTF8); - if (!teamIDFromCD) { - Security::Syslog::error("Could not get team identifier (%s)", teamID()); - MacOSError::throwMe(errSecCSInternalError); - } - - if (CFStringCompare(teamIDFromCert, teamIDFromCD, 0) != kCFCompareEqualTo) { - Security::Syslog::error("Team identifier in the signing certificate (%s) does not match the team identifier (%s) in the code directory", cfString(teamIDFromCert).c_str(), teamID()); - MacOSError::throwMe(errSecCSSignatureInvalid); - } - } - } - } - - CODESIGN_EVAL_STATIC_SIGNATURE_RESULT(this, trustResult, mCertChain ? (int)CFArrayGetCount(mCertChain) : 0); - switch (trustResult) { - case kSecTrustResultProceed: - case kSecTrustResultUnspecified: - break; // success - case kSecTrustResultDeny: - MacOSError::throwMe(CSSMERR_APPLETP_TRUST_SETTING_DENY); // user reject - case kSecTrustResultInvalid: - assert(false); // should never happen - MacOSError::throwMe(CSSMERR_TP_NOT_TRUSTED); - default: - { - OSStatus result; - MacOSError::check(SecTrustGetCssmResultCode(mTrust, &result)); - // if we have a valid timestamp, CMS validates against (that) signing time and all is well. - // If we don't have one, may validate against *now*, and must be able to tolerate expiration. - if (mSigningTimestamp == 0) { // no timestamp available - if (((result == CSSMERR_TP_CERT_EXPIRED) || (result == CSSMERR_TP_CERT_NOT_VALID_YET)) - && !(actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED)) { - CODESIGN_EVAL_STATIC_SIGNATURE_EXPIRED(this); - actionData.ActionFlags |= CSSM_TP_ACTION_ALLOW_EXPIRED; // (this also allows postdated certs) - continue; // retry validation while tolerating expiration - } - } - Security::Syslog::error("SecStaticCode: verification failed (trust result %d, error %d)", trustResult, (int)result); - MacOSError::throwMe(result); - } - } - - if (mSigningTimestamp) { - CFIndex rootix = CFArrayGetCount(mCertChain); - if (SecCertificateRef mainRoot = SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, rootix-1))) - if (isAppleCA(mainRoot)) { - // impose policy: if the signature itself draws to Apple, then so must the timestamp signature - CFRef tsCerts; - OSStatus result = CMSDecoderCopySignerTimestampCertificates(cms, 0, &tsCerts.aref()); - if (result) { - Security::Syslog::error("SecStaticCode: could not get timestamp certificates (error %d)", (int)result); - MacOSError::check(result); - } - CFIndex tsn = CFArrayGetCount(tsCerts); - bool good = tsn > 0 && isAppleCA(SecCertificateRef(CFArrayGetValueAtIndex(tsCerts, tsn-1))); - if (!good) { - result = CSSMERR_TP_NOT_TRUSTED; - Security::Syslog::error("SecStaticCode: timestamp policy verification failed (error %d)", (int)result); - MacOSError::throwMe(result); - } - } - } - - return actionData.ActionFlags & CSSM_TP_ACTION_ALLOW_EXPIRED; - } -} - - -// -// Return the TP policy used for signature verification. -// This may be a simple SecPolicyRef or a CFArray of policies. -// The caller owns the return value. -// -static SecPolicyRef makeCRLPolicy() -{ - CFRef policy; - MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref())); - CSSM_APPLE_TP_CRL_OPTIONS options; - memset(&options, 0, sizeof(options)); - options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION; - options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT; - CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; - MacOSError::check(SecPolicySetValue(policy, &optData)); - return policy.yield(); -} - -static SecPolicyRef makeOCSPPolicy() -{ - CFRef policy; - MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref())); - CSSM_APPLE_TP_OCSP_OPTIONS options; - memset(&options, 0, sizeof(options)); - options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION; - options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT; - CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; - MacOSError::check(SecPolicySetValue(policy, &optData)); - return policy.yield(); -} - -CFArrayRef SecStaticCode::verificationPolicies() -{ - CFRef core; - MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, - &CSSMOID_APPLE_TP_CODE_SIGNING, &core.aref())); - if (mValidationFlags & kSecCSNoNetworkAccess) { - // Skips all revocation since they require network connectivity - // therefore annihilates kSecCSEnforceRevocationChecks if present - CFRef no_revoc = SecPolicyCreateRevocation(kSecRevocationNetworkAccessDisabled); - return makeCFArray(2, core.get(), no_revoc.get()); - } - else if (mValidationFlags & kSecCSEnforceRevocationChecks) { - // Add CRL and OCSPPolicies - CFRef crl = makeCRLPolicy(); - CFRef ocsp = makeOCSPPolicy(); - return makeCFArray(3, core.get(), crl.get(), ocsp.get()); - } else { - return makeCFArray(1, core.get()); - } -} - - -// -// Validate a particular sealed, cached resource against its (special) CodeDirectory slot. -// The resource must already have been placed in the cache. -// This does NOT perform basic validation. -// -void SecStaticCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) -{ - assert(slot <= cdSlotMax); - CFDataRef data = mCache[slot]; - assert(data); // must be cached - if (data == CFDataRef(kCFNull)) { - if (codeDirectory()->slotIsPresent(-slot)) // was supposed to be there... - MacOSError::throwMe(fail); // ... and is missing - } else { - if (!codeDirectory()->validateSlot(CFDataGetBytePtr(data), CFDataGetLength(data), -slot)) - MacOSError::throwMe(fail); - } -} - - -// -// Perform static validation of the main executable. -// This reads the main executable from disk and validates it against the -// CodeDirectory code slot array. -// Note that this is NOT an in-memory validation, and is thus potentially -// subject to timing attacks. -// -void SecStaticCode::validateExecutable() -{ - if (!validatedExecutable()) { - try { - DTRACK(CODESIGN_EVAL_STATIC_EXECUTABLE, this, - (char*)this->mainExecutablePath().c_str(), codeDirectory()->nCodeSlots); - const CodeDirectory *cd = this->codeDirectory(); - if (!cd) - MacOSError::throwMe(errSecCSUnsigned); - AutoFileDesc fd(mainExecutablePath(), O_RDONLY); - fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass) - if (Universal *fat = mRep->mainExecutableImage()) - fd.seek(fat->archOffset()); - size_t pageSize = cd->pageSize ? (1 << cd->pageSize) : 0; - size_t remaining = cd->codeLimit; - for (uint32_t slot = 0; slot < cd->nCodeSlots; ++slot) { - size_t size = min(remaining, pageSize); - if (!cd->validateSlot(fd, size, slot)) { - CODESIGN_EVAL_STATIC_EXECUTABLE_FAIL(this, (int)slot); - MacOSError::throwMe(errSecCSSignatureFailed); - } - remaining -= size; - } - mExecutableValidated = true; - mExecutableValidResult = errSecSuccess; - } catch (const CommonError &err) { - mExecutableValidated = true; - mExecutableValidResult = err.osStatus(); - throw; - } catch (...) { - secdebug("staticCode", "%p executable validation threw non-common exception", this); - mExecutableValidated = true; - mExecutableValidResult = errSecCSInternalError; - throw; - } - } - assert(validatedExecutable()); - if (mExecutableValidResult != errSecSuccess) - MacOSError::throwMe(mExecutableValidResult); -} - - -// -// Perform static validation of sealed resources and nested code. -// -// This performs a whole-code static resource scan and effectively -// computes a concordance between what's on disk and what's in the ResourceDirectory. -// Any unsanctioned difference causes an error. -// -unsigned SecStaticCode::estimateResourceWorkload() -{ - // workload estimate = number of sealed files - CFDictionaryRef sealedResources = resourceDictionary(); - CFDictionaryRef files = cfget(sealedResources, "files2"); - if (files == NULL) - files = cfget(sealedResources, "files"); - return files ? unsigned(CFDictionaryGetCount(files)) : 0; -} - -void SecStaticCode::validateResources(SecCSFlags flags) -{ - // do we have a superset of this requested validation cached? - bool doit = true; - if (mResourcesValidated) { // have cached outcome - if (!(flags & kSecCSCheckNestedCode) || mResourcesDeep) // was deep or need no deep scan - doit = false; - } - - if (doit) { - if (mLimitedAsync == NULL) { - mLimitedAsync = new LimitedAsync(diskRep()->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey); - } - - try { - // sanity first - CFDictionaryRef sealedResources = resourceDictionary(); - if (this->resourceBase()) // disk has resources - if (sealedResources) - /* go to work below */; - else - MacOSError::throwMe(errSecCSResourcesNotFound); - else // disk has no resources - if (sealedResources) - MacOSError::throwMe(errSecCSResourcesNotFound); - else - return; // no resources, not sealed - fine (no work) - - // found resources, and they are sealed - DTRACK(CODESIGN_EVAL_STATIC_RESOURCES, this, - (char*)this->mainExecutablePath().c_str(), 0); - - // scan through the resources on disk, checking each against the resourceDirectory - mResourcesValidContext = new CollectingContext(*this); // collect all failures in here - - // use V2 resource seal if available, otherwise fall back to V1 - CFDictionaryRef rules; - CFDictionaryRef files; - uint32_t version; - if (CFDictionaryGetValue(sealedResources, CFSTR("files2"))) { // have V2 signature - rules = cfget(sealedResources, "rules2"); - files = cfget(sealedResources, "files2"); - version = 2; - } else { // only V1 available - rules = cfget(sealedResources, "rules"); - files = cfget(sealedResources, "files"); - version = 1; - } - if (!rules || !files) - MacOSError::throwMe(errSecCSResourcesInvalid); - - // check for weak resource rules - bool strict = flags & kSecCSStrictValidate; - if (strict) { - if (hasWeakResourceRules(rules, version, mAllowOmissions)) - if (mTolerateErrors.find(errSecCSWeakResourceRules) == mTolerateErrors.end()) - MacOSError::throwMe(errSecCSWeakResourceRules); - if (version == 1) - if (mTolerateErrors.find(errSecCSWeakResourceEnvelope) == mTolerateErrors.end()) - MacOSError::throwMe(errSecCSWeakResourceEnvelope); - } - - Dispatch::Group group; - Dispatch::Group &groupRef = group; // (into block) - - // scan through the resources on disk, checking each against the resourceDirectory - __block CFRef resourceMap = makeCFMutableDictionary(files); - string base = cfString(this->resourceBase()); - ResourceBuilder resources(base, base, rules, codeDirectory()->hashType, strict, mTolerateErrors); - this->mResourceScope = &resources; - diskRep()->adjustResources(resources); - - resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const string relpath, ResourceBuilder::Rule *rule) { - CFDictionaryRemoveValue(resourceMap, CFTempString(relpath)); - bool isSymlink = (ent->fts_info == FTS_SL); - - void (^validate)() = ^{ - validateResource(files, relpath, isSymlink, *mResourcesValidContext, flags, version); - reportProgress(); - }; - - mLimitedAsync->perform(groupRef, validate); - }); - group.wait(); // wait until all async resources have been validated as well - - unsigned leftovers = unsigned(CFDictionaryGetCount(resourceMap)); - if (leftovers > 0) { - secdebug("staticCode", "%d sealed resource(s) not found in code", int(leftovers)); - CFDictionaryApplyFunction(resourceMap, SecStaticCode::checkOptionalResource, mResourcesValidContext); - } - - // now check for any errors found in the reporting context - mResourcesValidated = true; - mResourcesDeep = flags & kSecCSCheckNestedCode; - if (mResourcesValidContext->osStatus() != errSecSuccess) - mResourcesValidContext->throwMe(); - } catch (const CommonError &err) { - mResourcesValidated = true; - mResourcesDeep = flags & kSecCSCheckNestedCode; - mResourcesValidResult = err.osStatus(); - throw; - } catch (...) { - secdebug("staticCode", "%p executable validation threw non-common exception", this); - mResourcesValidated = true; - mResourcesDeep = flags & kSecCSCheckNestedCode; - mResourcesValidResult = errSecCSInternalError; - throw; - } - } - assert(validatedResources()); - if (mResourcesValidResult) - MacOSError::throwMe(mResourcesValidResult); - if (mResourcesValidContext->osStatus() != errSecSuccess) - mResourcesValidContext->throwMe(); -} - - -void SecStaticCode::checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context) -{ - ValidationContext *ctx = static_cast(context); - ResourceSeal seal(value); - if (!seal.optional()) { - if (key && CFGetTypeID(key) == CFStringGetTypeID()) { - CFTempURL tempURL(CFStringRef(key), false, ctx->code.resourceBase()); - if (!tempURL.get()) { - ctx->reportProblem(errSecCSBadDictionaryFormat, kSecCFErrorResourceSeal, key); - } else { - ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, tempURL); - } - } else { - ctx->reportProblem(errSecCSBadResource, kSecCFErrorResourceSeal, key); - } - } -} - - -static bool isOmitRule(CFTypeRef value) -{ - if (CFGetTypeID(value) == CFBooleanGetTypeID()) - return value == kCFBooleanFalse; - CFDictionary rule(value, errSecCSResourceRulesInvalid); - return rule.get("omit") == kCFBooleanTrue; -} - -bool SecStaticCode::hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions) -{ - // compute allowed omissions - CFRef defaultOmissions = this->diskRep()->allowedResourceOmissions(); - if (!defaultOmissions) - MacOSError::throwMe(errSecCSInternalError); - CFRef allowed = CFArrayCreateMutableCopy(NULL, 0, defaultOmissions); - if (allowedOmissions) - CFArrayAppendArray(allowed, allowedOmissions, CFRangeMake(0, CFArrayGetCount(allowedOmissions))); - CFRange range = CFRangeMake(0, CFArrayGetCount(allowed)); - - // check all resource rules for weakness - string catchAllRule = (version == 1) ? "^Resources/" : "^.*"; - __block bool coversAll = false; - __block bool forbiddenOmission = false; - CFArrayRef allowedRef = allowed.get(); // (into block) - CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid); - rules.apply(^(CFStringRef key, CFTypeRef value) { - string pattern = cfString(key, errSecCSResourceRulesInvalid); - if (pattern == catchAllRule && value == kCFBooleanTrue) { - coversAll = true; - return; - } - if (isOmitRule(value)) - forbiddenOmission |= !CFArrayContainsValue(allowedRef, range, key); - }); - - return !coversAll || forbiddenOmission; -} - - -// -// Load, validate, cache, and return CFDictionary forms of sealed resources. -// -CFDictionaryRef SecStaticCode::infoDictionary() -{ - if (!mInfoDict) { - mInfoDict.take(getDictionary(cdInfoSlot, errSecCSInfoPlistFailed)); - secdebug("staticCode", "%p loaded InfoDict %p", this, mInfoDict.get()); - } - return mInfoDict; -} - -CFDictionaryRef SecStaticCode::entitlements() -{ - if (!mEntitlements) { - validateDirectory(); - if (CFDataRef entitlementData = component(cdEntitlementSlot)) { - validateComponent(cdEntitlementSlot); - const EntitlementBlob *blob = reinterpret_cast(CFDataGetBytePtr(entitlementData)); - if (blob->validateBlob()) { - mEntitlements.take(blob->entitlements()); - secdebug("staticCode", "%p loaded Entitlements %p", this, mEntitlements.get()); - } - // we do not consider a different blob type to be an error. We think it's a new format we don't understand - } - } - return mEntitlements; -} - -CFDictionaryRef SecStaticCode::resourceDictionary(bool check /* = true */) -{ - if (mResourceDict) // cached - return mResourceDict; - if (CFRef dict = getDictionary(cdResourceDirSlot, check)) - if (cfscan(dict, "{rules=%Dn,files=%Dn}")) { - secdebug("staticCode", "%p loaded ResourceDict %p", - this, mResourceDict.get()); - return mResourceDict = dict; - } - // bad format - return NULL; -} - - -// -// Load and cache the resource directory base. -// Note that the base is optional for each DiskRep. -// -CFURLRef SecStaticCode::resourceBase() -{ - if (!mGotResourceBase) { - string base = mRep->resourcesRootPath(); - if (!base.empty()) - mResourceBase.take(makeCFURL(base, true)); - mGotResourceBase = true; - } - return mResourceBase; -} - - -// -// Load a component, validate it, convert it to a CFDictionary, and return that. -// This will force load and validation, which means that it will perform basic -// validation if it hasn't been done yet. -// -CFDictionaryRef SecStaticCode::getDictionary(CodeDirectory::SpecialSlot slot, bool check /* = true */) -{ - if (check) - validateDirectory(); - if (CFDataRef infoData = component(slot)) { - validateComponent(slot); - if (CFDictionaryRef dict = makeCFDictionaryFrom(infoData)) - return dict; - else - MacOSError::throwMe(errSecCSBadDictionaryFormat); - } - return NULL; -} - - -// -// Load, validate, and return a sealed resource. -// The resource data (loaded in to memory as a blob) is returned and becomes -// the responsibility of the caller; it is NOT cached by SecStaticCode. -// -// A resource that is not sealed will not be returned, and an error will be thrown. -// A missing resource will cause an error unless it's marked optional in the Directory. -// Under no circumstances will a corrupt resource be returned. -// NULL will only be returned for a resource that is neither sealed nor present -// (or that is sealed, absent, and marked optional). -// If the ResourceDictionary itself is not sealed, this function will always fail. -// -// There is currently no interface for partial retrieval of the resource data. -// (Since the ResourceDirectory does not currently support segmentation, all the -// data would have to be read anyway, but it could be read into a reusable buffer.) -// -CFDataRef SecStaticCode::resource(string path, ValidationContext &ctx) -{ - if (CFDictionaryRef rdict = resourceDictionary()) { - if (CFTypeRef file = cfget(rdict, "files.%s", path.c_str())) { - ResourceSeal seal = file; - if (!resourceBase()) // no resources in DiskRep - MacOSError::throwMe(errSecCSResourcesNotFound); - if (seal.nested()) - MacOSError::throwMe(errSecCSResourcesNotSealed); // (it's nested code) - CFRef fullpath = makeCFURL(path, false, resourceBase()); - if (CFRef data = cfLoadFile(fullpath)) { - MakeHash hasher(this->codeDirectory()); - hasher->update(CFDataGetBytePtr(data), CFDataGetLength(data)); - if (hasher->verify(seal.hash())) - return data.yield(); // good - else - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered - } else { - if (!seal.optional()) - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing - else - return NULL; // validly missing - } - } else - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase())); - return NULL; - } else - MacOSError::throwMe(errSecCSResourcesNotSealed); -} - -CFDataRef SecStaticCode::resource(string path) -{ - ValidationContext ctx(*this); - return resource(path, ctx); -} - -void SecStaticCode::validateResource(CFDictionaryRef files, string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version) -{ - if (!resourceBase()) // no resources in DiskRep - MacOSError::throwMe(errSecCSResourcesNotFound); - CFRef fullpath = makeCFURL(path, false, resourceBase()); - if (CFTypeRef file = CFDictionaryGetValue(files, CFTempString(path))) { - ResourceSeal seal = file; - if (seal.nested()) { - if (isSymlink) - return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type - string suffix = ".framework"; - bool isFramework = (path.length() > suffix.length()) - && (path.compare(path.length()-suffix.length(), suffix.length(), suffix) == 0); - validateNestedCode(fullpath, seal, flags, isFramework); - } else if (seal.link()) { - if (!isSymlink) - return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type - validateSymlinkResource(cfString(fullpath), cfString(seal.link()), ctx, flags); - } else if (seal.hash()) { // genuine file - if (isSymlink) - return ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type - AutoFileDesc fd(cfString(fullpath), O_RDONLY, FileDesc::modeMissingOk); // open optional file - if (fd) { - MakeHash hasher(this->codeDirectory()); - hashFileData(fd, hasher.get()); - if (hasher->verify(seal.hash())) - return; // verify good - else - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // altered - } else { - if (!seal.optional()) - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceMissing, fullpath); // was sealed but is now missing - else - return; // validly missing - } - } else - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, fullpath); // changed type - return; - } - if (version == 1) { // version 1 ignores symlinks altogether - char target[PATH_MAX]; - if (::readlink(cfString(fullpath).c_str(), target, sizeof(target)) > 0) - return; - } - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAdded, CFTempURL(path, false, resourceBase())); -} - -void SecStaticCode::validateSymlinkResource(std::string fullpath, std::string seal, ValidationContext &ctx, SecCSFlags flags) -{ - static const char* const allowedDestinations[] = { - "/System/", - "/Library/", - NULL - }; - char target[PATH_MAX]; - ssize_t len = ::readlink(fullpath.c_str(), target, sizeof(target)-1); - if (len < 0) - UnixError::check(-1); - target[len] = '\0'; - std::string fulltarget = target; - if (target[0] != '/') { - size_t lastSlash = fullpath.rfind('/'); - fulltarget = fullpath.substr(0, lastSlash) + '/' + target; - } - if (seal != target) { - ctx.reportProblem(errSecCSBadResource, kSecCFErrorResourceAltered, CFTempString(fullpath)); - return; - } - if ((mValidationFlags & (kSecCSStrictValidate|kSecCSRestrictSymlinks)) == (kSecCSStrictValidate|kSecCSRestrictSymlinks)) { - char resolved[PATH_MAX]; - if (realpath(fulltarget.c_str(), resolved)) { - assert(resolved[0] == '/'); - size_t rlen = strlen(resolved); - if (target[0] == '/') { - // absolute symlink; only allow absolute links to system locations - for (const char* const* pathp = allowedDestinations; *pathp; pathp++) { - size_t dlen = strlen(*pathp); - if (rlen > dlen && strncmp(resolved, *pathp, dlen) == 0) - return; // target inside /System, deemed okay - } - } else { - // everything else must be inside the bundle(s) - for (const SecStaticCode* code = this; code; code = code->mOuterScope) { - string root = code->mResourceScope->root(); - if (strncmp(resolved, root.c_str(), root.size()) == 0) { - if (code->mResourceScope->includes(resolved + root.length() + 1)) - return; // located in resource stack && included in envelope - else - break; // located but excluded from envelope (deny) - } - } - } - } - // if we fell through, flag a symlink error - if (mTolerateErrors.find(errSecCSInvalidSymlink) == mTolerateErrors.end()) - ctx.reportProblem(errSecCSInvalidSymlink, kSecCFErrorResourceAltered, CFTempString(fullpath)); - } -} - -void SecStaticCode::validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework) -{ - CFRef req; - if (SecRequirementCreateWithString(seal.requirement(), kSecCSDefaultFlags, &req.aref())) - MacOSError::throwMe(errSecCSResourcesInvalid); - - // recursively verify this nested code - try { - if (!(flags & kSecCSCheckNestedCode)) - flags |= kSecCSBasicValidateOnly; - SecPointer code = new SecStaticCode(DiskRep::bestGuess(cfString(path))); - code->initializeFromParent(*this); - code->staticValidate(flags, SecRequirement::required(req)); - - if (isFramework && (flags & kSecCSStrictValidate)) - try { - validateOtherVersions(path, flags, req, code); - } catch (const CSError &err) { - MacOSError::throwMe(errSecCSBadFrameworkVersion); - } catch (const MacOSError &err) { - MacOSError::throwMe(errSecCSBadFrameworkVersion); - } - - } catch (CSError &err) { - if (err.error == errSecCSReqFailed) { - mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path); - return; - } - err.augment(kSecCFErrorPath, path); - throw; - } catch (const MacOSError &err) { - if (err.error == errSecCSReqFailed) { - mResourcesValidContext->reportProblem(errSecCSBadNestedCode, kSecCFErrorResourceAltered, path); - return; - } - CSError::throwMe(err.error, kSecCFErrorPath, path); - } -} - -void SecStaticCode::validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code) -{ - // Find out what current points to and do not revalidate - std::string mainPath = cfStringRelease(code->diskRep()->copyCanonicalPath()); - - char main_path[PATH_MAX]; - bool foundTarget = false; - - /* If it failed to get the target of the symlink, do not fail. It is a performance loss, - not a security hole */ - if (realpath(mainPath.c_str(), main_path) != NULL) - foundTarget = true; - - std::ostringstream versionsPath; - versionsPath << cfString(path) << "/Versions/"; - - DirScanner scanner(versionsPath.str()); - - if (scanner.initialized()) { - struct dirent *entry = NULL; - while ((entry = scanner.getNext()) != NULL) { - std::ostringstream fullPath; - - if (entry->d_type != DT_DIR || - strcmp(entry->d_name, ".") == 0 || - strcmp(entry->d_name, "..") == 0 || - strcmp(entry->d_name, "Current") == 0) - continue; - - fullPath << versionsPath.str() << entry->d_name; - - char real_full_path[PATH_MAX]; - if (realpath(fullPath.str().c_str(), real_full_path) == NULL) - UnixError::check(-1); - - // Do case insensitive comparions because realpath() was called for both paths - if (foundTarget && strcmp(main_path, real_full_path) == 0) - continue; - - SecPointer frameworkVersion = new SecStaticCode(DiskRep::bestGuess(real_full_path)); - frameworkVersion->initializeFromParent(*this); - frameworkVersion->staticValidate(flags, SecRequirement::required(req)); - } - } -} - - -// -// Test a CodeDirectory flag. -// Returns false if there is no CodeDirectory. -// May throw if the CodeDirectory is present but somehow invalid. -// -bool SecStaticCode::flag(uint32_t tested) -{ - if (const CodeDirectory *cd = this->codeDirectory(false)) - return cd->flags & tested; - else - return false; -} - - -// -// Retrieve the full SuperBlob containing all internal requirements. -// -const Requirements *SecStaticCode::internalRequirements() -{ - if (CFDataRef reqData = component(cdRequirementsSlot)) { - const Requirements *req = (const Requirements *)CFDataGetBytePtr(reqData); - if (!req->validateBlob()) - MacOSError::throwMe(errSecCSReqInvalid); - return req; - } else - return NULL; -} - - -// -// Retrieve a particular internal requirement by type. -// -const Requirement *SecStaticCode::internalRequirement(SecRequirementType type) -{ - if (const Requirements *reqs = internalRequirements()) - return reqs->find(type); - else - return NULL; -} - - -// -// Return the Designated Requirement (DR). This can be either explicit in the -// Internal Requirements component, or implicitly generated on demand here. -// Note that an explicit DR may have been implicitly generated at signing time; -// we don't distinguish this case. -// -const Requirement *SecStaticCode::designatedRequirement() -{ - if (const Requirement *req = internalRequirement(kSecDesignatedRequirementType)) { - return req; // explicit in signing data - } else { - if (!mDesignatedReq) - mDesignatedReq = defaultDesignatedRequirement(); - return mDesignatedReq; - } -} - - -// -// Generate the default Designated Requirement (DR) for this StaticCode. -// Ignore any explicit DR it may contain. -// -const Requirement *SecStaticCode::defaultDesignatedRequirement() -{ - if (flag(kSecCodeSignatureAdhoc)) { - // adhoc signature: return a cdhash requirement for all architectures - __block Requirement::Maker maker; - Requirement::Maker::Chain chain(maker, opOr); - - // insert cdhash requirement for all architectures - chain.add(); - maker.cdhash(this->cdHash()); - handleOtherArchitectures(^(SecStaticCode *subcode) { - if (CFDataRef cdhash = subcode->cdHash()) { - chain.add(); - maker.cdhash(cdhash); - } - }); - return maker.make(); - } else { - // full signature: Gin up full context and let DRMaker do its thing - validateDirectory(); // need the cert chain - Requirement::Context context(this->certificates(), - this->infoDictionary(), - this->entitlements(), - this->identifier(), - this->codeDirectory() - ); - return DRMaker(context).make(); - } -} - - -// -// Validate a SecStaticCode against the internal requirement of a particular type. -// -void SecStaticCode::validateRequirements(SecRequirementType type, SecStaticCode *target, - OSStatus nullError /* = errSecSuccess */) -{ - DTRACK(CODESIGN_EVAL_STATIC_INTREQ, this, type, target, nullError); - if (const Requirement *req = internalRequirement(type)) - target->validateRequirement(req, nullError ? nullError : errSecCSReqFailed); - else if (nullError) - MacOSError::throwMe(nullError); - else - /* accept it */; -} - -/* Public Key Hash for root:/C=US/O=VeriSign, Inc./OU=Class 3 Public Primary Certification Authority */ -static const UInt8 retryRootBytes[] = {0x00,0xd8,0x5a,0x4c,0x25,0xc1,0x22,0xe5,0x8b,0x31,0xef,0x6d,0xba,0xf3,0xcc,0x5f,0x29,0xf1,0x0d,0x61}; - -// -// Validate this StaticCode against an external Requirement -// -bool SecStaticCode::satisfiesRequirement(const Requirement *req, OSStatus failure) -{ - bool result = false; - assert(req); - validateDirectory(); - result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure); - if (result == false) { - /* Fix for rdar://problem/21437632: Work around untrusted root in validation chain */ - CFArrayRef certs = certificates(); - if (!certs || ((int)CFArrayGetCount(certs) < 1)) { - return false; - } - SecCertificateRef root = cert((int)CFArrayGetCount(certs) - 1); - if (!root) { - return false; - } - CFDataRef rootHash = SecCertificateCopyPublicKeySHA1Digest(root); - if (!rootHash) { - return false; - } - - if ((CFDataGetLength(rootHash) == sizeof(retryRootBytes)) && - !memcmp(CFDataGetBytePtr(rootHash), retryRootBytes, sizeof(retryRootBytes))) { - // retry with a rebuilt certificate chain, this time evaluating anchor trust - Security::Syslog::debug("Requirements validation failed: retrying"); - mResourcesValidated = mValidated = false; - setValidationFlags(mValidationFlags | kSecCSCheckTrustedAnchors); - - validateDirectory(); - result = req->validates(Requirement::Context(mCertChain, infoDictionary(), entitlements(), codeDirectory()->identifier(), codeDirectory()), failure); - } - CFRelease(rootHash); - } - - return result; -} - -void SecStaticCode::validateRequirement(const Requirement *req, OSStatus failure) -{ - if (!this->satisfiesRequirement(req, failure)) - MacOSError::throwMe(failure); -} - -// -// Retrieve one certificate from the cert chain. -// Positive and negative indices can be used: -// [ leaf, intermed-1, ..., intermed-n, anchor ] -// 0 1 ... -2 -1 -// Returns NULL if unavailable for any reason. -// -SecCertificateRef SecStaticCode::cert(int ix) -{ - validateDirectory(); // need cert chain - if (mCertChain) { - CFIndex length = CFArrayGetCount(mCertChain); - if (ix < 0) - ix += length; - if (ix >= 0 && ix < length) - return SecCertificateRef(CFArrayGetValueAtIndex(mCertChain, ix)); - } - return NULL; -} - -CFArrayRef SecStaticCode::certificates() -{ - validateDirectory(); // need cert chain - return mCertChain; -} - - -// -// Gather (mostly) API-official information about this StaticCode. -// -// This method lives in the twilight between the API and internal layers, -// since it generates API objects (Sec*Refs) for return. -// -CFDictionaryRef SecStaticCode::signingInformation(SecCSFlags flags) -{ - // - // Start with the pieces that we return even for unsigned code. - // This makes Sec[Static]CodeRefs useful as API-level replacements - // of our internal OSXCode objects. - // - CFRef dict = makeCFMutableDictionary(1, - kSecCodeInfoMainExecutable, CFTempURL(this->mainExecutablePath()).get() - ); - - // - // If we're not signed, this is all you get - // - if (!this->isSigned()) - return dict.yield(); - - // - // Add the generic attributes that we always include - // - CFDictionaryAddValue(dict, kSecCodeInfoIdentifier, CFTempString(this->identifier())); - CFDictionaryAddValue(dict, kSecCodeInfoFlags, CFTempNumber(this->codeDirectory(false)->flags.get())); - CFDictionaryAddValue(dict, kSecCodeInfoFormat, CFTempString(this->format())); - CFDictionaryAddValue(dict, kSecCodeInfoSource, CFTempString(this->signatureSource())); - CFDictionaryAddValue(dict, kSecCodeInfoUnique, this->cdHash()); - const CodeDirectory* cd = this->codeDirectory(false); - CFDictionaryAddValue(dict, kSecCodeInfoDigestAlgorithm, CFTempNumber(cd->hashType)); - if (cd->platform) - CFDictionaryAddValue(dict, kSecCodeInfoPlatformIdentifier, CFTempNumber(cd->platform)); - - // - // Deliver any Info.plist only if it looks intact - // - try { - if (CFDictionaryRef info = this->infoDictionary()) - CFDictionaryAddValue(dict, kSecCodeInfoPList, info); - } catch (...) { } // don't deliver Info.plist if questionable - - // - // kSecCSSigningInformation adds information about signing certificates and chains - // - if (flags & kSecCSSigningInformation) - try { - if (CFArrayRef certs = this->certificates()) - CFDictionaryAddValue(dict, kSecCodeInfoCertificates, certs); - if (CFDataRef sig = this->signature()) - CFDictionaryAddValue(dict, kSecCodeInfoCMS, sig); - if (mTrust) - CFDictionaryAddValue(dict, kSecCodeInfoTrust, mTrust); - if (CFAbsoluteTime time = this->signingTime()) - if (CFRef date = CFDateCreate(NULL, time)) - CFDictionaryAddValue(dict, kSecCodeInfoTime, date); - if (CFAbsoluteTime time = this->signingTimestamp()) - if (CFRef date = CFDateCreate(NULL, time)) - CFDictionaryAddValue(dict, kSecCodeInfoTimestamp, date); - if (const char *teamID = this->teamID()) - CFDictionaryAddValue(dict, kSecCodeInfoTeamIdentifier, CFTempString(teamID)); - } catch (...) { } - - // - // kSecCSRequirementInformation adds information on requirements - // - if (flags & kSecCSRequirementInformation) - try { - if (const Requirements *reqs = this->internalRequirements()) { - CFDictionaryAddValue(dict, kSecCodeInfoRequirements, - CFTempString(Dumper::dump(reqs))); - CFDictionaryAddValue(dict, kSecCodeInfoRequirementData, CFTempData(*reqs)); - } - - const Requirement *dreq = this->designatedRequirement(); - CFRef dreqRef = (new SecRequirement(dreq))->handle(); - CFDictionaryAddValue(dict, kSecCodeInfoDesignatedRequirement, dreqRef); - if (this->internalRequirement(kSecDesignatedRequirementType)) { // explicit - CFRef ddreqRef = (new SecRequirement(this->defaultDesignatedRequirement(), true))->handle(); - CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, ddreqRef); - } else { // implicit - CFDictionaryAddValue(dict, kSecCodeInfoImplicitDesignatedRequirement, dreqRef); - } - } catch (...) { } - - try { - if (CFDataRef ent = this->component(cdEntitlementSlot)) { - CFDictionaryAddValue(dict, kSecCodeInfoEntitlements, ent); - if (CFDictionaryRef entdict = this->entitlements()) - CFDictionaryAddValue(dict, kSecCodeInfoEntitlementsDict, entdict); - } - } catch (...) { } - - // - // kSecCSInternalInformation adds internal information meant to be for Apple internal - // use (SPI), and not guaranteed to be stable. Primarily, this is data we want - // to reliably transmit through the API wall so that code outside the Security.framework - // can use it without having to play nasty tricks to get it. - // - if (flags & kSecCSInternalInformation) - try { - if (mDir) - CFDictionaryAddValue(dict, kSecCodeInfoCodeDirectory, mDir); - CFDictionaryAddValue(dict, kSecCodeInfoCodeOffset, CFTempNumber(mRep->signingBase())); - if (CFRef rdict = getDictionary(cdResourceDirSlot, false)) // suppress validation - CFDictionaryAddValue(dict, kSecCodeInfoResourceDirectory, rdict); - } catch (...) { } - - - // - // kSecCSContentInformation adds more information about the physical layout - // of the signed code. This is (only) useful for packaging or patching-oriented - // applications. - // - if (flags & kSecCSContentInformation) - if (CFRef files = mRep->modifiedFiles()) - CFDictionaryAddValue(dict, kSecCodeInfoChangedFiles, files); - - return dict.yield(); -} - - -// -// Resource validation contexts. -// The default context simply throws a CSError, rudely terminating the operation. -// -SecStaticCode::ValidationContext::~ValidationContext() -{ /* virtual */ } - -void SecStaticCode::ValidationContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value) -{ - CSError::throwMe(rc, type, value); -} - -void SecStaticCode::CollectingContext::reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value) -{ - StLock _(mLock); - if (mStatus == errSecSuccess) - mStatus = rc; // record first failure for eventual error return - if (type) { - if (!mCollection) - mCollection.take(makeCFMutableDictionary()); - CFMutableArrayRef element = CFMutableArrayRef(CFDictionaryGetValue(mCollection, type)); - if (!element) { - element = makeCFMutableArray(0); - if (!element) - CFError::throwMe(); - CFDictionaryAddValue(mCollection, type, element); - CFRelease(element); - } - CFArrayAppendValue(element, value); - } -} - -void SecStaticCode::CollectingContext::throwMe() -{ - assert(mStatus != errSecSuccess); - throw CSError(mStatus, mCollection.retain()); -} - - -// -// Master validation driver. -// This is the static validation (only) driver for the API. -// -// SecStaticCode exposes an a la carte menu of topical validators applying -// to a given object. The static validation API pulls them together reliably, -// but it also adds two matrix dimensions: architecture (for "fat" Mach-O binaries) -// and nested code. This function will crawl a suitable cross-section of this -// validation matrix based on which options it is given, creating temporary -// SecStaticCode objects on the fly to complete the task. -// (The point, of course, is to do as little duplicate work as possible.) -// -void SecStaticCode::staticValidate(SecCSFlags flags, const SecRequirement *req) -{ - setValidationFlags(flags); - - // initialize progress/cancellation state - if (flags & kSecCSReportProgress) - prepareProgress(estimateResourceWorkload() + 2); // +1 head, +1 tail - - // core components: once per architecture (if any) - this->staticValidateCore(flags, req); - if (flags & kSecCSCheckAllArchitectures) - handleOtherArchitectures(^(SecStaticCode* subcode) { - if (flags & kSecCSCheckGatekeeperArchitectures) { - Universal *fat = subcode->diskRep()->mainExecutableImage(); - assert(fat && fat->narrowed()); // handleOtherArchitectures gave us a focused architecture slice - Architecture arch = fat->bestNativeArch(); // actually, the ONLY one - if ((arch.cpuType() & ~CPU_ARCH_MASK) == CPU_TYPE_POWERPC) - return; // irrelevant to Gatekeeper - } - subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) architecture - subcode->staticValidateCore(flags, req); - }); - reportProgress(); - - // allow monitor intervention in source validation phase - reportEvent(CFSTR("prepared"), NULL); - - // resources: once for all architectures - if (!(flags & kSecCSDoNotValidateResources)) - this->validateResources(flags); - - // perform strict validation if desired - if (flags & kSecCSStrictValidate) - mRep->strictValidate(codeDirectory(), mTolerateErrors); - reportProgress(); - - // allow monitor intervention - if (CFRef veto = reportEvent(CFSTR("validated"), NULL)) { - if (CFGetTypeID(veto) == CFNumberGetTypeID()) - MacOSError::throwMe(cfNumber(veto.as())); - else - MacOSError::throwMe(errSecCSBadCallbackValue); - } -} - -void SecStaticCode::staticValidateCore(SecCSFlags flags, const SecRequirement *req) -{ - try { - this->validateNonResourceComponents(); // also validates the CodeDirectory - if (!(flags & kSecCSDoNotValidateExecutable)) - this->validateExecutable(); - if (req) - this->validateRequirement(req->requirement(), errSecCSReqFailed); - } catch (CSError &err) { - if (Universal *fat = this->diskRep()->mainExecutableImage()) // Mach-O - if (MachO *mach = fat->architecture()) { - err.augment(kSecCFErrorArchitecture, CFTempString(mach->architecture().displayName())); - delete mach; - } - throw; - } catch (const MacOSError &err) { - // add architecture information if we can get it - if (Universal *fat = this->diskRep()->mainExecutableImage()) - if (MachO *mach = fat->architecture()) { - CFTempString arch(mach->architecture().displayName()); - delete mach; - CSError::throwMe(err.error, kSecCFErrorArchitecture, arch); - } - throw; - } -} - - -// -// A helper that generates SecStaticCode objects for all but the primary architecture -// of a fat binary and calls a block on them. -// If there's only one architecture (or this is an architecture-agnostic code), -// nothing happens quickly. -// -void SecStaticCode::handleOtherArchitectures(void (^handle)(SecStaticCode* other)) -{ - if (Universal *fat = this->diskRep()->mainExecutableImage()) { - Universal::Architectures architectures; - fat->architectures(architectures); - if (architectures.size() > 1) { - DiskRep::Context ctx; - size_t activeOffset = fat->archOffset(); - for (Universal::Architectures::const_iterator arch = architectures.begin(); arch != architectures.end(); ++arch) { - ctx.offset = fat->archOffset(*arch); - if (ctx.offset > SIZE_MAX) - MacOSError::throwMe(errSecCSInternalError); - ctx.size = fat->lengthOfSlice((size_t)ctx.offset); - if (ctx.offset != activeOffset) { // inactive architecture; check it - SecPointer subcode = new SecStaticCode(DiskRep::bestGuess(this->mainExecutablePath(), &ctx)); - subcode->detachedSignature(this->mDetachedSig); // carry over explicit (but not implicit) detached signature - if (this->teamID() == NULL || subcode->teamID() == NULL) { - if (this->teamID() != subcode->teamID()) - MacOSError::throwMe(errSecCSSignatureInvalid); - } else if (strcmp(this->teamID(), subcode->teamID()) != 0) - MacOSError::throwMe(errSecCSSignatureInvalid); - handle(subcode); - } - } - } - } -} - -// -// A method that takes a certificate chain (certs) and evaluates -// if it is a Mac or IPhone developer cert, an app store distribution cert, -// or a developer ID -// -bool SecStaticCode::isAppleDeveloperCert(CFArrayRef certs) -{ - static const std::string appleDeveloperRequirement = "(" + std::string(WWDRRequirement) + ") or (" + MACWWDRRequirement + ") or (" + developerID + ") or (" + distributionCertificate + ") or (" + iPhoneDistributionCert + ")"; - SecPointer req = new SecRequirement(parseRequirement(appleDeveloperRequirement), true); - Requirement::Context ctx(certs, NULL, NULL, "", NULL); - - return req->requirement()->validates(ctx); -} - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/StaticCode.h b/OSX/include/security_codesigning/StaticCode.h deleted file mode 100644 index c74ae3e7..00000000 --- a/OSX/include/security_codesigning/StaticCode.h +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// StaticCode - SecStaticCode API objects -// -#ifndef _H_STATICCODE -#define _H_STATICCODE - -#include "cs.h" -#include "csutilities.h" -#include "Requirements.h" -#include "requirement.h" -#include "diskrep.h" -#include "codedirectory.h" -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -class SecCode; - - -// -// A SecStaticCode object represents the file system version of some code. -// There's a lot of pieces to this, and we'll bring them all into -// memory here (lazily) and let you fondle them with ease. -// -// Note that concrete knowledge of where stuff is stored resides in the DiskRep -// object we hold. DiskReps allocate, retrieve, and return data to us. We are -// responsible for interpreting, caching, and validating them. (In other words, -// DiskReps know where stuff is and how it is stored, but we know what it means.) -// -// Data accessors (returning CFDataRef, CFDictionaryRef, various pointers, etc.) -// cache those values internally and return unretained(!) references ("Get" style) -// that are valid as long as the SecStaticCode object's lifetime, or until -// resetValidity() is called, whichever is sooner. If you need to keep them longer, -// retain or copy them as needed. -// -class SecStaticCode : public SecCFObject { - NOCOPY(SecStaticCode) - -protected: - // - // A context for resource validation operations, to tailor error response. - // The base class throws an exception immediately and ignores detail data. - // - class ValidationContext { - public: - ValidationContext(SecStaticCode &c) : code(c) { } - virtual ~ValidationContext(); - virtual void reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value); - - virtual OSStatus osStatus() { return noErr; } - virtual void throwMe() { } - - SecStaticCode &code; - }; - - // - // A CollectingContext collects all error details and throws an annotated final error. - // - class CollectingContext : public ValidationContext { - public: - CollectingContext(SecStaticCode &c) : ValidationContext(c), mStatus(errSecSuccess) { } - void reportProblem(OSStatus rc, CFStringRef type, CFTypeRef value); - - OSStatus osStatus() { return mStatus; } - operator OSStatus () const { return mStatus; } - void throwMe() __attribute__((noreturn)); - - private: - CFRef mCollection; - OSStatus mStatus; - Mutex mLock; - }; - -public: - SECCFFUNCTIONS(SecStaticCode, SecStaticCodeRef, - errSecCSInvalidObjectRef, gCFObjects().StaticCode) - - // implicitly convert SecCodeRefs to their SecStaticCodeRefs - static SecStaticCode *requiredStatic(SecStaticCodeRef ref); // convert SecCodeRef - static SecCode *optionalDynamic(SecStaticCodeRef ref); // extract SecCodeRef or NULL if static - - SecStaticCode(DiskRep *rep); - virtual ~SecStaticCode() throw(); - - void initializeFromParent(const SecStaticCode& parent); - - bool equal(SecCFObject &other); - CFHashCode hash(); - - void detachedSignature(CFDataRef sig); // attach an explicitly given detached signature - void checkForSystemSignature(); // check for and attach system-supplied detached signature - - const CodeDirectory *codeDirectory(bool check = true); - CFDataRef cdHash(); - CFDataRef signature(); - CFAbsoluteTime signingTime(); - CFAbsoluteTime signingTimestamp(); - bool isSigned() { return codeDirectory(false) != NULL; } - DiskRep *diskRep() { return mRep; } - bool isDetached() const { return mRep->base() != mRep; } - std::string mainExecutablePath() { return mRep->mainExecutablePath(); } - CFURLRef copyCanonicalPath() const { return mRep->copyCanonicalPath(); } - std::string identifier() { return codeDirectory()->identifier(); } - const char *teamID() { return codeDirectory()->teamID(); } - std::string format() const { return mRep->format(); } - std::string signatureSource(); - virtual CFDataRef component(CodeDirectory::SpecialSlot slot, OSStatus fail = errSecCSSignatureFailed); - virtual CFDictionaryRef infoDictionary(); - - CFDictionaryRef entitlements(); - - CFDictionaryRef resourceDictionary(bool check = true); - CFURLRef resourceBase(); - CFDataRef resource(std::string path); - CFDataRef resource(std::string path, ValidationContext &ctx); - void validateResource(CFDictionaryRef files, std::string path, bool isSymlink, ValidationContext &ctx, SecCSFlags flags, uint32_t version); - void validateSymlinkResource(std::string fullpath, std::string seal, ValidationContext &ctx, SecCSFlags flags); - - bool flag(uint32_t tested); - - SecCodeCallback monitor() const { return mMonitor; } - void setMonitor(SecCodeCallback monitor) { mMonitor = monitor; } - CFTypeRef reportEvent(CFStringRef stage, CFDictionaryRef info); - void reportProgress(unsigned amount = 1); - - void setValidationFlags(SecCSFlags flags) { mValidationFlags = flags; } - void setValidationModifiers(CFDictionaryRef modifiers); - - void resetValidity(); // clear validation caches (if something may have changed) - - bool validated() const { return mValidated; } - bool revocationChecked() const { return mRevocationChecked; } - bool valid() const - { assert(validated()); return mValidated && (mValidationResult == errSecSuccess); } - bool validatedExecutable() const { return mExecutableValidated; } - bool validatedResources() const { return mResourcesValidated; } - - void prepareProgress(unsigned workload); - void cancelValidation(); - - void validateDirectory(); - virtual void validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail = errSecCSSignatureFailed); - void validateNonResourceComponents(); - unsigned estimateResourceWorkload(); - void validateResources(SecCSFlags flags); - void validateExecutable(); - void validateNestedCode(CFURLRef path, const ResourceSeal &seal, SecCSFlags flags, bool isFramework); - - const Requirements *internalRequirements(); - const Requirement *internalRequirement(SecRequirementType type); - const Requirement *designatedRequirement(); - const Requirement *defaultDesignatedRequirement(); // newly allocated (caller owns) - - void validateRequirements(SecRequirementType type, SecStaticCode *target, - OSStatus nullError = errSecSuccess); // target against my [type], throws - void validateRequirement(const Requirement *req, OSStatus failure); // me against [req], throws - bool satisfiesRequirement(const Requirement *req, OSStatus failure); // me against [req], returns on clean miss - - // certificates are available after signature validation (they are stored in the CMS signature) - SecCertificateRef cert(int ix); // get a cert from the cert chain - CFArrayRef certificates(); // get the entire certificate chain - - CFDictionaryRef signingInformation(SecCSFlags flags); // omnibus information-gathering API (creates new dictionary) - - static bool isAppleDeveloperCert(CFArrayRef certs); // determines if this is an apple developer certificate for libraray validation - -public: - void staticValidate(SecCSFlags flags, const SecRequirement *req); - void staticValidateCore(SecCSFlags flags, const SecRequirement *req); - -protected: - CFDictionaryRef getDictionary(CodeDirectory::SpecialSlot slot, bool check = true); // component value as a dictionary - bool verifySignature(); - CFArrayRef verificationPolicies(); - - static void checkOptionalResource(CFTypeRef key, CFTypeRef value, void *context); - bool hasWeakResourceRules(CFDictionaryRef rulesDict, uint32_t version, CFArrayRef allowedOmissions); - - void handleOtherArchitectures(void (^handle)(SecStaticCode* other)); - -private: - void validateOtherVersions(CFURLRef path, SecCSFlags flags, SecRequirementRef req, SecStaticCode *code); - -private: - RefPointer mRep; // on-disk representation - CFRef mDetachedSig; // currently applied explicit detached signature - - // private validation modifiers (only used by Gatekeeper checkfixes) - MacOSErrorSet mTolerateErrors; // soft error conditions to ignore - CFRef mAllowOmissions; // additionally allowed resource omissions - - // master validation state - bool mValidated; // core validation was attempted - bool mRevocationChecked; // the signature was checked for revocation - OSStatus mValidationResult; // outcome of core validation - bool mValidationExpired; // outcome had expired certificates - - // static executable validation state (nested within mValidated/mValid) - bool mExecutableValidated; // tried to validate executable file - OSStatus mExecutableValidResult; // outcome if mExecutableValidated - - // static resource validation state (nested within mValidated/mValid) - bool mResourcesValidated; // tried to validate resources - bool mResourcesDeep; // cached validation was deep - OSStatus mResourcesValidResult; // outcome if mResourceValidated or... - ValidationContext *mResourcesValidContext; // resource error reporting funnel - - // validation progress state (set when static validation starts) - SecCSFlags mValidationFlags; // API flags passed to static validation - unsigned mTotalWork; // total expected work (arbitrary units) - unsigned mCurrentWork; // currently completed work - bool mCancelPending; // cancellation was requested - Dispatch::Queue mProgressQueue; // progress reporting queue - - // nested validation support - const SecStaticCode *mOuterScope; // containing code (if this is a nested validation; weak) - ResourceBuilder *mResourceScope; // current Resource validation stack (while validating; weak) - - - // cached contents - CFRef mDir; // code directory data - CFRef mSignature; // CMS signature data - CFAbsoluteTime mSigningTime; // (signed) signing time - CFAbsoluteTime mSigningTimestamp; // Timestamp time (from timestamping authority) - CFRef mCache[cdSlotCount]; // NULL => not tried, kCFNull => absent, other => present - - // alternative cache forms (storage may depend on cached contents above) - CFRef mInfoDict; // derived from mCache slot - CFRef mEntitlements; // derived from mCache slot - CFRef mResourceDict; // derived from mCache slot - const Requirement *mDesignatedReq; // cached designated req if we made one up - CFRef mCDHash; // hash of CodeDirectory - - bool mGotResourceBase; // asked mRep for resourceBasePath - CFRef mResourceBase; // URL form of resource base directory - - SecCodeCallback mMonitor; // registered monitor callback - - LimitedAsync *mLimitedAsync; // limited async workers for verification - - // signature verification outcome (mTrust == NULL => not done yet) - CFRef mTrust; // outcome of crypto validation (valid or not) - CFRef mCertChain; - CSSM_TP_APPLE_EVIDENCE_INFO *mEvalDetails; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_STATICCODE diff --git a/OSX/include/security_codesigning/antlrplugin.cpp b/OSX/include/security_codesigning/antlrplugin.cpp deleted file mode 100644 index 0e4dee56..00000000 --- a/OSX/include/security_codesigning/antlrplugin.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2007,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include "antlrplugin.h" -#include "cserror.h" -#include "RequirementLexer.hpp" -#include "RequirementParser.hpp" -#include - - -namespace Security { -namespace CodeSigning { - -namespace Parser = Security_CodeSigning; - - -// -// Lexer input adapters -// -class StdioInputStream : public antlr::InputBuffer { -public: - StdioInputStream(FILE *fp) : mFile(fp) { } - int getChar() { return fgetc(mFile); } - -private: - FILE *mFile; -}; - -class StringInputStream : public antlr::InputBuffer { -public: - StringInputStream(const string &s) : mInput(s), mPos(mInput.begin()) { } - int getChar() { return (mPos == mInput.end()) ? EOF : *mPos++; } - -private: - string mInput; - string::const_iterator mPos; -}; - - -// -// Generic parser driver -// -template -const Result *parse(Source source, Result *(Parser::RequirementParser::*rule)(), std::string &errors) -{ - Input input(source); - Parser::RequirementLexer lexer(input); - Parser::RequirementParser parser(lexer); - try { - const Result *result = (parser.*rule)(); - errors = parser.errors; - if (errors.empty()) - return result; - else - ::free((void *)result); - } catch (const antlr::TokenStreamException &ex) { - errors = ex.toString() + "\n"; - } - return NULL; // signal failure -} - - -// -// Hook up each supported parsing action to the plugin interface -// -static -const Requirement *fileRequirement(FILE *source, string &errors) -{ return parse(source, &Parser::RequirementParser::requirement, errors); } - -static -const Requirement *stringRequirement(string source, string &errors) -{ return parse(source, &Parser::RequirementParser::requirement, errors); } - -static -const Requirements *fileRequirements(FILE *source, string &errors) -{ return parse(source, &Parser::RequirementParser::requirementSet, errors); } - -static -const Requirements *stringRequirements(string source, string &errors) -{ return parse(source, &Parser::RequirementParser::requirementSet, errors); } - -static -const BlobCore *fileGeneric(FILE *source, string &errors) -{ return parse(source, &Parser::RequirementParser::autosense, errors); } - -static -const BlobCore *stringGeneric(string source, string &errors) -{ return parse(source, &Parser::RequirementParser::autosense, errors); } - - -// -// Basic plugin hookup -// -static AntlrPlugin plugin = { - fileRequirement, - fileRequirements, - fileGeneric, - stringRequirement, - stringRequirements, - stringGeneric -}; - -AntlrPlugin *findAntlrPlugin() -{ - return &plugin; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/antlrplugin.h b/OSX/include/security_codesigning/antlrplugin.h deleted file mode 100644 index 6ebb0abc..00000000 --- a/OSX/include/security_codesigning/antlrplugin.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Plugin interface for internal Security plug-ins -// -#ifndef _H_ANTLRPLUGIN -#define _H_ANTLRPLUGIN - -#include -#include "requirement.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// The plugin proxy. -// -// During loading, one instance of this object will be created by the plugin -// and returned through the (one and only) dynamically-linked method of the plugin. -// All further interaction then proceeds through methods of this object. -// -// -class AntlrPlugin { -public: - typedef const Requirement *FileRequirement(std::FILE *source, std::string &errors); - FileRequirement *fileRequirement; - typedef const Requirements *FileRequirements(std::FILE *source, std::string &errors); - FileRequirements *fileRequirements; - typedef const BlobCore *FileGeneric(std::FILE *source, std::string &errors); - FileGeneric *fileGeneric; - typedef const Requirement *StringRequirement(std::string source, std::string &errors); - StringRequirement *stringRequirement; - typedef const Requirements *StringRequirements(std::string source, std::string &errors); - StringRequirements *stringRequirements; - typedef const BlobCore *StringGeneric(std::string source, std::string &errors); - StringGeneric *stringGeneric; -}; - -extern "C" { - AntlrPlugin *findAntlrPlugin(); - typedef AntlrPlugin *FindAntlrPlugin(); -} - -#define FINDANTLRPLUGIN "findAntlrPlugin" - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_ANTLRPLUGIN diff --git a/OSX/include/security_codesigning/bundlediskrep.cpp b/OSX/include/security_codesigning/bundlediskrep.cpp deleted file mode 100644 index cf3a41d8..00000000 --- a/OSX/include/security_codesigning/bundlediskrep.cpp +++ /dev/null @@ -1,691 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "bundlediskrep.h" -#include "filediskrep.h" -#include "dirscanner.h" -#include -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Local helpers -// -static std::string findDistFile(const std::string &directory); - - -// -// We make a CFBundleRef immediately, but everything else is lazy -// -BundleDiskRep::BundleDiskRep(const char *path, const Context *ctx) - : mBundle(CFBundleCreate(NULL, CFTempURL(path))) -{ - if (!mBundle) - MacOSError::throwMe(errSecCSBadBundleFormat); - setup(ctx); - CODESIGN_DISKREP_CREATE_BUNDLE_PATH(this, (char*)path, (void*)ctx, mExecRep); -} - -BundleDiskRep::BundleDiskRep(CFBundleRef ref, const Context *ctx) -{ - mBundle = ref; // retains - setup(ctx); - CODESIGN_DISKREP_CREATE_BUNDLE_REF(this, ref, (void*)ctx, mExecRep); -} - -BundleDiskRep::~BundleDiskRep() -{ -} - -void BundleDiskRep::checkMoved(CFURLRef oldPath, CFURLRef newPath) -{ - char cOld[PATH_MAX]; - char cNew[PATH_MAX]; - // The realpath call is important because alot of Framework bundles have a symlink - // to their "Current" version binary in the main bundle - if (realpath(cfString(oldPath).c_str(), cOld) == NULL || - realpath(cfString(newPath).c_str(), cNew) == NULL) - MacOSError::throwMe(errSecCSInternalError); - - if (strcmp(cOld, cNew) != 0) - recordStrictError(errSecCSAmbiguousBundleFormat); -} - -// common construction code -void BundleDiskRep::setup(const Context *ctx) -{ - mInstallerPackage = false; // default - - // capture the path of the main executable before descending into a specific version - CFRef mainExecBefore = CFBundleCopyExecutableURL(mBundle); - CFRef infoPlistBefore = _CFBundleCopyInfoPlistURL(mBundle); - - // validate the bundle root; fish around for the desired framework version - string root = cfStringRelease(copyCanonicalPath()); - string contents = root + "/Contents"; - string supportFiles = root + "/Support Files"; - string version = root + "/Versions/" - + ((ctx && ctx->version) ? ctx->version : "Current") - + "/."; - if (::access(contents.c_str(), F_OK) == 0) { // not shallow - DirValidator val; - val.require("^Contents$", DirValidator::directory); // duh - val.allow("^(\\.LSOverride|\\.DS_Store|Icon\r|\\.SoftwareDepot\\.tracking)$", DirValidator::file | DirValidator::noexec); - try { - val.validate(root, errSecCSUnsealedAppRoot); - } catch (const MacOSError &err) { - recordStrictError(err.error); - } - } else if (::access(supportFiles.c_str(), F_OK) == 0) { // ancient legacy boondoggle bundle - // treat like a shallow bundle; do not allow Versions arbitration - } else if (::access(version.c_str(), F_OK) == 0) { // versioned bundle - if (CFBundleRef versionBundle = CFBundleCreate(NULL, CFTempURL(version))) - mBundle.take(versionBundle); // replace top bundle ref - else - MacOSError::throwMe(errSecCSStaticCodeNotFound); - validateFrameworkRoot(root); - } else { - if (ctx && ctx->version) // explicitly specified - MacOSError::throwMe(errSecCSStaticCodeNotFound); - } - - CFDictionaryRef infoDict = CFBundleGetInfoDictionary(mBundle); - assert(infoDict); // CFBundle will always make one up for us - CFTypeRef mainHTML = CFDictionaryGetValue(infoDict, CFSTR("MainHTML")); - CFTypeRef packageVersion = CFDictionaryGetValue(infoDict, CFSTR("IFMajorVersion")); - - // conventional executable bundle: CFBundle identifies an executable for us - if (CFRef mainExec = CFBundleCopyExecutableURL(mBundle)) // if CFBundle claims an executable... - if (mainHTML == NULL) { // ... and it's not a widget - - // Note that this check is skipped if there is a specific framework version checked. - // That's because you know what you are doing if you are looking at a specific version. - // This check is designed to stop someone who did a verification on an app root, from mistakenly - // verifying a framework - if (!ctx || !ctx->version) { - if (mainExecBefore) - checkMoved(mainExecBefore, mainExec); - if (infoPlistBefore) - if (CFRef infoDictPath = _CFBundleCopyInfoPlistURL(mBundle)) - checkMoved(infoPlistBefore, infoDictPath); - } - - mMainExecutableURL = mainExec; - mExecRep = DiskRep::bestFileGuess(this->mainExecutablePath(), ctx); - if (!mExecRep->fd().isPlainFile(this->mainExecutablePath())) - recordStrictError(errSecCSRegularFile); - mFormat = "bundle with " + mExecRep->format(); - return; - } - - // widget - if (mainHTML) { - if (CFGetTypeID(mainHTML) != CFStringGetTypeID()) - MacOSError::throwMe(errSecCSBadBundleFormat); - mMainExecutableURL.take(makeCFURL(cfString(CFStringRef(mainHTML)), false, - CFRef(CFBundleCopySupportFilesDirectoryURL(mBundle)))); - if (!mMainExecutableURL) - MacOSError::throwMe(errSecCSBadBundleFormat); - mExecRep = new FileDiskRep(this->mainExecutablePath().c_str()); - if (!mExecRep->fd().isPlainFile(this->mainExecutablePath())) - recordStrictError(errSecCSRegularFile); - mFormat = "widget bundle"; - return; - } - - // do we have a real Info.plist here? - if (CFRef infoURL = _CFBundleCopyInfoPlistURL(mBundle)) { - // focus on the Info.plist (which we know exists) as the nominal "main executable" file - mMainExecutableURL = infoURL; - mExecRep = new FileDiskRep(this->mainExecutablePath().c_str()); - if (!mExecRep->fd().isPlainFile(this->mainExecutablePath())) - recordStrictError(errSecCSRegularFile); - if (packageVersion) { - mInstallerPackage = true; - mFormat = "installer package bundle"; - } else { - mFormat = "bundle"; - } - return; - } - - // we're getting desperate here. Perhaps an oldish-style installer package? Look for a *.dist file - std::string distFile = findDistFile(this->resourcesRootPath()); - if (!distFile.empty()) { - mMainExecutableURL = makeCFURL(distFile); - mExecRep = new FileDiskRep(this->mainExecutablePath().c_str()); - if (!mExecRep->fd().isPlainFile(this->mainExecutablePath())) - recordStrictError(errSecCSRegularFile); - mInstallerPackage = true; - mFormat = "installer package bundle"; - return; - } - - // this bundle cannot be signed - MacOSError::throwMe(errSecCSBadBundleFormat); -} - - -// -// Return the full path to the one-and-only file named something.dist in a directory. -// Return empty string if none; throw an exception if multiple. Do not descend into subdirectories. -// -static std::string findDistFile(const std::string &directory) -{ - std::string found; - char *paths[] = {(char *)directory.c_str(), NULL}; - FTS *fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_NOSTAT, NULL); - bool root = true; - while (FTSENT *ent = fts_read(fts)) { - switch (ent->fts_info) { - case FTS_F: - case FTS_NSOK: - if (!strcmp(ent->fts_path + ent->fts_pathlen - 5, ".dist")) { // found plain file foo.dist - if (found.empty()) // first found - found = ent->fts_path; - else // multiple *.dist files (bad) - MacOSError::throwMe(errSecCSBadBundleFormat); - } - break; - case FTS_D: - if (!root) - fts_set(fts, ent, FTS_SKIP); // don't descend - root = false; - break; - default: - break; - } - } - fts_close(fts); - return found; -} - - -// -// Create a path to a bundle signing resource, by name. -// If the BUNDLEDISKREP_DIRECTORY directory exists in the bundle's support directory, files -// will be read and written there. Otherwise, they go directly into the support directory. -// -string BundleDiskRep::metaPath(const char *name) -{ - if (mMetaPath.empty()) { - string support = cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle)); - mMetaPath = support + "/" BUNDLEDISKREP_DIRECTORY; - if (::access(mMetaPath.c_str(), F_OK) == 0) { - mMetaExists = true; - } else { - mMetaPath = support; - mMetaExists = false; - } - } - return mMetaPath + "/" + name; -} - - -// -// Try to create the meta-file directory in our bundle. -// Does nothing if the directory already exists. -// Throws if an error occurs. -// -void BundleDiskRep::createMeta() -{ - string meta = metaPath(BUNDLEDISKREP_DIRECTORY); - if (!mMetaExists) { - if (::mkdir(meta.c_str(), 0755) == 0) { - copyfile(cfStringRelease(copyCanonicalPath()).c_str(), meta.c_str(), NULL, COPYFILE_SECURITY); - mMetaPath = meta; - mMetaExists = true; - } else if (errno != EEXIST) - UnixError::throwMe(); - } -} - -// -// Load's a CFURL and makes sure that it is a regular file and not a symlink (or fifo, etc.) -// -CFDataRef BundleDiskRep::loadRegularFile(CFURLRef url) -{ - assert(url); - - CFDataRef data = NULL; - - std::string path(cfString(url)); - - AutoFileDesc fd(path); - - if (!fd.isPlainFile(path)) - recordStrictError(errSecCSRegularFile); - - data = cfLoadFile(fd, fd.fileSize()); - - if (!data) { - secdebug(__PRETTY_FUNCTION__, "failed to load %s", cfString(url).c_str()); - MacOSError::throwMe(errSecCSInternalError); - } - - return data; -} - -// -// Load and return a component, by slot number. -// Info.plist components come from the bundle, always (we don't look -// for Mach-O embedded versions). -// Everything else comes from the embedded blobs of a Mach-O image, or from -// files located in the Contents directory of the bundle. -// -CFDataRef BundleDiskRep::component(CodeDirectory::SpecialSlot slot) -{ - switch (slot) { - // the Info.plist comes from the magic CFBundle-indicated place and ONLY from there - case cdInfoSlot: - if (CFRef info = _CFBundleCopyInfoPlistURL(mBundle)) - return loadRegularFile(info); - else - return NULL; - // by default, we take components from the executable image or files - default: - if (CFDataRef data = mExecRep->component(slot)) - return data; - // falling through - // but the following always come from files - case cdResourceDirSlot: - if (const char *name = CodeDirectory::canonicalSlotName(slot)) - return metaData(name); - else - return NULL; - } -} - - -// -// The binary identifier is taken directly from the main executable. -// -CFDataRef BundleDiskRep::identification() -{ - return mExecRep->identification(); -} - - -// -// Various aspects of our DiskRep personality. -// -CFURLRef BundleDiskRep::copyCanonicalPath() -{ - if (CFURLRef url = CFBundleCopyBundleURL(mBundle)) - return url; - CFError::throwMe(); -} - -string BundleDiskRep::mainExecutablePath() -{ - return cfString(mMainExecutableURL); -} - -string BundleDiskRep::resourcesRootPath() -{ - return cfStringRelease(CFBundleCopySupportFilesDirectoryURL(mBundle)); -} - -void BundleDiskRep::adjustResources(ResourceBuilder &builder) -{ - // exclude entire contents of meta directory - builder.addExclusion("^" BUNDLEDISKREP_DIRECTORY "$"); - builder.addExclusion("^" CODERESOURCES_LINK "$"); // ancient-ish symlink into it - - // exclude the store manifest directory - builder.addExclusion("^" STORE_RECEIPT_DIRECTORY "$"); - - // exclude the main executable file - string resources = resourcesRootPath(); - if (resources.compare(resources.size() - 2, 2, "/.") == 0) // chop trailing /. - resources = resources.substr(0, resources.size()-2); - string executable = mainExecutablePath(); - if (!executable.compare(0, resources.length(), resources, 0, resources.length()) - && executable[resources.length()] == '/') // is proper directory prefix - builder.addExclusion(string("^") - + ResourceBuilder::escapeRE(executable.substr(resources.length()+1)) + "$", ResourceBuilder::softTarget); -} - - - -Universal *BundleDiskRep::mainExecutableImage() -{ - return mExecRep->mainExecutableImage(); -} - -size_t BundleDiskRep::signingBase() -{ - return mExecRep->signingBase(); -} - -size_t BundleDiskRep::signingLimit() -{ - return mExecRep->signingLimit(); -} - -string BundleDiskRep::format() -{ - return mFormat; -} - -CFArrayRef BundleDiskRep::modifiedFiles() -{ - CFMutableArrayRef files = CFArrayCreateMutableCopy(NULL, 0, mExecRep->modifiedFiles()); - checkModifiedFile(files, cdCodeDirectorySlot); - checkModifiedFile(files, cdSignatureSlot); - checkModifiedFile(files, cdResourceDirSlot); - checkModifiedFile(files, cdEntitlementSlot); - return files; -} - -void BundleDiskRep::checkModifiedFile(CFMutableArrayRef files, CodeDirectory::SpecialSlot slot) -{ - if (CFDataRef data = mExecRep->component(slot)) // provided by executable file - CFRelease(data); - else if (const char *resourceName = CodeDirectory::canonicalSlotName(slot)) { - string file = metaPath(resourceName); - if (::access(file.c_str(), F_OK) == 0) - CFArrayAppendValue(files, CFTempURL(file)); - } -} - -FileDesc &BundleDiskRep::fd() -{ - return mExecRep->fd(); -} - -void BundleDiskRep::flush() -{ - mExecRep->flush(); -} - - -// -// Defaults for signing operations -// -string BundleDiskRep::recommendedIdentifier(const SigningContext &) -{ - if (CFStringRef identifier = CFBundleGetIdentifier(mBundle)) - return cfString(identifier); - if (CFDictionaryRef infoDict = CFBundleGetInfoDictionary(mBundle)) - if (CFStringRef identifier = CFStringRef(CFDictionaryGetValue(infoDict, kCFBundleNameKey))) - return cfString(identifier); - - // fall back to using the canonical path - return canonicalIdentifier(cfStringRelease(this->copyCanonicalPath())); -} - -string BundleDiskRep::resourcesRelativePath() -{ - // figure out the resource directory base. Clean up some gunk inserted by CFBundle in frameworks - string rbase = this->resourcesRootPath(); - size_t pos = rbase.find("/./"); // gratuitously inserted by CFBundle in some frameworks - while (pos != std::string::npos) { - rbase = rbase.replace(pos, 2, "", 0); - pos = rbase.find("/./"); - } - if (rbase.substr(rbase.length()-2, 2) == "/.") // produced by versioned bundle implicit "Current" case - rbase = rbase.substr(0, rbase.length()-2); // ... so take it off for this - - // find the resources directory relative to the resource base - string resources = cfStringRelease(CFBundleCopyResourcesDirectoryURL(mBundle)); - if (resources == rbase) - resources = ""; - else if (resources.compare(0, rbase.length(), rbase, 0, rbase.length()) != 0) // Resources not in resource root - MacOSError::throwMe(errSecCSBadBundleFormat); - else - resources = resources.substr(rbase.length() + 1) + "/"; // differential path segment - - return resources; -} - -CFDictionaryRef BundleDiskRep::defaultResourceRules(const SigningContext &ctx) -{ - string resources = this->resourcesRelativePath(); - - // installer package rules - if (mInstallerPackage) - return cfmake("{rules={" - "'^.*' = #T" // include everything, but... - "%s = {optional=#T, weight=1000}" // make localizations optional - "'^.*/.*\\.pkg/' = {omit=#T, weight=10000}" // and exclude all nested packages (by name) - "}}", - (string("^") + resources + ".*\\.lproj/").c_str() - ); - - // old (V1) executable bundle rules - compatible with before - if (ctx.signingFlags() & kSecCSSignV1) // *** must be exactly the same as before *** - return cfmake("{rules={" - "'^version.plist$' = #T" // include version.plist - "%s = #T" // include Resources - "%s = {optional=#T, weight=1000}" // make localizations optional - "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files - "}}", - (string("^") + resources).c_str(), - (string("^") + resources + ".*\\.lproj/").c_str(), - (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str() - ); - - // FMJ (everything is a resource) rules - if (ctx.signingFlags() & kSecCSSignOpaque) // Full Metal Jacket - everything is a resource file - return cfmake("{rules={" - "'^.*' = #T" // everything is a resource - "'^Info\\.plist$' = {omit=#T,weight=10}" // explicitly exclude this for backward compatibility - "}}"); - - // new (V2) executable bundle rules - return cfmake("{" // *** the new (V2) world *** - "rules={" // old (V1; legacy) version - "'^version.plist$' = #T" // include version.plist - "%s = #T" // include Resources - "%s = {optional=#T, weight=1000}" // make localizations optional - "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files - "},rules2={" - "'^.*' = #T" // include everything as a resource, with the following exceptions - "'^[^/]+$' = {nested=#T, weight=10}" // files directly in Contents - "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=10}" // dynamic repositories - "'.*\\.dSYM($|/)' = {weight=11}" // but allow dSYM directories in code locations (parallel to their code) - "'^(.*/)?\\.DS_Store$' = {omit=#T,weight=2000}" // ignore .DS_Store files - "'^Info\\.plist$' = {omit=#T, weight=20}" // excluded automatically now, but old systems need to be told - "'^version\\.plist$' = {weight=20}" // include version.plist as resource - "'^embedded\\.provisionprofile$' = {weight=20}" // include embedded.provisionprofile as resource - "'^PkgInfo$' = {omit=#T, weight=20}" // traditionally not included - "%s = {weight=20}" // Resources override default nested (widgets) - "%s = {optional=#T, weight=1000}" // make localizations optional - "%s = {omit=#T, weight=1100}" // exclude all locversion.plist files - "}}", - - (string("^") + resources).c_str(), - (string("^") + resources + ".*\\.lproj/").c_str(), - (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str(), - - (string("^") + resources).c_str(), - (string("^") + resources + ".*\\.lproj/").c_str(), - (string("^") + resources + ".*\\.lproj/locversion.plist$").c_str() - ); -} - - -CFArrayRef BundleDiskRep::allowedResourceOmissions() -{ - return cfmake("[" - "'^(.*/)?\\.DS_Store$'" - "'^Info\\.plist$'" - "'^PkgInfo$'" - "%s" - "]", - (string("^") + this->resourcesRelativePath() + ".*\\.lproj/locversion.plist$").c_str() - ); -} - - -const Requirements *BundleDiskRep::defaultRequirements(const Architecture *arch, const SigningContext &ctx) -{ - return mExecRep->defaultRequirements(arch, ctx); -} - -size_t BundleDiskRep::pageSize(const SigningContext &ctx) -{ - return mExecRep->pageSize(ctx); -} - - -// -// Strict validation. -// Takes an array of CFNumbers of errors to tolerate. -// -void BundleDiskRep::strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated) -{ - std::vector fatalErrors; - set_difference(mStrictErrors.begin(), mStrictErrors.end(), tolerated.begin(), tolerated.end(), back_inserter(fatalErrors)); - if (!fatalErrors.empty()) - MacOSError::throwMe(fatalErrors[0]); - mExecRep->strictValidate(cd, tolerated); -} - -void BundleDiskRep::recordStrictError(OSStatus error) -{ - mStrictErrors.insert(error); -} - - -// -// Check framework root for unsafe symlinks and unsealed content. -// -void BundleDiskRep::validateFrameworkRoot(string root) -{ - // build regex element that matches either the "Current" symlink, or the name of the current version - string current = "Current"; - char currentVersion[PATH_MAX]; - ssize_t len = ::readlink((root + "/Versions/Current").c_str(), currentVersion, sizeof(currentVersion)-1); - if (len > 0) { - currentVersion[len] = '\0'; - current = string("(Current|") + ResourceBuilder::escapeRE(currentVersion) + ")"; - } - - DirValidator val; - val.require("^Versions$", DirValidator::directory | DirValidator::descend); // descend into Versions directory - val.require("^Versions/[^/]+$", DirValidator::directory); // require at least one version - val.require("^Versions/Current$", DirValidator::symlink, // require Current symlink... - "^(\\./)?(\\.\\.[^/]+|\\.?[^\\./][^/]*)$"); // ...must point to a version - val.allow("^(Versions/)?\\.DS_Store$", DirValidator::file | DirValidator::noexec); // allow .DS_Store files - val.allow("^[^/]+$", DirValidator::symlink, ^ string (const string &name, const string &target) { - // top-level symlinks must point to namesake in current version - return string("^(\\./)?Versions/") + current + "/" + ResourceBuilder::escapeRE(name) + "$"; - }); - // module.map must be regular non-executable file, or symlink to module.map in current version - val.allow("^module\\.map$", DirValidator::file | DirValidator::noexec | DirValidator::symlink, - string("^(\\./)?Versions/") + current + "/module\\.map$"); - - try { - val.validate(root, errSecCSUnsealedFrameworkRoot); - } catch (const MacOSError &err) { - recordStrictError(err.error); - } -} - - -// -// Writers -// -DiskRep::Writer *BundleDiskRep::writer() -{ - return new Writer(this); -} - -BundleDiskRep::Writer::Writer(BundleDiskRep *r) - : rep(r), mMadeMetaDirectory(false) -{ - execWriter = rep->mExecRep->writer(); -} - - -// -// Write a component. -// Note that this isn't concerned with Mach-O writing; this is handled at -// a much higher level. If we're called, we write to a file in the Bundle's meta directory. -// -void BundleDiskRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - switch (slot) { - default: - if (!execWriter->attribute(writerLastResort)) // willing to take the data... - return execWriter->component(slot, data); // ... so hand it through - // execWriter doesn't want the data; store it as a resource file (below) - case cdResourceDirSlot: - // the resource directory always goes into a bundle file - if (const char *name = CodeDirectory::canonicalSlotName(slot)) { - rep->createMeta(); - string path = rep->metaPath(name); - AutoFileDesc fd(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); - fd.writeAll(CFDataGetBytePtr(data), CFDataGetLength(data)); - } else - MacOSError::throwMe(errSecCSBadBundleFormat); - } -} - - -// -// Remove all signature data -// -void BundleDiskRep::Writer::remove() -{ - // remove signature from the executable - execWriter->remove(); - - // remove signature files from bundle - for (CodeDirectory::SpecialSlot slot = 0; slot < cdSlotCount; slot++) - remove(slot); - remove(cdSignatureSlot); -} - -void BundleDiskRep::Writer::remove(CodeDirectory::SpecialSlot slot) -{ - if (const char *name = CodeDirectory::canonicalSlotName(slot)) - if (::unlink(rep->metaPath(name).c_str())) - switch (errno) { - case ENOENT: // not found - that's okay - break; - default: - UnixError::throwMe(); - } -} - - -void BundleDiskRep::Writer::flush() -{ - execWriter->flush(); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/bundlediskrep.h b/OSX/include/security_codesigning/bundlediskrep.h deleted file mode 100644 index b1b4db4b..00000000 --- a/OSX/include/security_codesigning/bundlediskrep.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// bundlediskrep - bundle directory disk representation -// -#ifndef _H_BUNDLEDISKREP -#define _H_BUNDLEDISKREP - -#include "diskrep.h" -#include "machorep.h" - -namespace Security { -namespace CodeSigning { - - -#define BUNDLEDISKREP_DIRECTORY "_CodeSignature" -#define CODERESOURCES_LINK "CodeResources" -#define STORE_RECEIPT_DIRECTORY "_MASReceipt" - - -// -// A BundleDiskRep represents a standard Mac OS X bundle on disk. -// The bundle is expected to have an Info.plist, and a "main executable file" -// of some sort (as indicated therein). -// The BundleDiskRep stores the necessary components in the main executable -// if it is in Mach-O format, or in files in a _CodeSignature directory if not. -// This DiskRep supports resource sealing. -// -class BundleDiskRep : public DiskRep { -public: - BundleDiskRep(const char *path, const Context *ctx = NULL); - BundleDiskRep(CFBundleRef ref, const Context *ctx = NULL); - ~BundleDiskRep(); - - CFDataRef component(CodeDirectory::SpecialSlot slot); - CFDataRef identification(); - std::string mainExecutablePath(); - CFURLRef copyCanonicalPath(); - std::string resourcesRootPath(); - std::string resourcesRelativePath(); - void adjustResources(ResourceBuilder &builder); - Universal *mainExecutableImage(); - size_t signingBase(); - size_t signingLimit(); - std::string format(); - CFArrayRef modifiedFiles(); - UnixPlusPlus::FileDesc &fd(); - void flush(); - - std::string recommendedIdentifier(const SigningContext &ctx); - CFDictionaryRef defaultResourceRules(const SigningContext &ctx); - const Requirements *defaultRequirements(const Architecture *arch, const SigningContext &ctx); - size_t pageSize(const SigningContext &ctx); - - void strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated); - CFArrayRef allowedResourceOmissions(); - - CFBundleRef bundle() const { return mBundle; } - -public: - Writer *writer(); - class Writer; - friend class Writer; - -protected: - std::string metaPath(const char *name); - CFDataRef metaData(const char *name) { return cfLoadFile(CFTempURL(metaPath(name))); } - void createMeta(); // (try to) create the meta-file directory - -private: - void setup(const Context *ctx); // shared init - void checkModifiedFile(CFMutableArrayRef files, CodeDirectory::SpecialSlot slot); - CFDataRef loadRegularFile(CFURLRef url); - void recordStrictError(OSStatus error); - void validateFrameworkRoot(std::string root); - void checkMoved(CFURLRef oldPath, CFURLRef newPath); - -private: - CFRef mBundle; - std::string mMetaPath; // path to directory containing signing files - bool mMetaExists; // separate meta-file directory exists - CFRef mMainExecutableURL; // chosen main executable URL - bool mInstallerPackage; // is an installer (not executable) bundle - string mFormat; // format description string - RefPointer mExecRep; // DiskRep for main executable file - std::set mStrictErrors; // strict validation errors encountered -}; - - -// -// Writers -// -// -class BundleDiskRep::Writer : public DiskRep::Writer { - friend class BundleDiskRep; -public: - Writer(BundleDiskRep *r); - - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); - void remove(); - void flush(); - -protected: - DiskRep *execRep() { return rep->mExecRep; } - void remove(CodeDirectory::SpecialSlot slot); - -protected: - RefPointer rep; - RefPointer execWriter; - bool mMadeMetaDirectory; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_BUNDLEDISKREP diff --git a/OSX/include/security_codesigning/cdbuilder.cpp b/OSX/include/security_codesigning/cdbuilder.cpp deleted file mode 100644 index 719a01b3..00000000 --- a/OSX/include/security_codesigning/cdbuilder.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cdbuilder - constructor for CodeDirectories -// -#include "cdbuilder.h" -#include -#include - -using namespace UnixPlusPlus; -using LowLevelMemoryUtilities::alignUp; - - -namespace Security { -namespace CodeSigning { - - -// -// Create an (empty) builder -// -CodeDirectory::Builder::Builder(HashAlgorithm digestAlgorithm) - : mFlags(0), - mHashType(digestAlgorithm), - mPlatform(0), - mSpecialSlots(0), - mCodeSlots(0), - mScatter(NULL), - mScatterSize(0), - mDir(NULL) -{ - mDigestLength = (uint32_t)MakeHash(this)->digestLength(); - mSpecial = (unsigned char *)calloc(cdSlotMax, mDigestLength); -} - -CodeDirectory::Builder::~Builder() -{ - ::free(mSpecial); - ::free(mScatter); -} - - -// -// Set the source of the main executable (i.e. the code pages) -// -void CodeDirectory::Builder::executable(string path, - size_t pagesize, size_t offset, size_t length) -{ - mExec.close(); // any previously opened one - mExec.open(path); - mPageSize = pagesize; - mExecOffset = offset; - mExecLength = length; -} - -void CodeDirectory::Builder::reopen(string path, size_t offset, size_t length) -{ - assert(mExec); // already called executable() - mExec.close(); - mExec.open(path); - mExecOffset = offset; - mExecLength = length; -} - - -// -// Set the source for one special slot -// -void CodeDirectory::Builder::specialSlot(SpecialSlot slot, CFDataRef data) -{ - assert(slot <= cdSlotMax); - MakeHash hash(this); - hash->update(CFDataGetBytePtr(data), CFDataGetLength(data)); - hash->finish(specialSlot(slot)); - if (slot >= mSpecialSlots) - mSpecialSlots = slot; -} - - -// -// Allocate a Scatter vector -// -CodeDirectory::Scatter *CodeDirectory::Builder::scatter(unsigned count) -{ - mScatterSize = (count + 1) * sizeof(Scatter); - if (!(mScatter = (Scatter *)::realloc(mScatter, mScatterSize))) - UnixError::throwMe(ENOMEM); - ::memset(mScatter, 0, mScatterSize); - return mScatter; -} - -// This calculates the fixed size of the code directory -// Because of , if the team ID -// field is not used, we leave out the team ID offset -// as well, to keep cd hashes consistent between -// versions. -const size_t CodeDirectory::Builder::fixedSize(const uint32_t version) -{ - size_t cdSize = sizeof(CodeDirectory); - if (version < supportsTeamID) - cdSize -= sizeof(mDir->teamIDOffset); - - return cdSize; -} - -// -// Calculate the size we'll need for the CodeDirectory as described so far -// -size_t CodeDirectory::Builder::size(const uint32_t version) -{ - assert(mExec); // must have called executable() - if (mExecLength == 0) - mExecLength = mExec.fileSize() - mExecOffset; - - // how many code pages? - if (mExecLength <= 0) { // no code, no slots - mCodeSlots = 0; - } else if (mPageSize == 0) { // indefinite - one page - mCodeSlots = 1; - } else { // finite - calculate from file size - mCodeSlots = (mExecLength - 1) / mPageSize + 1; - } - - size_t offset = fixedSize(version); - size_t offset0 = offset; - - offset += mScatterSize; // scatter vector - offset += mIdentifier.size() + 1; // size of identifier (with null byte) - if (mTeamID.size()) - offset += mTeamID.size() + 1; // size of teamID (with null byte) - offset += (mCodeSlots + mSpecialSlots) * mDigestLength; // hash vector - if (offset <= offset0) - UnixError::throwMe(ENOEXEC); - - return offset; -} - - -// -// Take everything added to date and wrap it up in a shiny new CodeDirectory. -// -// Note that this only constructs a CodeDirectory; it does not touch any subsidiary -// structures (resource tables, etc.), nor does it create any signature to secure -// the CodeDirectory. -// The returned CodeDirectory object is yours, and you may modify it as desired. -// But the memory layout is set here, so the various sizes and counts should be good -// when you call build(). -// It's up to us to order the dynamic fields as we wish; but note that we currently -// don't pad them, and so they should be allocated in non-increasing order of required -// alignment. Make sure to keep the code here in sync with the size-calculating code above. -// -CodeDirectory *CodeDirectory::Builder::build() -{ - assert(mExec); // must have (successfully) called executable() - uint32_t version; - - // size and allocate - size_t identLength = mIdentifier.size() + 1; - size_t teamIDLength = mTeamID.size() + 1; - - // Determine the version - if (mTeamID.size()) { - version = currentVersion; - } else { - version = supportsScatter; - } - - size_t total = size(version); - if (!(mDir = (CodeDirectory *)calloc(1, total))) // initialize to zero - UnixError::throwMe(ENOMEM); - - if (mExecLength > UINT32_MAX) - MacOSError::throwMe(errSecCSTooBig); - - // fill header - mDir->initialize(total); - mDir->version = version; - mDir->flags = mFlags; - mDir->nSpecialSlots = (uint32_t)mSpecialSlots; - mDir->nCodeSlots = (uint32_t)mCodeSlots; - mDir->codeLimit = (uint32_t)mExecLength; - mDir->hashType = mHashType; - mDir->platform = mPlatform; - mDir->hashSize = mDigestLength; - if (mPageSize) { - int pglog; - assert(frexp(mPageSize, &pglog) == 0.5); // must be power of 2 - frexp(mPageSize, &pglog); - assert(pglog < 256); - mDir->pageSize = pglog - 1; - } else - mDir->pageSize = 0; // means infinite page size - - // locate and fill flex fields - size_t offset = fixedSize(mDir->version); - - if (mScatter) { - mDir->scatterOffset = (uint32_t)offset; - memcpy(mDir->scatterVector(), mScatter, mScatterSize); - offset += mScatterSize; - } - - mDir->identOffset = (uint32_t)offset; - memcpy(mDir->identifier(), mIdentifier.c_str(), identLength); - offset += identLength; - - if (mTeamID.size()) { - mDir->teamIDOffset = (uint32_t)offset; - memcpy(mDir->teamID(), mTeamID.c_str(), teamIDLength); - offset += teamIDLength; - } - // (add new flexibly-allocated fields here) - - mDir->hashOffset = (uint32_t)(offset + mSpecialSlots * mDigestLength); - offset += (mSpecialSlots + mCodeSlots) * mDigestLength; - assert(offset == total); // matches allocated size - - // fill special slots - memset((*mDir)[(int)-mSpecialSlots], 0, mDigestLength * mSpecialSlots); - for (size_t slot = 1; slot <= mSpecialSlots; ++slot) - memcpy((*mDir)[(int)-slot], specialSlot((SpecialSlot)slot), mDigestLength); - - // fill code slots - mExec.seek(mExecOffset); - size_t remaining = mExecLength; - for (unsigned int slot = 0; slot < mCodeSlots; ++slot) { - size_t thisPage = min(mPageSize, remaining); - MakeHash hasher(this); - generateHash(hasher, mExec, (*mDir)[slot], thisPage); - remaining -= thisPage; - } - - // all done. Pass ownership to caller - return mDir; -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/cdbuilder.h b/OSX/include/security_codesigning/cdbuilder.h deleted file mode 100644 index 21f92405..00000000 --- a/OSX/include/security_codesigning/cdbuilder.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cdbuilder - constructor for CodeDirectories -// -#ifndef _H_CDBUILDER -#define _H_CDBUILDER - -#include "codedirectory.h" - - -namespace Security { -namespace CodeSigning { - - -// -// Builder can construct CodeDirectories from pieces: -// Builder builder(...); -// builder.variousSetters(withSuitableData); -// CodeDirectory *result = builder.build(); -// Builder is not reusable. -// -class CodeDirectory::Builder { -public: - Builder(HashAlgorithm digestAlgorithm); - ~Builder(); - - void executable(string path, size_t pagesize, size_t offset, size_t length); - void reopen(string path, size_t offset, size_t length); - - void specialSlot(SpecialSlot slot, CFDataRef data); - void identifier(const std::string &code) { mIdentifier = code; } - void teamID(const std::string &team) { mTeamID = team; } - void flags(uint32_t f) { mFlags = f; } - void platform(uint8_t p) { mPlatform = p; } - - Scatter *scatter(unsigned count); // allocate that many scatter elements (w/o sentinel) - Scatter *scatter() { return mScatter; } // return already allocated scatter vector - - size_t size(const uint32_t version); // calculate size - CodeDirectory *build(); // build CodeDirectory and return it - const size_t fixedSize(const uint32_t version); // calculate fixed size of the CodeDirectory - - DynamicHash *getHash() const { return CodeDirectory::hashFor(this->mHashType); } - -private: - Hashing::Byte *specialSlot(SpecialSlot slot) - { assert(slot > 0 && slot <= cdSlotMax); return mSpecial + (slot - 1) * mDigestLength; } - Hashing::Byte *specialSlot(SpecialSlot slot) const - { assert(slot > 0 && slot <= cdSlotMax); return mSpecial + (slot - 1) * mDigestLength; } - -private: - Hashing::Byte *mSpecial; // array of special slot hashes - UnixPlusPlus::AutoFileDesc mExec; // main executable file - size_t mExecOffset; // starting offset in mExec - size_t mExecLength; // total bytes of file to sign - size_t mPageSize; // page size of executable (bytes) - uint32_t mFlags; // CodeDirectory flags - uint32_t mHashType; // digest algorithm code - uint8_t mPlatform; // platform identifier - uint32_t mDigestLength; // number of bytes in a single glue digest - std::string mIdentifier; // canonical identifier - std::string mTeamID; // team identifier - - size_t mSpecialSlots; // highest special slot set - size_t mCodeSlots; // number of code pages (slots) - - Scatter *mScatter; // scatter vector - size_t mScatterSize; // number of scatter elements allocated (incl. sentinel) - - CodeDirectory *mDir; // what we're building -}; - - -} // CodeSigning -} // Security - - -#endif //_H_CDBUILDER diff --git a/OSX/include/security_codesigning/codedirectory.cpp b/OSX/include/security_codesigning/codedirectory.cpp deleted file mode 100644 index 7697e273..00000000 --- a/OSX/include/security_codesigning/codedirectory.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// codedirectory - format and operations for code signing "code directory" structures -// -#include "codedirectory.h" -#include "csutilities.h" -#include "CSCommonPriv.h" - -using namespace UnixPlusPlus; - - -namespace Security { -namespace CodeSigning { - - -// -// Highest understood special slot in this CodeDirectory. -// -CodeDirectory::SpecialSlot CodeDirectory::maxSpecialSlot() const -{ - SpecialSlot slot = this->nSpecialSlots; - if (slot > cdSlotMax) - slot = cdSlotMax; - return slot; -} - - -// -// Canonical filesystem names for select slot numbers. -// These are variously used for filenames, extended attribute names, etc. -// to get some consistency in naming. These are for storing signing-related -// data; they have no bearing on the actual hash slots in the CodeDirectory. -// -const char *CodeDirectory::canonicalSlotName(SpecialSlot slot) -{ - switch (slot) { - case cdRequirementsSlot: - return kSecCS_REQUIREMENTSFILE; - case cdResourceDirSlot: - return kSecCS_RESOURCEDIRFILE; - case cdCodeDirectorySlot: - return kSecCS_CODEDIRECTORYFILE; - case cdSignatureSlot: - return kSecCS_SIGNATUREFILE; - case cdApplicationSlot: - return kSecCS_APPLICATIONFILE; - case cdEntitlementSlot: - return kSecCS_ENTITLEMENTFILE; - default: - return NULL; - } -} - - -// -// Canonical attributes of SpecialSlots. -// -unsigned CodeDirectory::slotAttributes(SpecialSlot slot) -{ - switch (slot) { - case cdRequirementsSlot: - return cdComponentIsBlob; // global - case cdCodeDirectorySlot: - return cdComponentPerArchitecture | cdComponentIsBlob; - case cdSignatureSlot: - return cdComponentPerArchitecture; // raw - case cdEntitlementSlot: - return cdComponentIsBlob; // global - case cdIdentificationSlot: - return cdComponentPerArchitecture; // raw - default: - return 0; // global, raw - } -} - - -// -// Symbolic names for code directory special slots. -// These are only used for debug output. They are not API-official. -// Needs to be coordinated with the cd*Slot enumeration in codedirectory.h. -// -#if !defined(NDEBUG) -const char * const CodeDirectory::debugSlotName[] = { - "codedirectory", - "info", - "requirements", - "resources", - "application", - "entitlement" -}; -#endif //NDEBUG - - -// -// Check a CodeDirectory for basic integrity. This should ensure that the -// version is understood by our code, and that the internal structure -// (offsets etc.) is intact. In particular, it must make sure that no offsets -// point outside the CodeDirectory. -// Throws if the directory is corrupted or out of versioning bounds. -// Returns if the version is usable (perhaps with degraded features due to -// compatibility hacks). -// -// Note: There are some things we don't bother checking because they won't -// cause crashes, and will just be flagged as nonsense later. For example, -// a Bad Guy could overlap the identifier and hash fields, which is nonsense -// but not dangerous. -// -void CodeDirectory::checkIntegrity() const -{ - // check version for support - if (!this->validateBlob()) - MacOSError::throwMe(errSecCSSignatureInvalid); // busted - if (version > compatibilityLimit) - MacOSError::throwMe(errSecCSSignatureUnsupported); // too new - no clue - if (version < earliestVersion) - MacOSError::throwMe(errSecCSSignatureUnsupported); // too old - can't support - if (version > currentVersion) - secdebug("codedir", "%p version 0x%x newer than current 0x%x", - this, uint32_t(version), currentVersion); - - // now check interior offsets for validity - if (!stringAt(identOffset)) - MacOSError::throwMe(errSecCSSignatureFailed); // identifier out of blob range - if (version >= supportsTeamID && teamIDOffset != 0 && !stringAt(teamIDOffset)) - MacOSError::throwMe(errSecCSSignatureFailed); // identifier out of blob range - if (!contains(hashOffset - int64_t(hashSize) * nSpecialSlots, hashSize * (int64_t(nSpecialSlots) + nCodeSlots))) - MacOSError::throwMe(errSecCSSignatureFailed); // hash array out of blob range - if (const Scatter *scatter = this->scatterVector()) { - // the optional scatter vector is terminated with an element having (count == 0) - unsigned int pagesConsumed = 0; - for (;; scatter++) { - if (!contains(scatter, sizeof(Scatter))) - MacOSError::throwMe(errSecCSSignatureFailed); - if (scatter->count == 0) - break; - pagesConsumed += scatter->count; - } - if (!contains((*this)[pagesConsumed-1], hashSize)) // referenced too many main hash slots - MacOSError::throwMe(errSecCSSignatureFailed); - } - - // check consistency between the page-coverage fields - if (pageSize) { - if (codeLimit == 0) // can't have paged signatures with no covered data - MacOSError::throwMe(errSecCSSignatureFailed); - size_t coveredPages = ((codeLimit-1) >> pageSize) + 1; // page slots required to cover codeLimit - if (coveredPages != nCodeSlots) - MacOSError::throwMe(errSecCSSignatureFailed); - } else { - if ((codeLimit > 0) != nCodeSlots) // must have one code slot, or none if no code - MacOSError::throwMe(errSecCSSignatureFailed); - } -} - - -// -// Validate a slot against data in memory. -// -bool CodeDirectory::validateSlot(const void *data, size_t length, Slot slot) const -{ - secdebug("codedir", "%p validating slot %d", this, int(slot)); - MakeHash hasher(this); - Hashing::Byte digest[hasher->digestLength()]; - generateHash(hasher, data, length, digest); - return memcmp(digest, (*this)[slot], hasher->digestLength()) == 0; -} - - -// -// Validate a slot against the contents of an open file. At most 'length' bytes -// will be read from the file. -// -bool CodeDirectory::validateSlot(FileDesc fd, size_t length, Slot slot) const -{ - MakeHash hasher(this); - Hashing::Byte digest[hasher->digestLength()]; - generateHash(hasher, fd, digest, length); - return memcmp(digest, (*this)[slot], hasher->digestLength()) == 0; -} - - -// -// Check whether a particular slot is present. -// Absense is indicated by either a zero hash, or by lying outside -// the slot range. -// -bool CodeDirectory::slotIsPresent(Slot slot) const -{ - if (slot >= -Slot(nSpecialSlots) && slot < Slot(nCodeSlots)) { - const Hashing::Byte *digest = (*this)[slot]; - for (unsigned n = 0; n < hashSize; n++) - if (digest[n]) - return true; // non-zero digest => present - } - return false; // absent -} - - -// -// Given a hash type code, create an appropriate subclass of DynamicHash -// and return it. The caller owns the object and must delete it when done. -// This function never returns NULL. It throws if the hashType is unsuupported, -// or if there's an error creating the hasher. -// -DynamicHash *CodeDirectory::hashFor(HashAlgorithm hashType) -{ - switch (hashType) { - case kSecCodeSignatureHashSHA1: return new CCHashInstance(kCCDigestSHA1); - case kSecCodeSignatureHashSHA256: return new CCHashInstance(kCCDigestSHA256); - case kSecCodeSignatureHashSHA256Truncated: return new CCHashInstance(kCCDigestSHA256, SHA1::digestLength); - default: - MacOSError::throwMe(errSecCSSignatureUnsupported); - } -} - - -// -// Generate the canonical cdhash - the internal hash of the CodeDirectory itself. -// We currently truncate to 20 bytes because that's what the kernel can deal with. -// -CFDataRef CodeDirectory::cdhash() const -{ - MakeHash hash(this); - Hashing::Byte digest[hash->digestLength()]; - hash->update(this, this->length()); - hash->finish(digest); - return makeCFData(digest, min(hash->digestLength(), size_t(kSecCodeCDHashLength))); -} - - -// -// Hash the next limit bytes of a file and return the digest. -// If the file is shorter, hash as much as you can. -// Limit==0 means unlimited (to end of file). -// Return how many bytes were actually hashed. -// Throw on any errors. -// -size_t CodeDirectory::generateHash(DynamicHash *hasher, FileDesc fd, Hashing::Byte *digest, size_t limit) -{ - size_t size = hashFileData(fd, hasher, limit); - hasher->finish(digest); - return size; -} - - -// -// Ditto, but hash a memory buffer instead. -// -size_t CodeDirectory::generateHash(DynamicHash *hasher, const void *data, size_t length, Hashing::Byte *digest) -{ - hasher->update(data, length); - hasher->finish(digest); - return length; -} - - -// -// Turn a hash of canonical type into a hex string -// -std::string CodeDirectory::hexHash(const unsigned char *hash) const -{ - size_t size = this->hashSize; - char result[2*size+1]; - for (unsigned n = 0; n < size; n++) - sprintf(result+2*n, "%02.2x", hash[n]); - return result; -} - - -// -// Generate a screening code string from a (complete) CodeDirectory. -// This can be used to make a lightweight pre-screening code from (just) a CodeDirectory. -// -std::string CodeDirectory::screeningCode() const -{ - if (slotIsPresent(-cdInfoSlot)) // has Info.plist - return "I" + hexHash((*this)[-cdInfoSlot]); // use Info.plist hash - if (pageSize == 0) // good-enough proxy for "not a Mach-O file" - return "M" + hexHash((*this)[0]); // use hash of main executable - return "N"; // no suitable screening code -} - - -} // CodeSigning -} // Security - - -// -// Canonical text form for user-settable code directory flags. -// Note: This table is actually exported from Security.framework. -// -const SecCodeDirectoryFlagTable kSecCodeDirectoryFlagTable[] = { - { "host", kSecCodeSignatureHost, true }, - { "adhoc", kSecCodeSignatureAdhoc, false }, - { "hard", kSecCodeSignatureForceHard, true }, - { "kill", kSecCodeSignatureForceKill, true }, - { "expires", kSecCodeSignatureForceExpiration, true }, - { "restrict", kSecCodeSignatureRestrict, true }, - { "enforcement", kSecCodeSignatureEnforcement, true }, - { "library-validation", kSecCodeSignatureLibraryValidation, true }, - { NULL } -}; diff --git a/OSX/include/security_codesigning/codedirectory.h b/OSX/include/security_codesigning/codedirectory.h deleted file mode 100644 index 9e074099..00000000 --- a/OSX/include/security_codesigning/codedirectory.h +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// codedirectory - format and operations for code signing "code directory" structures -// -// A CodeDirectory is the top level object describing a particular instance -// of (static) code. It contains hashes of other objects that further describe -// parts of that code; these hashes hold the various pieces together. -// -// This means that if you reliably ascertain the contents of a CodeDirectory, -// you can verify the integrity of the entire code object it represents - the -// CodeDirectory can stand as a proxy for that code. -// -// Code signatures usually use CMS to sign the CodeDirectory to form full -// signature blobs; ad-hoc signatures simply record the interior hash of the -// CodeDirectory directly. The interior hash of the CodeDirectory is also widely -// used as concordance for a particular code instance - in essence, for -// different processes (or a process and the kernel) to "compare notes" -// to make sure they refer to the same code. -// -#ifndef _H_CODEDIRECTORY -#define _H_CODEDIRECTORY - -#include -#include -#include -#include -#include - - -namespace Security { -namespace CodeSigning { - - -// -// Conventional string names for various code signature components. -// Depending on storage, these may end up as filenames, extended attribute names, etc. -// -#define kSecCS_CODEDIRECTORYFILE "CodeDirectory" // CodeDirectory -#define kSecCS_SIGNATUREFILE "CodeSignature" // CMS Signature -#define kSecCS_REQUIREMENTSFILE "CodeRequirements" // internal requirements -#define kSecCS_RESOURCEDIRFILE "CodeResources" // resource directory -#define kSecCS_APPLICATIONFILE "CodeApplication" // application-specific resource -#define kSecCS_ENTITLEMENTFILE "CodeEntitlements" // entitlement configuration - - -// -// Special hash slot values. In a CodeDirectory, these show up at negative slot -// indices. This enumeration is also used widely in various internal APIs, and as -// type values in embedded SuperBlobs. -// -// How to add a new special slot type: -// 1. Add the new name at the end of the primary or virtual slot array (below). -// 2a. For slots representing existing code pieces, follow the ball for cdInfoSlot. -// 2b. For slots representing global signature components, follow the ball for cdResourceDirSlot. -// 2c. For slots representing per-architecture signature components, follow the ball for cdEntitlementSlot. -// ("Follow the ball" -> Global search for that name and do likewise.) -// -enum { - // - // Primary slot numbers. - // These values are potentially present in the CodeDirectory hash array - // under their negative values. They are also used in APIs and SuperBlobs. - // Note that zero must not be used for these (it's page 0 of the main code array), - // and it is important to assign contiguous (very) small values for them. - // - cdInfoSlot = 1, // Info.plist - cdRequirementsSlot = 2, // internal requirements - cdResourceDirSlot = 3, // resource directory - cdApplicationSlot = 4, // Application specific slot - cdEntitlementSlot = 5, // embedded entitlement configuration - // (add further primary slot numbers here) - - cdSlotCount, // total number of special slots (+1 for slot 0) - cdSlotMax = cdSlotCount - 1, // highest special slot number (as a positive number) - - // - // Virtual slot numbers. - // These values are NOT used in the CodeDirectory hash array. They are used as - // internal API identifiers and as types in SuperBlobs. - // Zero is okay to use here; and we assign that to the CodeDirectory itself so - // it shows up first in (properly sorted) SuperBlob indices. The rest of the - // numbers is set Far Away so the primary slot set can expand safely. - // It's okay to have large gaps in these assignments. - // - cdCodeDirectorySlot = 0, // CodeDirectory - cdSignatureSlot = 0x10000, // CMS signature - cdIdentificationSlot, // identification blob - // (add further virtual slot numbers here) -}; - - -// -// Special hash slot attributes. -// This is a central description of attributes of each slot. -// Various places in Code Signing pick up those attributes and act accordingly. -// -enum { - cdComponentPerArchitecture = 1, // slot value differs for each Mach-O architecture - cdComponentIsBlob = 2, // slot value is a Blob (need not be BlobWrapped) -}; - - -// -// A signature with a nonzero platform identifier value, when endorsed as originated by Apple, -// identifies code as belonging to a particular operating system deliverable set. Some system -// components restrict functionality to platform binaries. The actual values are arbitrary. -// -typedef uint8_t PlatformIdentifier; -static const PlatformIdentifier noPlatform = 0; -static const unsigned int maxPlatform = 255; // stored in a uint8_t - - -// -// A CodeDirectory is a typed Blob describing the secured pieces of a program. -// This structure describes the common header and provides access to the variable-size -// elements packed after it. For help in constructing a CodeDirectory, use the nested -// Builder class. -// -// At the heart of a CodeDirectory lies a packed array of hash digests. -// The array's zero-index element is at offset hashOffset, and the array covers -// elements in the range [-nSpecialSlots .. nCodeSlots-1]. Non-negative indices -// denote pages of the main executable. Negative indices indicate "special" hashes, -// each of a different thing (see cd*Slot constants above). -// Special slots that are in range but not present are zeroed out. Unallocated special -// slots are also presumed absent; this is not an error. (Thus the range of special -// slots can be extended at will.) -// -// HOW TO MANAGE COMPATIBILITY: -// Each CodeDirectory has a format (compatibility) version. Two constants control -// versioning: -// * currentVersion is the version used for newly created CodeDirectories. -// * compatibilityLimit is the highest version the code will accept as compatible. -// Test for version < currentVersion to detect old formats that may need special -// handling; this is done in checkIntegrity(). The current code rejects versions -// below earliestVersion. -// Break backward compatibility by rejecting versions that are unsuitable. -// Accept currentVersion < version <= compatibilityLimit as versions newer than -// those understood by this code but engineered (by newer code) to be backward -// compatible. Reject version > compatibilityLimit as incomprehensible gibberish. -// -// When creating a new version, increment currentVersion. When adding new fixed fields, -// just append them; the flex fields will shift to make room. To add new flex fields, -// add a fixed field containing the new field's offset and add suitable computations -// to the Builder to place the new data (right) before the hash array. Remember to check -// for offset in-range in checkIntegrity(). Older code will then simply ignore your -// new fields on load/read. -// Add flag bits to the existing flags field to add features that step outside -// of the linear versioning stream. Leave the 'spare' fields alone unless you need -// something extraordinarily weird - they're meant to be the final escape when everything -// else fails. -// As you create new versions, consider moving the compatibilityLimit out to open up -// new room for backward compatibility. -// To break backward compatibility intentionally, move currentVersion beyond the -// old compatibilityLimit (and move compatibilityLimit further out). -// -class CodeDirectory: public Blob { -public: - Endian version; // compatibility version - Endian flags; // setup and mode flags - Endian hashOffset; // offset of hash slot element at index zero - Endian identOffset; // offset of identifier string - Endian nSpecialSlots; // number of special hash slots - Endian nCodeSlots; // number of ordinary (code) hash slots - Endian codeLimit; // limit to main image signature range - uint8_t hashSize; // size of each hash digest (bytes) - uint8_t hashType; // type of hash (kSecCodeSignatureHash* constants) - uint8_t platform; // platform identifier; zero if not platform binary - uint8_t pageSize; // log2(page size in bytes); 0 => infinite - Endian spare2; // unused (must be zero) - Endian scatterOffset; // offset of optional scatter vector (zero if absent) - Endian teamIDOffset; // offset of optional teamID string - - // works with the version field; see comments above - static const uint32_t currentVersion = 0x20200; // "version 2.2" - static const uint32_t compatibilityLimit = 0x2F000; // "version 3 with wiggle room" - - static const uint32_t earliestVersion = 0x20001; // earliest supported version - static const uint32_t supportsScatter = 0x20100; // first version to support scatter option - static const uint32_t supportsTeamID = 0x20200; // first version to support team ID option - - void checkIntegrity() const; // throws if inconsistent or unsupported version - - typedef uint32_t HashAlgorithm; // types of internal glue hashes - typedef int Slot; // slot index (negative for special slots) - typedef unsigned int SpecialSlot; // positive special slot index (not for code slots) - - const char *identifier() const { return at(identOffset); } - char *identifier() { return at(identOffset); } - - // main hash array access - SpecialSlot maxSpecialSlot() const; - - unsigned char *operator [] (Slot slot) - { - assert(slot >= int(-nSpecialSlots) && slot < int(nCodeSlots)); - return at(hashOffset) + hashSize * slot; - } - - const unsigned char *operator [] (Slot slot) const - { - assert(slot >= int(-nSpecialSlots) && slot < int(nCodeSlots)); - return at(hashOffset) + hashSize * slot; - } - - // - // The main page hash array can be "scattered" across the code file - // by specifying an array of Scatter elements, terminated with an - // element whose count field is zero. - // The scatter vector is optional; if absent, the hash array covers - // a single contiguous range of pages. CodeDirectory versions below - // supportsScatter never have scatter vectors (they lack the scatterOffset field). - // - struct Scatter { - Endian count; // number of pages; zero for sentinel (only) - Endian base; // first page number - Endian targetOffset; // byte offset in target - Endian spare; // reserved (must be zero) - }; - Scatter *scatterVector() // first scatter vector element (NULL if none) - { return (version >= supportsScatter && scatterOffset) ? at(scatterOffset) : NULL; } - const Scatter *scatterVector() const - { return (version >= supportsScatter && scatterOffset) ? at(scatterOffset) : NULL; } - - const char *teamID() const { return version >= supportsTeamID && teamIDOffset ? at(teamIDOffset) : NULL; } - char *teamID() { return version >= supportsTeamID && teamIDOffset ? at(teamIDOffset) : NULL; } - -public: - bool validateSlot(const void *data, size_t size, Slot slot) const; // validate memory buffer against page slot - bool validateSlot(UnixPlusPlus::FileDesc fd, size_t size, Slot slot) const; // read and validate file - bool slotIsPresent(Slot slot) const; - - class Builder; - -public: - static DynamicHash *hashFor(HashAlgorithm hashType); // create a DynamicHash subclass for (hashType) digests - DynamicHash *getHash() const { return hashFor(this->hashType); } // make one for me - CFDataRef cdhash() const; - - std::string hexHash(const unsigned char *hash) const; // encode any canonical-type hash as a hex string - -protected: - static size_t generateHash(DynamicHash *hash, UnixPlusPlus::FileDesc fd, Hashing::Byte *digest, size_t limit = 0); // hash to count or end of file - static size_t generateHash(DynamicHash *hash, const void *data, size_t length, Hashing::Byte *digest); // hash data buffer - -public: - // - // Information about SpecialSlots. - // This specifies meta-data about slots themselves; - // it does not work with the contents of hash slots. - // - static const char *canonicalSlotName(SpecialSlot slot); - static unsigned slotAttributes(SpecialSlot slot); - IFDEBUG(static const char * const debugSlotName[]); - -public: - // - // Canonical screening code. Requires a fully formed CodeDirectory. - // - std::string screeningCode() const; -}; - - -} // CodeSigning -} // Security - - -#endif //_H_CODEDIRECTORY diff --git a/OSX/include/security_codesigning/cs.cpp b/OSX/include/security_codesigning/cs.cpp deleted file mode 100644 index 787d75b4..00000000 --- a/OSX/include/security_codesigning/cs.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cs.h - code signing core header -// -#include "cs.h" -#include - -namespace Security { -namespace CodeSigning { - - -ModuleNexus gCFObjects; - -CFObjects::CFObjects() - : Code("SecCode"), - StaticCode("SecStaticCode"), - Requirement("SecRequirements"), - CodeSigner("SecCodeSigner") -{ -} - - -OSStatus dbError(const SQLite3::Error &err) -{ - switch (err.error) { - case SQLITE_PERM: - case SQLITE_READONLY: - case SQLITE_AUTH: - return errSecCSSigDBDenied; - case SQLITE_CANTOPEN: - case SQLITE_EMPTY: - case SQLITE_NOTADB: - return errSecCSSigDBAccess; - default: - return SecKeychainErrFromOSStatus(err.osStatus()); - } -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/cs.h b/OSX/include/security_codesigning/cs.h deleted file mode 100644 index 9e40ac8e..00000000 --- a/OSX/include/security_codesigning/cs.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cs.h - code signing core header -// -#ifndef _H_CS -#define _H_CS - -#include "cserror.h" -#include "codesigning_dtrace.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Security { -namespace CodeSigning { - - -// -// API per-thread globals -// -struct PerThread { - SecCSFlags flags; // flags of pending API call -}; - - -// -// API globals -// -struct CFObjects { - CFObjects(); - CFClass Code; - CFClass StaticCode; - CFClass Requirement; - CFClass CodeSigner; - - ThreadNexus perThread; - - SecCSFlags &flags() { return perThread().flags; } -}; - -extern ModuleNexus gCFObjects; - -OSStatus dbError(const SQLite3::Error &err); - - -// -// Code Signing API brackets -// -#define BEGIN_CSAPI \ - try { - -#define END_CSAPI \ - } \ - catch (const UnixError &err) { \ - switch (err.error) { \ - case ENOEXEC: return errSecCSBadObjectFormat; \ - default: return err.osStatus(); \ - }} \ - catch (const MacOSError &err) { return err.osStatus(); } \ - catch (const SQLite3::Error &err) { return dbError(err); } \ - catch (const CommonError &err) { return SecKeychainErrFromOSStatus(err.osStatus()); } \ - catch (const std::bad_alloc &) { return errSecAllocate; } \ - catch (...) { return errSecCSInternalError; } \ - return errSecSuccess; - -#define END_CSAPI_ERRORS \ - } \ - catch (const CSError &err) { return err.cfError(errors); } \ - catch (const UnixError &err) { \ - switch (err.error) { \ - case ENOEXEC: return CSError::cfError(errors, errSecCSBadObjectFormat); \ - default: return CSError::cfError(errors, err.osStatus()); \ - }} \ - catch (const MacOSError &err) { return CSError::cfError(errors, err.osStatus()); } \ - catch (const SQLite3::Error &err) { return CSError::cfError(errors, dbError(err)); } \ - catch (const CommonError &err) { return CSError::cfError(errors, SecKeychainErrFromOSStatus(err.osStatus())); } \ - catch (const std::bad_alloc &) { return CSError::cfError(errors, errSecAllocate); } \ - catch (...) { return CSError::cfError(errors, errSecCSInternalError); } \ - return errSecSuccess; - -#define END_CSAPI1(bad) } catch (...) { return bad; } - - -#define END_CSAPI_ERRORS1(bad) \ - } \ - catch (const CSError &err) { err.cfError(errors); } \ - catch (const UnixError &err) { \ - switch (err.error) { \ - case ENOEXEC: CSError::cfError(errors, errSecCSBadObjectFormat); \ - default: CSError::cfError(errors, err.osStatus()); \ - }} \ - catch (const MacOSError &err) { CSError::cfError(errors, err.osStatus()); } \ - catch (const SQLite3::Error &err) { CSError::cfError(errors, dbError(err)); } \ - catch (const CommonError &err) { CSError::cfError(errors, SecKeychainErrFromOSStatus(err.osStatus())); } \ - catch (const std::bad_alloc &) { CSError::cfError(errors, errSecAllocate); } \ - catch (...) { CSError::cfError(errors, errSecCSInternalError); } \ - return bad; - - -// -// A version of CodeSigning::Required -// -template -static inline T &Required(T *ptr) -{ - if (ptr == NULL) - MacOSError::throwMe(errSecCSObjectRequired); - return *ptr; -} - -static inline void Required(const void *ptr) -{ - if (ptr == NULL) - MacOSError::throwMe(errSecCSObjectRequired); -} - - -// -// Check flags against a validity mask -// -static inline void checkFlags(SecCSFlags flags, SecCSFlags acceptable = 0) -{ - if (flags & ~acceptable) - MacOSError::throwMe(errSecCSInvalidFlags); -} - - -// -// DTrace USDT function bracket. -// Use like this: -// DTRACK(PROVIDER_PROBE_PREFIX, arguments-after-this); -// which will call -// PROVIDER_PROBE_PREFIX_START(this, arguments-after-this) -// and -// PROVIDER_PROBE_PREFIX_END(this) -// -#define DTRACK(_prefix, _obj, _args...) \ - if (_prefix ## _START_ENABLED()) _prefix ## _START((_obj), ## _args); \ - struct _DTFrame ## _prefix { void *me; \ - _DTFrame ## _prefix(void *m) : me(m) { } \ - ~_DTFrame ## _prefix() { _prefix ## _END(me); } \ - } _dtframe##_prefix((_obj)); - - -} // CodeSigning -} // Security - -#endif //_H_CS diff --git a/OSX/include/security_codesigning/cscdefs.c b/OSX/include/security_codesigning/cscdefs.c deleted file mode 100644 index 401c1a6c..00000000 --- a/OSX/include/security_codesigning/cscdefs.c +++ /dev/null @@ -1,4 +0,0 @@ -#include -#include -#include -#include "cscdefs.h" diff --git a/OSX/include/security_codesigning/cscdefs.h b/OSX/include/security_codesigning/cscdefs.h deleted file mode 100644 index 4c3b9985..00000000 --- a/OSX/include/security_codesigning/cscdefs.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Magic numbers used by Code Signing - */ -enum { - CSMAGIC_REQUIREMENT = 0xfade0c00, /* single Requirement blob */ - CSMAGIC_REQUIREMENTS = 0xfade0c01, /* Requirements vector (internal requirements) */ - CSMAGIC_CODEDIRECTORY = 0xfade0c02, /* CodeDirectory blob */ - CSMAGIC_EMBEDDED_SIGNATURE = 0xfade0cc0, /* embedded form of signature data */ - CSMAGIC_DETACHED_SIGNATURE = 0xfade0cc1, /* multi-arch collection of embedded signatures */ - - CSSLOT_CODEDIRECTORY = 0, /* slot index for CodeDirectory */ -}; - - -/* - * Structure of an embedded-signature SuperBlob - */ -typedef struct __BlobIndex { - uint32_t type; /* type of entry */ - uint32_t offset; /* offset of entry */ -} CS_BlobIndex; - -typedef struct __SuperBlob { - uint32_t magic; /* magic number */ - uint32_t length; /* total length of SuperBlob */ - uint32_t count; /* number of index entries following */ - CS_BlobIndex index[]; /* (count) entries */ - /* followed by Blobs in no particular order as indicated by offsets in index */ -} CS_SuperBlob; - - -/* - * C form of a CodeDirectory. - */ -typedef struct __CodeDirectory { - uint32_t magic; /* magic number (CSMAGIC_CODEDIRECTORY) */ - uint32_t length; /* total length of CodeDirectory blob */ - uint32_t version; /* compatibility version */ - uint32_t flags; /* setup and mode flags */ - uint32_t hashOffset; /* offset of hash slot element at index zero */ - uint32_t identOffset; /* offset of identifier string */ - uint32_t nSpecialSlots; /* number of special hash slots */ - uint32_t nCodeSlots; /* number of ordinary (code) hash slots */ - uint32_t codeLimit; /* limit to main image signature range */ - uint8_t hashSize; /* size of each hash in bytes */ - uint8_t hashType; /* type of hash (cdHashType* constants) */ - uint8_t spare1; /* unused (must be zero) */ - uint8_t pageSize; /* log2(page size in bytes); 0 => infinite */ - uint32_t spare2; /* unused (must be zero) */ - /* followed by dynamic content as located by offset fields above */ -} CS_CodeDirectory; - - -/* - * Sample code to locate the CodeDirectory from an embedded signature blob - */ -static inline const CS_CodeDirectory *findCodeDirectory(const CS_SuperBlob *embedded) -{ - if (embedded && ntohl(embedded->magic) == CSMAGIC_EMBEDDED_SIGNATURE) { - const CS_BlobIndex *limit = &embedded->index[ntohl(embedded->count)]; - const CS_BlobIndex *p; - for (p = embedded->index; p < limit; ++p) - if (ntohl(p->type) == CSSLOT_CODEDIRECTORY) { - const unsigned char *base = (const unsigned char *)embedded; - const CS_CodeDirectory *cd = (const CS_CodeDirectory *)(base + ntohl(p->offset)); - if (cd->magic == CSMAGIC_CODEDIRECTORY) - return cd; - else - break; - } - } - // not found - return NULL; -} - - -/* - * Locating a page hash - */ -static inline const unsigned char *hashes(const CS_CodeDirectory *cd, unsigned page) -{ - const unsigned char *base = (const unsigned char *)cd; - assert(page < ntohl(cd->nCodeSlots)); - - // "20" below is the size of a SHA-1 hash. There's got to be a constant for that - // where you get your SHA-1 functions from. This can also be had as cd->hashSize - // (but the constant is marginally faster, I suppose) - return base + ntohl(cd->hashOffset) + page * 20; -} diff --git a/OSX/include/security_codesigning/csdatabase.cpp b/OSX/include/security_codesigning/csdatabase.cpp deleted file mode 100644 index a8bdf7f3..00000000 --- a/OSX/include/security_codesigning/csdatabase.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csdb - system-supported Code Signing related database interfaces -// -#include "csdatabase.h" -#include "detachedrep.h" - -namespace Security { -namespace CodeSigning { - -using namespace SQLite; - - -// -// The one and only SignatureDatabase object. -// It auto-adapts to readonly vs. writable use. -// -ModuleNexus signatureDatabase; -ModuleNexus signatureDatabaseWriter; - - -// -// Default path to the signature database. -// -const char SignatureDatabase::defaultPath[] = "/var/db/DetachedSignatures"; - - -// -// Creation commands to initialize the system database. -// -const char schema[] = "\ - create table if not exists code ( \n\ - id integer primary key on conflict replace autoincrement not null, \n\ - global integer null references global (id), \n\ - identifier text not null, \n\ - architecture integer, \n\ - identification blob not null unique on conflict replace, \n\ - signature blob not null, \n\ - created text default current_timestamp \n\ - ); \n\ - create index if not exists identifier_index on code (identifier); \n\ - create index if not exists architecture_index on code (architecture); \n\ - create index if not exists id_index on code (identification); \n\ - \n\ - create table if not exists global ( \n\ - id integer primary key on conflict replace autoincrement not null, \n\ - sign_location text not null, \n\ - signature blob null \n\ - ); \n\ - create index if not exists location_index on global (sign_location); \n\ -"; - - - -// -// Open the database (creating it if necessary and possible). -// Note that this isn't creating the schema; we do that on first write. -// -SignatureDatabase::SignatureDatabase(const char *path, int flags) - : SQLite::Database(path, flags, true) // lenient open -{ -} - -SignatureDatabase::~SignatureDatabase() -{ /* virtual */ } - - -// -// Consult the database to find code by identification blob. -// Return the signature and (optional) global data blobs. -// -FilterRep *SignatureDatabase::findCode(DiskRep *rep) -{ - if (CFRef identification = rep->identification()) - if (!this->empty()) { - SQLite::Statement query(*this, - "select code.signature, global.signature from code, global \ - where code.identification = ?1 and code.global = global.id;"); - query.bind(1) = identification.get(); - if (query.nextRow()) { - CFRef sig = query[0].data(); - CFRef gsig = query[1].data(); - return new DetachedRep(sig, gsig, rep, "system"); - } - } - - // no joy - return NULL; -} - - -// -// Given a unified detached signature blob, store its data in the database. -// This writes exactly one Global record, plus one Code record per architecture -// (where non-architectural code is treated as single-architecture). -// -void SignatureDatabaseWriter::storeCode(const BlobCore *sig, const char *location) -{ - if (!this->isOpen()) // failed database open or creation - MacOSError::throwMe(errSecCSDBAccess); - Transaction xa(*this, Transaction::exclusive); // lock out everyone - if (this->empty()) - this->execute(schema); // initialize schema - if (const EmbeddedSignatureBlob *esig = EmbeddedSignatureBlob::specific(sig)) { // architecture-less - int64 globid = insertGlobal(location, NULL); - insertCode(globid, 0, esig); - xa.commit(); - return; - } else if (const DetachedSignatureBlob *dsblob = DetachedSignatureBlob::specific(sig)) { - int64 globid = insertGlobal(location, dsblob->find(0)); - unsigned count = dsblob->count(); - for (unsigned n = 0; n < count; n++) - if (uint32_t arch = dsblob->type(n)) - insertCode(globid, arch, EmbeddedSignatureBlob::specific(dsblob->blob(n))); - xa.commit(); - return; - } - - MacOSError::throwMe(errSecCSSignatureInvalid); - -} - -int64 SignatureDatabaseWriter::insertGlobal(const char *location, const BlobCore *blob) -{ - Statement insert(*this, "insert into global (sign_location, signature) values (?1, ?2);"); - insert.bind(1) = location; - if (blob) - insert.bind(2).blob(blob, blob->length(), true); - insert(); - return lastInsert(); -} - -void SignatureDatabaseWriter::insertCode(int64 globid, int arch, const EmbeddedSignatureBlob *sig) -{ - // retrieve binary identifier (was added by signer) - const BlobWrapper *ident = BlobWrapper::specific(sig->find(cdIdentificationSlot)); - assert(ident); - - // extract CodeDirectory to get some information from it - const CodeDirectory *cd = CodeDirectory::specific(sig->find(cdCodeDirectorySlot)); - assert(cd); - - // write the record - Statement insert(*this, - "insert into code (global, identifier, architecture, identification, signature) values (?1, ?2, ?3, ?4, ?5);"); - insert.bind(1) = globid; - insert.bind(2) = cd->identifier(); - if (arch) - insert.bind(3) = arch; - insert.bind(4).blob(ident->data(), ident->length(), true); - insert.bind(5).blob(sig, sig->length(), true); - insert(); -} - - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/csdatabase.h b/OSX/include/security_codesigning/csdatabase.h deleted file mode 100644 index c2790fa7..00000000 --- a/OSX/include/security_codesigning/csdatabase.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2007,2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csdb - system-supported Code Signing related database interfaces -// -#ifndef _H_CSDATABASE -#define _H_CSDATABASE - -#include "diskrep.h" -#include "sigblob.h" -#include -#include -#include -#include - - -namespace Security { -namespace CodeSigning { - -namespace SQLite = SQLite3; - - -class SignatureDatabase : public SQLite::Database { -public: - SignatureDatabase(const char *path = defaultPath, - int flags = SQLITE_OPEN_READONLY); - virtual ~SignatureDatabase(); - - FilterRep *findCode(DiskRep *rep); - -public: - static const char defaultPath[]; -}; - - -class SignatureDatabaseWriter : public SignatureDatabase { -public: - SignatureDatabaseWriter(const char *path = defaultPath, - int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) - : SignatureDatabase(path, flags) { } - - void storeCode(const BlobCore *sig, const char *location); - -private: - SQLite::int64 insertGlobal(const char *location, const BlobCore *blob); - void insertCode(SQLite::int64 globid, int arch, const EmbeddedSignatureBlob *sig); -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CSDATABASE diff --git a/OSX/include/security_codesigning/cserror.cpp b/OSX/include/security_codesigning/cserror.cpp deleted file mode 100644 index 1e6d98e7..00000000 --- a/OSX/include/security_codesigning/cserror.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cserror.h - extended-diagnostics Code Signing errors -// -#include "cs.h" -#include - -namespace Security { -namespace CodeSigning { - - -// -// We need a nothrow destructor -// -CSError::~CSError() throw () -{ } - - -// -// Create and throw various forms of CSError -// -void CSError::throwMe(OSStatus rc) -{ - throw CSError(rc); -} - -void CSError::throwMe(OSStatus rc, CFDictionaryRef dict) -{ - throw CSError(rc, dict); -} - -void CSError::throwMe(OSStatus rc, CFStringRef key, CFTypeRef value) -{ - throw CSError(rc, cfmake("{%O=%O}", key, value)); -} - - -// -// Add a key/value pair to the dictionary -// -void CSError::augment(CFStringRef key, CFTypeRef value) -{ - mInfoDict.take(cfmake("{+%O,%O=%O}", mInfoDict.get(), key, value)); -} - - -// -// Convert exception-carried error information to CFError form -// -OSStatus CSError::cfError(CFErrorRef *errors) const -{ - if (errors) // errors argument was specified - *errors = CFErrorCreate(NULL, kCFErrorDomainOSStatus, this->osStatus(), this->infoDict()); - return this->osStatus(); -} - -OSStatus CSError::cfError(CFErrorRef *errors, OSStatus rc) -{ - if (errors) - *errors = CFErrorCreate(NULL, kCFErrorDomainOSStatus, rc, NULL); - return rc; -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/cserror.h b/OSX/include/security_codesigning/cserror.h deleted file mode 100644 index f46528f1..00000000 --- a/OSX/include/security_codesigning/cserror.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cserror.h - extended-diagnostics Code Signing errors -// -#ifndef _H_CSERRORS -#define _H_CSERRORS - -#include -#include - - -namespace Security { -namespace CodeSigning { - - -// -// Special tailored exceptions to transmit additional error information -// -class CSError : public MacOSError { -public: - CSError(OSStatus rc) : MacOSError(rc) { } - CSError(OSStatus rc, CFDictionaryRef dict) : MacOSError(rc), mInfoDict(dict) { } // takes dict - ~CSError() throw (); - - static void throwMe(OSStatus rc) __attribute__((noreturn)); - static void throwMe(OSStatus rc, CFDictionaryRef info) __attribute__ ((noreturn)); // takes dict - static void throwMe(OSStatus rc, CFStringRef key, CFTypeRef value) __attribute__((noreturn)); - - void augment(CFStringRef key, CFTypeRef value); - - CFDictionaryRef infoDict() const { return mInfoDict; } - -public: - OSStatus cfError(CFErrorRef *errors) const; - static OSStatus cfError(CFErrorRef *errors, OSStatus rc); - -private: - CFRef mInfoDict; -}; - - -} // CodeSigning -} // Security - -#endif //_H_CSERRORS diff --git a/OSX/include/security_codesigning/csgeneric.cpp b/OSX/include/security_codesigning/csgeneric.cpp deleted file mode 100644 index f8986325..00000000 --- a/OSX/include/security_codesigning/csgeneric.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csgeneric - generic Code representative -// -#include "csgeneric.h" -#include "cs.h" -#include "StaticCode.h" -#include -#include - -namespace Security { -namespace CodeSigning { - -using MachPlusPlus::Port; - - -// -// Common call-out code for cshosting RPC service -// -#define CALL(host, name, args...) \ - OSStatus result; \ - if (cshosting_client_ ## name (host, mig_get_reply_port(), &result, args)) \ - MacOSError::throwMe(errSecCSNotAHost); \ - MacOSError::check(result); - - -// -// Construct a running process representation -// -GenericCode::GenericCode(SecCode *host, SecGuestRef guestRef) - : SecCode(host), mGuestRef(guestRef) -{ -} - - -// -// Identify a guest by attribute set, and return a new GenericCode representing it. -// This uses cshosting RPCs to ask the host (or its proxy). -// -SecCode *GenericCode::locateGuest(CFDictionaryRef attributes) -{ - if (Port host = hostingPort()) { - CFRef attrData; - void *attrPtr = NULL; size_t attrLength = 0; - if (attributes) { - attrData.take(CFPropertyListCreateXMLData(NULL, attributes)); - attrPtr = (void *)CFDataGetBytePtr(attrData); - attrLength = CFDataGetLength(attrData); - } - GuestChain guestPath; - mach_msg_type_number_t guestPathLength; - mach_port_t subport; - CALL(host, findGuest, guestRef(), attrPtr, (mach_msg_type_number_t)attrLength, - &guestPath, &guestPathLength, &subport); - CODESIGN_GUEST_LOCATE_GENERIC(this, guestPath, guestPathLength, subport); - SecPointer code = this; - for (unsigned n = 0; n < guestPathLength; n++) - code = new GenericCode(code, guestPath[n]); - return code.yield(); - } else - return NULL; // not found, no error -} - - -// -// Identify a guest by returning its StaticCode and running CodeDirectory hash. -// This uses cshosting RPCs to ask the host (or its proxy). -// -SecStaticCode *GenericCode::identifyGuest(SecCode *guest, CFDataRef *cdhashOut) -{ - if (GenericCode *iguest = dynamic_cast(guest)) { - FilePathOut path; - CFRef cdhash; - CFDictionary attributes(errSecCSHostProtocolInvalidAttribute); - identifyGuest(iguest->guestRef(), path, cdhash.aref(), attributes.aref()); - DiskRep::Context ctx; - if (CFNumberRef architecture = attributes.get(kSecGuestAttributeArchitecture)) { - cpu_type_t cpu = cfNumber(architecture); - if (CFNumberRef subarchitecture = attributes.get(kSecGuestAttributeSubarchitecture)) - ctx.arch = Architecture(cpu, cfNumber(subarchitecture)); - else - ctx.arch = Architecture(cpu); - } - SecPointer code = new GenericStaticCode(DiskRep::bestGuess(path, &ctx)); - CODESIGN_GUEST_IDENTIFY_GENERIC(iguest, iguest->guestRef(), code); - if (cdhash) { - CODESIGN_GUEST_CDHASH_GENERIC(iguest, (void *)CFDataGetBytePtr(cdhash), (unsigned)CFDataGetLength(cdhash)); - *cdhashOut = cdhash.yield(); - } - return code.yield(); - } else - MacOSError::throwMe(errSecCSNotAHost); -} - -// helper to drive the identifyGuest hosting IPC and return results as CF objects -void GenericCode::identifyGuest(SecGuestRef guest, char *path, CFDataRef &cdhash, CFDictionaryRef &attributes) -{ - if (Port host = hostingPort()) { - HashDataOut hash; - uint32_t hashLength; - XMLBlobOut attr; - uint32_t attrLength; - CALL(host, identifyGuest, guest, path, hash, &hashLength, &attr, &attrLength); - if (hashLength) - cdhash = makeCFData(hash, hashLength); - if (attrLength) { - CFRef attrData = makeCFData(attr, attrLength); - attributes = makeCFDictionaryFrom(attrData); -#if ROSETTA_TEST_HACK - CFMutableDictionaryRef hattr = makeCFMutableDictionary(attributes); - CFDictionaryAddValue(hattr, kSecGuestAttributeArchitecture, CFTempNumber(CPU_TYPE_POWERPC)); - CFRelease(attributes); - attributes = hattr; -#endif - } - } else - MacOSError::throwMe(errSecCSNotAHost); -} - - -// -// Get the Code Signing Status Word for a Code. -// This uses cshosting RPCs to ask the host (or its proxy). -// -SecCodeStatus GenericCode::getGuestStatus(SecCode *guest) -{ - if (Port host = hostingPort()) { - uint32_t status; - CALL(host, guestStatus, safe_cast(guest)->guestRef(), &status); - return status; - } else - MacOSError::throwMe(errSecCSNotAHost); -} - - -// -// Status changes are transmitted through the cshosting RPCs. -// -void GenericCode::changeGuestStatus(SecCode *iguest, SecCodeStatusOperation operation, CFDictionaryRef arguments) -{ - if (/* GenericCode *guest = */dynamic_cast(iguest)) - switch (operation) { - case kSecCodeOperationNull: - break; - case kSecCodeOperationInvalidate: - case kSecCodeOperationSetHard: - case kSecCodeOperationSetKill: - MacOSError::throwMe(errSecCSUnimplemented); - break; - default: - MacOSError::throwMe(errSecCSUnimplemented); - } - else - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -// -// Return the Hosting Port for this Code. -// May return MACH_PORT_NULL if the code is not a code host. -// Throws if we can't get the hosting port for some reason (and can't positively -// determine that there is none). -// -// Note that we do NOT cache negative outcomes. Being a host is a dynamic property, -// and this Code may not have commenced hosting operations yet. For non- (or not-yet-)hosts -// we simply return NULL. -// -Port GenericCode::hostingPort() -{ - if (!mHostingPort) { - if (staticCode()->codeDirectory()->flags & kSecCodeSignatureHost) { - mHostingPort = getHostingPort(); - CODESIGN_GUEST_HOSTINGPORT(this, mHostingPort); - } - } - return mHostingPort; -} - - -// -// A pure GenericHost has no idea where to get a hosting port from. -// This method must be overridden to get one. -// However, we do handle a contiguous chain of GenericCodes by deferring -// to our next-higher host for it. -// -mach_port_t GenericCode::getHostingPort() -{ - if (GenericCode *genericHost = dynamic_cast(host())) - return genericHost->getHostingPort(); - else - MacOSError::throwMe(errSecCSNotAHost); -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/csgeneric.h b/OSX/include/security_codesigning/csgeneric.h deleted file mode 100644 index 0a3a1729..00000000 --- a/OSX/include/security_codesigning/csgeneric.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csgeneric - generic Code representative -// -#ifndef _H_CSGENERIC -#define _H_CSGENERIC - -#include "Code.h" -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// A SecCode that represents "generic" code. -// Generic code is, well, generic. It doesn't have any real resources that define it, -// and so it's defined, de facto, by its host. The Code Signing subsystem has no special -// knowledge as to its nature, and so it just asks the host about everything. The asking -// is done via the cshosting Mach RPC protocol, which can be implemented by hosts in whichever -// way they find reasonable. This code doesn't care, as long as someone is answering. -// -// It is all right to subclass GenericCode to inherit access to the cshosting protocol. -// -class GenericCode : public SecCode { -public: - GenericCode(SecCode *host, SecGuestRef guestRef = kSecNoGuest); - - SecCode *locateGuest(CFDictionaryRef attributes); - SecStaticCode *identifyGuest(SecCode *guest, CFDataRef *cdhash); - SecCodeStatus getGuestStatus(SecCode *guest); - void changeGuestStatus(SecCode *guest, SecCodeStatusOperation operation, CFDictionaryRef arguments); - - SecGuestRef guestRef() const { return mGuestRef; } - -protected: - MachPlusPlus::Port hostingPort(); - virtual mach_port_t getHostingPort(); - -private: - void identifyGuest(SecGuestRef guest, char *path, CFDataRef &cdhash, CFDictionaryRef &attributes); - -private: - MachPlusPlus::Port mHostingPort; // cached hosting port for this Code - SecGuestRef mGuestRef; // guest reference -}; - - -// -// We don't need a GenericCode variant of SecStaticCode -// -typedef SecStaticCode GenericStaticCode; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CSGENERIC diff --git a/OSX/include/security_codesigning/cskernel.cpp b/OSX/include/security_codesigning/cskernel.cpp deleted file mode 100644 index 530fa722..00000000 --- a/OSX/include/security_codesigning/cskernel.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cskernel - Kernel implementation of the Code Signing Host Interface. -// -// The kernel host currently supports only UNIX processes as guests. -// It tracks then by their pid. Perhaps one day we'll get a more stable -// means of tracking processes that doesn't involve reusing identifiers. -// -// The kernel host could represent non-process guests one day. One candidate -// are Kernel Extensions. -// -#include "cskernel.h" -#include "csprocess.h" -#include "kerneldiskrep.h" -#include "machorep.h" -#include -#include -#include // MAXPATHLEN - -namespace Security { -namespace CodeSigning { - - -// -// The running-kernel singletons -// -ModuleNexus KernelCode::globals; - -KernelCode::Globals::Globals() -{ - code = new KernelCode; - staticCode = new KernelStaticCode; -} - -KernelCode::KernelCode() - : SecCode(NULL) -{ -} - -KernelStaticCode::KernelStaticCode() - : SecStaticCode(new KernelDiskRep()) -{ -} - - -// -// Identify our guests (UNIX processes) by attribute. -// The only supported lookup attribute is currently the pid. (We could support -// task ports, but those can easily be mapped to pids.) -// Note that we don't actually validate the pid here; if it's invalid, we'll notice -// when we try to ask the kernel about it later. -// -SecCode *KernelCode::locateGuest(CFDictionaryRef attributes) -{ - if (CFTypeRef attr = CFDictionaryGetValue(attributes, kSecGuestAttributePid)) { - RefPointer diskRep = NULL; - - if (CFGetTypeID(attr) != CFNumberGetTypeID()) - MacOSError::throwMe(errSecCSInvalidAttributeValues); - - pid_t pid = cfNumber(CFNumberRef(attr)); - - if (CFDictionaryGetValue(attributes, kSecGuestAttributeDynamicCode) != NULL) { - CFDataRef infoPlist = (CFDataRef)CFDictionaryGetValue(attributes, kSecGuestAttributeDynamicCodeInfoPlist); - if (infoPlist && CFGetTypeID(infoPlist) != CFDataGetTypeID()) - MacOSError::throwMe(errSecCSInvalidAttributeValues); - - try { - diskRep = new PidDiskRep(pid, infoPlist); - } catch (...) { } - } - return (new ProcessCode(cfNumber(CFNumberRef(attr)), diskRep))->retain(); - } else - MacOSError::throwMe(errSecCSUnsupportedGuestAttributes); -} - - -// -// We map guests to disk by calling a kernel service. -// It is here that we verify that our user-space concept of the code identity -// matches the kernel's idea (to defeat just-in-time switching attacks). -// -SecStaticCode *KernelCode::identifyGuest(SecCode *iguest, CFDataRef *cdhash) -{ - if (ProcessCode *guest = dynamic_cast(iguest)) { - - if (guest->pidBased()) { - - SecPointer code = new ProcessDynamicCode(guest); - - SHA1::Digest kernelHash; - MacOSError::check(::csops(guest->pid(), CS_OPS_CDHASH, kernelHash, sizeof(kernelHash))); - *cdhash = makeCFData(kernelHash, sizeof(kernelHash)); - - return code.yield(); - } - - char path[2 * MAXPATHLEN]; // reasonable upper limit - if (::proc_pidpath(guest->pid(), path, sizeof(path))) { - off_t offset; - csops(guest, CS_OPS_PIDOFFSET, &offset, sizeof(offset)); - SecPointer code = new ProcessStaticCode(DiskRep::bestGuess(path, (size_t)offset)); - CODESIGN_GUEST_IDENTIFY_PROCESS(guest, guest->pid(), code); - if (cdhash) { - SHA1::Digest kernelHash; - if (::csops(guest->pid(), CS_OPS_CDHASH, kernelHash, sizeof(kernelHash)) == -1) - switch (errno) { - case EBADEXEC: // means "no CodeDirectory hash for this program" - *cdhash = NULL; - break; - case ESRCH: - MacOSError::throwMe(errSecCSNoSuchCode); - default: - UnixError::throwMe(); - } - else // succeeded - *cdhash = makeCFData(kernelHash, sizeof(kernelHash)); - CODESIGN_GUEST_CDHASH_PROCESS(guest, kernelHash, sizeof(kernelHash)); - } - return code.yield(); - } else - UnixError::throwMe(); - } - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -// -// We obtain the guest's status by asking the kernel -// -SecCodeStatus KernelCode::getGuestStatus(SecCode *iguest) -{ - if (ProcessCode *guest = dynamic_cast(iguest)) { - uint32_t pFlags; - csops(guest, CS_OPS_STATUS, &pFlags); - secdebug("kcode", "guest %p(%d) kernel status 0x%x", guest, guest->pid(), pFlags); - return pFlags; - } else - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -// -// We tell the kernel to make status changes -// -void KernelCode::changeGuestStatus(SecCode *iguest, SecCodeStatusOperation operation, CFDictionaryRef arguments) -{ - if (ProcessCode *guest = dynamic_cast(iguest)) - switch (operation) { - case kSecCodeOperationNull: - break; - case kSecCodeOperationInvalidate: - csops(guest, CS_OPS_MARKINVALID); - break; - case kSecCodeOperationSetHard: - csops(guest, CS_OPS_MARKHARD); - break; - case kSecCodeOperationSetKill: - csops(guest, CS_OPS_MARKKILL); - break; - default: - MacOSError::throwMe(errSecCSUnimplemented); - } - else - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -// -// The StaticCode for the running kernel is explicit. -// We can't ask our own host for it, naturally. -// -void KernelCode::identify() -{ - mStaticCode.take(globals().staticCode->retain()); - // the kernel isn't currently signed, so we don't get a cdHash for it -} - - -// -// Interface to kernel csops() system call. -// -void KernelCode::csops(ProcessCode *proc, unsigned int op, void *addr, size_t length) -{ - if (::csops(proc->pid(), op, addr, length) == -1) { - switch (errno) { - case ESRCH: - MacOSError::throwMe(errSecCSNoSuchCode); - default: - UnixError::throwMe(); - } - } -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/cskernel.h b/OSX/include/security_codesigning/cskernel.h deleted file mode 100644 index 444981a6..00000000 --- a/OSX/include/security_codesigning/cskernel.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// cskernel - Kernel implementation of the Code Signing Host Interface -// -#ifndef _H_CSKERNEL -#define _H_CSKERNEL - -#include "Code.h" -#include "StaticCode.h" -#include - -namespace Security { -namespace CodeSigning { - - -class ProcessCode; - - -// -// The nominal StaticCode representing the kernel on disk. -// This is barely used, since we don't validate the kernel (it's the root of trust) -// and we don't activate new kernels at runtime. -// -class KernelStaticCode : public SecStaticCode { -public: - KernelStaticCode(); - -private: -}; - - -// -// A SecCode that represents the system's running kernel. -// We usually only have one of those in the system at one time. :-) -// -class KernelCode : public SecCode { -public: - KernelCode(); - - SecCode *locateGuest(CFDictionaryRef attributes); - SecStaticCode *identifyGuest(SecCode *guest, CFDataRef *cdhash); - SecCodeStatus getGuestStatus(SecCode *guest); - void changeGuestStatus(SecCode *guest, SecCodeStatusOperation operation, CFDictionaryRef arguments); - - static KernelCode *active() { return globals().code; } - -public: - struct Globals { - Globals(); - SecPointer code; - SecPointer staticCode; - }; - static ModuleNexus globals; - -protected: - void identify(); - void csops(ProcessCode *proc, unsigned int op, void *addr = NULL, size_t length = 0); -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CSKERNEL diff --git a/OSX/include/security_codesigning/csprocess.cpp b/OSX/include/security_codesigning/csprocess.cpp deleted file mode 100644 index bc406aa3..00000000 --- a/OSX/include/security_codesigning/csprocess.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csprocess - UNIX process implementation of the Code Signing Host Interface -// -#include "csprocess.h" -#include "cskernel.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// Construct a running process representation -// -ProcessCode::ProcessCode(pid_t pid, PidDiskRep *pidDiskRep /*= NULL */) - : GenericCode(KernelCode::active()), mPid(pid), mPidBased(pidDiskRep) -{ -} - - -mach_port_t ProcessCode::getHostingPort() -{ - return SecurityServer::ClientSession().hostingPort(pid()); -} - -/* - * - */ - -ProcessDynamicCode::ProcessDynamicCode(ProcessCode *guest) - : SecStaticCode(guest->pidBased()), mGuest(guest) -{ -} - -CFDataRef ProcessDynamicCode::component(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) -{ - if (slot == cdInfoSlot && !mGuest->pidBased()->supportInfoPlist()) - return NULL; - else if (slot == cdResourceDirSlot) - return NULL; - return SecStaticCode::component(slot, fail); -} - -CFDictionaryRef ProcessDynamicCode::infoDictionary() -{ - if (mGuest->pidBased()->supportInfoPlist()) - return SecStaticCode::infoDictionary(); - return makeCFDictionary(0); -} - -void ProcessDynamicCode::validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail /* = errSecCSSignatureFailed */) -{ - if (slot == cdInfoSlot && !mGuest->pidBased()->supportInfoPlist()) - return; - else if (slot == cdResourceDirSlot) - return; - SecStaticCode::validateComponent(slot, fail); -} - - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/csprocess.h b/OSX/include/security_codesigning/csprocess.h deleted file mode 100644 index f98126bd..00000000 --- a/OSX/include/security_codesigning/csprocess.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2006,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csprocess - UNIX process implementation of the Code Signing Host Interface -// -#ifndef _H_CSPROCESS -#define _H_CSPROCESS - -#include "csgeneric.h" -#include "StaticCode.h" -#include "PidDiskRep.h" -#include - -namespace Security { -namespace CodeSigning { - - -// -// A SecCode that represents a running UNIX process. -// Processes are identified by pid. -// -// ProcessCode inherits GenericCode's access to the cshosting Mach protocol to -// deal with guests. -// -class ProcessCode : public GenericCode { -public: - ProcessCode(pid_t pid, PidDiskRep *pidDiskRep = NULL); - ~ProcessCode() throw () { } - - pid_t pid() const { return mPid; } - PidDiskRep *pidBased() const { return mPidBased; } - - mach_port_t getHostingPort(); - -private: - pid_t mPid; - RefPointer mPidBased; -}; - - -// -// We don't need a GenericCode variant of ProcessCode -// -typedef SecStaticCode ProcessStaticCode; - -class ProcessDynamicCode : public SecStaticCode { -public: - ProcessDynamicCode(ProcessCode *diskRep); - - CFDataRef component(CodeDirectory::SpecialSlot slot, OSStatus fail = errSecCSSignatureFailed); - - CFDictionaryRef infoDictionary(); - - void validateComponent(CodeDirectory::SpecialSlot slot, OSStatus fail = errSecCSSignatureFailed); -private: - ProcessCode *mGuest; - -}; - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CSPROCESS diff --git a/OSX/include/security_codesigning/csutilities.cpp b/OSX/include/security_codesigning/csutilities.cpp deleted file mode 100644 index c6f0231b..00000000 --- a/OSX/include/security_codesigning/csutilities.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csutilities - miscellaneous utilities for the code signing implementation -// -#include "csutilities.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// Test for the canonical Apple CA certificate -// -bool isAppleCA(SecCertificateRef cert) -{ - SecAppleTrustAnchorFlags flags = 0; - if (SecIsInternalRelease()) - flags |= kSecAppleTrustAnchorFlagsIncludeTestAnchors; - return SecIsAppleTrustAnchor(cert, flags); -} - - -// -// Calculate the canonical hash of a certificate, given its raw (DER) data. -// -void hashOfCertificate(const void *certData, size_t certLength, SHA1::Digest digest) -{ - SHA1 hasher; - hasher(certData, certLength); - hasher.finish(digest); -} - - -// -// Ditto, given a SecCertificateRef -// -void hashOfCertificate(SecCertificateRef cert, SHA1::Digest digest) -{ - assert(cert); - CSSM_DATA certData; - MacOSError::check(SecCertificateGetData(cert, &certData)); - hashOfCertificate(certData.Data, certData.Length, digest); -} - - -// -// One-stop hash-certificate-and-compare -// -bool verifyHash(SecCertificateRef cert, const Hashing::Byte *digest) -{ - SHA1::Digest dig; - hashOfCertificate(cert, dig); - return !memcmp(dig, digest, SHA1::digestLength); -} - - -// -// Check to see if a certificate contains a particular field, by OID. This works for extensions, -// even ones not recognized by the local CL. It does not return any value, only presence. -// -bool certificateHasField(SecCertificateRef cert, const CSSM_OID &oid) -{ - assert(cert); - CSSM_DATA *value; - switch (OSStatus rc = SecCertificateCopyFirstFieldValue(cert, &oid, &value)) { - case errSecSuccess: - MacOSError::check(SecCertificateReleaseFirstFieldValue(cert, &oid, value)); - return true; // extension found by oid - case errSecUnknownTag: - break; // oid not recognized by CL - continue below - default: - MacOSError::throwMe(rc); // error: fail - } - - // check the CL's bag of unrecognized extensions - CSSM_DATA **values; - bool found = false; - if (SecCertificateCopyFieldValues(cert, &CSSMOID_X509V3CertificateExtensionCStruct, &values)) - return false; // no unrecognized extensions - no match - if (values) - for (CSSM_DATA **p = values; *p; p++) { - const CSSM_X509_EXTENSION *ext = (const CSSM_X509_EXTENSION *)(*p)->Data; - if (oid == ext->extnId) { - found = true; - break; - } - } - MacOSError::check(SecCertificateReleaseFieldValues(cert, &CSSMOID_X509V3CertificateExtensionCStruct, values)); - return found; -} - - -// -// Retrieve X.509 policy extension OIDs, if any. -// This currently ignores policy qualifiers. -// -bool certificateHasPolicy(SecCertificateRef cert, const CSSM_OID &policyOid) -{ - bool matched = false; - assert(cert); - CSSM_DATA *data; - if (OSStatus rc = SecCertificateCopyFirstFieldValue(cert, &CSSMOID_CertificatePolicies, &data)) - MacOSError::throwMe(rc); - if (data && data->Data && data->Length == sizeof(CSSM_X509_EXTENSION)) { - const CSSM_X509_EXTENSION *ext = (const CSSM_X509_EXTENSION *)data->Data; - assert(ext->format == CSSM_X509_DATAFORMAT_PARSED); - const CE_CertPolicies *policies = (const CE_CertPolicies *)ext->value.parsedValue; - if (policies) - for (unsigned int n = 0; n < policies->numPolicies; n++) { - const CE_PolicyInformation &cp = policies->policies[n]; - if (cp.certPolicyId == policyOid) { - matched = true; - break; - } - } - } - SecCertificateReleaseFirstFieldValue(cert, &CSSMOID_PolicyConstraints, data); - return matched; -} - - -// -// Copyfile -// -Copyfile::Copyfile() -{ - if (!(mState = copyfile_state_alloc())) - UnixError::throwMe(); -} - -void Copyfile::set(uint32_t flag, const void *value) -{ - check(::copyfile_state_set(mState, flag, value)); -} - -void Copyfile::get(uint32_t flag, void *value) -{ - check(::copyfile_state_set(mState, flag, value)); -} - -void Copyfile::operator () (const char *src, const char *dst, copyfile_flags_t flags) -{ - check(::copyfile(src, dst, mState, flags)); -} - -void Copyfile::check(int rc) -{ - if (rc < 0) - UnixError::throwMe(); -} - - -// -// MessageTracer support -// -MessageTrace::MessageTrace(const char *domain, const char *signature) -{ - mAsl = asl_new(ASL_TYPE_MSG); - if (domain) - asl_set(mAsl, "com.apple.message.domain", domain); - if (signature) - asl_set(mAsl, "com.apple.message.signature", signature); -} - -void MessageTrace::add(const char *key, const char *format, ...) -{ - va_list args; - va_start(args, format); - char value[200]; - vsnprintf(value, sizeof(value), format, args); - va_end(args); - asl_set(mAsl, (string("com.apple.message.") + key).c_str(), value); -} - -void MessageTrace::send(const char *format, ...) -{ - va_list args; - va_start(args, format); - asl_vlog(NULL, mAsl, ASL_LEVEL_NOTICE, format, args); - va_end(args); -} - - - -// Resource limited async workers for doing work on nested bundles -LimitedAsync::LimitedAsync(bool async) -{ - // validate multiple resources concurrently if bundle resides on solid-state media - - // How many async workers to spin off. If zero, validating only happens synchronously. - long async_workers = 0; - - long ncpu = sysconf(_SC_NPROCESSORS_ONLN); - - if (async && ncpu > 0) - async_workers = ncpu - 1; // one less because this thread also validates - - mResourceSemaphore = new Dispatch::Semaphore(async_workers); -} - -LimitedAsync::LimitedAsync(LimitedAsync &limitedAsync) -{ - mResourceSemaphore = new Dispatch::Semaphore(*limitedAsync.mResourceSemaphore); -} - -LimitedAsync::~LimitedAsync() -{ - delete mResourceSemaphore; -} - -bool LimitedAsync::perform(Dispatch::Group &groupRef, void (^block)()) { - __block Dispatch::SemaphoreWait wait(*mResourceSemaphore, DISPATCH_TIME_NOW); - - if (wait.acquired()) { - dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - - groupRef.enqueue(defaultQueue, ^{ - // Hold the semaphore count until the worker is done validating. - Dispatch::SemaphoreWait innerWait(wait); - block(); - }); - return true; - } else { - block(); - return false; - } -} - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/csutilities.h b/OSX/include/security_codesigning/csutilities.h deleted file mode 100644 index 1de14505..00000000 --- a/OSX/include/security_codesigning/csutilities.h +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// csutilities - miscellaneous utilities for the code signing implementation -// -// This is a collection of odds and ends that wouldn't fit anywhere else. -// The common theme is that the contents are otherwise naturally homeless. -// -#ifndef _H_CSUTILITIES -#define _H_CSUTILITIES - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// Test for the canonical Apple CA certificate -// -bool isAppleCA(SecCertificateRef cert); - - -// -// Calculate canonical hashes of certificate. -// This is simply defined as (always) the SHA1 hash of the DER. -// -void hashOfCertificate(const void *certData, size_t certLength, SHA1::Digest digest); -void hashOfCertificate(SecCertificateRef cert, SHA1::Digest digest); -bool verifyHash(SecCertificateRef cert, const Hashing::Byte *digest); - - -// -// Calculate hashes of (a section of) a file. -// Starts at the current file position. -// Extends to end of file, or (if limit > 0) at most limit bytes. -// Returns number of bytes digested. -// -template -size_t hashFileData(UnixPlusPlus::FileDesc fd, _Hash *hasher, size_t limit = 0) -{ - unsigned char buffer[4096]; - size_t total = 0; - for (;;) { - size_t size = sizeof(buffer); - if (limit && limit < size) - size = limit; - size_t got = fd.read(buffer, size); - total += got; - if (fd.atEnd()) - break; - hasher->update(buffer, got); - if (limit && (limit -= got) == 0) - break; - } - return total; -} - -template -size_t hashFileData(const char *path, _Hash *hasher) -{ - UnixPlusPlus::AutoFileDesc fd(path); - return hashFileData(fd, hasher); -} - - -// -// Check to see if a certificate contains a particular field, by OID. This works for extensions, -// even ones not recognized by the local CL. It does not return any value, only presence. -// -bool certificateHasField(SecCertificateRef cert, const CSSM_OID &oid); -bool certificateHasPolicy(SecCertificateRef cert, const CSSM_OID &policyOid); - - -// -// Encapsulation of the copyfile(3) API. -// This is slated to go into utilities once stable. -// -class Copyfile { -public: - Copyfile(); - ~Copyfile() { copyfile_state_free(mState); } - - operator copyfile_state_t () const { return mState; } - - void set(uint32_t flag, const void *value); - void get(uint32_t flag, void *value); - - void operator () (const char *src, const char *dst, copyfile_flags_t flags); - -private: - void check(int rc); - -private: - copyfile_state_t mState; -}; - - -// -// MessageTracer support -// -class MessageTrace { -public: - MessageTrace(const char *domain, const char *signature); - ~MessageTrace() { ::asl_free(mAsl); } - void add(const char *key, const char *format, ...); - void send(const char *format, ...); - -private: - aslmsg mAsl; -}; - - -// -// A reliable uid set/reset bracket -// -class UidGuard { -public: - UidGuard() : mPrevious(-1) { } - UidGuard(uid_t uid) : mPrevious(-1) { seteuid(uid); } - ~UidGuard() - { - if (active()) - UnixError::check(::seteuid(mPrevious)); - } - - bool seteuid(uid_t uid) - { - if (uid == geteuid()) - return true; // no change, don't bother the kernel - if (!active()) - mPrevious = ::geteuid(); - return ::seteuid(uid) == 0; - } - - bool active() const { return mPrevious != uid_t(-1); } - operator bool () const { return active(); } - uid_t saved() const { assert(active()); return mPrevious; } - -private: - uid_t mPrevious; -}; - - -// This class provides resource limited parallelization, -// used for work on nested bundles (e.g. signing or validating them). - -// We only spins off async workers if they are available right now, -// otherwise we continue synchronously in the current thread. -// This is important because we must progress at all times, otherwise -// deeply nested bundles will deadlock on waiting for resource validation, -// with no available workers to actually do so. -// Their nested resources, however, may again spin off async workers if -// available. - -class LimitedAsync { - NOCOPY(LimitedAsync) -public: - LimitedAsync(bool async); - LimitedAsync(LimitedAsync& limitedAsync); - virtual ~LimitedAsync(); - - bool perform(Dispatch::Group &groupRef, void (^block)()); - -private: - Dispatch::Semaphore *mResourceSemaphore; -}; - - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CSUTILITIES diff --git a/OSX/include/security_codesigning/detachedrep.cpp b/OSX/include/security_codesigning/detachedrep.cpp deleted file mode 100644 index 257fe65a..00000000 --- a/OSX/include/security_codesigning/detachedrep.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2006-2008,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// detachedrep - prefix diskrep representing a detached signature stored in a file -// -#include "detachedrep.h" - - -namespace Security { -namespace CodeSigning { - - -// -// We construct a DetachedRep from the data blob of the detached signature -// and a reference of the original DiskRep we chain to. -// We accept an EmbeddedSignatureBlob (for a non-architected signature) -// or a DetachedSignatureBlob (for architected signatures) that is a SuperBlob -// of EmbeddedSignatureBlobs. -// -DetachedRep::DetachedRep(CFDataRef sig, DiskRep *orig, const std::string &source) - : FilterRep(orig), mSig(sig), mFull(true), mSource(source) -{ - const BlobCore *sigBlob = reinterpret_cast(CFDataGetBytePtr(sig)); - if (sigBlob->is()) { // architecture-less - if ((mArch = EmbeddedSignatureBlob::specific(sigBlob))) { - mGlobal = NULL; - CODESIGN_DISKREP_CREATE_DETACHED(this, orig, (char*)source.c_str(), NULL); - return; - } - } else if (sigBlob->is()) // architecture collection - if (const DetachedSignatureBlob *dsblob = DetachedSignatureBlob::specific(sigBlob)) - if (Universal *fat = orig->mainExecutableImage()) - if (const BlobCore *blob = dsblob->find(fat->bestNativeArch().cpuType())) - if ((mArch = EmbeddedSignatureBlob::specific(blob))) - if ((mGlobal = EmbeddedSignatureBlob::specific(dsblob->find(0)))) { - CODESIGN_DISKREP_CREATE_DETACHED(this, orig, (char*)source.c_str(), (void*)mGlobal); - return; - } - MacOSError::throwMe(errSecCSSignatureInvalid); -} - - -// -// Here's a version to construct a DetachedRep if we already have the right architecture -// and (optional) associated global blob. Just take them. -// -DetachedRep::DetachedRep(CFDataRef sig, CFDataRef gsig, DiskRep *orig, const std::string &source) - : FilterRep(orig), mSig(sig), mGSig(gsig), mFull(false), mSource(source) -{ - const BlobCore *sigBlob = reinterpret_cast(CFDataGetBytePtr(sig)); - mArch = EmbeddedSignatureBlob::specific(sigBlob); - if (!mArch) - MacOSError::throwMe(errSecCSSignatureInvalid); - if (gsig) { - const BlobCore *gsigBlob = reinterpret_cast(CFDataGetBytePtr(gsig)); - mGlobal = EmbeddedSignatureBlob::specific(gsigBlob); - if (!mGlobal) - MacOSError::throwMe(errSecCSSignatureInvalid); - } else - mGlobal = NULL; - CODESIGN_DISKREP_CREATE_DETACHED(this, orig, (char*)source.c_str(), (void*)mGlobal); -} - - -// -// We look up components by first checking for a per-architecture item, -// then for a global item in the detached signature, and finally falling -// back on the original DiskRep (for static components). -// -CFDataRef DetachedRep::component(CodeDirectory::SpecialSlot slot) -{ - if (CFDataRef result = mArch->component(slot)) - return result; - if (mGlobal) - if (CFDataRef result = mGlobal->component(slot)) - return result; - return this->base()->component(slot); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/detachedrep.h b/OSX/include/security_codesigning/detachedrep.h deleted file mode 100644 index 64266b38..00000000 --- a/OSX/include/security_codesigning/detachedrep.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2006-2008,2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// detachedrep - prefix diskrep representing a detached signature stored in a file -// -#ifndef _H_DETACHEDREP -#define _H_DETACHEDREP - -#include "diskrep.h" -#include "sigblob.h" - -namespace Security { -namespace CodeSigning { - - -// -// We use a DetachedRep to interpose (filter) the genuine DiskRep representing -// the code on disk, *if* a detached signature was set on this object. In this -// situation, mRep will point to a (2 element) chain of DiskReps. -// -// This is a neat way of dealing with the (unusual) detached-signature case -// without disturbing things unduly. Consider DetachedDiskRep to be closely -// married to SecStaticCode; it's unlikely to work right if you use it elsewhere. -// -// Note that there's no *writing* code here. Writing detached signatures is handled -// specially in the signing code. -// -class DetachedRep : public FilterRep { -public: - DetachedRep(CFDataRef sig, DiskRep *orig, const std::string &source); // SuperBlob of all architectures - DetachedRep(CFDataRef sig, CFDataRef gsig, DiskRep *orig, const std::string &source); // one architecture + globals - - CFDataRef component(CodeDirectory::SpecialSlot slot); - - bool fullSignature() const { return mFull; } - const std::string &source() const { return mSource; } - -private: - CFCopyRef mSig, mGSig; - bool mFull; // full detached signature (explicitly given) - const EmbeddedSignatureBlob *mArch; // current architecture; points into mSignature - const EmbeddedSignatureBlob *mGlobal; // shared elements; points into mSignature - std::string mSource; // source description (readable) -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_DETACHEDREP diff --git a/OSX/include/security_codesigning/dirscanner.cpp b/OSX/include/security_codesigning/dirscanner.cpp deleted file mode 100644 index 0d16d74f..00000000 --- a/OSX/include/security_codesigning/dirscanner.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include -#include "dirscanner.h" - -namespace Security { -namespace CodeSigning { - - -DirScanner::DirScanner(const char *path) - : init(false) -{ - this->path = std::string(path); - this->initialize(); -} - -DirScanner::DirScanner(string path) - : init(false) -{ - this->path = path; - this->initialize(); -} - -DirScanner::~DirScanner() -{ - if (this->dp != NULL) - (void) closedir(this->dp); -} - -void DirScanner::initialize() -{ - if (this->dp == NULL) { - errno = 0; - if ((this->dp = opendir(this->path.c_str())) == NULL) { - if (errno == ENOENT) { - init = false; - } else { - UnixError::check(-1); - } - } else - init = true; - } else - MacOSError::throwMe(errSecInternalError); -} - -struct dirent * DirScanner::getNext() -{ - return readdir(this->dp); -} - -bool DirScanner::initialized() -{ - return this->init; -} - - -DirValidator::~DirValidator() -{ - for (Rules::iterator it = mRules.begin(); it != mRules.end(); ++it) - delete *it; -} - -void DirValidator::validate(const string &root, OSStatus error) -{ - std::set reqMatched; - FTS fts(root); - while (FTSENT *ent = fts_read(fts)) { - const char *relpath = ent->fts_path + root.size() + 1; // skip prefix + "/" - bool executable = ent->fts_statp->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH); - Rule *rule = NULL; - switch (ent->fts_info) { - case FTS_F: - secdebug("dirval", "file %s", ent->fts_path); - rule = match(relpath, file, executable); - break; - case FTS_SL: { - secdebug("dirval", "symlink %s", ent->fts_path); - char target[PATH_MAX]; - ssize_t len = ::readlink(ent->fts_accpath, target, sizeof(target)-1); - if (len < 0) - UnixError::throwMe(); - target[len] = '\0'; - rule = match(relpath, symlink, executable, target); - break; - } - case FTS_D: - secdebug("dirval", "entering %s", ent->fts_path); - if (ent->fts_level == FTS_ROOTLEVEL) - continue; // skip root directory - rule = match(relpath, directory, executable); - if (!rule || !(rule->flags & descend)) - fts_set(fts, ent, FTS_SKIP); // do not descend - break; - case FTS_DP: - secdebug("dirval", "leaving %s", ent->fts_path); - continue; - default: - secdebug("dirval", "type %d (errno %d): %s", ent->fts_info, ent->fts_errno, ent->fts_path); - MacOSError::throwMe(error); // not a file, symlink, or directory - } - if (!rule) - MacOSError::throwMe(error); // no match - else if (rule->flags & required) - reqMatched.insert(rule); - } - if (reqMatched.size() != mRequireCount) { - secdebug("dirval", "matched %d of %d required rules", reqMatched.size(), mRequireCount); - MacOSError::throwMe(error); // not all required rules were matched - } -} - -DirValidator::Rule * DirValidator::match(const char *path, uint32_t flags, bool executable, const char *target) -{ - for (Rules::iterator it = mRules.begin(); it != mRules.end(); ++it) { - Rule *rule = *it; - if ((rule->flags & flags) - && !(executable && (rule->flags & noexec)) - && rule->match(path) - && (!target || rule->matchTarget(path, target))) - return rule; - } - return NULL; -} - -DirValidator::FTS::FTS(const string &path, int options) -{ - const char * paths[2] = { path.c_str(), NULL }; - mFTS = fts_open((char * const *)paths, options, NULL); - if (!mFTS) - UnixError::throwMe(); -} - -DirValidator::FTS::~FTS() -{ - fts_close(mFTS); -} - -DirValidator::Rule::Rule(const string &pattern, uint32_t flags, TargetPatternBuilder targetBlock) - : ResourceBuilder::Rule(pattern, 0, flags), mTargetBlock(NULL) -{ - if (targetBlock) - mTargetBlock = Block_copy(targetBlock); -} - -DirValidator::Rule::~Rule() -{ - if (mTargetBlock) - Block_release(mTargetBlock); -} - -bool DirValidator::Rule::matchTarget(const char *path, const char *target) const -{ - if (!mTargetBlock) - MacOSError::throwMe(errSecCSInternalError); - string pattern = mTargetBlock(path, target); - if (pattern.empty()) - return true; // always match empty pattern - secdebug("dirval", "%s: match target %s against %s", path, target, pattern.c_str()); - regex_t re; - if (::regcomp(&re, pattern.c_str(), REG_EXTENDED | REG_NOSUB)) - MacOSError::throwMe(errSecCSInternalError); - int rv = ::regexec(&re, target, 0, NULL, 0); - ::regfree(&re); - switch (rv) { - case 0: - return true; - case REG_NOMATCH: - return false; - default: - MacOSError::throwMe(errSecCSInternalError); - } -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/dirscanner.h b/OSX/include/security_codesigning/dirscanner.h deleted file mode 100644 index ddd5e56f..00000000 --- a/OSX/include/security_codesigning/dirscanner.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#ifndef _H_DIRSCANNER -#define _H_DIRSCANNER - -#include "resources.h" -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -class DirScanner { -public: - DirScanner(const char *path); - DirScanner(string path); - ~DirScanner(); - - struct dirent *getNext(); // gets the next item out of this DirScanner - bool initialized(); // returns false if the constructor failed to initialize the dirent - -private: - string path; - DIR *dp = NULL; - void initialize(); - bool init; -}; - - -class DirValidator { -public: - DirValidator() : mRequireCount(0) { } - ~DirValidator(); - - enum { - file = 0x01, - directory = 0x02, - symlink = 0x04, - noexec = 0x08, - required = 0x10, - descend = 0x20, - }; - - typedef std::string (^TargetPatternBuilder)(const std::string &name, const std::string &target); - -private: - class Rule : public ResourceBuilder::Rule { - public: - Rule(const std::string &pattern, uint32_t flags, TargetPatternBuilder targetBlock); - ~Rule(); - - bool matchTarget(const char *path, const char *target) const; - - private: - TargetPatternBuilder mTargetBlock; - }; - void addRule(Rule *rule) { mRules.push_back(rule); } - - class FTS { - public: - FTS(const std::string &path, int options = FTS_PHYSICAL | FTS_COMFOLLOW | FTS_NOCHDIR); - ~FTS(); - - operator ::FTS* () const { return mFTS; } - - private: - ::FTS *mFTS; - }; - -public: - void allow(const std::string &namePattern, uint32_t flags, TargetPatternBuilder targetBlock = NULL) - { addRule(new Rule(namePattern, flags, targetBlock)); } - void require(const std::string &namePattern, uint32_t flags, TargetPatternBuilder targetBlock = NULL) - { addRule(new Rule(namePattern, flags | required, targetBlock)); mRequireCount++; } - - void allow(const std::string &namePattern, uint32_t flags, std::string targetPattern) - { allow(namePattern, flags, ^ string (const std::string &name, const std::string &target) { return targetPattern; }); } - void require(const std::string &namePattern, uint32_t flags, std::string targetPattern) - { require(namePattern, flags, ^ string (const std::string &name, const std::string &target) { return targetPattern; }); } - - void validate(const std::string &root, OSStatus error); - -private: - Rule * match(const char *relpath, uint32_t flags, bool executable, const char *target = NULL); - -private: - typedef std::vector Rules; - Rules mRules; - int mRequireCount; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_DIRSCANNER diff --git a/OSX/include/security_codesigning/diskrep.cpp b/OSX/include/security_codesigning/diskrep.cpp deleted file mode 100644 index af0a336b..00000000 --- a/OSX/include/security_codesigning/diskrep.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// diskrep - disk representations of code -// -#include "diskrep.h" -#include -#include - -// specific disk representations created by the bestGuess() function -#include "filediskrep.h" -#include "bundlediskrep.h" -#include "slcrep.h" - - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Abstract features -// -DiskRep::DiskRep() -{ -} - -DiskRep::~DiskRep() -{ - CODESIGN_DISKREP_DESTROY(this); -} - - -// -// Normal DiskReps are their own base. -// -DiskRep *DiskRep::base() -{ - return this; -} - - -// -// By default, DiskReps are read-only. -// -DiskRep::Writer *DiskRep::writer() -{ - MacOSError::throwMe(errSecCSUnimplemented); -} - - -void DiskRep::Writer::addDiscretionary(CodeDirectory::Builder &) -{ - // do nothing -} - - -// -// Given a file system path, come up with the most likely correct -// disk representation for what's there. -// This is, strictly speaking, a heuristic that could be fooled - there's -// no fool-proof rule for figuring this out. But we'd expect this to work -// fine in ordinary use. If you happen to know what you're looking at -// (say, a bundle), then just create the suitable subclass of DiskRep directly. -// That's quite legal. -// The optional context argument can provide additional information that guides the guess. -// -DiskRep *DiskRep::bestGuess(const char *path, const Context *ctx) -{ - try { - if (!(ctx && ctx->fileOnly)) { - struct stat st; - if (::stat(path, &st)) - UnixError::throwMe(); - - // if it's a directory, assume it's a bundle - if ((st.st_mode & S_IFMT) == S_IFDIR) // directory - assume bundle - return new BundleDiskRep(path, ctx); - - // see if it's the main executable of a recognized bundle - if (CFRef pathURL = makeCFURL(path)) - if (CFRef bundle = _CFBundleCreateWithExecutableURLIfMightBeBundle(NULL, pathURL)) - return new BundleDiskRep(bundle, ctx); - } - - // try the various single-file representations - AutoFileDesc fd(path, O_RDONLY); - if (MachORep::candidate(fd)) - return new MachORep(path, ctx); - if (DYLDCacheRep::candidate(fd)) - return new DYLDCacheRep(path); - - // ultimate fallback - the generic file representation - return new FileDiskRep(path); - - } catch (const CommonError &error) { - switch (error.unixError()) { - case ENOENT: - MacOSError::throwMe(errSecCSStaticCodeNotFound); - default: - throw; - } - } -} - - -DiskRep *DiskRep::bestFileGuess(const char *path, const Context *ctx) -{ - Context dctx; - if (ctx) - dctx = *ctx; - dctx.fileOnly = true; - return bestGuess(path, &dctx); -} - - -// -// Given a main executable known to be a Mach-O binary, and an offset into -// the file of the actual architecture desired (of a Universal file), -// produce a suitable MachORep. -// This function does not consider non-MachO binaries. It does however handle -// bundles with Mach-O main executables correctly. -// -DiskRep *DiskRep::bestGuess(const char *path, size_t archOffset) -{ - try { - // is it the main executable of a bundle? - if (CFRef pathURL = makeCFURL(path)) - if (CFRef bundle = _CFBundleCreateWithExecutableURLIfMightBeBundle(NULL, pathURL)) { - Context ctx; ctx.offset = archOffset; - return new BundleDiskRep(bundle, &ctx); // ask bundle to make bundle-with-MachO-at-offset - } - // else, must be a Mach-O binary - Context ctx; ctx.offset = archOffset; - return new MachORep(path, &ctx); - } catch (const CommonError &error) { - switch (error.unixError()) { - case ENOENT: - MacOSError::throwMe(errSecCSStaticCodeNotFound); - default: - throw; - } - } -} - - -// -// Default behaviors of DiskRep -// -string DiskRep::resourcesRootPath() -{ - return ""; // has no resources directory -} - -void DiskRep::adjustResources(ResourceBuilder &builder) -{ - // do nothing -} - -Universal *DiskRep::mainExecutableImage() -{ - return NULL; // no Mach-O executable -} - -size_t DiskRep::signingBase() -{ - return 0; // whole file (start at beginning) -} - -CFArrayRef DiskRep::modifiedFiles() -{ - // by default, claim (just) the main executable modified - CFRef mainURL = makeCFURL(mainExecutablePath()); - return makeCFArray(1, mainURL.get()); -} - -void DiskRep::flush() -{ - // nothing cached -} - - -CFDictionaryRef DiskRep::defaultResourceRules(const SigningContext &) -{ - return NULL; // none -} - -const Requirements *DiskRep::defaultRequirements(const Architecture *, const SigningContext &) -{ - return NULL; // none -} - -size_t DiskRep::pageSize(const SigningContext &) -{ - return monolithicPageSize; // unpaged (monolithic) -} - - -void DiskRep::strictValidate(const CodeDirectory*, const ToleratedErrors&) -{ - // do nothing -} - -CFArrayRef DiskRep::allowedResourceOmissions() -{ - return NULL; -} - - -// -// Given some string (usually a pathname), derive a suggested signing identifier -// in a canonical way (so there's some consistency). -// -// This is a heuristic. First we lop off any leading directories and final (non-numeric) -// extension. Then we walk backwards, eliminating numeric extensions except the first one. -// Thus, libfrotz7.3.5.dylib becomes libfrotz7, mumble.77.plugin becomes mumble.77, -// and rumble.rb becomes rumble. This isn't perfect, but it ought to handle 98%+ of -// the common varieties out there. Specify an explicit identifier for the oddballs. -// -// This is called by the various recommendedIdentifier() methods, who are -// free to modify or override it. -// -// Note: We use strchr("...") instead of is*() here because we do not -// wish to be influenced by locale settings. -// -std::string DiskRep::canonicalIdentifier(const std::string &name) -{ - string s = name; - string::size_type p; - - // lop off any directory prefixes - if ((p = s.rfind('/')) != string::npos) - s = s.substr(p+1); - - // remove any final extension (last dot) unless it's numeric - if ((p = s.rfind('.')) != string::npos && !strchr("0123456789", s[p+1])) - s = s.substr(0, p); - - // eat numeric suffixes except the first one; roughly: - // foo.2.3.4 => foo.2, foo2.3 => foo2, foo.9 => foo.9, foo => foo - if (strchr("0123456789.", s[0])) // starts with digit or . - return s; // ... so don't mess with it - p = s.size()-1; - // foo3.5^, foo.3.5^, foo3^, foo.3^, foo^ - while (strchr("0123456789.", s[p])) - p--; - // fo^o3.5, fo^o.3.5, fo^o3, fo^o.3, fo^o - p++; - // foo^3.5, foo^.3.5, foo^3, foo^.3, foo^ - if (s[p] == '.') - p++; - // foo^3.5, foo.^3.5, foo^3, foo.^3, foo^ - while (p < s.size() && strchr("0123456789", s[p])) - p++; - // foo3^.5, foo.3^.5, foo3^, foo.3^, foo^ - return s.substr(0, p); -} - - -// -// Writers -// -DiskRep::Writer::Writer(uint32_t attrs) - : mArch(CPU_TYPE_ANY), mAttributes(attrs) -{ -} - -DiskRep::Writer::~Writer() -{ /* virtual */ } - -uint32_t DiskRep::Writer::attributes() const -{ return mAttributes; } - -void DiskRep::Writer::flush() -{ /* do nothing */ } - -void DiskRep::Writer::remove() -{ - MacOSError::throwMe(errSecCSNotSupported); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/diskrep.h b/OSX/include/security_codesigning/diskrep.h deleted file mode 100644 index b9219521..00000000 --- a/OSX/include/security_codesigning/diskrep.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// diskrep - disk representations of code -// -#ifndef _H_DISKREP -#define _H_DISKREP - -#include "cs.h" -#include "codedirectory.h" -#include "cdbuilder.h" -#include "requirement.h" -#include "resources.h" -#include // for class Architecture -#include -#include -#include - -namespace Security { -namespace CodeSigning { - -class ResourceBuilder; - - -// -// DiskRep is an abstract interface to code somewhere located by -// a file system path. It presents the ability to read and write -// Code Signing-related information about such code without exposing -// the details of the storage locations or formats. -// -class DiskRep : public RefCount { -public: - class SigningContext; - - typedef std::set ToleratedErrors; - -public: - DiskRep(); - virtual ~DiskRep(); - virtual DiskRep *base(); - virtual CFDataRef component(CodeDirectory::SpecialSlot slot) = 0; // fetch component - virtual CFDataRef identification() = 0; // binary lookup identifier - virtual std::string mainExecutablePath() = 0; // path to main executable - virtual CFURLRef copyCanonicalPath() = 0; // path to whole code - virtual std::string resourcesRootPath(); // resource directory if any [none] - virtual void adjustResources(ResourceBuilder &builder); // adjust resource rule set [no change] - virtual Universal *mainExecutableImage(); // Mach-O image if Mach-O based [null] - virtual size_t signingBase(); // start offset of signed area in main executable [zero] - virtual size_t signingLimit() = 0; // size of signed area in main executable - virtual std::string format() = 0; // human-readable type string - virtual CFArrayRef modifiedFiles(); // list of files modified by signing [main execcutable only] - virtual UnixPlusPlus::FileDesc &fd() = 0; // a cached file descriptor for main executable file - virtual void flush(); // flush caches (refetch as needed) - - // default values for signing operations - virtual std::string recommendedIdentifier(const SigningContext &ctx) = 0; // default identifier - virtual CFDictionaryRef defaultResourceRules(const SigningContext &ctx); // default resource rules [none] - virtual const Requirements *defaultRequirements(const Architecture *arch, - const SigningContext &ctx); // default internal requirements [none] - virtual size_t pageSize(const SigningContext &ctx); // default main executable page size [infinite, i.e. no paging] - - virtual void strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated); // perform strict validation - virtual CFArrayRef allowedResourceOmissions(); // allowed (default) resource omission rules - - bool mainExecutableIsMachO() { return mainExecutableImage() != NULL; } - - // shorthands - CFDataRef codeDirectory() { return component(cdCodeDirectorySlot); } - CFDataRef signature() { return component(cdSignatureSlot); } - -public: - class Writer; - virtual Writer *writer(); // Writer factory - -public: - // optional information that might be used to create a suitable DiskRep. All optional - struct Context { - Context() : arch(Architecture::none), version(NULL), offset(0), fileOnly(false), inMemory(NULL), size(0) { } - Architecture arch; // explicit architecture (choose amongst universal variants) - const char *version; // bundle version (string) - off_t offset; // explicit file offset - bool fileOnly; // only consider single-file representations (no bundles etc.) - const void *inMemory; // consider using in-memory copy at this address - size_t size; // size of this mach-o slice - }; - - static DiskRep *bestGuess(const char *path, const Context *ctx = NULL); // canonical heuristic, any path - static DiskRep *bestFileGuess(const char *path, const Context *ctx = NULL); // ctx (if any) + fileOnly - static DiskRep *bestGuess(const char *path, size_t archOffset); // Mach-O at given file offset only - - // versions using std::string paths (merely a convenience) - static DiskRep *bestGuess(const std::string &path, const Context *ctx = NULL) - { return bestGuess(path.c_str(), ctx); } - static DiskRep *bestGuess(const std::string &path, size_t archOffset) { return bestGuess(path.c_str(), archOffset); } - static DiskRep *bestFileGuess(const std::string &path, const Context *ctx = NULL) { return bestFileGuess(path.c_str(), ctx); } - -public: - // see DiskRep::Writer docs for why this is here - class SigningContext { - protected: - SigningContext() { } - - public: - virtual std::string sdkPath(const std::string &path) const = 0; - virtual bool isAdhoc() const = 0; - virtual SecCSFlags signingFlags() const = 0; - }; - -protected: - // canonically derive a suggested signing identifier from some string - static std::string canonicalIdentifier(const std::string &name); - -public: - static const size_t segmentedPageSize = 4096; // default page size for system-paged signatures - static const size_t monolithicPageSize = 0; // default page size for non-Mach-O executables -}; - - -// -// Write-access objects. -// At this layer they are quite abstract, carrying just the functionality needed -// for the signing machinery to place data wherever it should go. Each DiskRep subclass -// that supports writing signing data to a place inside the code needs to implement -// a subclass of Writer and return an instance in the DiskRep::writer() method when asked. -// -// The Writer class is subclassed interestingly by the Mach-O multi-architecture signing code, -// which is handled as a special case. This means that not all Writer subclass objects were made -// by DiskRep::writer, and it is unwise to assume so. -// -// Note that the methods that provide defaults for signing operations are in DiskRep rather -// than here. That's because writers abstract data *sending*, and are virtual on management -// of stored data, while DiskRep is virtual on the existing code object, which is where -// we get our defaults from. -// -class DiskRep::Writer : public RefCount { -public: - Writer(uint32_t attrs = 0); - virtual ~Writer(); - virtual void component(CodeDirectory::SpecialSlot slot, CFDataRef data) = 0; - virtual uint32_t attributes() const; - virtual void addDiscretionary(CodeDirectory::Builder &builder); - virtual void remove(); - virtual void flush(); - - bool attribute(uint32_t attr) const { return mAttributes & attr; } - - void signature(CFDataRef data) { component(cdSignatureSlot, data); } - void codeDirectory(const CodeDirectory *cd) - { component(cdCodeDirectorySlot, CFTempData(cd->data(), cd->length())); } - -private: - Architecture mArch; - uint32_t mAttributes; -}; - -// -// Writer attributes. Defaults should be off-bits. -// -enum { - writerLastResort = 0x0001, // prefers not to store attributes itself - writerNoGlobal = 0x0002, // has only per-architecture storage -}; - - -// -// A prefix DiskRep that filters (only) signature-dependent behavior and passes -// all code-dependent behavior off to an underlying (different) DiskRep. -// FilterRep subclasses are typically "stacked" on top of their base DiskRep, and -// then used in their place. -// -class FilterRep : public DiskRep { -public: - FilterRep(DiskRep *orig) : mOriginal(orig) { } - - DiskRep *base() { return mOriginal; } - - // things that look at signature components are filtered - CFDataRef component(CodeDirectory::SpecialSlot slot) = 0; - - // the rest of the virtual behavior devolves on the original DiskRep - CFDataRef identification() { return mOriginal->identification(); } - std::string mainExecutablePath() { return mOriginal->mainExecutablePath(); } - CFURLRef copyCanonicalPath() { return mOriginal->copyCanonicalPath(); } - std::string resourcesRootPath() { return mOriginal->resourcesRootPath(); } - void adjustResources(ResourceBuilder &builder) { return mOriginal->adjustResources(builder); } - Universal *mainExecutableImage() { return mOriginal->mainExecutableImage(); } - size_t signingBase() { return mOriginal->signingBase(); } - size_t signingLimit() { return mOriginal->signingLimit(); } - std::string format() { return mOriginal->format(); } - CFArrayRef modifiedFiles() { return mOriginal->modifiedFiles(); } - UnixPlusPlus::FileDesc &fd() { return mOriginal->fd(); } - void flush() { return mOriginal->flush(); } - - std::string recommendedIdentifier(const SigningContext &ctx) - { return mOriginal->recommendedIdentifier(ctx); } - CFDictionaryRef defaultResourceRules(const SigningContext &ctx) - { return mOriginal->defaultResourceRules(ctx); } - const Requirements *defaultRequirements(const Architecture *arch, const SigningContext &ctx) - { return mOriginal->defaultRequirements(arch, ctx); } - size_t pageSize(const SigningContext &ctx) { return mOriginal->pageSize(ctx); } - - void strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated) { mOriginal->strictValidate(cd, tolerated); } - CFArrayRef allowedResourceOmissions() { return mOriginal->allowedResourceOmissions(); } - -private: - RefPointer mOriginal; // underlying representation -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_DISKREP diff --git a/OSX/include/security_codesigning/drmaker.cpp b/OSX/include/security_codesigning/drmaker.cpp deleted file mode 100644 index 7883755f..00000000 --- a/OSX/include/security_codesigning/drmaker.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// drmaker - create automatic Designated Requirements -// -#include "drmaker.h" -#include "csutilities.h" -#include -#include -//#include - -namespace Security { -namespace CodeSigning { - - -static const uint8_t adcSdkMarker[] = { APPLE_EXTENSION_OID, 2, 1 }; // iOS intermediate marker -const CSSM_DATA adcSdkMarkerOID = { sizeof(adcSdkMarker), (uint8_t *)adcSdkMarker }; - -static const uint8_t caspianSdkMarker[] = { APPLE_EXTENSION_OID, 2, 6 }; // Caspian intermediate marker -const CSSM_DATA devIdSdkMarkerOID = { sizeof(caspianSdkMarker), (uint8_t *)caspianSdkMarker }; -static const uint8_t caspianLeafMarker[] = { APPLE_EXTENSION_OID, 1, 13 }; // Caspian leaf certificate marker -const CSSM_DATA devIdLeafMarkerOID = { sizeof(caspianLeafMarker), (uint8_t *)caspianLeafMarker }; - - - -DRMaker::DRMaker(const Requirement::Context &context) - : ctx(context) -{ -} - -DRMaker::~DRMaker() -{ -} - - -// -// Generate the default (implicit) Designated Requirement for this StaticCode. -// This is a heuristic of sorts, and may change over time (for the better, we hope). -// -Requirement *DRMaker::make() -{ - // we can't make an explicit DR for a (proposed) ad-hoc signing because that requires the CodeDirectory (which we ain't got yet) - if (ctx.certCount() == 0) - return NULL; - - // always require the identifier - this->put(opAnd); - this->ident(ctx.identifier); - - if (isAppleCA(ctx.cert(Requirement::anchorCert)) -#if defined(TEST_APPLE_ANCHOR) - || !memcmp(anchorHash, Requirement::testAppleAnchorHash(), SHA1::digestLength) -#endif - ) - appleAnchor(); - else - nonAppleAnchor(); - - return Maker::make(); -} - - -void DRMaker::nonAppleAnchor() -{ - // get the Organization DN element for the leaf - CFRef leafOrganization; - MacOSError::check(SecCertificateCopySubjectComponent(ctx.cert(Requirement::leafCert), - &CSSMOID_OrganizationName, &leafOrganization.aref())); - - // now step up the cert chain looking for the first cert with a different one - int slot = Requirement::leafCert; // start at leaf - if (leafOrganization) { - while (SecCertificateRef ca = ctx.cert(slot+1)) { // NULL if you over-run the anchor slot - CFRef caOrganization; - MacOSError::check(SecCertificateCopySubjectComponent(ca, &CSSMOID_OrganizationName, &caOrganization.aref())); - if (!caOrganization || CFStringCompare(leafOrganization, caOrganization, 0) != kCFCompareEqualTo) - break; - slot++; - } - if (slot == ctx.certCount() - 1) // went all the way to the anchor... - slot = Requirement::anchorCert; // ... so say that - } - - // nail the last cert with the leaf's Organization value - SHA1::Digest authorityHash; - hashOfCertificate(ctx.cert(slot), authorityHash); - this->anchor(slot, authorityHash); -} - - -void DRMaker::appleAnchor() -{ - if (isIOSSignature()) { - // get the Common Name DN element for the leaf - CFRef leafCN; - MacOSError::check(SecCertificateCopySubjectComponent(ctx.cert(Requirement::leafCert), - &CSSMOID_CommonName, &leafCN.aref())); - - // apple anchor generic and ... - this->put(opAnd); - this->anchorGeneric(); // apple generic anchor and... - // ... leaf[subject.CN] = and ... - this->put(opAnd); - this->put(opCertField); // certificate - this->put(0); // leaf - this->put("subject.CN"); // [subject.CN] - this->put(matchEqual); // = - this->putData(leafCN); // - // ... cert 1[field.] exists - this->put(opCertGeneric); // certificate - this->put(1); // 1 - this->putData(adcSdkMarkerOID.Data, adcSdkMarkerOID.Length); // [field.] - this->put(matchExists); // exists - return; - } - - if (isDeveloperIDSignature()) { - // get the Organizational Unit DN element for the leaf (it contains the TEAMID) - CFRef teamID; - MacOSError::check(SecCertificateCopySubjectComponent(ctx.cert(Requirement::leafCert), - &CSSMOID_OrganizationalUnitName, &teamID.aref())); - - // apple anchor generic and ... - this->put(opAnd); - this->anchorGeneric(); // apple generic anchor and... - - // ... certificate 1[intermediate marker oid] exists and ... - this->put(opAnd); - this->put(opCertGeneric); // certificate - this->put(1); // 1 - this->putData(caspianSdkMarker, sizeof(caspianSdkMarker)); - this->put(matchExists); // exists - - // ... certificate leaf[Caspian cert oid] exists and ... - this->put(opAnd); - this->put(opCertGeneric); // certificate - this->put(0); // leaf - this->putData(caspianLeafMarker, sizeof(caspianLeafMarker)); - this->put(matchExists); // exists - - // ... leaf[subject.OU] = - this->put(opCertField); // certificate - this->put(0); // leaf - this->put("subject.OU"); // [subject.OU] - this->put(matchEqual); // = - this->putData(teamID); // TEAMID - return; - } - - // otherwise, claim this program for Apple Proper - this->anchor(); -} - -bool DRMaker::isIOSSignature() -{ - if (ctx.certCount() == 3) // leaf, one intermediate, anchor - if (SecCertificateRef intermediate = ctx.cert(1)) // get intermediate - if (certificateHasField(intermediate, CssmOid::overlay(adcSdkMarkerOID))) - return true; - return false; -} - -bool DRMaker::isDeveloperIDSignature() -{ - if (ctx.certCount() == 3) // leaf, one intermediate, anchor - if (SecCertificateRef intermediate = ctx.cert(1)) // get intermediate - if (certificateHasField(intermediate, CssmOid::overlay(devIdSdkMarkerOID))) - return true; - return false; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/drmaker.h b/OSX/include/security_codesigning/drmaker.h deleted file mode 100644 index 704c3611..00000000 --- a/OSX/include/security_codesigning/drmaker.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// drmaker - create Designated Requirements -// -#ifndef _H_DRMAKER -#define _H_DRMAKER - -#include "reqmaker.h" - -namespace Security { -namespace CodeSigning { - - -// -// Some useful certificate OID markers -// -extern const CSSM_DATA adcSdkMarkerOID; -extern const CSSM_DATA devIdSdkMarkerOID; -extern const CSSM_DATA devIdLeafMarkerOID; - - - -// -// A Maker of Designated Requirements -// -class DRMaker : public Requirement::Maker { -public: - DRMaker(const Requirement::Context &context); - virtual ~DRMaker(); - - const Requirement::Context &ctx; - -public: - Requirement *make(); - -private: - void appleAnchor(); - void nonAppleAnchor(); - bool isIOSSignature(); - bool isDeveloperIDSignature(); -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_DRMAKER diff --git a/OSX/include/security_codesigning/evaluationmanager.cpp b/OSX/include/security_codesigning/evaluationmanager.cpp deleted file mode 100644 index d64d6e1a..00000000 --- a/OSX/include/security_codesigning/evaluationmanager.cpp +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include "evaluationmanager.h" -#include "policyengine.h" -#include -#include -#include -#include - - - - -namespace Security { -namespace CodeSigning { - - - - -#pragma mark - EvaluationTask - - -// -// An evaluation task object manages the assessment - either directly, or in the -// form of waiting for another evaluation task to finish an assessment on the -// same target. -// -class EvaluationTask -{ -public: - CFURLRef path() const { return mPath.get(); } - AuthorityType type() const { return mType; } - bool isSharable() const { return mSharable; } - void setUnsharable() { mSharable = false; } - -private: - EvaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type); - virtual ~EvaluationTask(); - void performEvaluation(SecAssessmentFlags flags, CFDictionaryRef context); - void waitForCompletion(SecAssessmentFlags flags, CFMutableDictionaryRef result); - - PolicyEngine *mPolicyEngine; - AuthorityType mType; - dispatch_queue_t mWorkQueue; - dispatch_queue_t mFeedbackQueue; - dispatch_semaphore_t mAssessmentLock; - __block dispatch_once_t mAssessmentKicked; - int32_t mReferenceCount; - int32_t mEvalCount; -// This whole thing is a pre-existing crutch and must be fixed soon. -#define UNOFFICIAL_MAX_XPC_ID_LENGTH 127 - char mXpcActivityName[UNOFFICIAL_MAX_XPC_ID_LENGTH]; - bool mSharable; - - CFCopyRef mPath; - CFCopyRef mResult; - std::vector mFeedback; - - std::exception_ptr mExceptionToRethrow; - - friend class EvaluationManager; -}; - - -EvaluationTask::EvaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type) : - mPolicyEngine(engine), mType(type), mAssessmentLock(dispatch_semaphore_create(0)), - mAssessmentKicked(0), mReferenceCount(0), mEvalCount(0), mSharable(true), - mExceptionToRethrow(0) -{ - mXpcActivityName[0] = 0; - - mWorkQueue = dispatch_queue_create("EvaluationTask", 0); - mFeedbackQueue = dispatch_queue_create("EvaluationTaskFeedback", 0); - - mPath = path; - mResult.take(makeCFMutableDictionary()); -} - - -EvaluationTask::~EvaluationTask() -{ - dispatch_release(mFeedbackQueue); - dispatch_release(mWorkQueue); - dispatch_release(mAssessmentLock); -} - - -void EvaluationTask::performEvaluation(SecAssessmentFlags flags, CFDictionaryRef context) -{ - bool performTheEvaluation = false; - bool lowPriority = flags & kSecAssessmentFlagLowPriority; - - // each evaluation task performs at most a single evaluation - if (OSAtomicIncrement32Barrier(&mEvalCount) == 1) - performTheEvaluation = true; - - // define a block to run when the assessment has feedback available - SecAssessmentFeedback relayFeedback = ^Boolean(CFStringRef type, CFDictionaryRef information) { - - __block Boolean proceed = true; - dispatch_sync(mFeedbackQueue, ^{ - if (mFeedback.size() > 0) { - proceed = false; // we need at least one interested party to proceed - // forward the feedback to all registered listeners - for (int i = 0; i < mFeedback.size(); ++i) { - proceed |= mFeedback[i](type, information); - } - } - }); - if (!proceed) - this->setUnsharable(); // don't share an expiring evaluation task - return proceed; - }; - - - // if the calling context has a feedback block, register it to listen to - // our feedback relay - dispatch_sync(mFeedbackQueue, ^{ - SecAssessmentFeedback feedback = (SecAssessmentFeedback)CFDictionaryGetValue(context, kSecAssessmentContextKeyFeedback); - if (feedback && CFGetTypeID(feedback) == CFGetTypeID(relayFeedback)) - mFeedback.push_back(feedback); - }); - - // if we haven't already started the evaluation (we're the first interested - // party), do it now - if (performTheEvaluation) { - dispatch_semaphore_t startLock = dispatch_semaphore_create(0); - - // create the assessment block - dispatch_async(mWorkQueue, dispatch_block_create_with_qos_class(DISPATCH_BLOCK_ENFORCE_QOS_CLASS, QOS_CLASS_UTILITY, 0, ^{ - // signal that the assessment is ready to start - dispatch_semaphore_signal(startLock); - - // wait until we're permitted to start the assessment. if we're in low - // priority mode, this will not happen until we're on AC power. if not - // in low priority mode, we're either already free to perform the - // assessment or we will be quite soon - dispatch_semaphore_wait(mAssessmentLock, DISPATCH_TIME_FOREVER); - - // Unregister a possibly still scheduled activity, as it lost its point. - if (strlen(mXpcActivityName)) { - xpc_activity_unregister(mXpcActivityName); - } - - // copy the original context into our own mutable dictionary and replace - // (or assign) the feedback entry within it to our multi-receiver - // feedback relay block - CFRef contextOverride = makeCFMutableDictionary(context); - CFDictionaryRemoveValue(contextOverride.get(), kSecAssessmentContextKeyFeedback); - CFDictionaryAddValue(contextOverride.get(), kSecAssessmentContextKeyFeedback, relayFeedback); - - try { - // perform the evaluation - switch (mType) { - case kAuthorityExecute: - mPolicyEngine->evaluateCode(mPath.get(), kAuthorityExecute, flags, contextOverride.get(), mResult.get(), true); - break; - case kAuthorityInstall: - mPolicyEngine->evaluateInstall(mPath.get(), flags, contextOverride.get(), mResult.get()); - break; - case kAuthorityOpenDoc: - mPolicyEngine->evaluateDocOpen(mPath.get(), flags, contextOverride.get(), mResult.get()); - break; - default: - MacOSError::throwMe(errSecCSInvalidAttributeValues); - break; - } - } catch(...) { - mExceptionToRethrow = std::current_exception(); - } - - })); - - // wait for the assessment to start - dispatch_semaphore_wait(startLock, DISPATCH_TIME_FOREVER); - dispatch_release(startLock); - - if (lowPriority) { - // This whole thing is a crutch and should be handled differently. - // Maybe by having just one activity that just kicks off all remaining - // background assessments, CTS determines that it's a good time. - - // reduce the bundle path name to just the app component and generate an - // xpc_activity identifier from it. this identifier should be smaller than - // 128 characters due to rdar://problem/20094806 - string path = cfString(mPath); - size_t bundleNamePosition = path.rfind('/'); - const char *bundleName = "/default"; - if (bundleNamePosition != string::npos) - bundleName = path.c_str() + bundleNamePosition; - snprintf(mXpcActivityName, UNOFFICIAL_MAX_XPC_ID_LENGTH, "com.apple.security.assess%s", bundleName); - - // schedule the assessment to be permitted to run (beyond start) -- this - // will either happen once we're no longer on battery power, or - // immediately, based on the flag value of kSecAssessmentFlagLowPriority - xpc_object_t criteria = xpc_dictionary_create(NULL, NULL, 0); - xpc_dictionary_set_bool(criteria, XPC_ACTIVITY_REPEATING, false); - xpc_dictionary_set_int64(criteria, XPC_ACTIVITY_DELAY, 0); - xpc_dictionary_set_int64(criteria, XPC_ACTIVITY_GRACE_PERIOD, 0); - - xpc_dictionary_set_string(criteria, XPC_ACTIVITY_PRIORITY, XPC_ACTIVITY_PRIORITY_MAINTENANCE); - xpc_dictionary_set_bool(criteria, XPC_ACTIVITY_ALLOW_BATTERY, false); - - xpc_activity_register(mXpcActivityName, criteria, ^(xpc_activity_t activity) { - dispatch_once(&mAssessmentKicked, ^{ - dispatch_semaphore_signal(mAssessmentLock); - }); - }); - xpc_release(criteria); - } - } - - // If this is a foreground assessment to begin with, or if an assessment - // with an existing task has been requested in the foreground, kick it - // immediately. - if (!lowPriority) { - dispatch_once(&mAssessmentKicked, ^{ - dispatch_semaphore_signal(mAssessmentLock); - }); - } -} - - - -void EvaluationTask::waitForCompletion(SecAssessmentFlags flags, CFMutableDictionaryRef result) -{ - // if the caller didn't request low priority we will elevate the dispatch - // queue priority via our wait block - dispatch_qos_class_t qos_class = QOS_CLASS_USER_INITIATED; - if (flags & kSecAssessmentFlagLowPriority) - qos_class = QOS_CLASS_UTILITY; - - // wait for the assessment to complete; our wait block will queue up behind - // the assessment and the copy its results - dispatch_sync(mWorkQueue, dispatch_block_create_with_qos_class (DISPATCH_BLOCK_ENFORCE_QOS_CLASS, qos_class, 0, ^{ - // copy the class result back to the caller - cfDictionaryApplyBlock(mResult.get(), ^(const void *key, const void *value){ - CFDictionaryAddValue(result, key, value); - }); - })); - - if (mExceptionToRethrow) std::rethrow_exception(mExceptionToRethrow); -} - - - -#pragma mark - - - -static Boolean evaluationTasksAreEqual(const EvaluationTask *task1, const EvaluationTask *task2) -{ - if (!task1->isSharable() || !task2->isSharable()) return false; - if ((task1->type() != task2->type()) || - (cfString(task1->path()) != cfString(task2->path()))) - return false; - - return true; -} - - - - -#pragma mark - EvaluationManager - - -EvaluationManager *EvaluationManager::globalManager() -{ - static EvaluationManager *singleton; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - singleton = new EvaluationManager(); - }); - return singleton; -} - - -EvaluationManager::EvaluationManager() -{ - static CFDictionaryValueCallBacks evalTaskValueCallbacks = kCFTypeDictionaryValueCallBacks; - evalTaskValueCallbacks.equal = (CFDictionaryEqualCallBack)evaluationTasksAreEqual; - evalTaskValueCallbacks.retain = NULL; - evalTaskValueCallbacks.release = NULL; - mCurrentEvaluations.take( - CFDictionaryCreateMutable(NULL, - 0, - &kCFTypeDictionaryKeyCallBacks, - &evalTaskValueCallbacks)); - - mListLockQueue = dispatch_queue_create("EvaluationManagerSyncronization", 0); -} - - -EvaluationManager::~EvaluationManager() -{ - dispatch_release(mListLockQueue); -} - - -EvaluationTask *EvaluationManager::evaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result) -{ - __block EvaluationTask *evalTask = NULL; - - dispatch_sync(mListLockQueue, ^{ - // is path already being evaluated? - if (!(flags & kSecAssessmentFlagIgnoreActiveAssessments)) - evalTask = (EvaluationTask *)CFDictionaryGetValue(mCurrentEvaluations.get(), path); - if (!evalTask) { - // create a new task for the evaluation - evalTask = new EvaluationTask(engine, path, type); - if (flags & kSecAssessmentFlagIgnoreActiveAssessments) - evalTask->setUnsharable(); - CFDictionaryAddValue(mCurrentEvaluations.get(), path, evalTask); - } - evalTask->mReferenceCount++; - }); - - if (evalTask) - evalTask->performEvaluation(flags, context); - - return evalTask; -} - - -void EvaluationManager::waitForCompletion(EvaluationTask *task, SecAssessmentFlags flags, CFMutableDictionaryRef result) -{ - task->waitForCompletion(flags, result); -} - - -void EvaluationManager::removeTask(EvaluationTask *task) -{ - dispatch_sync(mListLockQueue, ^{ - // are we done with this evaluation task? - if (--task->mReferenceCount == 0) { - // yes -- remove it from our list and delete the object - CFDictionaryRemoveValue(mCurrentEvaluations.get(), task->path()); - delete task; - } - }); -} - - - -} // end namespace CodeSigning -} // end namespace Security - diff --git a/OSX/include/security_codesigning/evaluationmanager.h b/OSX/include/security_codesigning/evaluationmanager.h deleted file mode 100644 index bad99dc4..00000000 --- a/OSX/include/security_codesigning/evaluationmanager.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_EVALUATIONMANAGER -#define _H_EVALUATIONMANAGER - -#include "policydb.h" -#include - -namespace Security { -namespace CodeSigning { - - -class PolicyEngine; -class EvaluationTask; /* an opaque type */ - -// -// EvaluationManager manages a list of concurrent evaluation tasks (each of -// which is wrapped within an EvaluationTask object). -// -class EvaluationManager -{ -public: - static EvaluationManager *globalManager(); - - EvaluationTask *evaluationTask(PolicyEngine *engine, CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result); - void waitForCompletion(EvaluationTask *task, SecAssessmentFlags flags, CFMutableDictionaryRef result); - void removeTask(EvaluationTask *task); - -private: - CFCopyRef mCurrentEvaluations; - EvaluationManager(); - ~EvaluationManager(); - - dispatch_queue_t mListLockQueue; -}; - - - -} // end namespace CodeSigning -} // end namespace Security - -#endif //_H_EVALUATIONMANAGER - diff --git a/OSX/include/security_codesigning/filediskrep.cpp b/OSX/include/security_codesigning/filediskrep.cpp deleted file mode 100644 index d0e294dc..00000000 --- a/OSX/include/security_codesigning/filediskrep.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "filediskrep.h" -#include "StaticCode.h" -#include -#include - - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Everything's lazy in here -// -FileDiskRep::FileDiskRep(const char *path) - : SingleDiskRep(path) -{ - CODESIGN_DISKREP_CREATE_FILE(this, (char*)path); -} - - -// -// Produce an extended attribute name from a canonical slot name -// -string FileDiskRep::attrName(const char *name) -{ - static const char prefix[] = "com.apple.cs."; - return string(prefix) + name; -} - - -// -// Retrieve an extended attribute by name -// -CFDataRef FileDiskRep::getAttribute(const char *name) -{ - string aname = attrName(name); - try { - ssize_t length = fd().getAttrLength(aname); - if (length < 0) - return NULL; // no such attribute - CFMallocData buffer(length); - fd().getAttr(aname, buffer, length); - return buffer; - } catch (const UnixError &err) { - // recover some errors that happen in (relatively) benign circumstances - switch (err.error) { - case ENOTSUP: // no extended attributes on this filesystem - case EPERM: // filesystem objects to name(?) - return NULL; - default: - throw; - } - } -} - - -// -// Extract and return a component by slot number. -// If we have a Mach-O binary, use embedded components. -// Otherwise, look for and return the extended attribute, if any. -// -CFDataRef FileDiskRep::component(CodeDirectory::SpecialSlot slot) -{ - if (const char *name = CodeDirectory::canonicalSlotName(slot)) - return getAttribute(name); - else - return NULL; -} - - -// -// Generate a suggested set of internal requirements. -// We don't really have to say much. However, if we encounter a file that -// starts with the magic "#!" script marker, we do suggest that this should -// be a valid host if we can reasonably make out what that is. -// -const Requirements *FileDiskRep::defaultRequirements(const Architecture *, const SigningContext &ctx) -{ - // read start of file - char buffer[256]; - size_t length = fd().read(buffer, sizeof(buffer), 0); - if (length > 3 && buffer[0] == '#' && buffer[1] == '!' && buffer[2] == '/') { - // isolate (full) path element in #!/full/path -some -other -stuff - if (length == sizeof(buffer)) - length--; - buffer[length] = '\0'; - char *cmd = buffer + 2; - cmd[strcspn(cmd, " \t\n\r\f")] = '\0'; - secdebug("filediskrep", "looks like a script for %s", cmd); - if (cmd[1]) - try { - // find path on disk, get designated requirement (if signed) - string path = ctx.sdkPath(cmd); - if (RefPointer rep = DiskRep::bestFileGuess(path)) - if (SecPointer code = new SecStaticCode(rep)) - if (const Requirement *req = code->designatedRequirement()) { - CODESIGN_SIGN_DEP_INTERP(this, (char*)cmd, (void*)req); - // package up as host requirement and return that - Requirements::Maker maker; - maker.add(kSecHostRequirementType, req->clone()); - return maker.make(); - } - } catch (...) { - secdebug("filediskrep", "exception getting host requirement (ignored)"); - } - } - return NULL; -} - - -string FileDiskRep::format() -{ - return "generic"; -} - - -// -// FileDiskRep::Writers -// -DiskRep::Writer *FileDiskRep::writer() -{ - return new Writer(this); -} - - -// -// Write a component. -// Note that this isn't concerned with Mach-O writing; this is handled at -// a much higher level. If we're called, it's extended attribute time. -// -void FileDiskRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - try { - fd().setAttr(attrName(CodeDirectory::canonicalSlotName(slot)), - CFDataGetBytePtr(data), CFDataGetLength(data)); - } catch (const UnixError &error) { - if (error.error == ERANGE) - MacOSError::throwMe(errSecCSCMSTooLarge); - throw; - } -} - - -// -// Clear all signing data -// -void FileDiskRep::Writer::remove() -{ - for (CodeDirectory::SpecialSlot slot = 0; slot < cdSlotCount; slot++) - if (const char *name = CodeDirectory::canonicalSlotName(slot)) - fd().removeAttr(attrName(name)); - fd().removeAttr(attrName(kSecCS_SIGNATUREFILE)); -} - - -// -// We are NOT the preferred store for components because our approach -// (extended attributes) suffers from some serious limitations. -// -bool FileDiskRep::Writer::preferredStore() -{ - return false; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/filediskrep.h b/OSX/include/security_codesigning/filediskrep.h deleted file mode 100644 index 77733782..00000000 --- a/OSX/include/security_codesigning/filediskrep.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// filediskrep - single-file executable disk representation -// -#ifndef _H_FILEDISKREP -#define _H_FILEDISKREP - -#include "singlediskrep.h" -#include "machorep.h" -#include - -namespace Security { -namespace CodeSigning { - - -// -// A FileDiskRep represents a single code file on disk. We assume nothing about -// the format or contents of the file and impose no structure on it, other than -// assuming that all relevant code is contained in the file's data bytes. -// By default, we seal the entire file data as a single page. -// -// This is the ultimate fallback disk format. It is used if no other pattern -// applies. As such it is important that we do not introduce any assumptions -// here. Know that you do not know what any of the file means. -// -// FileDiskrep stores components in extended file attributes, one attribute -// per component. Note that this imposes size limitations on component size -// that may well be prohibitive in some applications. -// -// This DiskRep does not support resource sealing. -// -class FileDiskRep : public SingleDiskRep { -public: - FileDiskRep(const char *path); - - CFDataRef component(CodeDirectory::SpecialSlot slot); - std::string format(); - - const Requirements *defaultRequirements(const Architecture *arch, const SigningContext &ctx); - -public: - DiskRep::Writer *writer(); - class Writer; - friend class Writer; - -protected: - CFDataRef getAttribute(const char *name); - static std::string attrName(const char *name); -}; - - -// -// The write side of a FileDiskRep -// -class FileDiskRep::Writer : public SingleDiskRep::Writer { - friend class FileDiskRep; -public: - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); - void remove(); - bool preferredStore(); - -protected: - Writer(FileDiskRep *r) : SingleDiskRep::Writer(r, writerLastResort) { } - RefPointer rep; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_FILEDISKREP diff --git a/OSX/include/security_codesigning/kerneldiskrep.cpp b/OSX/include/security_codesigning/kerneldiskrep.cpp deleted file mode 100644 index 91f62435..00000000 --- a/OSX/include/security_codesigning/kerneldiskrep.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "kerneldiskrep.h" -#include - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Everything about the kernel is pretty much fixed, so there's -// no state to maintain. -// -KernelDiskRep::KernelDiskRep() -{ - CODESIGN_DISKREP_CREATE_KERNEL(this); -} - - -// -// We can't pull any resources from the kernel. -// And we know where it all is. -// -CFDataRef KernelDiskRep::component(CodeDirectory::SpecialSlot slot) -{ - return NULL; -} - -CFDataRef KernelDiskRep::identification() -{ - return NULL; -} - - -CFURLRef KernelDiskRep::copyCanonicalPath() -{ - return makeCFURL("/mach_kernel"); -} - -string KernelDiskRep::recommendedIdentifier(const SigningContext &) -{ - utsname names; - UnixError::check(::uname(&names)); - return string("kernel.") + names.sysname; -} - -size_t KernelDiskRep::signingLimit() -{ - return 0; // don't bother -} - -string KernelDiskRep::format() -{ - return "system kernel"; -} - -UnixPlusPlus::FileDesc &KernelDiskRep::fd() -{ - UnixError::throwMe(EINVAL); // don't have one -} - -string KernelDiskRep::mainExecutablePath() -{ - return "/mach_kernel"; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/kerneldiskrep.h b/OSX/include/security_codesigning/kerneldiskrep.h deleted file mode 100644 index deb1facf..00000000 --- a/OSX/include/security_codesigning/kerneldiskrep.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// kerneldiskrep - the kernel's own disk representation. -// -// This is a very special case. -// It's here primarily so we don't have to add special cases for the kernel -// all over the higher layers. -// -#ifndef _H_KERNELDISKREP -#define _H_KERNELDISKREP - -#include "diskrep.h" - -namespace Security { -namespace CodeSigning { - - -// -// A KernelDiskRep represents a (the) kernel on disk. -// It has no write support, so we can't sign the kernel, -// which is fine since we unconditionally trust it anyway. -// -class KernelDiskRep : public DiskRep { -public: - KernelDiskRep(); - - CFDataRef component(CodeDirectory::SpecialSlot slot); - CFDataRef identification(); - std::string mainExecutablePath(); - CFURLRef copyCanonicalPath(); - size_t signingLimit(); - std::string format(); - UnixPlusPlus::FileDesc &fd(); - - std::string recommendedIdentifier(const SigningContext &ctx); -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_KERNELDISKREP diff --git a/OSX/include/security_codesigning/machorep.cpp b/OSX/include/security_codesigning/machorep.cpp deleted file mode 100644 index d362b5ab..00000000 --- a/OSX/include/security_codesigning/machorep.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/* - * Copyright (c) 2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// machorep - DiskRep mix-in for handling Mach-O main executables -// -#include "machorep.h" -#include "StaticCode.h" -#include "reqmaker.h" - - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Object management. -// We open the main executable lazily, so nothing much happens on construction. -// If the context specifies a file offset, we directly pick that Mach-O binary (only). -// if it specifies an architecture, we try to pick that. Otherwise, we deliver the whole -// Universal object (which will usually deliver the "native" architecture later). -// -MachORep::MachORep(const char *path, const Context *ctx) - : SingleDiskRep(path), mSigningData(NULL) -{ - if (ctx) - if (ctx->offset) - mExecutable = new Universal(fd(), (size_t)ctx->offset, ctx->size); - else if (ctx->arch) { - auto_ptr full(new Universal(fd())); - mExecutable = new Universal(fd(), full->archOffset(ctx->arch), full->archLength(ctx->arch)); - } else - mExecutable = new Universal(fd()); - else - mExecutable = new Universal(fd()); - - assert(mExecutable); - CODESIGN_DISKREP_CREATE_MACHO(this, (char*)path, (void*)ctx); -} - -MachORep::~MachORep() -{ - delete mExecutable; - ::free(mSigningData); -} - - -// -// Sniffer function for "plausible Mach-O binary" -// -bool MachORep::candidate(FileDesc &fd) -{ - switch (Universal::typeOf(fd)) { - case MH_EXECUTE: - case MH_DYLIB: - case MH_DYLINKER: - case MH_BUNDLE: - case MH_KEXT_BUNDLE: - case MH_PRELOAD: - return true; // dynamic image; supported - case MH_OBJECT: - return false; // maybe later... - default: - return false; // not Mach-O (or too exotic) - } -} - - - -// -// Nowadays, the main executable object is created upon construction. -// -Universal *MachORep::mainExecutableImage() -{ - return mExecutable; -} - - -// -// Signing base is the start of the Mach-O architecture we're using -// -size_t MachORep::signingBase() -{ - return mainExecutableImage()->archOffset(); -} - - -// -// We choose the binary identifier for a Mach-O binary as follows: -// - If the Mach-O headers have a UUID command, use the UUID. -// - Otherwise, use the SHA-1 hash of the (entire) load commands. -// -CFDataRef MachORep::identification() -{ - std::auto_ptr macho(mainExecutableImage()->architecture()); - return identificationFor(macho.get()); -} - -CFDataRef MachORep::identificationFor(MachO *macho) -{ - // if there is a LC_UUID load command, use the UUID contained therein - if (const load_command *cmd = macho->findCommand(LC_UUID)) { - const uuid_command *uuidc = reinterpret_cast(cmd); - // uuidc->cmdsize should be sizeof(uuid_command), so if it is not, - // something is wrong. Fail out. - if (macho->flip(uuidc->cmdsize) != sizeof(uuid_command)) - MacOSError::throwMe(errSecCSSignatureInvalid); - char result[4 + sizeof(uuidc->uuid)]; - memcpy(result, "UUID", 4); - memcpy(result+4, uuidc->uuid, sizeof(uuidc->uuid)); - return makeCFData(result, sizeof(result)); - } - - // otherwise, use the SHA-1 hash of the entire load command area (this is way, way obsolete) - SHA1 hash; - hash(&macho->header(), sizeof(mach_header)); - hash(macho->loadCommands(), macho->commandLength()); - SHA1::Digest digest; - hash.finish(digest); - return makeCFData(digest, sizeof(digest)); -} - - -// -// Retrieve a component from the executable. -// This reads the entire signing SuperBlob when first called for an executable, -// and then caches it for further use. -// Note that we could read individual components directly off disk and only cache -// the SuperBlob Index directory. Our caller (usually SecStaticCode) is expected -// to cache the pieces anyway. -// -CFDataRef MachORep::component(CodeDirectory::SpecialSlot slot) -{ - switch (slot) { - case cdInfoSlot: - return infoPlist(); - default: - return embeddedComponent(slot); - } -} - - -// Retrieve a component from the embedded signature SuperBlob (if present). -// This reads the entire signing SuperBlob when first called for an executable, -// and then caches it for further use. -// Note that we could read individual components directly off disk and only cache -// the SuperBlob Index directory. Our caller (usually SecStaticCode) is expected -// to cache the pieces anyway. But it's not clear that the resulting multiple I/O -// calls wouldn't be slower in the end. -// -CFDataRef MachORep::embeddedComponent(CodeDirectory::SpecialSlot slot) -{ - if (!mSigningData) { // fetch and cache - auto_ptr macho(mainExecutableImage()->architecture()); - if (macho.get()) - if (const linkedit_data_command *cs = macho->findCodeSignature()) { - size_t offset = macho->flip(cs->dataoff); - size_t length = macho->flip(cs->datasize); - if ((mSigningData = EmbeddedSignatureBlob::readBlob(macho->fd(), macho->offset() + offset, length))) { - secdebug("machorep", "%zd signing bytes in %d blob(s) from %s(%s)", - mSigningData->length(), mSigningData->count(), - mainExecutablePath().c_str(), macho->architecture().name()); - } else { - secdebug("machorep", "failed to read signing bytes from %s(%s)", - mainExecutablePath().c_str(), macho->architecture().name()); - MacOSError::throwMe(errSecCSSignatureInvalid); - } - } - } - if (mSigningData) - return mSigningData->component(slot); - - // not found - return NULL; -} - - -// -// Extract an embedded Info.plist from the file. -// Returns NULL if none is found. -// -CFDataRef MachORep::infoPlist() -{ - CFRef info; - try { - auto_ptr macho(mainExecutableImage()->architecture()); - if (const section *sect = macho->findSection("__TEXT", "__info_plist")) { - if (macho->is64()) { - const section_64 *sect64 = reinterpret_cast(sect); - info.take(macho->dataAt(macho->flip(sect64->offset), (size_t)macho->flip(sect64->size))); - } else { - info.take(macho->dataAt(macho->flip(sect->offset), macho->flip(sect->size))); - } - } - } catch (...) { - secdebug("machorep", "exception reading embedded Info.plist"); - } - return info.yield(); -} - - -// -// Provide a (vaguely) human readable characterization of this code -// -string MachORep::format() -{ - if (Universal *fat = mainExecutableImage()) { - Universal::Architectures archs; - fat->architectures(archs); - if (fat->isUniversal()) { - string s = "Mach-O universal ("; - for (Universal::Architectures::const_iterator it = archs.begin(); - it != archs.end(); ++it) { - if (it != archs.begin()) - s += " "; - s += it->displayName(); - } - return s + ")"; - } else { - assert(archs.size() == 1); - return string("Mach-O thin (") + archs.begin()->displayName() + ")"; - } - } else - return "Mach-O (unrecognized format)"; -} - - -// -// Flush cached data -// -void MachORep::flush() -{ - size_t offset = mExecutable->offset(); - size_t length = mExecutable->length(); - delete mExecutable; - mExecutable = NULL; - ::free(mSigningData); - mSigningData = NULL; - SingleDiskRep::flush(); - mExecutable = new Universal(fd(), offset, length); -} - - -// -// Return a recommended unique identifier. -// If our file has an embedded Info.plist, use the CFBundleIdentifier from that. -// Otherwise, use the default. -// -string MachORep::recommendedIdentifier(const SigningContext &ctx) -{ - if (CFDataRef info = infoPlist()) { - if (CFRef dict = makeCFDictionaryFrom(info)) { - CFStringRef code = CFStringRef(CFDictionaryGetValue(dict, kCFBundleIdentifierKey)); - if (code && CFGetTypeID(code) != CFStringGetTypeID()) - MacOSError::throwMe(errSecCSBadDictionaryFormat); - if (code) - return cfString(code); - } else - MacOSError::throwMe(errSecCSBadDictionaryFormat); - } - - // ah well. Use the default - return SingleDiskRep::recommendedIdentifier(ctx); -} - - -// -// The default suggested requirements for Mach-O binaries are as follows: -// Library requirement: Composed from dynamic load commands. -// -const Requirements *MachORep::defaultRequirements(const Architecture *arch, const SigningContext &ctx) -{ - assert(arch); // enforced by signing infrastructure - Requirements::Maker maker; - - // add library requirements from DYLIB commands (if any) - if (Requirement *libreq = libraryRequirements(arch, ctx)) - maker.add(kSecLibraryRequirementType, libreq); // takes ownership - - // that's all - return maker.make(); -} - -Requirement *MachORep::libraryRequirements(const Architecture *arch, const SigningContext &ctx) -{ - auto_ptr macho(mainExecutableImage()->architecture(*arch)); - Requirement::Maker maker; - Requirement::Maker::Chain chain(maker, opOr); - - if (macho.get()) - if (const linkedit_data_command *ldep = macho->findLibraryDependencies()) { - size_t offset = macho->flip(ldep->dataoff); - size_t length = macho->flip(ldep->datasize); - if (LibraryDependencyBlob *deplist = LibraryDependencyBlob::readBlob(macho->fd(), macho->offset() + offset, length)) { - try { - secdebug("machorep", "%zd library dependency bytes in %d blob(s) from %s(%s)", - deplist->length(), deplist->count(), - mainExecutablePath().c_str(), macho->architecture().name()); - unsigned count = deplist->count(); - // we could walk through DYLIB load commands in parallel. We just don't need anything from them so far - for (unsigned n = 0; n < count; n++) { - const Requirement *req = NULL; - if (const BlobCore *dep = deplist->blob(n)) { - if ((req = Requirement::specific(dep))) { - // binary code requirement; good to go - } else if (const BlobWrapper *wrap = BlobWrapper::specific(dep)) { - // blob-wrapped text form - convert to binary requirement - std::string reqString = std::string((const char *)wrap->data(), wrap->length()); - CFRef areq; - MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &areq.aref())); - CFRef reqData; - MacOSError::check(SecRequirementCopyData(areq, kSecCSDefaultFlags, &reqData.aref())); - req = Requirement::specific((const BlobCore *)CFDataGetBytePtr(reqData)); - } else { - secdebug("machorep", "unexpected blob type 0x%x in slot %d of binary dependencies", dep->magic(), n); - continue; - } - chain.add(); - maker.copy(req); - } else - secdebug("machorep", "missing DR info for library index %d", n); - } - ::free(deplist); - } catch (...) { - ::free(deplist); - throw; - } - } - } - if (chain.empty()) - return NULL; - else - return maker.make(); -} - - -// -// Default to system page size for segmented (paged) signatures -// -size_t MachORep::pageSize(const SigningContext &) -{ - return segmentedPageSize; -} - - -// -// Strict validation -// -void MachORep::strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated) -{ - // if the constructor found suspicious issues, fail a struct validation now - if (mExecutable->isSuspicious() && tolerated.find(errSecCSBadMainExecutable) == tolerated.end()) - MacOSError::throwMe(errSecCSBadMainExecutable); - - // the signature's code extent must be what we would have picked (no funny hand editing) - if (cd) { - auto_ptr macho(mExecutable->architecture()); - if (cd->codeLimit != macho->signingExtent()) - MacOSError::throwMe(errSecCSSignatureInvalid); - } -} - - -// -// FileDiskRep::Writers -// -DiskRep::Writer *MachORep::writer() -{ - return new Writer(this); -} - - -// -// Write a component. -// MachORep::Writers don't write to components directly; the signing code uses special -// knowledge of the Mach-O format to build embedded signatures and blasts them directly -// to disk. Thus this implementation will never be called (and, if called, will simply fail). -// -void MachORep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - assert(false); - MacOSError::throwMe(errSecCSInternalError); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/machorep.h b/OSX/include/security_codesigning/machorep.h deleted file mode 100644 index 07bba9e4..00000000 --- a/OSX/include/security_codesigning/machorep.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// machorep - DiskRep mix-in for handling Mach-O main executables -// -#ifndef _H_MACHOREP -#define _H_MACHOREP - -#include "singlediskrep.h" -#include "sigblob.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// MachORep is a DiskRep class that supports code signatures -// directly embedded in Mach-O binary files. -// -// It does not have write support (for writing signatures); -// writing multi-architecture binaries is complicated enough -// that it's driven directly from the signing code, with no -// abstractions to get in the way. -// -class MachORep : public SingleDiskRep { -public: - MachORep(const char *path, const Context *ctx = NULL); - virtual ~MachORep(); - - CFDataRef component(CodeDirectory::SpecialSlot slot); - CFDataRef identification(); - Universal *mainExecutableImage(); - size_t signingBase(); - std::string format(); - - std::string recommendedIdentifier(const SigningContext &ctx); - const Requirements *defaultRequirements(const Architecture *arch, const SigningContext &ctx); - size_t pageSize(const SigningContext &ctx); - - void strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated); - - void flush(); // flush cache - - static bool candidate(UnixPlusPlus::FileDesc &fd); - -public: - static CFDataRef identificationFor(MachO *macho); - -public: - DiskRep::Writer *writer(); - class Writer; - friend class Writer; - -protected: - CFDataRef embeddedComponent(CodeDirectory::SpecialSlot slot); - CFDataRef infoPlist(); - Requirement *libraryRequirements(const Architecture *arch, const SigningContext &ctx); - -private: - Universal *mExecutable; // cached Mach-O/Universal reference to mainExecutablePath() - EmbeddedSignatureBlob *mSigningData; // cached signing data from current architecture -}; - - -// -// The write side of a MachORep. -// This is purposely dysfunctional; Mach-O signatures are written -// by code in signerutils, not by DiskRep::Writers. -// -class MachORep::Writer : public SingleDiskRep::Writer { - friend class FileDiskRep; -public: - Writer(MachORep *r) : SingleDiskRep::Writer(r, writerNoGlobal) { } - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_MACHOREP diff --git a/OSX/include/security_codesigning/opaquewhitelist.cpp b/OSX/include/security_codesigning/opaquewhitelist.cpp deleted file mode 100644 index 7fbde5fc..00000000 --- a/OSX/include/security_codesigning/opaquewhitelist.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "opaquewhitelist.h" -#include "csutilities.h" -#include "StaticCode.h" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - -using namespace SQLite; - - -static std::string hashString(CFDataRef hash); -static void attachOpaque(SecStaticCodeRef code, SecAssessmentFeedback feedback); - - -// -// Open the database -// -OpaqueWhitelist::OpaqueWhitelist(const char *path, int flags) - : SQLite::Database(path ? path : opaqueDatabase, flags) -{ - SQLite::Statement createConditions(*this, - "CREATE TABLE IF NOT EXISTS conditions (" - " label text," - " weight real not null unique," - " source text," - " identifier text," - " version text," - " conditions text not null);" - ); - createConditions.execute(); - mOverrideQueue = dispatch_queue_create("com.apple.security.assessment.whitelist-override", DISPATCH_QUEUE_SERIAL); -} - -OpaqueWhitelist::~OpaqueWhitelist() -{ - dispatch_release(mOverrideQueue); -} - - -// -// Check if a code object is whitelisted -// -bool OpaqueWhitelist::contains(SecStaticCodeRef codeRef, SecAssessmentFeedback feedback, OSStatus reason) -{ - // make our own copy of the code object, so we can poke at it without disturbing the original - SecPointer code = new SecStaticCode(SecStaticCode::requiredStatic(codeRef)->diskRep()); - - CFCopyRef current = code->cdHash(); // current cdhash - CFDataRef opaque = NULL; // holds computed opaque cdhash - bool match = false; // holds final result - - if (!current) - return false; // unsigned - - // collect auxiliary information for trace - CFRef info; - std::string team = ""; - CFStringRef cfVersion = NULL, cfShortVersion = NULL, cfExecutable = NULL; - if (errSecSuccess == SecCodeCopySigningInformation(code->handle(false), kSecCSSigningInformation, &info.aref())) { - if (CFStringRef cfTeam = CFStringRef(CFDictionaryGetValue(info, kSecCodeInfoTeamIdentifier))) - team = cfString(cfTeam); - if (CFDictionaryRef infoPlist = CFDictionaryRef(CFDictionaryGetValue(info, kSecCodeInfoPList))) { - if (CFTypeRef version = CFDictionaryGetValue(infoPlist, kCFBundleVersionKey)) - if (CFGetTypeID(version) == CFStringGetTypeID()) - cfVersion = CFStringRef(version); - if (CFTypeRef shortVersion = CFDictionaryGetValue(infoPlist, _kCFBundleShortVersionStringKey)) - if (CFGetTypeID(shortVersion) == CFStringGetTypeID()) - cfShortVersion = CFStringRef(shortVersion); - if (CFTypeRef executable = CFDictionaryGetValue(infoPlist, kCFBundleExecutableKey)) - if (CFGetTypeID(executable) == CFStringGetTypeID()) - cfExecutable = CFStringRef(executable); - } - } - - // compute and attach opaque signature - attachOpaque(code->handle(false), feedback); - opaque = code->cdHash(); - - // lookup current cdhash in whitelist - SQLite::Statement lookup(*this, "SELECT opaque FROM whitelist WHERE current=:current" - " AND opaque != 'disable override'"); - lookup.bind(":current") = current.get(); - while (lookup.nextRow()) { - CFRef expected = lookup[0].data(); - if (CFEqual(opaque, expected)) { - match = true; // actual opaque cdhash matches expected - break; - } - } - - // prepare strings for use inside block - std::string currentHash = hashString(current); - std::string opaqueHash = hashString(opaque); - - // send a trace indicating the result - MessageTrace trace("com.apple.security.assessment.whitelist2", code->identifier().c_str()); - trace.add("signature2", "%s", currentHash.c_str()); - trace.add("signature3", "%s", opaqueHash.c_str()); - trace.add("result", match ? "pass" : "fail"); - trace.add("reason", "%d", reason); - if (!team.empty()) - trace.add("teamid", "%s", team.c_str()); - if (cfVersion) - trace.add("version", "%s", cfString(cfVersion).c_str()); - if (cfShortVersion) - trace.add("version2", "%s", cfString(cfShortVersion).c_str()); - if (cfExecutable) - trace.add("execname", "%s", cfString(cfExecutable).c_str()); - trace.send(""); - - return match; -} - - -// -// Obtain special validation conditions for a static code, based on database configuration. -// -CFDictionaryRef OpaqueWhitelist::validationConditionsFor(SecStaticCodeRef code) -{ - // figure out which team key to use - std::string team = "UNKNOWN"; - CFStringRef cfId = NULL; - CFStringRef cfVersion = NULL; - CFRef info; // holds lifetimes for the above - if (errSecSuccess == SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())) { - if (CFStringRef cfTeam = CFStringRef(CFDictionaryGetValue(info, kSecCodeInfoTeamIdentifier))) - team = cfString(cfTeam); - cfId = CFStringRef(CFDictionaryGetValue(info, kSecCodeInfoIdentifier)); - if (CFDictionaryRef infoPlist = CFDictionaryRef(CFDictionaryGetValue(info, kSecCodeInfoPList))) - if (CFTypeRef version = CFDictionaryGetValue(infoPlist, _kCFBundleShortVersionStringKey)) - if (CFGetTypeID(version) == CFStringGetTypeID()) - cfVersion = CFStringRef(version); - } - if (cfId == NULL) // unsigned; punt - return NULL; - - // find the highest weight matching condition. We perform no merging and the heaviest rule wins - SQLite::Statement matches(*this, - "SELECT conditions FROM conditions" - " WHERE (source = :source or source IS NULL)" - " AND (identifier = :identifier or identifier is NULL)" - " AND ((:version IS NULL AND version IS NULL) OR (version = :version OR version IS NULL))" - " ORDER BY weight DESC" - " LIMIT 1" - ); - matches.bind(":source") = team; - matches.bind(":identifier") = cfString(cfId); - if (cfVersion) - matches.bind(":version") = cfString(cfVersion); - if (matches.nextRow()) { - CFTemp conditions((const char*)matches[0]); - return conditions.yield(); - } - // no matches - return NULL; -} - - -// -// Convert a SHA1 hash to a hex string -// -static std::string hashString(CFDataRef hash) -{ - if (CFDataGetLength(hash) != sizeof(SHA1::Digest)) { - return std::string(); - } else { - const UInt8 *bytes = CFDataGetBytePtr(hash); - char s[2 * SHA1::digestLength + 1]; - for (unsigned n = 0; n < SHA1::digestLength; n++) - sprintf(&s[2*n], "%2.2x", bytes[n]); - return std::string(s); - } -} - - -// -// Add a code object to the whitelist -// -void OpaqueWhitelist::add(SecStaticCodeRef codeRef) -{ - // make our own copy of the code object - SecPointer code = new SecStaticCode(SecStaticCode::requiredStatic(codeRef)->diskRep()); - - CFCopyRef current = code->cdHash(); - attachOpaque(code->handle(false), NULL); // compute and attach an opaque signature - CFDataRef opaque = code->cdHash(); - - SQLite::Statement insert(*this, "INSERT OR REPLACE INTO whitelist (current,opaque) VALUES (:current, :opaque)"); - insert.bind(":current") = current.get(); - insert.bind(":opaque") = opaque; - insert.execute(); -} - - -// -// Generate and attach an ad-hoc opaque signature -// -static void attachOpaque(SecStaticCodeRef code, SecAssessmentFeedback feedback) -{ - CFTemp rules("{" // same resource rules as used for collection - "rules={" - "'^.*' = #T" - "'^Info\\.plist$' = {omit=#T,weight=10}" - "},rules2={" - "'^(Frameworks|SharedFrameworks|Plugins|Plug-ins|XPCServices|Helpers|MacOS)/' = {nested=#T, weight=0}" - "'^.*' = #T" - "'^Info\\.plist$' = {omit=#T,weight=10}" - "'^[^/]+$' = {top=#T, weight=0}" - "}" - "}"); - - CFRef signature = CFDataCreateMutable(NULL, 0); - CFTemp arguments("{%O=%O, %O=#N, %O=%O}", - kSecCodeSignerDetached, signature.get(), - kSecCodeSignerIdentity, /* kCFNull, */ - kSecCodeSignerResourceRules, rules.get()); - CFRef signer; - SecCSFlags creationFlags = kSecCSSignOpaque | kSecCSSignNoV1 | kSecCSSignBundleRoot; - SecCSFlags operationFlags = 0; - - if (feedback) - operationFlags |= kSecCSReportProgress; - MacOSError::check(SecStaticCodeSetCallback(code, kSecCSDefaultFlags, NULL, ^CFTypeRef(SecStaticCodeRef code, CFStringRef stage, CFDictionaryRef info) { - if (CFEqual(stage, CFSTR("progress"))) { - bool proceed = feedback(kSecAssessmentFeedbackProgress, info); - if (!proceed) - SecStaticCodeCancelValidation(code, kSecCSDefaultFlags); - } - return NULL; - })); - - MacOSError::check(SecCodeSignerCreate(arguments, creationFlags, &signer.aref())); - MacOSError::check(SecCodeSignerAddSignature(signer, code, operationFlags)); - MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags)); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/opaquewhitelist.h b/OSX/include/security_codesigning/opaquewhitelist.h deleted file mode 100644 index 066efcbe..00000000 --- a/OSX/include/security_codesigning/opaquewhitelist.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_OPAQUEWHITELIST -#define _H_OPAQUEWHITELIST - -#include "SecAssessment.h" -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -namespace SQLite = SQLite3; - - -static const char opaqueDatabase[] = "/var/db/gkopaque.bundle/Contents/Resources/gkopaque.db"; - - -class OpaqueWhitelist : public SQLite::Database { -public: - OpaqueWhitelist(const char *path = NULL, int flags = SQLITE_OPEN_READWRITE); - virtual ~OpaqueWhitelist(); - -public: - void add(SecStaticCodeRef code); - bool contains(SecStaticCodeRef code, SecAssessmentFeedback feedback, OSStatus reason); - - CFDictionaryRef validationConditionsFor(SecStaticCodeRef code); - -private: - dispatch_queue_t mOverrideQueue; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif //_H_OPAQUEWHITELIST diff --git a/OSX/include/security_codesigning/piddiskrep.cpp b/OSX/include/security_codesigning/piddiskrep.cpp deleted file mode 100644 index f3488088..00000000 --- a/OSX/include/security_codesigning/piddiskrep.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2012-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "piddiskrep.h" -#include "sigblob.h" -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - -void -PidDiskRep::fetchData(void) -{ - xpc_connection_t conn = xpc_connection_create("com.apple.CodeSigningHelper", - dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); - xpc_connection_set_event_handler(conn, ^(xpc_object_t object){ }); - xpc_connection_resume(conn); - - xpc_object_t request = xpc_dictionary_create(NULL, NULL, 0); - assert(request != NULL); - xpc_dictionary_set_string(request, "command", "fetchData"); - xpc_dictionary_set_int64(request, "pid", mPid); - - xpc_object_t reply = xpc_connection_send_message_with_reply_sync(conn, request); - if (reply && xpc_get_type(reply) == XPC_TYPE_DICTIONARY) { - const void *data; - size_t size; - - if (!mInfoPlist) { - data = xpc_dictionary_get_data(reply, "infoPlist", &size); - if (data && size > 0 && size < 50 * 1024) - mInfoPlist.take(CFDataCreate(NULL, (const UInt8 *)data, (CFIndex)size)); - } - if (!mBundleURL) { - data = xpc_dictionary_get_data(reply, "bundleURL", &size); - if (data && size > 0 && size < 50 * 1024) - mBundleURL.take(CFURLCreateWithBytes(NULL, (const UInt8 *)data, (CFIndex)size, kCFStringEncodingUTF8, NULL)); - } - } - if (reply) - xpc_release(reply); - - xpc_release(request); - xpc_release(conn); - - if (!mBundleURL) - MacOSError::throwMe(errSecCSNoSuchCode); -} - - -PidDiskRep::PidDiskRep(pid_t pid, CFDataRef infoPlist) -{ - BlobCore header; - CODESIGN_DISKREP_CREATE_KERNEL(this); - - mPid = pid; - mInfoPlist = infoPlist; - - fetchData(); - - int rcent = ::csops(pid, CS_OPS_BLOB, &header, sizeof(header)); - if (rcent == 0) - MacOSError::throwMe(errSecCSNoSuchCode); - - if (errno != ERANGE) - UnixError::throwMe(errno); - - if (header.length() > 1024 * 1024) - MacOSError::throwMe(errSecCSNoSuchCode); - - uint32_t bufferLen = (uint32_t)header.length(); - mBuffer = new uint8_t [bufferLen]; - - UnixError::check(::csops(pid, CS_OPS_BLOB, mBuffer, bufferLen)); - - const EmbeddedSignatureBlob *b = (const EmbeddedSignatureBlob *)mBuffer; - if (!b->validateBlob(bufferLen)) - MacOSError::throwMe(errSecCSSignatureInvalid); -} - -PidDiskRep::~PidDiskRep() -{ - if (mBuffer) - delete [] mBuffer; -} - - -bool PidDiskRep::supportInfoPlist() -{ - return mInfoPlist; -} - - -CFDataRef PidDiskRep::component(CodeDirectory::SpecialSlot slot) -{ - if (slot == cdInfoSlot) - return mInfoPlist.retain(); - - EmbeddedSignatureBlob *b = (EmbeddedSignatureBlob *)this->blob(); - return b->component(slot); -} - -CFDataRef PidDiskRep::identification() -{ - return NULL; -} - - -CFURLRef PidDiskRep::copyCanonicalPath() -{ - return mBundleURL.retain(); -} - -string PidDiskRep::recommendedIdentifier(const SigningContext &) -{ - return string("pid") + to_string(mPid); -} - -size_t PidDiskRep::signingLimit() -{ - return 0; -} - -string PidDiskRep::format() -{ - return "pid diskrep"; -} - -UnixPlusPlus::FileDesc &PidDiskRep::fd() -{ - UnixError::throwMe(EINVAL); -} - -string PidDiskRep::mainExecutablePath() -{ - char path[MAXPATHLEN * 2]; - if(::proc_pidpath(mPid, path, sizeof(path)) == 0) - UnixError::throwMe(errno); - - return path; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/piddiskrep.h b/OSX/include/security_codesigning/piddiskrep.h deleted file mode 100644 index fc1e3249..00000000 --- a/OSX/include/security_codesigning/piddiskrep.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2012-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// PidDiskRep -// -#ifndef _H_PIDDISKREP -#define _H_PIDDISKREP - -#include "diskrep.h" - -namespace Security { -namespace CodeSigning { - - -// -// A KernelDiskRep represents a (the) kernel on disk. -// It has no write support, so we can't sign the kernel, -// which is fine since we unconditionally trust it anyway. -// -class PidDiskRep : public DiskRep { -public: - PidDiskRep(pid_t pid, CFDataRef infoPlist); - ~PidDiskRep(); - - CFDataRef component(CodeDirectory::SpecialSlot slot); - CFDataRef identification(); - std::string mainExecutablePath(); - CFURLRef copyCanonicalPath(); - size_t signingLimit(); - std::string format(); - UnixPlusPlus::FileDesc &fd(); - - std::string recommendedIdentifier(const SigningContext &ctx); - - bool supportInfoPlist(); -private: - const BlobCore *blob() { return (const BlobCore *)mBuffer; } - void fetchData(void); - pid_t mPid; - uint8_t *mBuffer; - CFRef mInfoPlist; - CFRef mBundleURL; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_PIDDISKREP diff --git a/OSX/include/security_codesigning/policydb.cpp b/OSX/include/security_codesigning/policydb.cpp deleted file mode 100644 index be72b432..00000000 --- a/OSX/include/security_codesigning/policydb.cpp +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Copyright (c) 2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "cs.h" -#include "policydb.h" -#include "policyengine.h" -#include -#include -#include -#include -#include -#include -#include -#include "csdatabase.h" - -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -using namespace SQLite; - - -// -// Determine the database path -// -static const char *dbPath() -{ - if (const char *s = getenv("SYSPOLICYDATABASE")) - return s; - return defaultDatabase; -} - - -// -// Help mapping API-ish CFString keys to more convenient internal enumerations -// -typedef struct { - const CFStringRef &cstring; - uint enumeration; -} StringMap; - -static uint mapEnum(CFDictionaryRef context, CFStringRef attr, const StringMap *map, uint value = 0) -{ - if (context) - if (CFTypeRef value = CFDictionaryGetValue(context, attr)) - for (const StringMap *mp = map; mp->cstring; ++mp) - if (CFEqual(mp->cstring, value)) - return mp->enumeration; - return value; -} - -static const StringMap mapType[] = { - { kSecAssessmentOperationTypeExecute, kAuthorityExecute }, - { kSecAssessmentOperationTypeInstall, kAuthorityInstall }, - { kSecAssessmentOperationTypeOpenDocument, kAuthorityOpenDoc }, - { NULL } -}; - -AuthorityType typeFor(CFDictionaryRef context, AuthorityType type /* = kAuthorityInvalid */) -{ - return mapEnum(context, kSecAssessmentContextKeyOperation, mapType, type); -} - -CFStringRef typeNameFor(AuthorityType type) -{ - for (const StringMap *mp = mapType; mp->cstring; ++mp) - if (type == mp->enumeration) - return mp->cstring; - return CFStringCreateWithFormat(NULL, NULL, CFSTR("type %d"), type); -} - - -// -// Open the database -// -PolicyDatabase::PolicyDatabase(const char *path, int flags) - : SQLite::Database(path ? path : dbPath(), flags), - mLastExplicitCheck(0) -{ - // sqlite3 doesn't do foreign key support by default, have to turn this on per connection - SQLite::Statement foreign(*this, "PRAGMA foreign_keys = true"); - foreign.execute(); - - // Try upgrade processing if we may be open for write. - // Ignore any errors (we may have been downgraded to read-only) - // and try again later. - if (openFlags() & SQLITE_OPEN_READWRITE) - try { - upgradeDatabase(); - installExplicitSet(gkeAuthFile, gkeSigsFile); - } catch(...) { - } -} - -PolicyDatabase::~PolicyDatabase() -{ /* virtual */ } - - -// -// Quick-check the cache for a match. -// Return true on a cache hit, false on failure to confirm a hit for any reason. -// -bool PolicyDatabase::checkCache(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFMutableDictionaryRef result) -{ - // we currently don't use the cache for anything but execution rules - if (type != kAuthorityExecute) - return false; - - CFRef code; - MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref())); - if (SecStaticCodeCheckValidity(code, kSecCSBasicValidateOnly, NULL) != errSecSuccess) - return false; // quick pass - any error is a cache miss - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref())); - CFDataRef cdHash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); - - // check the cache table for a fast match - SQLite::Statement cached(*this, "SELECT object.allow, authority.label, authority FROM object, authority" - " WHERE object.authority = authority.id AND object.type = :type AND object.hash = :hash AND authority.disabled = 0" - " AND JULIANDAY('now') < object.expires;"); - cached.bind(":type").integer(type); - cached.bind(":hash") = cdHash; - if (cached.nextRow()) { - bool allow = int(cached[0]); - const char *label = cached[1]; - SQLite::int64 auth = cached[2]; - SYSPOLICY_ASSESS_CACHE_HIT(); - - // If its allowed, lets do a full validation unless if - // we are overriding the assessement, since that force - // the verdict to 'pass' at the end - - if (allow && !overrideAssessment(flags)) - MacOSError::check(SecStaticCodeCheckValidity(code, kSecCSDefaultFlags, NULL)); - - cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow); - PolicyEngine::addAuthority(flags, result, label, auth, kCFBooleanTrue); - return true; - } - return false; -} - - -// -// Purge the object cache of all expired entries. -// These are meant to run within the caller's transaction. -// -void PolicyDatabase::purgeAuthority() -{ - SQLite::Statement cleaner(*this, - "DELETE FROM authority WHERE expires <= JULIANDAY('now');"); - cleaner.execute(); -} - -void PolicyDatabase::purgeObjects() -{ - SQLite::Statement cleaner(*this, - "DELETE FROM object WHERE expires <= JULIANDAY('now');"); - cleaner.execute(); -} - -void PolicyDatabase::purgeObjects(double priority) -{ - SQLite::Statement cleaner(*this, - "DELETE FROM object WHERE expires <= JULIANDAY('now') OR (SELECT priority FROM authority WHERE id = object.authority) <= :priority;"); - cleaner.bind(":priority") = priority; - cleaner.execute(); -} - - -// -// Database migration -// -std::string PolicyDatabase::featureLevel(const char *name) -{ - SQLite::Statement feature(*this, "SELECT value FROM feature WHERE name=:name"); - feature.bind(":name") = name; - if (feature.nextRow()) { - if (const char *value = feature[0]) - return value; - else - return "default"; // old engineering versions may have NULL values; tolerate this - } - return ""; // new feature (no level) -} - -void PolicyDatabase::addFeature(const char *name, const char *value, const char *remarks) -{ - SQLite::Statement feature(*this, "INSERT OR REPLACE INTO feature (name,value,remarks) VALUES(:name, :value, :remarks)"); - feature.bind(":name") = name; - feature.bind(":value") = value; - feature.bind(":remarks") = remarks; - feature.execute(); -} - -void PolicyDatabase::simpleFeature(const char *feature, void (^perform)()) -{ - if (!hasFeature(feature)) { - SQLite::Transaction update(*this); - perform(); - addFeature(feature, "upgraded", "upgraded"); - update.commit(); - } -} - -void PolicyDatabase::simpleFeature(const char *feature, const char *sql) -{ - simpleFeature(feature, ^{ - SQLite::Statement perform(*this, sql); - perform.execute(); - }); -} - - -void PolicyDatabase::upgradeDatabase() -{ - simpleFeature("bookmarkhints", - "CREATE TABLE bookmarkhints (" - " id INTEGER PRIMARY KEY AUTOINCREMENT, " - " bookmark BLOB," - " authority INTEGER NOT NULL" - " REFERENCES authority(id) ON DELETE CASCADE" - ")"); - - simpleFeature("codesignedpackages", ^{ - SQLite::Statement update(*this, - "UPDATE authority" - " SET requirement = 'anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and " - "(certificate leaf[field.1.2.840.113635.100.6.1.14] or certificate leaf[field.1.2.840.113635.100.6.1.13])'" - " WHERE type = 2 and label = 'Developer ID' and flags & :flag"); - update.bind(":flag") = kAuthorityFlagDefault; - update.execute(); - }); - - simpleFeature("filter_unsigned", - "ALTER TABLE authority ADD COLUMN filter_unsigned TEXT NULL" - ); - - simpleFeature("strict_apple_installer", ^{ - SQLite::Statement update(*this, - "UPDATE authority" - " SET requirement = 'anchor apple generic and certificate 1[subject.CN] = \"Apple Software Update Certification Authority\"'" - " WHERE flags & :flag AND label = 'Apple Installer'"); - update.bind(":flag") = kAuthorityFlagDefault; - update.execute(); - SQLite::Statement add(*this, - "INSERT INTO authority (type, label, flags, requirement)" - " VALUES (2, 'Mac App Store', :flags, 'anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.10] exists')"); - add.bind(":flags") = kAuthorityFlagDefault; - add.execute(); - }); -} - - -// -// Install Gatekeeper override (GKE) data. -// The arguments are paths to the authority and signature files. -// -void PolicyDatabase::installExplicitSet(const char *authfile, const char *sigfile) -{ - // only try this every gkeCheckInterval seconds - time_t now = time(NULL); - if (mLastExplicitCheck + gkeCheckInterval > now) - return; - mLastExplicitCheck = now; - - try { - if (CFRef authData = cfLoadFile(authfile)) { - CFDictionary auth(CFRef(makeCFDictionaryFrom(authData)), errSecCSDbCorrupt); - CFDictionaryRef content = auth.get(CFSTR("authority")); - std::string authUUID = cfString(auth.get(CFSTR("uuid"))); - if (authUUID.empty()) { - secdebug("gkupgrade", "no uuid in auth file; ignoring gke.auth"); - return; - } - std::string dbUUID; - SQLite::Statement uuidQuery(*this, "SELECT value FROM feature WHERE name='gke'"); - if (uuidQuery.nextRow()) - dbUUID = (const char *)uuidQuery[0]; - if (dbUUID == authUUID) { - secdebug("gkupgrade", "gke.auth already present, ignoring"); - return; - } - Syslog::notice("loading GKE %s (replacing %s)", authUUID.c_str(), dbUUID.empty() ? "nothing" : dbUUID.c_str()); - - // first, load code signatures. This is pretty much idempotent - if (sigfile) - if (FILE *sigs = fopen(sigfile, "r")) { - unsigned count = 0; - SignatureDatabaseWriter db; - while (const BlobCore *blob = BlobCore::readBlob(sigs)) { - db.storeCode(blob, ""); - count++; - } - secdebug("gkupgrade", "%d detached signature(s) loaded from override data", count); - fclose(sigs); - } - - // start transaction (atomic from here on out) - SQLite::Transaction loadAuth(*this, SQLite::Transaction::exclusive, "GKE_Upgrade"); - - // purge prior authority data - SQLite::Statement purge(*this, "DELETE FROM authority WHERE flags & :flag"); - purge.bind(":flag") = kAuthorityFlagWhitelist; - purge(); - - // load new data - CFIndex count = CFDictionaryGetCount(content); - CFStringRef keys[count]; - CFDictionaryRef values[count]; - CFDictionaryGetKeysAndValues(content, (const void **)keys, (const void **)values); - - SQLite::Statement insert(*this, "INSERT INTO authority (type, allow, requirement, label, filter_unsigned, flags, remarks)" - " VALUES (:type, 1, :requirement, 'GKE', :filter, :flags, :path)"); - for (CFIndex n = 0; n < count; n++) { - CFDictionary info(values[n], errSecCSDbCorrupt); - uint32_t flags = kAuthorityFlagWhitelist; - if (CFNumberRef versionRef = info.get("version")) { - int version = cfNumber(versionRef); - if (version >= 2) - flags |= kAuthorityFlagWhitelistV2; - } - insert.reset(); - insert.bind(":type") = cfString(info.get(CFSTR("type"))); - insert.bind(":path") = cfString(info.get(CFSTR("path"))); - insert.bind(":requirement") = "cdhash H\"" + cfString(info.get(CFSTR("cdhash"))) + "\""; - insert.bind(":filter") = cfString(info.get(CFSTR("screen"))); - insert.bind(":flags").integer(flags); - insert(); - } - - // we just changed the authority configuration at priority zero - this->purgeObjects(0); - - // update version and commit - addFeature("gke", authUUID.c_str(), "gke loaded"); - loadAuth.commit(); - } - } catch (...) { - secdebug("gkupgrade", "exception during GKE upgrade"); - } -} - - -// -// Check the override-enable master flag -// -#define SP_ENABLE_KEY CFSTR("enabled") -#define SP_ENABLED CFSTR("yes") -#define SP_DISABLED CFSTR("no") - -bool overrideAssessment(SecAssessmentFlags flags /* = 0 */) -{ - static bool enabled = true; - static dispatch_once_t once; - static int token = -1; - static int have_token = 0; - static dispatch_queue_t queue; - int check; - - if (flags & kSecAssessmentFlagEnforce) // explicitly disregard disables (force on) - return false; - - if (have_token && notify_check(token, &check) == NOTIFY_STATUS_OK && !check) - return !enabled; - - dispatch_once(&once, ^{ - if (notify_register_check(kNotifySecAssessmentMasterSwitch, &token) == NOTIFY_STATUS_OK) - have_token = 1; - queue = dispatch_queue_create("com.apple.SecAssessment.assessment", NULL); - }); - - dispatch_sync(queue, ^{ - /* upgrade configuration from emir, ignore all error since we might not be able to write to */ - if (::access(visibleSecurityFlagFile, F_OK) == 0) { - try { - setAssessment(true); - ::unlink(visibleSecurityFlagFile); - } catch (...) { - } - enabled = true; - return; - } - - try { - Dictionary * prefsDict = Dictionary::CreateDictionary(prefsFile); - if (prefsDict == NULL) - return; - - CFStringRef value = prefsDict->getStringValue(SP_ENABLE_KEY); - if (value && CFStringCompare(value, SP_DISABLED, 0) == 0) - enabled = false; - else - enabled = true; - delete prefsDict; - } catch(...) { - } - }); - - return !enabled; -} - -void setAssessment(bool masterSwitch) -{ - MutableDictionary *prefsDict = MutableDictionary::CreateMutableDictionary(prefsFile); - if (prefsDict == NULL) - prefsDict = new MutableDictionary::MutableDictionary(); - prefsDict->setValue(SP_ENABLE_KEY, masterSwitch ? SP_ENABLED : SP_DISABLED); - prefsDict->writePlistToFile(prefsFile); - delete prefsDict; - - /* make sure permissions is right */ - ::chmod(prefsFile, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - - notify_post(kNotifySecAssessmentMasterSwitch); - - /* reset the automatic rearm timer */ - resetRearmTimer("masterswitch"); -} - - -// -// Reset or query the automatic rearm timer -// -void resetRearmTimer(const char *event) -{ - CFRef now = CFDateCreate(NULL, CFAbsoluteTimeGetCurrent()); - CFTemp info("{event=%s, timestamp=%O}", event, now.get()); - CFRef infoData = makeCFData(info.get()); - UnixPlusPlus::AutoFileDesc fd(rearmTimerFile, O_WRONLY | O_CREAT | O_TRUNC, 0644); - fd.write(CFDataGetBytePtr(infoData), CFDataGetLength(infoData)); -} - -bool queryRearmTimer(CFTimeInterval &delta) -{ - if (CFRef infoData = cfLoadFile(rearmTimerFile)) { - if (CFRef info = makeCFDictionaryFrom(infoData)) { - CFDateRef timestamp = (CFDateRef)CFDictionaryGetValue(info, CFSTR("timestamp")); - if (timestamp && CFGetTypeID(timestamp) == CFDateGetTypeID()) { - delta = CFAbsoluteTimeGetCurrent() - CFDateGetAbsoluteTime(timestamp); - return true; - } - } - MacOSError::throwMe(errSecCSDbCorrupt); - } - return false; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/policydb.h b/OSX/include/security_codesigning/policydb.h deleted file mode 100644 index b26c7e6c..00000000 --- a/OSX/include/security_codesigning/policydb.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_POLICYDB -#define _H_POLICYDB - -#include "SecAssessment.h" -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -namespace SQLite = SQLite3; - - -static const char defaultDatabase[] = "/var/db/SystemPolicy"; -static const char visibleSecurityFlagFile[] = "/var/db/.sp_visible"; /* old duchess/emir style configration */ -static const char prefsFile[] = "/var/db/SystemPolicy-prefs.plist"; -static const char lastRejectFile[] = "/var/db/.LastGKReject"; -static const char lastApprovedFile[] = "/var/db/.LastGKApp"; -static const char rearmTimerFile[] = "/var/db/.GKRearmTimer"; - -static const char gkeAuthFile[] = "/var/db/gke.auth"; -static const char gkeSigsFile[] = "/var/db/gke.sigs"; -static const unsigned int gkeCheckInterval = 60; // seconds - - -// -// We use Julian dates in the database, because SQLite understands them well and they convert easily to/from CFAbsoluteTime -// -static const double never = 5000000; // canonical "never" julian date (an arbitrary point in the year 8977) -static const double julianBase = 2451910.5; // julian date of CFAbsoluteTime epoch - -static inline double dateToJulian(CFDateRef time) -{ return CFDateGetAbsoluteTime(time) / 86400.0 + julianBase; } - -static inline CFDateRef julianToDate(double julian) -{ return CFDateCreate(NULL, (julian - julianBase) * 86400); } - - -typedef SHA1::SDigest ObjectHash; - - -typedef uint AuthorityType; -enum { - kAuthorityInvalid = 0, // not a valid authority type - kAuthorityExecute = 1, // authorizes launch and execution - kAuthorityInstall = 2, // authorizes installation - kAuthorityOpenDoc = 3, // authorizes opening of documents -}; - - -// -// Defined flags for authority flags column -// -enum { - kAuthorityFlagVirtual = 0x0001, // virtual rule (anchoring object records) - kAuthorityFlagDefault = 0x0002, // rule is part of the original default set - kAuthorityFlagInhibitCache = 0x0004, // never cache outcome of this rule - kAuthorityFlagWhitelist = 0x1000, // whitelist override - kAuthorityFlagWhitelistV2 = 0x2000, // apply "deep" signature to this record -}; - - -// -// Mapping/translation to/from API space -// -AuthorityType typeFor(CFDictionaryRef context, AuthorityType type = kAuthorityInvalid); -CFStringRef typeNameFor(AuthorityType type) - CF_RETURNS_RETAINED; - - -// -// An open policy database. -// Usually read-only, but can be opened for write by privileged callers. -// This is a translucent wrapper around SQLite::Database; the caller -// is expected to work with statement rows. -// -class PolicyDatabase : public SQLite::Database { -public: - PolicyDatabase(const char *path = NULL, int flags = SQLITE_OPEN_READONLY); - virtual ~PolicyDatabase(); - -public: - bool checkCache(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFMutableDictionaryRef result); - -public: - void purgeAuthority(); - void purgeObjects(); - void purgeObjects(double priority);// - - void upgradeDatabase(); - std::string featureLevel(const char *feature); - bool hasFeature(const char *feature) { return !featureLevel(feature).empty(); } - void addFeature(const char *feature, const char *value, const char *remarks); - void simpleFeature(const char *feature, const char *sql); - void simpleFeature(const char *feature, void (^perform)()); - - void installExplicitSet(const char *auth, const char *sigs); - -private: - time_t mLastExplicitCheck; -}; - - -// -// Check the system-wide overriding flag file -// -bool overrideAssessment(SecAssessmentFlags flags = 0); -void setAssessment(bool masterSwitch); - - -// -// Reset or query the automatic rearm timer -// -void resetRearmTimer(const char *event); -bool queryRearmTimer(CFTimeInterval &delta); - -} // end namespace CodeSigning -} // end namespace Security - -#endif //_H_POLICYDB diff --git a/OSX/include/security_codesigning/policyengine.cpp b/OSX/include/security_codesigning/policyengine.cpp deleted file mode 100644 index f5b9cb29..00000000 --- a/OSX/include/security_codesigning/policyengine.cpp +++ /dev/null @@ -1,1106 +0,0 @@ -/* - * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "policyengine.h" -#include "xar++.h" -#include "quarantine++.h" -#include "codesigning_dtrace.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "diskrep.h" -#include "codedirectory.h" -#include "csutilities.h" -#include "StaticCode.h" - -#include -#include "SecCodePriv.h" -#undef check // Macro! Yech. - -extern "C" { -#include -} - - -namespace Security { -namespace CodeSigning { - -static const double NEGATIVE_HOLD = 60.0/86400; // 60 seconds to cache negative outcomes - -static const char RECORDER_DIR[] = "/tmp/gke-"; // recorder mode destination for detached signatures -enum { - recorder_code_untrusted = 0, // signed but untrusted - recorder_code_adhoc = 1, // unsigned; signature recorded - recorder_code_unable = 2, // unsigned; unable to record signature -}; - - -static void authorizeUpdate(SecAssessmentFlags flags, CFDictionaryRef context); -static bool codeInvalidityExceptions(SecStaticCodeRef code, CFMutableDictionaryRef result); -static CFTypeRef installerPolicy() CF_RETURNS_RETAINED; - - -// -// Core structure -// -PolicyEngine::PolicyEngine() - : PolicyDatabase(NULL, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) -{ -} - -PolicyEngine::~PolicyEngine() -{ } - - -// -// Top-level evaluation driver -// -void PolicyEngine::evaluate(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result) -{ - // update GKE - installExplicitSet(gkeAuthFile, gkeSigsFile); - - // find the global evaluation manager - EvaluationManager *evaluationManager = EvaluationManager::globalManager(); - - // perform the evaluation - EvaluationTask *evaluationTask = evaluationManager->evaluationTask(this, path, type, flags, context, result); - evaluationManager->waitForCompletion(evaluationTask, flags, result); - evaluationManager->removeTask(evaluationTask); - - // if rejected, reset the automatic rearm timer - if (CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict) == kCFBooleanFalse) - resetRearmTimer("reject"); -} - - -static std::string createWhitelistScreen(char type, SHA1 &hash) -{ - SHA1::Digest digest; - hash.finish(digest); - char buffer[2*SHA1::digestLength + 2] = { type }; - for (size_t n = 0; n < SHA1::digestLength; n++) - sprintf(buffer + 1 + 2*n, "%02.2x", digest[n]); - return buffer; -} - - -void PolicyEngine::evaluateCodeItem(SecStaticCodeRef code, CFURLRef path, AuthorityType type, SecAssessmentFlags flags, bool nested, CFMutableDictionaryRef result) -{ - - SQLite::Statement query(*this, - "SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority" - " WHERE type = :type" - " ORDER BY priority DESC;"); - query.bind(":type").integer(type); - - SQLite3::int64 latentID = 0; // first (highest priority) disabled matching ID - std::string latentLabel; // ... and associated label, if any - - while (query.nextRow()) { - bool allow = int(query[0]); - const char *reqString = query[1]; - SQLite3::int64 id = query[2]; - const char *label = query[3]; - double expires = query[4]; - sqlite3_int64 ruleFlags = query[5]; - SQLite3::int64 disabled = query[6]; -// const char *filter = query[7]; -// const char *remarks = query[8]; - - CFRef requirement; - MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref())); - switch (OSStatus rc = SecStaticCodeCheckValidity(code, kSecCSBasicValidateOnly | kSecCSCheckGatekeeperArchitectures, requirement)) { - case errSecSuccess: - break; // rule match; process below - case errSecCSReqFailed: - continue; // rule does not apply - case errSecCSVetoed: - return; // nested code has failed to pass - default: - MacOSError::throwMe(rc); // general error; pass to caller - } - - // if this rule is disabled, skip it but record the first matching one for posterity - if (disabled && latentID == 0) { - latentID = id; - latentLabel = label ? label : ""; - continue; - } - - // current rule is first rule (in priority order) that matched. Apply it - if (nested) // success, nothing to record - return; - - CFRef info; // as needed - if (flags & kSecAssessmentFlagRequestOrigin) { - if (!info) - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); - if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates))) - setOrigin(chain, result); - } - if (!(ruleFlags & kAuthorityFlagInhibitCache) && !(flags & kSecAssessmentFlagNoCache)) { // cache inhibit - if (!info) - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); - if (SecTrustRef trust = SecTrustRef(CFDictionaryGetValue(info, kSecCodeInfoTrust))) { - CFRef xinfo; - MacOSError::check(SecTrustCopyExtendedResult(trust, &xinfo.aref())); - if (CFDateRef limit = CFDateRef(CFDictionaryGetValue(xinfo, kSecTrustExpirationDate))) { - this->recordOutcome(code, allow, type, min(expires, dateToJulian(limit)), id); - } - } - } - if (allow) { - if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) { - if (!info) - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); - CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); - SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, cdhash ? CFDataGetBytePtr(cdhash) : NULL); - } - } else { - if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) { - if (!info) - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); - CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); - std::string cpath = cfString(path); - const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL; - SYSPOLICY_ASSESS_OUTCOME_DENY(cpath.c_str(), type, label, hashp); - SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, label, hashp, recorder_code_untrusted); - } - } - cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow); - addAuthority(flags, result, label, id); - return; - } - - // no applicable authority (but signed, perhaps temporarily). Deny by default - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref())); - if (flags & kSecAssessmentFlagRequestOrigin) { - if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates))) - setOrigin(chain, result); - } - if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) { - CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); - const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL; - std::string cpath = cfString(path); - SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath.c_str(), type, latentLabel.c_str(), hashp); - SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, latentLabel.c_str(), hashp, 0); - } - if (!(flags & kSecAssessmentFlagNoCache)) - this->recordOutcome(code, false, type, this->julianNow() + NEGATIVE_HOLD, latentID); - cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, false); - addAuthority(flags, result, latentLabel.c_str(), latentID); -} - - -void PolicyEngine::adjustValidation(SecStaticCodeRef code) -{ - CFRef conditions = mOpaqueWhitelist.validationConditionsFor(code); - SecStaticCodeSetValidationConditions(code, conditions); -} - - -bool PolicyEngine::temporarySigning(SecStaticCodeRef code, AuthorityType type, CFURLRef path, SecAssessmentFlags matchFlags) -{ - if (matchFlags == 0) { // playback; consult authority table for matches - DiskRep *rep = SecStaticCode::requiredStatic(code)->diskRep(); - std::string screen; - if (CFRef info = rep->component(cdInfoSlot)) { - SHA1 hash; - hash.update(CFDataGetBytePtr(info), CFDataGetLength(info)); - screen = createWhitelistScreen('I', hash); - } else if (rep->mainExecutableImage()) { - screen = "N"; - } else { - SHA1 hash; - hashFileData(rep->mainExecutablePath().c_str(), &hash); - screen = createWhitelistScreen('M', hash); - } - SQLite::Statement query(*this, - "SELECT flags FROM authority " - "WHERE type = :type" - " AND NOT flags & :flag" - " AND CASE WHEN filter_unsigned IS NULL THEN remarks = :remarks ELSE filter_unsigned = :screen END"); - query.bind(":type").integer(type); - query.bind(":flag").integer(kAuthorityFlagDefault); - query.bind(":screen") = screen; - query.bind(":remarks") = cfString(path); - if (!query.nextRow()) // guaranteed no matching rule - return false; - matchFlags = SQLite3::int64(query[0]); - } - - try { - // ad-hoc sign the code and attach the signature - CFRef signature = CFDataCreateMutable(NULL, 0); - CFTemp arguments("{%O=%O, %O=#N}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity); - CFRef signer; - MacOSError::check(SecCodeSignerCreate(arguments, (matchFlags & kAuthorityFlagWhitelistV2) ? kSecCSSignOpaque : kSecCSSignV1, &signer.aref())); - MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags)); - MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags)); - - SecRequirementRef dr = NULL; - SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, &dr); - CFStringRef drs = NULL; - SecRequirementCopyString(dr, kSecCSDefaultFlags, &drs); - - // if we're in GKE recording mode, save that signature and report its location - if (SYSPOLICY_RECORDER_MODE_ENABLED()) { - int status = recorder_code_unable; // ephemeral signature (not recorded) - if (geteuid() == 0) { - CFRef uuid = CFUUIDCreate(NULL); - std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig"; - try { - UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT); - fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature)); - status = recorder_code_adhoc; // recorded signature - SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str()); - } catch (...) { } - } - - // now report the D probe itself - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref())); - CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); - SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "", - cdhash ? CFDataGetBytePtr(cdhash) : NULL, status); - } - - return true; // it worked; we're now (well) signed - } catch (...) { } - - return false; -} - - -// -// Executable code. -// Read from disk, evaluate properly, cache as indicated. -// -void PolicyEngine::evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result, bool handleUnsigned) -{ - // not really a Gatekeeper function... but reject all "hard quarantined" files because they were made from sandboxed sources without download privilege - FileQuarantine qtn(cfString(path).c_str()); - if (qtn.flag(QTN_FLAG_HARD)) - MacOSError::throwMe(errSecCSFileHardQuarantined); - - CFCopyRef code; - MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref())); - - SecCSFlags validationFlags = kSecCSEnforceRevocationChecks | kSecCSCheckAllArchitectures; - if (!(flags & kSecAssessmentFlagAllowWeak)) - validationFlags |= kSecCSStrictValidate; - adjustValidation(code); - - // deal with a very special case (broken 10.6/10.7 Applet bundles) - OSStatus rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSBasicValidateOnly, NULL); - if (rc == errSecCSSignatureFailed) { - if (!codeInvalidityExceptions(code, result)) { // invalidly signed, no exceptions -> error - if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED()) - SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, false); - MacOSError::throwMe(rc); - } - // recognized exception - treat as unsigned - if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED()) - SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, true); - rc = errSecCSUnsigned; - } - - // ad-hoc sign unsigned code - if (rc == errSecCSUnsigned && handleUnsigned && (!overrideAssessment(flags) || SYSPOLICY_RECORDER_MODE_ENABLED())) { - if (temporarySigning(code, type, path, 0)) { - rc = errSecSuccess; // clear unsigned; we are now well-signed - validationFlags |= kSecCSBasicValidateOnly; // no need to re-validate deep contents - } - } - - // prepare for deep traversal of (hopefully) good signatures - SecAssessmentFeedback feedback = SecAssessmentFeedback(CFDictionaryGetValue(context, kSecAssessmentContextKeyFeedback)); - MacOSError::check(SecStaticCodeSetCallback(code, kSecCSDefaultFlags, NULL, ^CFTypeRef (SecStaticCodeRef item, CFStringRef cfStage, CFDictionaryRef info) { - string stage = cfString(cfStage); - if (stage == "prepared") { - if (!CFEqual(item, code)) // genuine nested (not top) code - adjustValidation(item); - } else if (stage == "progress") { - if (feedback && CFEqual(item, code)) { // top level progress - bool proceed = feedback(kSecAssessmentFeedbackProgress, info); - if (!proceed) - SecStaticCodeCancelValidation(code, kSecCSDefaultFlags); - } - } else if (stage == "validated") { - SecStaticCodeSetCallback(item, kSecCSDefaultFlags, NULL, NULL); // clear callback to avoid unwanted recursion - evaluateCodeItem(item, path, type, flags, item != code, result); - if (CFTypeRef verdict = CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict)) - if (CFEqual(verdict, kCFBooleanFalse)) - return makeCFNumber(OSStatus(errSecCSVetoed)); // (signal nested-code policy failure, picked up below) - } - return NULL; - })); - - // go for it! - switch (rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSCheckNestedCode | kSecCSRestrictSymlinks | kSecCSReportProgress, NULL)) { - case errSecSuccess: // continue below - break; - case errSecCSUnsigned: - cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "no usable signature"); - return; - case errSecCSVetoed: // nested code rejected by rule book; result was filled out there - return; - case errSecCSWeakResourceRules: - case errSecCSWeakResourceEnvelope: - case errSecCSResourceNotSupported: - case errSecCSAmbiguousBundleFormat: - case errSecCSSignatureNotVerifiable: - case errSecCSRegularFile: - case errSecCSBadMainExecutable: - case errSecCSBadFrameworkVersion: - case errSecCSUnsealedAppRoot: - case errSecCSUnsealedFrameworkRoot: - case errSecCSInvalidSymlink: - { - // consult the whitelist - bool allow = false; - const char *label; - // we've bypassed evaluateCodeItem before we failed validation. Explicitly apply it now - SecStaticCodeSetCallback(code, kSecCSDefaultFlags, NULL, NULL); - evaluateCodeItem(code, path, type, flags | kSecAssessmentFlagNoCache, false, result); - if (CFTypeRef verdict = CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict)) { - // verdict rendered from a nested component - signature not acceptable to Gatekeeper - if (CFEqual(verdict, kCFBooleanFalse)) // nested code rejected by rule book; result was filled out there - return; - if (CFEqual(verdict, kCFBooleanTrue) && !(flags & kSecAssessmentFlagIgnoreWhitelist)) - if (mOpaqueWhitelist.contains(code, feedback, rc)) - allow = true; - } - if (allow) { - label = "allowed cdhash"; - } else { - CFDictionaryReplaceValue(result, kSecAssessmentAssessmentVerdict, kCFBooleanFalse); - label = "obsolete resource envelope"; - } - cfadd(result, "{%O=%d}", kSecAssessmentAssessmentCodeSigningError, rc); - addAuthority(flags, result, label, 0, NULL, true); - return; - } - default: - MacOSError::throwMe(rc); - } -} - - -// -// Installer archive. -// Hybrid policy: If we detect an installer signature, use and validate that. -// If we don't, check for a code signature instead. -// -void PolicyEngine::evaluateInstall(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result) -{ - const AuthorityType type = kAuthorityInstall; - - // check for recent explicit approval, using a bookmark's FileResourceIdentifierKey - if (CFRef bookmark = cfLoadFile(lastApprovedFile)) { - Boolean stale; - if (CFRef url = CFURLCreateByResolvingBookmarkData(NULL, bookmark, - kCFBookmarkResolutionWithoutUIMask | kCFBookmarkResolutionWithoutMountingMask, NULL, NULL, &stale, NULL)) - if (CFRef savedIdent = CFDataRef(CFURLCreateResourcePropertyForKeyFromBookmarkData(NULL, kCFURLFileResourceIdentifierKey, bookmark))) - if (CFRef savedMod = CFDateRef(CFURLCreateResourcePropertyForKeyFromBookmarkData(NULL, kCFURLContentModificationDateKey, bookmark))) { - CFRef currentIdent; - CFRef currentMod; - if (CFURLCopyResourcePropertyForKey(path, kCFURLFileResourceIdentifierKey, ¤tIdent.aref(), NULL)) - if (CFURLCopyResourcePropertyForKey(path, kCFURLContentModificationDateKey, ¤tMod.aref(), NULL)) - if (CFEqual(savedIdent, currentIdent) && CFEqual(savedMod, currentMod)) { - cfadd(result, "{%O=#T}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "explicit preference"); - return; - } - } - } - - Xar xar(cfString(path).c_str()); - if (!xar) { - // follow the code signing path - evaluateCode(path, type, flags, context, result, true); - return; - } - - SQLite3::int64 latentID = 0; // first (highest priority) disabled matching ID - std::string latentLabel; // ... and associated label, if any - if (!xar.isSigned()) { - // unsigned xar - if (SYSPOLICY_ASSESS_OUTCOME_UNSIGNED_ENABLED()) - SYSPOLICY_ASSESS_OUTCOME_UNSIGNED(cfString(path).c_str(), type); - cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "no usable signature"); - return; - } - if (CFRef certs = xar.copyCertChain()) { - CFRef policy = installerPolicy(); - CFRef trust; - MacOSError::check(SecTrustCreateWithCertificates(certs, policy, &trust.aref())); -// MacOSError::check(SecTrustSetAnchorCertificates(trust, cfEmptyArray())); // no anchors - MacOSError::check(SecTrustSetOptions(trust, kSecTrustOptionAllowExpired | kSecTrustOptionImplicitAnchors)); - - SecTrustResultType trustResult; - MacOSError::check(SecTrustEvaluate(trust, &trustResult)); - CFRef chain; - CSSM_TP_APPLE_EVIDENCE_INFO *info; - MacOSError::check(SecTrustGetResult(trust, &trustResult, &chain.aref(), &info)); - - if (flags & kSecAssessmentFlagRequestOrigin) - setOrigin(chain, result); - - switch (trustResult) { - case kSecTrustResultProceed: - case kSecTrustResultUnspecified: - break; - default: - { - OSStatus rc; - MacOSError::check(SecTrustGetCssmResultCode(trust, &rc)); - MacOSError::throwMe(rc); - } - } - - SQLite::Statement query(*this, - "SELECT allow, requirement, id, label, flags, disabled FROM scan_authority" - " WHERE type = :type" - " ORDER BY priority DESC;"); - query.bind(":type").integer(type); - while (query.nextRow()) { - bool allow = int(query[0]); - const char *reqString = query[1]; - SQLite3::int64 id = query[2]; - const char *label = query[3]; - //sqlite_uint64 ruleFlags = query[4]; - SQLite3::int64 disabled = query[5]; - - CFRef requirement; - MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref())); - switch (OSStatus rc = SecRequirementEvaluate(requirement, chain, NULL, kSecCSDefaultFlags)) { - case errSecSuccess: // success - break; - case errSecCSReqFailed: // requirement missed, but otherwise okay - continue; - default: // broken in some way; all tests will fail like this so bail out - MacOSError::throwMe(rc); - } - if (disabled) { - if (latentID == 0) { - latentID = id; - if (label) - latentLabel = label; - } - continue; // the loop - } - - if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED() || SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED()) { - if (allow) - SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, NULL); - else - SYSPOLICY_ASSESS_OUTCOME_DENY(cfString(path).c_str(), type, label, NULL); - } - - // not adding to the object cache - we could, but it's not likely to be worth it - cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow); - addAuthority(flags, result, label, id); - return; - } - } - if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED()) - SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cfString(path).c_str(), type, latentLabel.c_str(), NULL); - - // no applicable authority. Deny by default - cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, latentLabel.c_str(), latentID); -} - - -// -// Create a suitable policy array for verification of installer signatures. -// -static SecPolicyRef makeCRLPolicy() -{ - CFRef policy; - MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_CRL, &policy.aref())); - CSSM_APPLE_TP_CRL_OPTIONS options; - memset(&options, 0, sizeof(options)); - options.Version = CSSM_APPLE_TP_CRL_OPTS_VERSION; - options.CrlFlags = CSSM_TP_ACTION_FETCH_CRL_FROM_NET | CSSM_TP_ACTION_CRL_SUFFICIENT; - CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; - MacOSError::check(SecPolicySetValue(policy, &optData)); - return policy.yield(); -} - -static SecPolicyRef makeOCSPPolicy() -{ - CFRef policy; - MacOSError::check(SecPolicyCopy(CSSM_CERT_X_509v3, &CSSMOID_APPLE_TP_REVOCATION_OCSP, &policy.aref())); - CSSM_APPLE_TP_OCSP_OPTIONS options; - memset(&options, 0, sizeof(options)); - options.Version = CSSM_APPLE_TP_OCSP_OPTS_VERSION; - options.Flags = CSSM_TP_ACTION_OCSP_SUFFICIENT; - CSSM_DATA optData = { sizeof(options), (uint8 *)&options }; - MacOSError::check(SecPolicySetValue(policy, &optData)); - return policy.yield(); -} - -static CFTypeRef installerPolicy() -{ - CFRef base = SecPolicyCreateBasicX509(); - CFRef crl = makeCRLPolicy(); - CFRef ocsp = makeOCSPPolicy(); - return makeCFArray(3, base.get(), crl.get(), ocsp.get()); -} - - -// -// LaunchServices-layer document open. -// We don't cache those at present. If we ever do, we need to authenticate CoreServicesUIAgent as the source of its risk assessment. -// -void PolicyEngine::evaluateDocOpen(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result) -{ - if (context) { - if (CFStringRef riskCategory = CFStringRef(CFDictionaryGetValue(context, kLSDownloadRiskCategoryKey))) { - FileQuarantine qtn(cfString(path).c_str()); - - if (CFEqual(riskCategory, kLSRiskCategorySafe) - || CFEqual(riskCategory, kLSRiskCategoryNeutral) - || CFEqual(riskCategory, kLSRiskCategoryUnknown) - || CFEqual(riskCategory, kLSRiskCategoryMayContainUnsafeExecutable)) { - cfadd(result, "{%O=#T}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "_XProtect"); - } else if (qtn.flag(QTN_FLAG_HARD)) { - MacOSError::throwMe(errSecCSFileHardQuarantined); - } else if (qtn.flag(QTN_FLAG_ASSESSMENT_OK)) { - cfadd(result, "{%O=#T}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "Prior Assessment"); - } else if (!overrideAssessment(flags)) { // no need to do more work if we're off - try { - evaluateCode(path, kAuthorityExecute, flags, context, result, false); - } catch (...) { - // some documents can't be code signed, so this may be quite benign - } - } - if (CFDictionaryGetValue(result, kSecAssessmentAssessmentVerdict) == NULL) { // no code signature to help us out - cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "_XProtect"); - } - addToAuthority(result, kLSDownloadRiskCategoryKey, riskCategory); - return; - } - } - // insufficient information from LS - deny by default - cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict); - addAuthority(flags, result, "Insufficient Context"); -} - - -// -// Result-creation helpers -// -void PolicyEngine::addAuthority(SecAssessmentFlags flags, CFMutableDictionaryRef parent, const char *label, SQLite::int64 row, CFTypeRef cacheInfo, bool weak) -{ - CFRef auth = makeCFMutableDictionary(); - if (label && label[0]) - cfadd(auth, "{%O=%s}", kSecAssessmentAssessmentSource, label); - if (row) - CFDictionaryAddValue(auth, kSecAssessmentAssessmentAuthorityRow, CFTempNumber(row)); - if (overrideAssessment(flags)) - CFDictionaryAddValue(auth, kSecAssessmentAssessmentAuthorityOverride, kDisabledOverride); - if (cacheInfo) - CFDictionaryAddValue(auth, kSecAssessmentAssessmentFromCache, cacheInfo); - if (weak) { - CFDictionaryAddValue(auth, kSecAssessmentAssessmentWeakSignature, kCFBooleanTrue); - CFDictionaryReplaceValue(parent, kSecAssessmentAssessmentAuthority, auth); - } else { - CFDictionaryAddValue(parent, kSecAssessmentAssessmentAuthority, auth); - } -} - -void PolicyEngine::addToAuthority(CFMutableDictionaryRef parent, CFStringRef key, CFTypeRef value) -{ - CFMutableDictionaryRef authority = CFMutableDictionaryRef(CFDictionaryGetValue(parent, kSecAssessmentAssessmentAuthority)); - assert(authority); - CFDictionaryAddValue(authority, key, value); -} - - -// -// Add a rule to the policy database -// -CFDictionaryRef PolicyEngine::add(CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context) -{ - // default type to execution - if (type == kAuthorityInvalid) - type = kAuthorityExecute; - - authorizeUpdate(flags, context); - CFDictionary ctx(context, errSecCSInvalidAttributeValues); - CFCopyRef target = inTarget; - CFRef bookmark = NULL; - std::string filter_unsigned; - - switch (type) { - case kAuthorityExecute: - normalizeTarget(target, type, ctx, &filter_unsigned); - // bookmarks are untrusted and just a hint to callers - bookmark = ctx.get(kSecAssessmentRuleKeyBookmark); - break; - case kAuthorityInstall: - if (inTarget && CFGetTypeID(inTarget) == CFURLGetTypeID()) { - // no good way to turn an installer file into a requirement. Pretend to succeeed so caller proceeds - CFRef properties = makeCFArray(2, kCFURLFileResourceIdentifierKey, kCFURLContentModificationDateKey); - CFRef error; - CFURLBookmarkCreationOptions options = kCFURLBookmarkCreationDoNotIncludeSandboxExtensionsMask | kCFURLBookmarkCreationMinimalBookmarkMask; - if (CFRef bookmark = CFURLCreateBookmarkData(NULL, CFURLRef(inTarget), options, properties, NULL, &error.aref())) { - UnixPlusPlus::AutoFileDesc fd(lastApprovedFile, O_WRONLY | O_CREAT | O_TRUNC); - fd.write(CFDataGetBytePtr(bookmark), CFDataGetLength(bookmark)); - return NULL; - } - } - break; - case kAuthorityOpenDoc: - // handle document-open differently: use quarantine flags for whitelisting - if (!target || CFGetTypeID(target) != CFURLGetTypeID()) // can only "add" file paths - MacOSError::throwMe(errSecCSInvalidObjectRef); - try { - std::string spath = cfString(target.as()); - FileQuarantine qtn(spath.c_str()); - qtn.setFlag(QTN_FLAG_ASSESSMENT_OK); - qtn.applyTo(spath.c_str()); - } catch (const CommonError &error) { - // could not set quarantine flag - report qualified success - return cfmake("{%O=%O,'assessment:error'=%d}", - kSecAssessmentAssessmentAuthorityOverride, CFSTR("error setting quarantine"), error.osStatus()); - } catch (...) { - return cfmake("{%O=%O}", kSecAssessmentAssessmentAuthorityOverride, CFSTR("unable to set quarantine")); - } - return NULL; - } - - // if we now have anything else, we're busted - if (!target || CFGetTypeID(target) != SecRequirementGetTypeID()) - MacOSError::throwMe(errSecCSInvalidObjectRef); - - double priority = 0; - string label; - bool allow = true; - double expires = never; - string remarks; - SQLite::uint64 dbFlags = kAuthorityFlagWhitelistV2; - - if (CFNumberRef pri = ctx.get(kSecAssessmentUpdateKeyPriority)) - CFNumberGetValue(pri, kCFNumberDoubleType, &priority); - if (CFStringRef lab = ctx.get(kSecAssessmentUpdateKeyLabel)) - label = cfString(lab); - if (CFDateRef time = ctx.get(kSecAssessmentUpdateKeyExpires)) - // we're using Julian dates here; convert from CFDate - expires = dateToJulian(time); - if (CFBooleanRef allowing = ctx.get(kSecAssessmentUpdateKeyAllow)) - allow = allowing == kCFBooleanTrue; - if (CFStringRef rem = ctx.get(kSecAssessmentUpdateKeyRemarks)) - remarks = cfString(rem); - - CFRef requirementText; - MacOSError::check(SecRequirementCopyString(target.as(), kSecCSDefaultFlags, &requirementText.aref())); - SQLite::Transaction xact(*this, SQLite3::Transaction::deferred, "add_rule"); - SQLite::Statement insert(*this, - "INSERT INTO authority (type, allow, requirement, priority, label, expires, filter_unsigned, remarks, flags)" - " VALUES (:type, :allow, :requirement, :priority, :label, :expires, :filter_unsigned, :remarks, :flags);"); - insert.bind(":type").integer(type); - insert.bind(":allow").integer(allow); - insert.bind(":requirement") = requirementText.get(); - insert.bind(":priority") = priority; - if (!label.empty()) - insert.bind(":label") = label; - insert.bind(":expires") = expires; - insert.bind(":filter_unsigned") = filter_unsigned.empty() ? NULL : filter_unsigned.c_str(); - if (!remarks.empty()) - insert.bind(":remarks") = remarks; - insert.bind(":flags").integer(dbFlags); - insert.execute(); - SQLite::int64 newRow = this->lastInsert(); - if (bookmark) { - SQLite::Statement bi(*this, "INSERT INTO bookmarkhints (bookmark, authority) VALUES (:bookmark, :authority)"); - bi.bind(":bookmark") = CFDataRef(bookmark); - bi.bind(":authority").integer(newRow); - bi.execute(); - } - this->purgeObjects(priority); - xact.commit(); - notify_post(kNotifySecAssessmentUpdate); - return cfmake("{%O=%d}", kSecAssessmentUpdateKeyRow, newRow); -} - - -CFDictionaryRef PolicyEngine::remove(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context) -{ - if (type == kAuthorityOpenDoc) { - // handle document-open differently: use quarantine flags for whitelisting - authorizeUpdate(flags, context); - if (!target || CFGetTypeID(target) != CFURLGetTypeID()) - MacOSError::throwMe(errSecCSInvalidObjectRef); - std::string spath = cfString(CFURLRef(target)).c_str(); - FileQuarantine qtn(spath.c_str()); - qtn.clearFlag(QTN_FLAG_ASSESSMENT_OK); - qtn.applyTo(spath.c_str()); - return NULL; - } - return manipulateRules("DELETE FROM authority", target, type, flags, context, true); -} - -CFDictionaryRef PolicyEngine::enable(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize) -{ - return manipulateRules("UPDATE authority SET disabled = 0", target, type, flags, context, authorize); -} - -CFDictionaryRef PolicyEngine::disable(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize) -{ - return manipulateRules("UPDATE authority SET disabled = 1", target, type, flags, context, authorize); -} - -CFDictionaryRef PolicyEngine::find(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context) -{ - SQLite::Statement query(*this); - selectRules(query, "SELECT scan_authority.id, scan_authority.type, scan_authority.requirement, scan_authority.allow, scan_authority.label, scan_authority.priority, scan_authority.remarks, scan_authority.expires, scan_authority.disabled, bookmarkhints.bookmark FROM scan_authority LEFT OUTER JOIN bookmarkhints ON scan_authority.id = bookmarkhints.authority", - "scan_authority", target, type, flags, context, - " ORDER BY priority DESC"); - CFRef found = makeCFMutableArray(0); - while (query.nextRow()) { - SQLite::int64 id = query[0]; - int type = int(query[1]); - const char *requirement = query[2]; - int allow = int(query[3]); - const char *label = query[4]; - double priority = query[5]; - const char *remarks = query[6]; - double expires = query[7]; - int disabled = int(query[8]); - CFRef bookmark = query[9].data(); - CFRef rule = makeCFMutableDictionary(5, - kSecAssessmentRuleKeyID, CFTempNumber(id).get(), - kSecAssessmentRuleKeyType, CFRef(typeNameFor(type)).get(), - kSecAssessmentRuleKeyRequirement, CFTempString(requirement).get(), - kSecAssessmentRuleKeyAllow, allow ? kCFBooleanTrue : kCFBooleanFalse, - kSecAssessmentRuleKeyPriority, CFTempNumber(priority).get() - ); - if (label) - CFDictionaryAddValue(rule, kSecAssessmentRuleKeyLabel, CFTempString(label)); - if (remarks) - CFDictionaryAddValue(rule, kSecAssessmentRuleKeyRemarks, CFTempString(remarks)); - if (expires != never) - CFDictionaryAddValue(rule, kSecAssessmentRuleKeyExpires, CFRef(julianToDate(expires))); - if (disabled) - CFDictionaryAddValue(rule, kSecAssessmentRuleKeyDisabled, CFTempNumber(disabled)); - if (bookmark) - CFDictionaryAddValue(rule, kSecAssessmentRuleKeyBookmark, bookmark); - CFArrayAppendValue(found, rule); - } - if (CFArrayGetCount(found) == 0) - MacOSError::throwMe(errSecCSNoMatches); - return cfmake("{%O=%O}", kSecAssessmentUpdateKeyFound, found.get()); -} - - -CFDictionaryRef PolicyEngine::update(CFTypeRef target, SecAssessmentFlags flags, CFDictionaryRef context) -{ - // update GKE - installExplicitSet(gkeAuthFile, gkeSigsFile); - - AuthorityType type = typeFor(context, kAuthorityInvalid); - CFStringRef edit = CFStringRef(CFDictionaryGetValue(context, kSecAssessmentContextKeyUpdate)); - CFDictionaryRef result; - if (CFEqual(edit, kSecAssessmentUpdateOperationAdd)) - result = this->add(target, type, flags, context); - else if (CFEqual(edit, kSecAssessmentUpdateOperationRemove)) - result = this->remove(target, type, flags, context); - else if (CFEqual(edit, kSecAssessmentUpdateOperationEnable)) - result = this->enable(target, type, flags, context, true); - else if (CFEqual(edit, kSecAssessmentUpdateOperationDisable)) - result = this->disable(target, type, flags, context, true); - else if (CFEqual(edit, kSecAssessmentUpdateOperationFind)) - result = this->find(target, type, flags, context); - else - MacOSError::throwMe(errSecCSInvalidAttributeValues); - if (result == NULL) - result = makeCFDictionary(0); // success, no details - return result; -} - - -// -// Construct and prepare an SQL query on the authority table, operating on some set of existing authority records. -// In essence, this appends a suitable WHERE clause to the stanza passed and prepares it on the statement given. -// -void PolicyEngine::selectRules(SQLite::Statement &action, std::string phrase, std::string table, - CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, std::string suffix /* = "" */) -{ - CFDictionary ctx(context, errSecCSInvalidAttributeValues); - CFCopyRef target = inTarget; - std::string filter_unsigned; // ignored; used just to trigger ad-hoc signing - normalizeTarget(target, type, ctx, &filter_unsigned); - - string label; - if (CFStringRef lab = ctx.get(kSecAssessmentUpdateKeyLabel)) - label = cfString(CFStringRef(lab)); - - if (!target) { - if (label.empty()) { - if (type == kAuthorityInvalid) { - action.query(phrase + suffix); - } else { - action.query(phrase + " WHERE " + table + ".type = :type" + suffix); - action.bind(":type").integer(type); - } - } else { // have label - if (type == kAuthorityInvalid) { - action.query(phrase + " WHERE " + table + ".label = :label" + suffix); - } else { - action.query(phrase + " WHERE " + table + ".type = :type AND " + table + ".label = :label" + suffix); - action.bind(":type").integer(type); - } - action.bind(":label") = label; - } - } else if (CFGetTypeID(target) == CFNumberGetTypeID()) { - action.query(phrase + " WHERE " + table + ".id = :id" + suffix); - action.bind(":id").integer(cfNumber(target.as())); - } else if (CFGetTypeID(target) == SecRequirementGetTypeID()) { - if (type == kAuthorityInvalid) - type = kAuthorityExecute; - CFRef requirementText; - MacOSError::check(SecRequirementCopyString(target.as(), kSecCSDefaultFlags, &requirementText.aref())); - action.query(phrase + " WHERE " + table + ".type = :type AND " + table + ".requirement = :requirement" + suffix); - action.bind(":type").integer(type); - action.bind(":requirement") = requirementText.get(); - } else - MacOSError::throwMe(errSecCSInvalidObjectRef); -} - - -// -// Execute an atomic change to existing records in the authority table. -// -CFDictionaryRef PolicyEngine::manipulateRules(const std::string &stanza, - CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize) -{ - SQLite::Transaction xact(*this, SQLite3::Transaction::deferred, "rule_change"); - SQLite::Statement action(*this); - if (authorize) - authorizeUpdate(flags, context); - selectRules(action, stanza, "authority", inTarget, type, flags, context); - action.execute(); - unsigned int changes = this->changes(); // latch change count - // We MUST purge objects with priority <= MAX(priority of any changed rules); - // but for now we just get lazy and purge them ALL. - if (changes) { - this->purgeObjects(1.0E100); - xact.commit(); - notify_post(kNotifySecAssessmentUpdate); - return cfmake("{%O=%d}", kSecAssessmentUpdateKeyCount, changes); - } - // no change; return an error - MacOSError::throwMe(errSecCSNoMatches); -} - - -// -// Fill in extra information about the originator of cryptographic credentials found - if any -// -void PolicyEngine::setOrigin(CFArrayRef chain, CFMutableDictionaryRef result) -{ - if (chain) - if (CFArrayGetCount(chain) > 0) - if (SecCertificateRef leaf = SecCertificateRef(CFArrayGetValueAtIndex(chain, 0))) - if (CFStringRef summary = SecCertificateCopyLongDescription(NULL, leaf, NULL)) { - CFDictionarySetValue(result, kSecAssessmentAssessmentOriginator, summary); - CFRelease(summary); - } -} - - -// -// Take an assessment outcome and record it in the object cache -// -void PolicyEngine::recordOutcome(SecStaticCodeRef code, bool allow, AuthorityType type, double expires, SQLite::int64 authority) -{ - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref())); - CFDataRef cdHash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique)); - assert(cdHash); // was signed - CFRef path; - MacOSError::check(SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref())); - assert(expires); - SQLite::Transaction xact(*this, SQLite3::Transaction::deferred, "caching"); - SQLite::Statement insert(*this, - "INSERT OR REPLACE INTO object (type, allow, hash, expires, path, authority)" - " VALUES (:type, :allow, :hash, :expires, :path," - " CASE :authority WHEN 0 THEN (SELECT id FROM authority WHERE label = 'No Matching Rule') ELSE :authority END" - " );"); - insert.bind(":type").integer(type); - insert.bind(":allow").integer(allow); - insert.bind(":hash") = cdHash; - insert.bind(":expires") = expires; - insert.bind(":path") = cfString(path); - insert.bind(":authority").integer(authority); - insert.execute(); - xact.commit(); -} - - -// -// Record a UI failure record after proper validation of the caller -// -void PolicyEngine::recordFailure(CFDictionaryRef info) -{ - CFRef infoData = makeCFData(info); - UnixPlusPlus::AutoFileDesc fd(lastRejectFile, O_WRONLY | O_CREAT | O_TRUNC); - fd.write(CFDataGetBytePtr(infoData), CFDataGetLength(infoData)); - notify_post(kNotifySecAssessmentRecordingChange); -} - - -// -// Perform update authorization processing. -// Throws an exception if authorization is denied. -// -static void authorizeUpdate(SecAssessmentFlags flags, CFDictionaryRef context) -{ - AuthorizationRef authorization = NULL; - - if (context) - if (CFTypeRef authkey = CFDictionaryGetValue(context, kSecAssessmentUpdateKeyAuthorization)) - if (CFGetTypeID(authkey) == CFDataGetTypeID()) { - CFDataRef authdata = CFDataRef(authkey); - if (CFDataGetLength(authdata) != sizeof(AuthorizationExternalForm)) - MacOSError::throwMe(errSecCSInvalidObjectRef); - MacOSError::check(AuthorizationCreateFromExternalForm((AuthorizationExternalForm *)CFDataGetBytePtr(authdata), &authorization)); - } - if (authorization == NULL) - MacOSError::throwMe(errSecCSDBDenied); - - AuthorizationItem right[] = { - { "com.apple.security.assessment.update", 0, NULL, 0 } - }; - AuthorizationRights rights = { sizeof(right) / sizeof(right[0]), right }; - MacOSError::check(AuthorizationCopyRights(authorization, &rights, NULL, - kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, NULL)); - - MacOSError::check(AuthorizationFree(authorization, kAuthorizationFlagDefaults)); -} - - -// -// Perform common argument normalizations for update operations -// -void PolicyEngine::normalizeTarget(CFRef &target, AuthorityType type, CFDictionary &context, std::string *signUnsigned) -{ - // turn CFURLs into (designated) SecRequirements - if (target && CFGetTypeID(target) == CFURLGetTypeID()) { - CFRef code; - CFURLRef path = target.as(); - MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref())); - switch (OSStatus rc = SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, (SecRequirementRef *)&target.aref())) { - case errSecSuccess: { - // use the *default* DR to avoid unreasonably wide DRs opening up Gatekeeper to attack - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSRequirementInformation, &info.aref())); - target = CFDictionaryGetValue(info, kSecCodeInfoImplicitDesignatedRequirement); - } - break; - case errSecCSUnsigned: - if (signUnsigned && temporarySigning(code, type, path, kAuthorityFlagWhitelistV2)) { // ad-hoc signed the code temporarily - MacOSError::check(SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, (SecRequirementRef *)&target.aref())); - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSInternalInformation, &info.aref())); - if (CFDataRef cdData = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoCodeDirectory))) - *signUnsigned = ((const CodeDirectory *)CFDataGetBytePtr(cdData))->screeningCode(); - break; - } - MacOSError::check(rc); - case errSecCSSignatureFailed: - // recover certain cases of broken signatures (well, try) - if (codeInvalidityExceptions(code, NULL)) { - // Ad-hoc sign the code in place (requiring a writable subject). This requires root privileges. - CFRef signer; - CFTemp arguments("{%O=#N}", kSecCodeSignerIdentity); - MacOSError::check(SecCodeSignerCreate(arguments, kSecCSSignOpaque, &signer.aref())); - MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags)); - MacOSError::check(SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, (SecRequirementRef *)&target.aref())); - break; - } - MacOSError::check(rc); - default: - MacOSError::check(rc); - } - if (context.get(kSecAssessmentUpdateKeyRemarks) == NULL) { - // no explicit remarks; add one with the path - CFRef path; - MacOSError::check(SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref())); - CFMutableDictionaryRef dict = makeCFMutableDictionary(context.get()); - CFDictionaryAddValue(dict, kSecAssessmentUpdateKeyRemarks, CFTempString(cfString(path))); - context.take(dict); - } - CFStringRef edit = CFStringRef(context.get(kSecAssessmentContextKeyUpdate)); - if (type == kAuthorityExecute && CFEqual(edit, kSecAssessmentUpdateOperationAdd)) { - // implicitly whitelist the code - mOpaqueWhitelist.add(code); - } - } -} - - -// -// Process special overrides for invalidly signed code. -// This is the (hopefully minimal) concessions we make to keep hurting our customers -// for our own prior mistakes... -// -static bool codeInvalidityExceptions(SecStaticCodeRef code, CFMutableDictionaryRef result) -{ - if (OSAIsRecognizedExecutableURL) { - CFRef info; - MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref())); - if (CFURLRef executable = CFURLRef(CFDictionaryGetValue(info, kSecCodeInfoMainExecutable))) { - SInt32 error; - if (OSAIsRecognizedExecutableURL(executable, &error)) { - if (result) - CFDictionaryAddValue(result, - kSecAssessmentAssessmentAuthorityOverride, CFSTR("ignoring known invalid applet signature")); - return true; - } - } - } - return false; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/policyengine.h b/OSX/include/security_codesigning/policyengine.h deleted file mode 100644 index 46083083..00000000 --- a/OSX/include/security_codesigning/policyengine.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_POLICYENGINE -#define _H_POLICYENGINE - -#include "SecAssessment.h" -#include "opaquewhitelist.h" -#include "evaluationmanager.h" -#include "policydb.h" -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -typedef uint EngineOperation; -enum { - opInvalid = 0, - opEvaluate, - opAddAuthority, - opRemoveAuthority, -}; - - -class PolicyEngine : public PolicyDatabase { -public: - PolicyEngine(); - virtual ~PolicyEngine(); - -public: - void evaluate(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result); - - CFDictionaryRef update(CFTypeRef target, SecAssessmentFlags flags, CFDictionaryRef context); - CFDictionaryRef add(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context); - CFDictionaryRef remove(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context); - CFDictionaryRef enable(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize); - CFDictionaryRef disable(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize); - CFDictionaryRef find(CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context); - - void recordFailure(CFDictionaryRef info); - -public: - static void addAuthority(SecAssessmentFlags flags, CFMutableDictionaryRef parent, const char *label, SQLite::int64 row = 0, CFTypeRef cacheInfo = NULL, bool weak = false); - static void addToAuthority(CFMutableDictionaryRef parent, CFStringRef key, CFTypeRef value); - -private: - void evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result, bool handleUnsigned); - void evaluateInstall(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result); - void evaluateDocOpen(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result); - - void evaluateCodeItem(SecStaticCodeRef code, CFURLRef path, AuthorityType type, SecAssessmentFlags flags, bool nested, CFMutableDictionaryRef result); - void adjustValidation(SecStaticCodeRef code); - bool temporarySigning(SecStaticCodeRef code, AuthorityType type, CFURLRef path, SecAssessmentFlags matchFlags); - void normalizeTarget(CFRef &target, AuthorityType type, CFDictionary &context, std::string *signUnsigned); - - void selectRules(SQLite::Statement &action, std::string stanza, std::string table, - CFTypeRef inTarget, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, std::string suffix = ""); - CFDictionaryRef manipulateRules(const std::string &stanza, - CFTypeRef target, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, bool authorize); - - void setOrigin(CFArrayRef chain, CFMutableDictionaryRef result); - - void recordOutcome(SecStaticCodeRef code, bool allow, AuthorityType type, double expires, SQLite::int64 authority); - -private: - OpaqueWhitelist mOpaqueWhitelist; - - friend class EvaluationManager; - friend class EvaluationTask; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif //_H_POLICYENGINE diff --git a/OSX/include/security_codesigning/quarantine++.cpp b/OSX/include/security_codesigning/quarantine++.cpp deleted file mode 100644 index ccf7a5c0..00000000 --- a/OSX/include/security_codesigning/quarantine++.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// xar++ - interface to XAR-format archive files -// -#include "quarantine++.h" - - -namespace Security { -namespace CodeSigning { - - -// -// Check the int result of a qtn API call. -// If the error is "not quarantined," note in the object (no error). -// Other qtn-specific errors are arbitrarily mapped to ENOSYS (this isn't -// important enough to subclass CommonError). -// -void FileQuarantine::check(int err) -{ - switch (err) { - case 0: - mQuarantined = true; - break; - case QTN_NOT_QUARANTINED: - mQuarantined = false; - return; - default: // some flavor of quarantine-not-available - UnixError::throwMe(err); - } -} - - -FileQuarantine::~FileQuarantine() -{ - if (mQtn) - qtn_file_free(mQtn); -} - - -FileQuarantine::FileQuarantine(const char *path) -{ - if (!(mQtn = qtn_file_alloc())) - UnixError::throwMe(); - check(qtn_file_init_with_path(mQtn, path)); -} - -FileQuarantine::FileQuarantine(int fd) -{ - if (!(mQtn = qtn_file_alloc())) - UnixError::throwMe(); - check(qtn_file_init_with_fd(mQtn, fd)); -} - - -void FileQuarantine::setFlags(uint32_t flags) -{ - if (mQuarantined) - check(qtn_file_set_flags(mQtn, flags)); -} - -void FileQuarantine::setFlag(uint32_t flag) -{ - if (mQuarantined) - setFlags(flags() | flag); -} - -void FileQuarantine::clearFlag(uint32_t flag) -{ - if (mQuarantined) - setFlags(flags() & ~flag); -} - -void FileQuarantine::applyTo(const char *path) -{ - check(qtn_file_apply_to_path(mQtn, path)); -} - -void FileQuarantine::applyTo(int fd) -{ - check(qtn_file_apply_to_fd(mQtn, fd)); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/quarantine++.h b/OSX/include/security_codesigning/quarantine++.h deleted file mode 100644 index b2680d5e..00000000 --- a/OSX/include/security_codesigning/quarantine++.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// quarantine++ - interface to XAR-format archive files -// -#ifndef _H_QUARANTINEPLUSPLUS -#define _H_QUARANTINEPLUSPLUS - -#include -#include - -extern "C" { -#include -} - -namespace Security { -namespace CodeSigning { - - -// -// A file quarantine object -// -class FileQuarantine { -public: - FileQuarantine(const char *path); - FileQuarantine(int fd); - virtual ~FileQuarantine(); - - uint32_t flags() const - { return qtn_file_get_flags(mQtn); } - bool flag(uint32_t f) const - { return this->flags() & f; } - - void setFlags(uint32_t flags); - void setFlag(uint32_t flag); - void clearFlag(uint32_t flag); - - void applyTo(const char *path); - void applyTo(int fd); - - operator bool() const { return mQtn != 0; } - bool quarantined() const { return mQuarantined; } - -private: - void check(int err); - -private: - qtn_file_t mQtn; // qtn handle - bool mQuarantined; // has quarantine information -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_QUARANTINEPLUSPLUS diff --git a/OSX/include/security_codesigning/reqdumper.cpp b/OSX/include/security_codesigning/reqdumper.cpp deleted file mode 100644 index c7e180f6..00000000 --- a/OSX/include/security_codesigning/reqdumper.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqdumper - Requirement un-parsing (disassembly) -// -#include "reqdumper.h" -#include // OID encoder -#include - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Table of reserved words (keywords), generated by ANTLR -// -static const char * const keywords[] = { -#include "RequirementKeywords.h" - "", - NULL -}; - - -// -// Printf to established output channel -// -void Dumper::print(const char *format, ...) -{ - char buffer[256]; - va_list args; - va_start(args, format); - vsnprintf(buffer, sizeof(buffer), format, args); - va_end(args); - mOutput += buffer; -} - - -// -// Dump the underlying Requirement program -// -void Dumper::dump() -{ - this->expr(); - - // remove any initial space - if (mOutput[0] == ' ') - mOutput = mOutput.substr(1); -} - - -// -// Dump an entire Requirements set, using temporary Dumper objects. -// -// This detects single Requirement inputs and dumps them successfully (using -// single-requirement syntax). No indication of error is returned in this case. -// -string Dumper::dump(const Requirements *reqs, bool debug /* = false */) -{ - if (!reqs) { - return "# no requirement(s)"; - } else if (reqs->magic() == Requirement::typeMagic) { // single requirement - return dump((const Requirement *)reqs) + "\n"; - } else { - string result; - for (unsigned n = 0; n < reqs->count(); n++) { - char prefix[200]; - if (reqs->type(n) < kSecRequirementTypeCount) - snprintf(prefix, sizeof(prefix), - "%s => ", Requirement::typeNames[reqs->type(n)]); - else - snprintf(prefix, sizeof(prefix), "/*unknown type*/ %d => ", reqs->type(n)); - Dumper dumper(reqs->blob(n), debug); - dumper.expr(); - result += prefix + dumper.value() + "\n"; - } - return result; - } -} - -string Dumper::dump(const Requirement *req, bool debug /* = false */) -{ - Dumper dumper(req, debug); - try { - dumper.dump(); - return dumper; - } catch (const CommonError &err) { - if (debug) { - char errstr[80]; - snprintf(errstr, sizeof(errstr), " !! error %ld !!", (unsigned long)err.osStatus()); - return dumper.value() + errstr; - } - throw; - } -} - -string Dumper::dump(const BlobCore *req, bool debug /* = false */) -{ - switch (req->magic()) { - case Requirement::typeMagic: - return dump(static_cast(req), debug); - break; - case Requirements::typeMagic: - return dump(static_cast(req), debug); - break; - default: - return "invalid data type"; - } -} - - -// -// Element dumpers. Output accumulates in internal buffer. -// -void Dumper::expr(SyntaxLevel level) -{ - if (mDebug) - print("/*@0x%x*/", pc()); - ExprOp op = ExprOp(get()); - switch (op & ~opFlagMask) { - case opFalse: - print("never"); - break; - case opTrue: - print("always"); - break; - case opIdent: - print("identifier "); - data(); - break; - case opAppleAnchor: - print("anchor apple"); - break; - case opAppleGenericAnchor: - print("anchor apple generic"); - break; - case opAnchorHash: - print("certificate"); certSlot(); print(" = "); hashData(); - break; - case opInfoKeyValue: - if (mDebug) - print("/*legacy*/"); - print("info["); dotString(); print("] = "); data(); - break; - case opAnd: - if (level < slAnd) - print("("); - expr(slAnd); - print(" and "); - expr(slAnd); - if (level < slAnd) - print(")"); - break; - case opOr: - if (level < slOr) - print("("); - expr(slOr); - print(" or "); - expr(slOr); - if (level < slOr) - print(")"); - break; - case opNot: - print("! "); - expr(slPrimary); - break; - case opCDHash: - print("cdhash "); - hashData(); - break; - case opInfoKeyField: - print("info["); dotString(); print("]"); match(); - break; - case opEntitlementField: - print("entitlement["); dotString(); print("]"); match(); - break; - case opCertField: - print("certificate"); certSlot(); print("["); dotString(); print("]"); match(); - break; - case opCertGeneric: - print("certificate"); certSlot(); print("["); - { - const unsigned char *data; size_t length; - getData(data, length); - print("field.%s", CssmOid((unsigned char *)data, length).toOid().c_str()); - } - print("]"); match(); - break; - case opCertPolicy: - print("certificate"); certSlot(); print("["); - { - const unsigned char *data; size_t length; - getData(data, length); - print("policy.%s", CssmOid((unsigned char *)data, length).toOid().c_str()); - } - print("]"); match(); - break; - case opTrustedCert: - print("certificate"); certSlot(); print("trusted"); - break; - case opTrustedCerts: - print("anchor trusted"); - break; - case opNamedAnchor: - print("anchor apple "); data(); - break; - case opNamedCode: - print("("); data(); print(")"); - break; - case opPlatform: - print("platform = %d", get()); - break; - default: - if (op & opGenericFalse) { - print(" false /* opcode %d */", op & ~opFlagMask); - break; - } else if (op & opGenericSkip) { - print(" /* opcode %d */", op & ~opFlagMask); - break; - } else { - print("OPCODE %d NOT UNDERSTOOD (ending print)", op); - return; - } - } -} - -void Dumper::certSlot() -{ - switch (int32_t slot = get()) { - case Requirement::anchorCert: - print(" root"); - break; - case Requirement::leafCert: - print(" leaf"); - break; - default: - print(" %d", slot); - break; - } -} - -void Dumper::match() -{ - switch (MatchOperation op = MatchOperation(get())) { - case matchExists: - print(" /* exists */"); - break; - case matchEqual: - print(" = "); data(); - break; - case matchContains: - print(" ~ "); data(); - break; - case matchBeginsWith: - print(" = "); data(); print("*"); - break; - case matchEndsWith: - print(" = *"); data(); - break; - case matchLessThan: - print(" < "); data(); - break; - case matchGreaterEqual: - print(" >= "); data(); - break; - case matchLessEqual: - print(" <= "); data(); - break; - case matchGreaterThan: - print(" > "); data(); - break; - default: - print("MATCH OPCODE %d NOT UNDERSTOOD", op); - break; - } -} - -void Dumper::hashData() -{ - print("H\""); - const unsigned char *data; size_t length; - getData(data, length); - printBytes(data, length); - print("\""); -} - -void Dumper::data(PrintMode bestMode /* = isSimple */, bool dotOkay /* = false */) -{ - const unsigned char *data; size_t length; - getData(data, length); - for (unsigned n = 0; n < length; n++) - if ((isalnum(data[n]) || (data[n] == '.' && dotOkay))) { // simple - if (n == 0 && isdigit(data[n])) // unquoted idents can't start with a digit - bestMode = isPrintable; - } else if (isgraph(data[n]) || isspace(data[n])) { - if (bestMode == isSimple) - bestMode = isPrintable; - } else { - bestMode = isBinary; - break; // pessimal - } - - if (bestMode == isSimple) { - string s((const char *)data, length); - for (const char * const * k = keywords; *k; k++) - if (s == *k) { - bestMode = isPrintable; // reserved word; need quotes - break; - } - } - - switch (bestMode) { - case isSimple: - print("%.*s", length, data); - break; - case isPrintable: - print("\""); - for (unsigned n = 0; n < length; n++) - switch (data[n]) { - case '\\': - case '"': - print("\\%c", data[n]); - break; - default: - print("%c", data[n]); - break; - } - print("\""); - break; - default: - print("0x"); - printBytes(data, length); - break; - } -} - -void Dumper::printBytes(const Byte *data, size_t length) -{ - for (unsigned n = 0; n < length; n++) - print("%02.2x", data[n]); -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/reqdumper.h b/OSX/include/security_codesigning/reqdumper.h deleted file mode 100644 index ebd9c25c..00000000 --- a/OSX/include/security_codesigning/reqdumper.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqdumper - Requirement un-parsing (disassembly) -// -#ifndef _H_REQDUMPER -#define _H_REQDUMPER - -#include "reqreader.h" -#include - - -namespace Security { -namespace CodeSigning { - - -// -// A decompiler for (compiled) requirements programs. -// This is intended to produce compiler-ready source, and the -// (decompile . compile) cycle is meant to be loss-less. -// -// Note that a Dumper is a type of Interpreter, so it can use the program stream -// accessors of the Interpreter. However, the evaluaton Context is absent, so -// actual validation functions must not be called. -// -class Dumper : public Requirement::Reader { -public: - explicit Dumper(const Requirement *req, bool debug = false) - : Reader(req), mDebug(debug) { } - - enum SyntaxLevel { - slPrimary, // syntax primary - slAnd, // conjunctive - slOr, // disjunctive - slTop // where we start - }; - - void dump(); // decompile this (entire) requirement - void expr(SyntaxLevel level = slTop); // decompile one requirement expression - - std::string value() const { return mOutput; } - operator std::string () const { return value(); } - - typedef unsigned char Byte; - -public: - // all-in-one dumping - static string dump(const Requirements *reqs, bool debug = false); - static string dump(const Requirement *req, bool debug = false); - static string dump(const BlobCore *req, bool debug = false); // dumps either - -protected: - enum PrintMode { - isSimple, // printable and does not require quotes - isPrintable, // can be quoted safely - isBinary // contains binary bytes (use 0xnnn form) - }; - void data(PrintMode bestMode = isSimple, bool dotOkay = false); - void dotString() { data(isSimple, true); } - void quotedString() { data(isPrintable); } - void hashData(); // H"bytes" - void certSlot(); // symbolic certificate slot indicator (explicit) - void match(); // a match suffix (op + value) - - void print(const char *format, ...); - -private: - void printBytes(const Byte *data, size_t length); // just write hex bytes - -private: - std::string mOutput; // output accumulator - bool mDebug; // include debug output in mOutput -}; - - -} // CodeSigning -} // Security - -#endif //_H_REQDUMPER diff --git a/OSX/include/security_codesigning/reqinterp.cpp b/OSX/include/security_codesigning/reqinterp.cpp deleted file mode 100644 index effd233e..00000000 --- a/OSX/include/security_codesigning/reqinterp.cpp +++ /dev/null @@ -1,583 +0,0 @@ -/* - * Copyright (c) 2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqinterp - Requirement language (exprOp) interpreter -// -#include "reqinterp.h" -#include "codesigning_dtrace.h" -#include -#include -#include -#include -#include "csutilities.h" - -namespace Security { -namespace CodeSigning { - - -// -// Fragment fetching, caching, and evaluation. -// -// Several language elements allow "calling" of separate requirement programs -// stored on disk as (binary) requirement blobs. The Fragments class takes care -// of finding, loading, caching, and evaluating them. -// -// This is a singleton for (process global) caching. It works fine as multiple instances, -// at a loss of caching effectiveness. -// -class Fragments { -public: - Fragments(); - - bool named(const std::string &name, const Requirement::Context &ctx) - { return evalNamed("subreq", name, ctx); } - bool namedAnchor(const std::string &name, const Requirement::Context &ctx) - { return evalNamed("anchorreq", name, ctx); } - -private: - bool evalNamed(const char *type, const std::string &name, const Requirement::Context &ctx); - CFDataRef fragment(const char *type, const std::string &name); - - typedef std::map > FragMap; - -private: - CFBundleRef mMyBundle; // Security.framework bundle - Mutex mLock; // lock for all of the below... - FragMap mFragments; // cached fragments -}; - -static ModuleNexus fragments; - - -// -// Magic certificate features -// -static CFStringRef appleIntermediateCN = CFSTR("Apple Code Signing Certification Authority"); -static CFStringRef appleIntermediateO = CFSTR("Apple Inc."); - - -// -// Main interpreter function. -// -// ExprOp code is in Polish Notation (operator followed by operands), -// and this engine uses opportunistic evaluation. -// -bool Requirement::Interpreter::evaluate() -{ return eval(stackLimit); } - -bool Requirement::Interpreter::eval(int depth) -{ - if (--depth <= 0) // nested too deeply - protect the stack - MacOSError::throwMe(errSecCSReqInvalid); - - ExprOp op = ExprOp(get()); - CODESIGN_EVAL_REQINT_OP(op, this->pc() - sizeof(uint32_t)); - switch (op & ~opFlagMask) { - case opFalse: - return false; - case opTrue: - return true; - case opIdent: - return mContext->directory && getString() == mContext->directory->identifier(); - case opAppleAnchor: - return appleSigned(); - case opAppleGenericAnchor: - return appleAnchored(); - case opAnchorHash: - { - SecCertificateRef cert = mContext->cert(get()); - return verifyAnchor(cert, getSHA1()); - } - case opInfoKeyValue: // [legacy; use opInfoKeyField] - { - string key = getString(); - return infoKeyValue(key, Match(CFTempString(getString()), matchEqual)); - } - case opAnd: - return eval(depth) & eval(depth); - case opOr: - return eval(depth) | eval(depth); - case opCDHash: - if (mContext->directory) { - CFRef cdhash = mContext->directory->cdhash(); - CFRef required = getHash(); - return CFEqual(cdhash, required); - } else - return false; - case opNot: - return !eval(depth); - case opInfoKeyField: - { - string key = getString(); - Match match(*this); - return infoKeyValue(key, match); - } - case opEntitlementField: - { - string key = getString(); - Match match(*this); - return entitlementValue(key, match); - } - case opCertField: - { - SecCertificateRef cert = mContext->cert(get()); - string key = getString(); - Match match(*this); - return certFieldValue(key, match, cert); - } - case opCertGeneric: - { - SecCertificateRef cert = mContext->cert(get()); - string key = getString(); - Match match(*this); - return certFieldGeneric(key, match, cert); - } - case opCertPolicy: - { - SecCertificateRef cert = mContext->cert(get()); - string key = getString(); - Match match(*this); - return certFieldPolicy(key, match, cert); - } - case opTrustedCert: - return trustedCert(get()); - case opTrustedCerts: - return trustedCerts(); - case opNamedAnchor: - return fragments().namedAnchor(getString(), *mContext); - case opNamedCode: - return fragments().named(getString(), *mContext); - case opPlatform: - { - int32_t targetPlatform = get(); - return mContext->directory && mContext->directory->platform == targetPlatform; - } - default: - // opcode not recognized - handle generically if possible, fail otherwise - if (op & (opGenericFalse | opGenericSkip)) { - // unknown opcode, but it has a size field and can be safely bypassed - skip(get()); - if (op & opGenericFalse) { - CODESIGN_EVAL_REQINT_UNKNOWN_FALSE(op); - return false; - } else { - CODESIGN_EVAL_REQINT_UNKNOWN_SKIPPED(op); - return eval(depth); - } - } - // unrecognized opcode and no way to interpret it - secdebug("csinterp", "opcode 0x%x cannot be handled; aborting", op); - MacOSError::throwMe(errSecCSUnimplemented); - } -} - - -// -// Evaluate an Info.plist key condition -// -bool Requirement::Interpreter::infoKeyValue(const string &key, const Match &match) -{ - if (mContext->info) // we have an Info.plist - if (CFTypeRef value = CFDictionaryGetValue(mContext->info, CFTempString(key))) - return match(value); - return false; -} - - -// -// Evaluate an entitlement condition -// -bool Requirement::Interpreter::entitlementValue(const string &key, const Match &match) -{ - if (mContext->entitlements) // we have an Info.plist - if (CFTypeRef value = CFDictionaryGetValue(mContext->entitlements, CFTempString(key))) - return match(value); - return false; -} - - -bool Requirement::Interpreter::certFieldValue(const string &key, const Match &match, SecCertificateRef cert) -{ - // no cert, no chance - if (cert == NULL) - return false; - - // a table of recognized keys for the "certificate[foo]" syntax - static const struct CertField { - const char *name; - const CSSM_OID *oid; - } certFields[] = { - { "subject.C", &CSSMOID_CountryName }, - { "subject.CN", &CSSMOID_CommonName }, - { "subject.D", &CSSMOID_Description }, - { "subject.L", &CSSMOID_LocalityName }, -// { "subject.C-L", &CSSMOID_CollectiveLocalityName }, // missing from Security.framework headers - { "subject.O", &CSSMOID_OrganizationName }, - { "subject.C-O", &CSSMOID_CollectiveOrganizationName }, - { "subject.OU", &CSSMOID_OrganizationalUnitName }, - { "subject.C-OU", &CSSMOID_CollectiveOrganizationalUnitName }, - { "subject.ST", &CSSMOID_StateProvinceName }, - { "subject.C-ST", &CSSMOID_CollectiveStateProvinceName }, - { "subject.STREET", &CSSMOID_StreetAddress }, - { "subject.C-STREET", &CSSMOID_CollectiveStreetAddress }, - { "subject.UID", &CSSMOID_UserID }, - { NULL, NULL } - }; - - // DN-component single-value match - for (const CertField *cf = certFields; cf->name; cf++) - if (cf->name == key) { - CFRef value; - if (OSStatus rc = SecCertificateCopySubjectComponent(cert, cf->oid, &value.aref())) { - secdebug("csinterp", "cert %p lookup for DN.%s failed rc=%d", cert, key.c_str(), (int)rc); - return false; - } - return match(value); - } - - // email multi-valued match (any of...) - if (key == "email") { - CFRef value; - if (OSStatus rc = SecCertificateCopyEmailAddresses(cert, &value.aref())) { - secdebug("csinterp", "cert %p lookup for email failed rc=%d", cert, (int)rc); - return false; - } - return match(value); - } - - // unrecognized key. Fail but do not abort to promote backward compatibility down the road - secdebug("csinterp", "cert field notation \"%s\" not understood", key.c_str()); - return false; -} - - -bool Requirement::Interpreter::certFieldGeneric(const string &key, const Match &match, SecCertificateRef cert) -{ - // the key is actually a (binary) OID value - CssmOid oid((char *)key.data(), key.length()); - return certFieldGeneric(oid, match, cert); -} - -bool Requirement::Interpreter::certFieldGeneric(const CssmOid &oid, const Match &match, SecCertificateRef cert) -{ - return cert && certificateHasField(cert, oid) && match(kCFBooleanTrue); -} - -bool Requirement::Interpreter::certFieldPolicy(const string &key, const Match &match, SecCertificateRef cert) -{ - // the key is actually a (binary) OID value - CssmOid oid((char *)key.data(), key.length()); - return certFieldPolicy(oid, match, cert); -} - -bool Requirement::Interpreter::certFieldPolicy(const CssmOid &oid, const Match &match, SecCertificateRef cert) -{ - return cert && certificateHasPolicy(cert, oid) && match(kCFBooleanTrue); -} - - -// -// Check the Apple-signed condition -// -bool Requirement::Interpreter::appleAnchored() -{ - if (SecCertificateRef cert = mContext->cert(anchorCert)) - if (isAppleCA(cert) -#if defined(TEST_APPLE_ANCHOR) - || verifyAnchor(cert, testAppleAnchorHash()) -#endif - ) - return true; - return false; -} - -bool Requirement::Interpreter::appleSigned() -{ - if (appleAnchored()) - if (SecCertificateRef intermed = mContext->cert(-2)) // first intermediate - // first intermediate common name match (exact) - if (certFieldValue("subject.CN", Match(appleIntermediateCN, matchEqual), intermed) - && certFieldValue("subject.O", Match(appleIntermediateO, matchEqual), intermed)) - return true; - return false; -} - - -// -// Verify an anchor requirement against the context -// -bool Requirement::Interpreter::verifyAnchor(SecCertificateRef cert, const unsigned char *digest) -{ - // get certificate bytes - if (cert) { - CSSM_DATA certData; - MacOSError::check(SecCertificateGetData(cert, &certData)); - - // verify hash - SHA1 hasher; - hasher(certData.Data, certData.Length); - return hasher.verify(digest); - } - return false; -} - - -// -// Check one or all certificate(s) in the cert chain against the Trust Settings database. -// -bool Requirement::Interpreter::trustedCerts() -{ - int anchor = mContext->certCount() - 1; - for (int slot = 0; slot <= anchor; slot++) - if (SecCertificateRef cert = mContext->cert(slot)) - switch (trustSetting(cert, slot == anchor)) { - case kSecTrustSettingsResultTrustRoot: - case kSecTrustSettingsResultTrustAsRoot: - return true; - case kSecTrustSettingsResultDeny: - return false; - case kSecTrustSettingsResultUnspecified: - break; - default: - assert(false); - return false; - } - else - return false; - return false; -} - -bool Requirement::Interpreter::trustedCert(int slot) -{ - if (SecCertificateRef cert = mContext->cert(slot)) { - int anchorSlot = mContext->certCount() - 1; - switch (trustSetting(cert, slot == anchorCert || slot == anchorSlot)) { - case kSecTrustSettingsResultTrustRoot: - case kSecTrustSettingsResultTrustAsRoot: - return true; - case kSecTrustSettingsResultDeny: - case kSecTrustSettingsResultUnspecified: - return false; - default: - assert(false); - return false; - } - } else - return false; -} - - -// -// Explicitly check one certificate against the Trust Settings database and report -// the findings. This is a helper for the various Trust Settings evaluators. -// -SecTrustSettingsResult Requirement::Interpreter::trustSetting(SecCertificateRef cert, bool isAnchor) -{ - // the SPI input is the uppercase hex form of the SHA-1 of the certificate... - assert(cert); - SHA1::Digest digest; - hashOfCertificate(cert, digest); - string Certhex = CssmData(digest, sizeof(digest)).toHex(); - for (string::iterator it = Certhex.begin(); it != Certhex.end(); ++it) - if (islower(*it)) - *it = toupper(*it); - - // call Trust Settings and see what it finds - SecTrustSettingsDomain domain; - SecTrustSettingsResult result; - CSSM_RETURN *errors = NULL; - uint32 errorCount = 0; - bool foundMatch, foundAny; - switch (OSStatus rc = SecTrustSettingsEvaluateCert( - CFTempString(Certhex), // settings index - &CSSMOID_APPLE_TP_CODE_SIGNING, // standard code signing policy - NULL, 0, // policy string (unused) - kSecTrustSettingsKeyUseAny, // no restriction on key usage @@@ - isAnchor, // consult system default anchor set - - &domain, // domain of found setting - &errors, &errorCount, // error set and maximum count - &result, // the actual setting - &foundMatch, &foundAny // optimization hints (not used) - )) { - case errSecSuccess: - ::free(errors); - if (foundMatch) - return result; - else - return kSecTrustSettingsResultUnspecified; - default: - ::free(errors); - MacOSError::throwMe(rc); - } -} - - -// -// Create a Match object from the interpreter stream -// -Requirement::Interpreter::Match::Match(Interpreter &interp) -{ - switch (mOp = interp.get()) { - case matchExists: - break; - case matchEqual: - case matchContains: - case matchBeginsWith: - case matchEndsWith: - case matchLessThan: - case matchGreaterThan: - case matchLessEqual: - case matchGreaterEqual: - mValue.take(makeCFString(interp.getString())); - break; - default: - // Assume this (unknown) match type has a single data argument. - // This gives us a chance to keep the instruction stream aligned. - interp.getString(); // discard - break; - } -} - - -// -// Execute a match against a candidate value -// -bool Requirement::Interpreter::Match::operator () (CFTypeRef candidate) const -{ - // null candidates always fail - if (!candidate) - return false; - - // interpret an array as matching alternatives (any one succeeds) - if (CFGetTypeID(candidate) == CFArrayGetTypeID()) { - CFArrayRef array = CFArrayRef(candidate); - CFIndex count = CFArrayGetCount(array); - for (CFIndex n = 0; n < count; n++) - if ((*this)(CFArrayGetValueAtIndex(array, n))) // yes, it's recursive - return true; - } - - switch (mOp) { - case matchExists: // anything but NULL and boolean false "exists" - return !CFEqual(candidate, kCFBooleanFalse); - case matchEqual: // equality works for all CF types - return CFEqual(candidate, mValue); - case matchContains: - if (CFGetTypeID(candidate) == CFStringGetTypeID()) { - CFStringRef value = CFStringRef(candidate); - if (CFStringFindWithOptions(value, mValue, CFRangeMake(0, CFStringGetLength(value)), 0, NULL)) - return true; - } - return false; - case matchBeginsWith: - if (CFGetTypeID(candidate) == CFStringGetTypeID()) { - CFStringRef value = CFStringRef(candidate); - if (CFStringFindWithOptions(value, mValue, CFRangeMake(0, CFStringGetLength(mValue)), 0, NULL)) - return true; - } - return false; - case matchEndsWith: - if (CFGetTypeID(candidate) == CFStringGetTypeID()) { - CFStringRef value = CFStringRef(candidate); - CFIndex matchLength = CFStringGetLength(mValue); - CFIndex start = CFStringGetLength(value) - matchLength; - if (start >= 0) - if (CFStringFindWithOptions(value, mValue, CFRangeMake(start, matchLength), 0, NULL)) - return true; - } - return false; - case matchLessThan: - return inequality(candidate, kCFCompareNumerically, kCFCompareLessThan, true); - case matchGreaterThan: - return inequality(candidate, kCFCompareNumerically, kCFCompareGreaterThan, true); - case matchLessEqual: - return inequality(candidate, kCFCompareNumerically, kCFCompareGreaterThan, false); - case matchGreaterEqual: - return inequality(candidate, kCFCompareNumerically, kCFCompareLessThan, false); - default: - // unrecognized match types can never match - return false; - } -} - - -bool Requirement::Interpreter::Match::inequality(CFTypeRef candidate, CFStringCompareFlags flags, - CFComparisonResult outcome, bool negate) const -{ - if (CFGetTypeID(candidate) == CFStringGetTypeID()) { - CFStringRef value = CFStringRef(candidate); - if ((CFStringCompare(value, mValue, flags) == outcome) == negate) - return true; - } - return false; -} - - -// -// External fragments -// -Fragments::Fragments() -{ - mMyBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security")); -} - - -bool Fragments::evalNamed(const char *type, const std::string &name, const Requirement::Context &ctx) -{ - if (CFDataRef fragData = fragment(type, name)) { - const Requirement *req = (const Requirement *)CFDataGetBytePtr(fragData); // was prevalidated as Requirement - return req->validates(ctx); - } - return false; -} - - -CFDataRef Fragments::fragment(const char *type, const std::string &name) -{ - string key = name + "!!" + type; // compound key - StLock _(mLock); // lock for cache access - FragMap::const_iterator it = mFragments.find(key); - if (it == mFragments.end()) { - CFRef fragData; // will always be set (NULL on any errors) - if (CFRef fragURL = CFBundleCopyResourceURL(mMyBundle, CFTempString(name), CFSTR("csreq"), CFTempString(type))) - if (CFRef data = cfLoadFile(fragURL)) { // got data - const Requirement *req = (const Requirement *)CFDataGetBytePtr(data); - if (req->validateBlob(CFDataGetLength(data))) // looks like a Requirement... - fragData = data; // ... so accept it - else - Syslog::warning("Invalid sub-requirement at %s", cfString(fragURL).c_str()); - } - if (CODESIGN_EVAL_REQINT_FRAGMENT_LOAD_ENABLED()) - CODESIGN_EVAL_REQINT_FRAGMENT_LOAD(type, name.c_str(), fragData ? CFDataGetBytePtr(fragData) : NULL); - mFragments[key] = fragData; // cache it, success or failure - return fragData; - } - CODESIGN_EVAL_REQINT_FRAGMENT_HIT(type, name.c_str()); - return it->second; -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/reqinterp.h b/OSX/include/security_codesigning/reqinterp.h deleted file mode 100644 index a221f96d..00000000 --- a/OSX/include/security_codesigning/reqinterp.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqinterp - Requirement language (exprOp) interpreter -// -#ifndef _H_REQINTERP -#define _H_REQINTERP - -#include -#include -#include // CssmOid - -namespace Security { -namespace CodeSigning { - - -// -// An interpreter for exprForm-type requirements. -// This is a simple Polish Notation stack evaluator. -// -class Requirement::Interpreter : public Requirement::Reader { -public: - Interpreter(const Requirement *req, const Context *ctx) : Reader(req), mContext(ctx) { } - - static const unsigned stackLimit = 1000; - - bool evaluate(); - -protected: - class Match { - public: - Match(Interpreter &interp); // reads match postfix from interp - Match(CFStringRef value, MatchOperation op) : mValue(value), mOp(op) { } // explicit - Match() : mValue(NULL), mOp(matchExists) { } // explict test for presence - bool operator () (CFTypeRef candidate) const; // match to candidate - - protected: - bool inequality(CFTypeRef candidate, CFStringCompareFlags flags, CFComparisonResult outcome, bool negate) const; - - private: - CFCopyRef mValue; // match value - MatchOperation mOp; // type of match - }; - -protected: - bool eval(int depth); - - bool infoKeyValue(const std::string &key, const Match &match); - bool entitlementValue(const std::string &key, const Match &match); - bool certFieldValue(const string &key, const Match &match, SecCertificateRef cert); - bool certFieldGeneric(const string &key, const Match &match, SecCertificateRef cert); - bool certFieldGeneric(const CssmOid &oid, const Match &match, SecCertificateRef cert); - bool certFieldPolicy(const string &key, const Match &match, SecCertificateRef cert); - bool certFieldPolicy(const CssmOid &oid, const Match &match, SecCertificateRef cert); - bool verifyAnchor(SecCertificateRef cert, const unsigned char *digest); - bool appleSigned(); - bool appleAnchored(); - bool trustedCerts(); - bool trustedCert(int slot); - - static SecTrustSettingsResult trustSetting(SecCertificateRef cert, bool isAnchor); - -private: - const Context * const mContext; -}; - - -} // CodeSigning -} // Security - -#endif //_H_REQINTERP diff --git a/OSX/include/security_codesigning/reqmaker.cpp b/OSX/include/security_codesigning/reqmaker.cpp deleted file mode 100644 index 034c3cf1..00000000 --- a/OSX/include/security_codesigning/reqmaker.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqmaker - Requirement assembler -// -#include "reqmaker.h" - -namespace Security { -namespace CodeSigning { - - -// -// Requirement::Makers -// -Requirement::Maker::Maker(Kind k) - : mSize(1024) -{ - mBuffer = (Requirement *)malloc(mSize); - mBuffer->initialize(); - mBuffer->kind(k); - mPC = sizeof(Requirement); -} - -// need at least (size) bytes in the creation buffer -void Requirement::Maker::require(size_t size) -{ - if (mPC + size > mSize) { - mSize *= 2; - if (mPC + size > mSize) - mSize = (Offset)(mPC + size); - if (!(mBuffer = (Requirement *)realloc(mBuffer, mSize))) - UnixError::throwMe(ENOMEM); - } -} - -// allocate (size) bytes at end of buffer and return pointer to that -void *Requirement::Maker::alloc(size_t size) -{ - // round size up to preserve alignment - size_t usedSize = LowLevelMemoryUtilities::alignUp(size, baseAlignment); - require(usedSize); - void *data = mBuffer->at(mPC); - mPC += usedSize; - - // clear any padding (avoid random bytes in code image) - const uint32_t zero = 0; - memcpy(mBuffer->at(mPC - usedSize + size), &zero, usedSize - size); - - // all done - return data; -} - -// put contiguous data blob -void Requirement::Maker::putData(const void *data, size_t length) -{ - put(uint32_t(length)); - memcpy(alloc(length), data, length); -} - -// Specialized Maker put operations -void Requirement::Maker::anchor() -{ - put(opAppleAnchor); -} - -void Requirement::Maker::anchorGeneric() -{ - put(opAppleGenericAnchor); -} - -void Requirement::Maker::anchor(int slot, SHA1::Digest digest) -{ - put(opAnchorHash); - put(slot); - putData(digest, SHA1::digestLength); -} - -void Requirement::Maker::anchor(int slot, const void *cert, size_t length) -{ - SHA1 hasher; - hasher(cert, length); - SHA1::Digest digest; - hasher.finish(digest); - anchor(slot, digest); -} - -void Requirement::Maker::trustedAnchor() -{ - put(opTrustedCerts); -} - -void Requirement::Maker::trustedAnchor(int slot) -{ - put(opTrustedCert); - put(slot); -} - -void Requirement::Maker::infoKey(const string &key, const string &value) -{ - put(opInfoKeyValue); - put(key); - put(value); -} - -void Requirement::Maker::ident(const string &identifier) -{ - put(opIdent); - put(identifier); -} - -void Requirement::Maker::cdhash(SHA1::Digest digest) -{ - put(opCDHash); - putData(digest, SHA1::digestLength); -} - -void Requirement::Maker::cdhash(CFDataRef digest) -{ - put(opCDHash); - putData(CFDataGetBytePtr(digest), CFDataGetLength(digest)); -} - -void Requirement::Maker::platform(int platformIdentifier) -{ - put(opPlatform); - put(platformIdentifier); -} - - -void Requirement::Maker::copy(const Requirement *req) -{ - assert(req); - if (req->kind() != exprForm) // don't know how to embed this - MacOSError::throwMe(errSecCSReqUnsupported); - this->copy(req->at(sizeof(Requirement)), req->length() - sizeof(Requirement)); -} - - -void *Requirement::Maker::insert(const Label &label, size_t length) -{ - require(length); - memmove(mBuffer->at(label.pos + length), - mBuffer->at(label.pos), mPC - label.pos); - mPC += length; - return mBuffer->at(label.pos); -} - - -Requirement *Requirement::Maker::make() -{ - mBuffer->length(mPC); - Requirement *result = mBuffer; - mBuffer = NULL; - return result; -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/reqmaker.h b/OSX/include/security_codesigning/reqmaker.h deleted file mode 100644 index 721fc1f3..00000000 --- a/OSX/include/security_codesigning/reqmaker.h +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqmaker - Requirement assembler -// -#ifndef _H_REQMAKER -#define _H_REQMAKER - -#include - -namespace Security { -namespace CodeSigning { - - -// -// A Requirement::Maker is a tool for creating a Requirement blob. -// It's primarily an assember for the binary requirements (exprOp) language. -// Initialize it, call put() methods to generate the exprOp program, then -// call make() to get the assembled Requirement blob, malloc'ed for you. -// The Maker is not reusable. -// -class Requirement::Maker { -public: - Maker(Kind k = exprForm); - ~Maker() { free(mBuffer); } - - template - T *alloc(size_t size) { return reinterpret_cast(alloc(size)); } - - template - void put(const T &value) { *alloc >(sizeof(T)) = value; } - void put(ExprOp op) { put(uint32_t(op)); } - void put(MatchOperation op) { put(uint32_t(op)); } - void put(const std::string &s) { putData(s.data(), s.size()); } - void put(const char *s) { putData(s, strlen(s)); } - void putData(const void *data, size_t length); - void putData(CFStringRef s) { put(cfString(s)); } - - void anchor(int slot, SHA1::Digest digest); // given slot/digest - void anchor(int slot, const void *cert, size_t length); // given slot/cert - void anchor(); // made-by-Apple - void anchorGeneric(); // anything drawn from the Apple anchor - - void trustedAnchor(); - void trustedAnchor(int slot); - - void infoKey(const std::string &key, const std::string &value); - void ident(const std::string &identHash); - void cdhash(SHA1::Digest digest); - void cdhash(CFDataRef digest); - void platform(int platformIdentifier); - - void copy(const void *data, size_t length) - { memcpy(this->alloc(length), data, length); } - void copy(const Requirement *req); // inline expand - - // - // Keep labels into exprOp code, and allow for "shifting in" - // prefix code as needed (exprOp is a prefix-code language). - // - struct Label { - const Offset pos; - Label(const Maker &maker) : pos((const Offset)maker.length()) { } - }; - void *insert(const Label &label, size_t length = sizeof(uint32_t)); - - template - Endian &insert(const Label &label, size_t length = sizeof(T)) - { return *reinterpret_cast*>(insert(label, length)); } - - // - // Help with making operator chains (foo AND bar AND baz...). - // Note that the empty case (no elements at all) must be resolved by the caller. - // - class Chain : public Label { - public: - Chain(Maker &myMaker, ExprOp op) - : Label(myMaker), maker(myMaker), mJoiner(op), mCount(0) { } - - void add() const - { if (mCount++) maker.insert(*this) = mJoiner; } - - Maker &maker; - bool empty() const { return mCount == 0; } - - private: - ExprOp mJoiner; - mutable unsigned mCount; - }; - - - // - // Over-all construction management - // - void kind(Kind k) { mBuffer->kind(k); } - size_t length() const { return mPC; } - Requirement *make(); - Requirement *operator () () { return make(); } - -protected: - void require(size_t size); - void *alloc(size_t size); - -private: - Requirement *mBuffer; - Offset mSize; - Offset mPC; -}; - - -} // CodeSigning -} // Security - -#endif //_H_REQMAKER diff --git a/OSX/include/security_codesigning/reqparser.cpp b/OSX/include/security_codesigning/reqparser.cpp deleted file mode 100644 index 8a0c370a..00000000 --- a/OSX/include/security_codesigning/reqparser.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqparser - interface to Requirement language parser/compiler -// -#include "reqparser.h" -#include "antlrplugin.h" -#include "cserror.h" -#include "codesigning_dtrace.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -struct PluginHost { - PluginHost(); - RefPointer plugin; - AntlrPlugin *antlr; -}; - -ModuleNexus plugin; - - -// -// The PluginHost constructor runs under the protection of ModuleNexus's constructor, -// so it doesn't have to worry about thread safety and such. -// -PluginHost::PluginHost() -{ - if (CFBundleRef securityFramework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security"))) - if (CFRef plugins = CFBundleCopyBuiltInPlugInsURL(securityFramework)) - if (CFRef pluginURL = makeCFURL("csparser.bundle", true, plugins)) { - plugin = new LoadableBundle(cfString(pluginURL).c_str()); - plugin->load(); - CODESIGN_LOAD_ANTLR(); - antlr = reinterpret_cast(plugin->lookupSymbol(FINDANTLRPLUGIN))(); - return; - } - - // can't load plugin - fail - MacOSError::throwMe(errSecCSInternalError); -} - - -// -// Drive a parsing function through the plugin harness and translate any errors -// into a CFError exception. -// -template -const Result *parse(Source source, const Result *(*AntlrPlugin::*func)(Source, string &)) -{ - string errors; - if (const Result *result = (plugin().antlr->*func)(source, errors)) - return result; - else - CSError::throwMe(errSecCSReqInvalid, kSecCFErrorRequirementSyntax, CFTempString(errors)); -} - - -// -// Implement the template instances by passing them through the plugin's eye-of-the-needle. -// Any other combination of input and output types will cause linker errors. -// -template <> -const Requirement *RequirementParser::operator () (std::FILE *source) -{ - return parse(source, &AntlrPlugin::fileRequirement); -} - -template <> -const Requirement *RequirementParser::operator () (const std::string &source) -{ - return parse(source, &AntlrPlugin::stringRequirement); -} - -template <> -const Requirements *RequirementParser::operator () (std::FILE *source) -{ - return parse(source, &AntlrPlugin::fileRequirements); -} - -template <> -const Requirements *RequirementParser::operator () (const std::string &source) -{ - return parse(source, &AntlrPlugin::stringRequirements); -} - -template <> -const BlobCore *RequirementParser::operator () (std::FILE *source) -{ - return parse(source, &AntlrPlugin::fileGeneric); -} - -template <> -const BlobCore *RequirementParser::operator () (const std::string &source) -{ - return parse(source, &AntlrPlugin::stringGeneric); -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/reqparser.h b/OSX/include/security_codesigning/reqparser.h deleted file mode 100644 index 3ecb9f48..00000000 --- a/OSX/include/security_codesigning/reqparser.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2006-2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqparser - interface to Requirement language parser/compiler -// -#ifndef _H_REQPARSER -#define _H_REQPARSER - -#include "requirement.h" - -namespace Security { -namespace CodeSigning { - - -// -// Generic parser interface -// -template -class RequirementParser { -public: - const ReqType *operator () (std::FILE *file); - const ReqType *operator () (const std::string &text); -}; - - -// -// Specifics for easier readability -// -template -inline const Requirement *parseRequirement(const Input &source) -{ return RequirementParser()(source); } - -template -inline const Requirements *parseRequirements(const Input &source) -{ return RequirementParser()(source); } - -template -inline const BlobCore *parseGeneric(const Input &source) -{ return RequirementParser()(source); } - - -} // CodeSigning -} // Security - -#endif //_H_REQPARSER diff --git a/OSX/include/security_codesigning/reqreader.cpp b/OSX/include/security_codesigning/reqreader.cpp deleted file mode 100644 index 63b1e352..00000000 --- a/OSX/include/security_codesigning/reqreader.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2007,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqreader - Requirement language (exprOp) reader/scanner -// -#include "reqreader.h" -#include -#include -#include // for hex encoding -#include "csutilities.h" - -namespace Security { -namespace CodeSigning { - - -// -// Requirement::Reader -// -Requirement::Reader::Reader(const Requirement *req) - : mReq(req), mPC(sizeof(Requirement)) -{ - assert(req); - if (req->kind() != exprForm) - MacOSError::throwMe(errSecCSReqUnsupported); -} - - -// -// Access helpers to retrieve various data types from the data stream -// -void Requirement::Reader::getData(const void *&data, size_t &length) -{ - length = get(); - checkSize(length); - data = (mReq->at(mPC)); - mPC += LowLevelMemoryUtilities::alignUp(length, baseAlignment); -} - -string Requirement::Reader::getString() -{ - const char *s; size_t length; - getData(s, length); - return string(s, length); -} - -CFDataRef Requirement::Reader::getHash() -{ - const unsigned char *s; size_t length; - getData(s, length); - return makeCFData(s, length); -} - -const unsigned char *Requirement::Reader::getSHA1() -{ - const unsigned char *digest; size_t length; - getData(digest, length); - if (length != CC_SHA1_DIGEST_LENGTH) - MacOSError::throwMe(errSecCSReqInvalid); - return digest; -} - -void Requirement::Reader::skip(size_t length) -{ - checkSize(length); - mPC += length; -} - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/reqreader.h b/OSX/include/security_codesigning/reqreader.h deleted file mode 100644 index b3f4a781..00000000 --- a/OSX/include/security_codesigning/reqreader.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2007,2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// reqreader - Requirement language (exprOp) reader/scanner -// -#ifndef _H_REQREADER -#define _H_REQREADER - -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// The Reader class provides structured access to a opExpr-type code requirement. -// -class Requirement::Reader { -public: - Reader(const Requirement *req); - - const Requirement *requirement() const { return mReq; } - - template T get(); - void getData(const void *&data, size_t &length); - - std::string getString(); - CFDataRef getHash(); - const unsigned char *getSHA1(); - - template void getData(T *&data, size_t &length) - { return getData(reinterpret_cast(data), length); } - -protected: - void checkSize(size_t length) - { - if (mPC + length < mPC || mPC + length > mReq->length()) - MacOSError::throwMe(errSecCSReqInvalid); - } - - void skip(size_t length); - - Offset pc() const { return mPC; } - bool atEnd() const { return mPC >= mReq->length(); } - -private: - const Requirement * const mReq; - Offset mPC; -}; - -template -T Requirement::Reader::get() -{ - checkSize(sizeof(T)); - const Endian *value = mReq->at >(mPC); - mPC += sizeof(T); - return *value; -} - - -} // CodeSigning -} // Security - -#endif //_H_REQREADER diff --git a/OSX/include/security_codesigning/requirement.cpp b/OSX/include/security_codesigning/requirement.cpp deleted file mode 100644 index 418c416b..00000000 --- a/OSX/include/security_codesigning/requirement.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2006-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// requirement - Code Requirement Blob description -// -#include "requirement.h" -#include "reqinterp.h" -#include "codesigning_dtrace.h" -#include -#include -#include -#include -#include - -#ifdef DEBUGDUMP -#include -#endif - -namespace Security { -namespace CodeSigning { - - -// -// Canonical names for requirement types -// -const char *const Requirement::typeNames[] = { - "invalid", - "host", - "guest", - "designated", - "library", - "plugin", -}; - - -// -// validate a requirement against a code context -// -void Requirement::validate(const Requirement::Context &ctx, OSStatus failure /* = errSecCSReqFailed */) const -{ - if (!this->validates(ctx, failure)) - MacOSError::throwMe(failure); -} - -bool Requirement::validates(const Requirement::Context &ctx, OSStatus failure /* = errSecCSReqFailed */) const -{ - CODESIGN_EVAL_REQINT_START((void*)this, (int)this->length()); - switch (kind()) { - case exprForm: - if (Requirement::Interpreter(this, &ctx).evaluate()) { - CODESIGN_EVAL_REQINT_END(this, 0); - return true; - } else { - CODESIGN_EVAL_REQINT_END(this, failure); - return false; - } - default: - CODESIGN_EVAL_REQINT_END(this, errSecCSReqUnsupported); - MacOSError::throwMe(errSecCSReqUnsupported); - } -} - - -// -// Retrieve one certificate from the cert chain. -// Positive and negative indices can be used: -// [ leaf, intermed-1, ..., intermed-n, anchor ] -// 0 1 ... -2 -1 -// Returns NULL if unavailable for any reason. -// -SecCertificateRef Requirement::Context::cert(int ix) const -{ - if (certs) { - if (ix < 0) - ix += certCount(); - if (ix >= CFArrayGetCount(certs)) - return NULL; - if (CFTypeRef element = CFArrayGetValueAtIndex(certs, ix)) - return SecCertificateRef(element); - } - return NULL; -} - -unsigned int Requirement::Context::certCount() const -{ - if (certs) - return (unsigned int)CFArrayGetCount(certs); - else - return 0; -} - - -// -// Produce the hash of a fake Apple root (only if compiled for internal testing) -// -#if defined(TEST_APPLE_ANCHOR) - -const char Requirement::testAppleAnchorEnv[] = "TEST_APPLE_ANCHOR"; - -const SHA1::Digest &Requirement::testAppleAnchorHash() -{ - static bool tried = false; - static SHA1::Digest testHash; - if (!tried) { - // see if we have one configured - if (const char *path = getenv(testAppleAnchorEnv)) - try { - UnixPlusPlus::FileDesc fd(path); - char buffer[2048]; // arbitrary limit - size_t size = fd.read(buffer, sizeof(buffer)); - SHA1 hash; - hash(buffer, size); - hash.finish(testHash); - Syslog::alert("ACCEPTING TEST AUTHORITY %s FOR APPLE CODE IDENTITY", path); - } catch (...) { } - tried = true; - } - return testHash; // will be zeroes (no match) if not configured -} - -#endif //TEST_APPLE_ANCHOR - - -// -// Debug dump support -// -#ifdef DEBUGDUMP - -void Requirement::dump() const -{ - Debug::dump("%s\n", Dumper::dump(this).c_str()); -} - -#endif //DEBUGDUMP - - -} // CodeSigning -} // Security diff --git a/OSX/include/security_codesigning/requirement.h b/OSX/include/security_codesigning/requirement.h deleted file mode 100644 index eb089475..00000000 --- a/OSX/include/security_codesigning/requirement.h +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) 2006-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// requirement - Code Requirement Blob description -// -#ifndef _H_REQUIREMENT -#define _H_REQUIREMENT - -#include -#include -#include -#include -#include "codedirectory.h" -#include - -namespace Security { -namespace CodeSigning { - - -// -// Single requirement. -// This is a contiguous binary blob, starting with this header -// and followed by binary expr-code. All links within the blob -// are offset-relative to the start of the header. -// This is designed to be a binary stable format. Note that we restrict -// outselves to 4GB maximum size (4 byte size/offset), and we expect real -// Requirement blobs to be fairly small (a few kilobytes at most). -// -// The "kind" field allows for adding different kinds of Requirements altogether -// in the future. We expect to stay within the framework of "opExpr" requirements, -// but it never hurts to have a way out. -// -class Requirement: public Blob { -public: - class Maker; // makes Requirement blobs - class Context; // evaluation context - class Reader; // structured reader - class Interpreter; // evaluation engine - - // different forms of Requirements. Right now, we only support exprForm ("opExprs") - enum Kind { - exprForm = 1 // prefix expr form - }; - - void kind(Kind k) { mKind = k; } - Kind kind() const { return Kind(uint32_t(mKind)); } - - // validate this requirement against a code context - void validate(const Context &ctx, OSStatus failure = errSecCSReqFailed) const; // throws on all failures - bool validates(const Context &ctx, OSStatus failure = errSecCSReqFailed) const; // returns on clean miss - - // certificate positions (within a standard certificate chain) - static const int leafCert = 0; // index for leaf (first in chain) - static const int anchorCert = -1; // index for anchor (last in chain) - -#if defined(TEST_APPLE_ANCHOR) - static const char testAppleAnchorEnv[]; - static const SHA1::Digest &testAppleAnchorHash(); -#endif //TEST_APPLE_ANCHOR - - // common alignment rule for all requirement forms - static const size_t baseAlignment = sizeof(uint32_t); // (we might as well say "four") - - // canonical (source) names of Requirement types (matched to SecRequirementType in CSCommon.h) - static const char *const typeNames[]; - - IFDUMP(void dump() const); - -private: - Endian mKind; // expression kind -}; - - -// -// An interpretation context -// -class Requirement::Context { -protected: - Context() - : certs(NULL), info(NULL), entitlements(NULL), identifier(""), directory(NULL) { } - -public: - Context(CFArrayRef certChain, CFDictionaryRef infoDict, CFDictionaryRef entitlementDict, - const std::string &ident, const CodeDirectory *dir) - : certs(certChain), info(infoDict), entitlements(entitlementDict), identifier(ident), directory(dir) { } - - CFArrayRef certs; // certificate chain - CFDictionaryRef info; // Info.plist - CFDictionaryRef entitlements; // entitlement plist - std::string identifier; // signing identifier - const CodeDirectory *directory; // CodeDirectory - - SecCertificateRef cert(int ix) const; // get a cert from the cert chain (NULL if not found) - unsigned int certCount() const; // length of cert chain (including root) -}; - - -// -// exprForm opcodes. -// -// Opcodes are broken into flags in the (HBO) high byte, and an opcode value -// in the remaining 24 bits. Note that opcodes will remain fairly small -// (almost certainly <60000), so we have the third byte to play around with -// in the future, if needed. For now, small opcodes effective reserve this byte -// as zero. -// The flag byte allows for limited understanding of unknown opcodes. It allows -// the interpreter to use the known opcode parts of the program while semi-creatively -// disregarding the parts it doesn't know about. An unrecognized opcode with zero -// flag byte causes evaluation to categorically fail, since the semantics of such -// an opcode cannot safely be predicted. -// -enum { - // semantic bits or'ed into the opcode - opFlagMask = 0xFF000000, // high bit flags - opGenericFalse = 0x80000000, // has size field; okay to default to false - opGenericSkip = 0x40000000, // has size field; skip and continue -}; - -enum ExprOp { - opFalse, // unconditionally false - opTrue, // unconditionally true - opIdent, // match canonical code [string] - opAppleAnchor, // signed by Apple as Apple's product - opAnchorHash, // match anchor [cert hash] - opInfoKeyValue, // *legacy* - use opInfoKeyField [key; value] - opAnd, // binary prefix expr AND expr [expr; expr] - opOr, // binary prefix expr OR expr [expr; expr] - opCDHash, // match hash of CodeDirectory directly [cd hash] - opNot, // logical inverse [expr] - opInfoKeyField, // Info.plist key field [string; match suffix] - opCertField, // Certificate field [cert index; field name; match suffix] - opTrustedCert, // require trust settings to approve one particular cert [cert index] - opTrustedCerts, // require trust settings to approve the cert chain - opCertGeneric, // Certificate component by OID [cert index; oid; match suffix] - opAppleGenericAnchor, // signed by Apple in any capacity - opEntitlementField, // entitlement dictionary field [string; match suffix] - opCertPolicy, // Certificate policy by OID [cert index; oid; match suffix] - opNamedAnchor, // named anchor type - opNamedCode, // named subroutine - opPlatform, // platform constraint [integer] - exprOpCount // (total opcode count in use) -}; - -// match suffix opcodes -enum MatchOperation { - matchExists, // anything but explicit "false" - no value stored - matchEqual, // equal (CFEqual) - matchContains, // partial match (substring) - matchBeginsWith, // partial match (initial substring) - matchEndsWith, // partial match (terminal substring) - matchLessThan, // less than (string with numeric comparison) - matchGreaterThan, // greater than (string with numeric comparison) - matchLessEqual, // less or equal (string with numeric comparison) - matchGreaterEqual, // greater or equal (string with numeric comparison) -}; - - -// -// We keep Requirement groups in SuperBlobs, indexed by SecRequirementType -// -typedef SuperBlob<0xfade0c01> Requirements; - - -// -// Byte order flippers -// -inline CodeSigning::ExprOp h2n(CodeSigning::ExprOp op) -{ - uint32_t intOp = (uint32_t) op; - return (CodeSigning::ExprOp) ::h2n(intOp); -} - -inline CodeSigning::ExprOp n2h(CodeSigning::ExprOp op) -{ - uint32_t intOp = (uint32_t) op; - return (CodeSigning::ExprOp) ::n2h(intOp); -} - - -inline CodeSigning::MatchOperation h2n(CodeSigning::MatchOperation op) -{ - return CodeSigning::MatchOperation(::h2n((uint32_t) op)); -} - -inline CodeSigning::MatchOperation n2h(CodeSigning::MatchOperation op) -{ - return CodeSigning::MatchOperation(::n2h((uint32_t) op)); -} - - -} // CodeSigning -} // Security - -#endif //_H_REQUIREMENT diff --git a/OSX/include/security_codesigning/resources.cpp b/OSX/include/security_codesigning/resources.cpp deleted file mode 100644 index 5695800e..00000000 --- a/OSX/include/security_codesigning/resources.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// resource directory construction and verification -// -#include "resources.h" -#include "csutilities.h" -#include -#include -#include -#include -#include - -// These are pretty nasty, but are a quick safe fix -// to pass information down to the gatekeeper collection tool -extern "C" { - int GKBIS_DS_Store_Present; - int GKBIS_Dot_underbar_Present; - int GKBIS_Num_localizations; - int GKBIS_Num_files; - int GKBIS_Num_dirs; - int GKBIS_Num_symlinks; -} - -namespace Security { -namespace CodeSigning { - - -static string removeTrailingSlash(string path) -{ - if (path.substr(path.length()-2, 2) == "/.") - return path.substr(0, path.length()-2); - else if (path.substr(path.length()-1, 1) == "/") - return path.substr(0, path.length()-1); - else - return path; -} - -// -// Construction and maintainance -// -ResourceBuilder::ResourceBuilder(const std::string &root, const std::string &relBase, - CFDictionaryRef rulesDict, CodeDirectory::HashAlgorithm hashType, bool strict, const MacOSErrorSet& toleratedErrors) - : mHashType(hashType), - mCheckUnreadable(strict && toleratedErrors.find(errSecCSSignatureNotVerifiable) == toleratedErrors.end()), - mCheckUnknownType(strict && toleratedErrors.find(errSecCSResourceNotSupported) == toleratedErrors.end()) -{ - assert(!root.empty()); - char realroot[PATH_MAX]; - if (realpath(root.c_str(), realroot) == NULL) - UnixError::throwMe(); - mRoot = realroot; - if (realpath(removeTrailingSlash(relBase).c_str(), realroot) == NULL) - UnixError::throwMe(); - mRelBase = realroot; - if (mRoot != mRelBase && mRelBase != mRoot + "/Contents") - MacOSError::throwMe(errSecCSInternalError); - const char * paths[2] = { mRoot.c_str(), NULL }; - mFTS = fts_open((char * const *)paths, FTS_PHYSICAL | FTS_COMFOLLOW | FTS_NOCHDIR, NULL); - if (!mFTS) - UnixError::throwMe(); - mRawRules = rulesDict; - CFDictionary rules(rulesDict, errSecCSResourceRulesInvalid); - rules.apply(this, &ResourceBuilder::addRule); -} - -ResourceBuilder::~ResourceBuilder() -{ - for (Rules::iterator it = mRules.begin(); it != mRules.end(); ++it) - delete *it; - fts_close(mFTS); // do not check error - it's not worth aborting over (double fault etc.) -} - - -// -// Parse and add one matching rule -// -void ResourceBuilder::addRule(CFTypeRef key, CFTypeRef value) -{ - string pattern = cfString(key, errSecCSResourceRulesInvalid); - unsigned weight = 1; - uint32_t flags = 0; - if (CFGetTypeID(value) == CFBooleanGetTypeID()) { - if (value == kCFBooleanFalse) - flags |= omitted; - } else { - CFDictionary rule(value, errSecCSResourceRulesInvalid); - if (CFNumberRef weightRef = rule.get("weight")) - weight = cfNumber(weightRef); - if (CFBooleanRef omitRef = rule.get("omit")) - if (omitRef == kCFBooleanTrue) - flags |= omitted; - if (CFBooleanRef optRef = rule.get("optional")) - if (optRef == kCFBooleanTrue) - flags |= optional; - if (CFBooleanRef nestRef = rule.get("nested")) - if (nestRef == kCFBooleanTrue) - flags |= nested; - } - addRule(new Rule(pattern, weight, flags)); -} - -static bool findStringEndingNoCase(const char *path, const char * end) -{ - size_t len_path = strlen(path); - size_t len_end = strlen(end); - - if (len_path >= len_end) { - return strcasecmp(path + (len_path - len_end), end) == 0; - } else - return false; -} - -// -// Locate the next non-ignored file, look up its rule, and return it. -// Returns NULL when we're out of files. -// -void ResourceBuilder::scan(Scanner next) -{ - bool first = true; - - while (FTSENT *ent = fts_read(mFTS)) { - static const char ds_store[] = ".DS_Store"; - const char *relpath = ent->fts_path + mRoot.size() + 1; // skip prefix + "/" - std::string rp; - if (mRelBase != mRoot) { - assert(mRelBase == mRoot + "/Contents"); - rp = "../" + string(relpath); - if (rp.substr(0, 12) == "../Contents/") - rp = rp.substr(12); - relpath = rp.c_str(); - } - switch (ent->fts_info) { - case FTS_F: - secdebug("rdirenum", "file %s", ent->fts_path); - GKBIS_Num_files++; - - // These are checks for the gatekeeper collection - static const char underbar[] = "._"; - if (strncasecmp(ent->fts_name, underbar, strlen(underbar)) == 0) - GKBIS_Dot_underbar_Present++; - - if (strcasecmp(ent->fts_name, ds_store) == 0) - GKBIS_DS_Store_Present++; - - if (Rule *rule = findRule(relpath)) - if (!(rule->flags & (omitted | exclusion))) - next(ent, rule->flags, string(relpath), rule); - break; - case FTS_SL: - // symlinks cannot ever be nested code, so quietly convert to resource file - secdebug("rdirenum", "symlink %s", ent->fts_path); - GKBIS_Num_symlinks++; - - if (strcasecmp(ent->fts_name, ds_store) == 0) - MacOSError::throwMe(errSecCSDSStoreSymlink); - - if (Rule *rule = findRule(relpath)) - if (!(rule->flags & (omitted | exclusion))) - next(ent, rule->flags & ~nested, string(relpath), rule); - break; - case FTS_D: - secdebug("rdirenum", "entering %s", ent->fts_path); - GKBIS_Num_dirs++; - - if (!first) { // skip root directory (relpath invalid) - if (Rule *rule = findRule(relpath)) { - if (rule->flags & nested) { - if (strchr(ent->fts_name, '.')) { // nested, has extension -> treat as nested bundle - next(ent, rule->flags, string(relpath), rule); - fts_set(mFTS, ent, FTS_SKIP); - } - } else if (rule->flags & exclusion) { // exclude the whole directory - fts_set(mFTS, ent, FTS_SKIP); - } - // else treat as normal directory and descend into it - } - } - // Report the number of localizations - if (findStringEndingNoCase(ent->fts_name, ".lproj")) - GKBIS_Num_localizations++; - first = false; - - break; - case FTS_DP: - secdebug("rdirenum", "leaving %s", ent->fts_path); - break; - case FTS_DNR: - secdebug("rdirenum", "cannot read directory %s", ent->fts_path); - if (mCheckUnreadable) - MacOSError::throwMe(errSecCSSignatureNotVerifiable); - break; - default: - secdebug("rdirenum", "type %d (errno %d): %s", - ent->fts_info, ent->fts_errno, ent->fts_path); - if (mCheckUnknownType) - MacOSError::throwMe(errSecCSResourceNotSupported); - break; - } - } -} - - -// -// Check a single for for inclusion in the resource envelope -// -bool ResourceBuilder::includes(string path) const -{ - // process first-directory exclusions - size_t firstslash = path.find('/'); - if (firstslash != string::npos) - if (Rule *rule = findRule(path.substr(0, firstslash))) - if (rule->flags & exclusion) - return rule->flags & softTarget; - - // process full match - if (Rule *rule = findRule(path)) - return !(rule->flags & (omitted | exclusion)) || (rule->flags & softTarget); - else - return false; -} - - -// -// Find the best-matching resource rule for an alleged resource file. -// Returns NULL if no rule matches, or an exclusion rule applies. -// -ResourceBuilder::Rule *ResourceBuilder::findRule(string path) const -{ - Rule *bestRule = NULL; - secdebug("rscan", "test %s", path.c_str()); - for (Rules::const_iterator it = mRules.begin(); it != mRules.end(); ++it) { - Rule *rule = *it; - secdebug("rscan", "try %s", rule->source.c_str()); - if (rule->match(path.c_str())) { - secdebug("rscan", "match"); - if (rule->flags & exclusion) { - secdebug("rscan", "excluded"); - return rule; - } - if (!bestRule || rule->weight > bestRule->weight) - bestRule = rule; - } - } - secdebug("rscan", "choosing %s (%d,0x%x)", - bestRule ? bestRule->source.c_str() : "NOTHING", - bestRule ? bestRule->weight : 0, - bestRule ? bestRule->flags : 0); - return bestRule; -} - - -// -// Hash a file and return a CFDataRef with the hash -// -CFDataRef ResourceBuilder::hashFile(const char *path) const -{ - UnixPlusPlus::AutoFileDesc fd(path); - fd.fcntl(F_NOCACHE, true); // turn off page caching (one-pass) - MakeHash hasher(this); - hashFileData(fd, hasher.get()); - Hashing::Byte digest[hasher->digestLength()]; - hasher->finish(digest); - return CFDataCreate(NULL, digest, sizeof(digest)); -} - - -// -// Regex matching objects -// -ResourceBuilder::Rule::Rule(const std::string &pattern, unsigned w, uint32_t f) - : weight(w), flags(f), source(pattern) -{ - if (::regcomp(this, pattern.c_str(), REG_EXTENDED | REG_NOSUB)) //@@@ REG_ICASE? - MacOSError::throwMe(errSecCSResourceRulesInvalid); - secdebug("csresource", "%p rule %s added (weight %d, flags 0x%x)", - this, pattern.c_str(), w, f); -} - -ResourceBuilder::Rule::~Rule() -{ - ::regfree(this); -} - -bool ResourceBuilder::Rule::match(const char *s) const -{ - switch (::regexec(this, s, 0, NULL, 0)) { - case 0: - return true; - case REG_NOMATCH: - return false; - default: - MacOSError::throwMe(errSecCSResourceRulesInvalid); - } -} - - -std::string ResourceBuilder::escapeRE(const std::string &s) -{ - string r; - for (string::const_iterator it = s.begin(); it != s.end(); ++it) { - char c = *it; - if (strchr("\\[]{}().+*?", c)) - r.push_back('\\'); - r.push_back(c); - } - return r; -} - - -// -// Resource Seals -// -ResourceSeal::ResourceSeal(CFTypeRef it) - : mDict(NULL), mHash(NULL), mRequirement(NULL), mLink(NULL), mFlags(0) -{ - if (it == NULL) - MacOSError::throwMe(errSecCSResourcesInvalid); - if (CFGetTypeID(it) == CFDataGetTypeID()) { - mHash = CFDataRef(it); - } else { - int optional = 0; - mDict = CFDictionaryRef(it); - bool err; - if (CFDictionaryGetValue(mDict, CFSTR("requirement"))) - err = !cfscan(mDict, "{requirement=%SO,?optional=%B}", &mRequirement, &optional); - else if (CFDictionaryGetValue(mDict, CFSTR("symlink"))) - err = !cfscan(mDict, "{symlink=%SO,?optional=%B}", &mLink, &optional); - else - err = !cfscan(mDict, "{hash=%XO,?optional=%B}", &mHash, &optional); - if (err) - MacOSError::throwMe(errSecCSResourcesInvalid); - if (optional) - mFlags |= ResourceBuilder::optional; - if (mRequirement) - mFlags |= ResourceBuilder::nested; - } -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/resources.h b/OSX/include/security_codesigning/resources.h deleted file mode 100644 index 4bdcc7e6..00000000 --- a/OSX/include/security_codesigning/resources.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// resource directory construction and verification -// -#ifndef _H_RSIGN -#define _H_RSIGN - -#include "codedirectory.h" -#include -#include -#include -#include "regex.h" -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// The builder of ResourceDirectories. -// -// Note that this *is* a ResourceEnumerator, which can enumerate -// its source directory once (only). -// -class ResourceBuilder { - NOCOPY(ResourceBuilder) -public: - ResourceBuilder(const std::string &root, const std::string &relBase, - CFDictionaryRef rulesDict, CodeDirectory::HashAlgorithm hashType, bool strict, const MacOSErrorSet& toleratedErrors); - ~ResourceBuilder(); - - std::string root() const { return mRoot; } - - enum { - optional = 0x01, // may be absent at runtime - omitted = 0x02, // do not seal even if present - nested = 0x04, // nested code (recursively signed) - exclusion = 0x10, // overriding exclusion (stop looking) - softTarget = 0x20, // valid symlink target even though omitted/excluded - }; - - typedef unsigned int Weight; - -public: - class Rule : private regex_t { - public: - Rule(const std::string &pattern, Weight weight, uint32_t flags); - ~Rule(); - - bool match(const char *s) const; - - const Weight weight; - const uint32_t flags; - std::string source; - }; - void addRule(Rule *rule) { mRules.push_back(rule); } - void addExclusion(const std::string &pattern, uint32_t flags = 0) { mRules.insert(mRules.begin(), new Rule(pattern, 0, exclusion | flags)); } - - static std::string escapeRE(const std::string &s); - - typedef void (^Scanner)(FTSENT *ent, uint32_t flags, const std::string relpath, Rule *rule); - void scan(Scanner next); - bool includes(string path) const; - Rule *findRule(string path) const; - - DynamicHash *getHash() const { return CodeDirectory::hashFor(this->mHashType); } - CFDataRef hashFile(const char *path) const; - - CFDictionaryRef rules() const { return mRawRules; } - -protected: - void addRule(CFTypeRef key, CFTypeRef value); - -private: - std::string mRoot, mRelBase; - FTS *mFTS; - CFCopyRef mRawRules; - typedef std::vector Rules; - Rules mRules; - CodeDirectory::HashAlgorithm mHashType; - bool mCheckUnreadable; - bool mCheckUnknownType; -}; - - -// -// The "seal" on a single resource. -// -class ResourceSeal { -public: - ResourceSeal(CFTypeRef ref); - -public: - operator bool () const { return mHash; } - bool operator ! () const { return mHash == NULL; } - - const Hashing::Byte *hash() const { return CFDataGetBytePtr(mHash); } - bool nested() const { return mFlags & ResourceBuilder::nested; } - bool optional() const { return mFlags & ResourceBuilder::optional; } - CFDictionaryRef dict() const { return mDict; } - CFStringRef requirement() const { return mRequirement; } - CFStringRef link() const { return mLink; } - -private: - CFDictionaryRef mDict; - CFDataRef mHash; - CFStringRef mRequirement; - CFStringRef mLink; - uint32_t mFlags; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_RSIGN diff --git a/OSX/include/security_codesigning/security_codesigning.d b/OSX/include/security_codesigning/security_codesigning.d deleted file mode 100644 index acbd15f1..00000000 --- a/OSX/include/security_codesigning/security_codesigning.d +++ /dev/null @@ -1,98 +0,0 @@ -/* - * DTrace static providers at the Code Signing layer - */ -#define int32_t int -#define uint32_t unsigned -#define mach_port_t uint32_t -#define bool uint8_t -#define off_t uint64_t - - -/* - * Basic semantic events of the code signing subsystem - */ -provider codesign { - probe diskrep__create__macho(void *me, const char *path, const void *ctx); - probe diskrep__create__bundle__path(void *me, const char *path, void *ctx, void *exec); - probe diskrep__create__bundle__ref(void *me, void *cfbundle, void *ctx, void *exec); - probe diskrep__create__file(void *me, const char *path); - probe diskrep__create__cfm(void *me, const char *path); - probe diskrep__create__slc(void *me, const char *path); - probe diskrep__create__detached(void *me, void *orig, const char *source, void *glob); - probe diskrep__create__kernel(void *me); - probe diskrep__destroy(void *me); - - probe static__create(void *me, void *host); - probe dynamic__create(void *me, void *rep); - - probe static__cdhash(void *me, const void *cdhash, uint32_t length); - probe static__attach__explicit(void *me, void *rep); - probe static__attach__system(void *me, void *rep); - - probe eval__dynamic__start(void *me, const char *path); - probe eval__dynamic__end(void *me); - probe eval__dynamic__root(void *me); - - probe eval__static__start(void *me, const char *path); - probe eval__static__end(void *me); - probe eval__static__reset(void *me); - - probe eval__static__executable__start(void *me, const char *path, uint32_t pages); - probe eval__static__executable__fail(void *me, uint32_t badPage); - probe eval__static__executable__end(void *me); - probe eval__static__resources__start(void *me, const char *path, int count); - probe eval__static__resources__end(void *me); - - probe eval__static__directory(void *me); - probe eval__static__intreq__start(void *me, uint32_t reqType, void *target, int32_t nullError); - probe eval__static__intreq__end(void *me); - - probe eval__static__signature__start(void *me, const char *path); - probe eval__static__signature__adhoc(void *me); - probe eval__static__signature__result(void *me, uint32_t result, uint32_t chainLength); - probe eval__static__signature__expired(void *me); - probe eval__static__signature__end(void *me); - - probe eval__reqint__start(const void *reqdata, uint32_t reqlength); - probe eval__reqint__end(const void *reqdata, uint32_t result); - probe eval__reqint__op(uint32_t opcode, uint32_t offset); - probe eval__reqint__unknown_false(uint32_t opcode); - probe eval__reqint__unknown_skipped(uint32_t opcode); - probe eval__reqint__fragment__load(const char *type, const char *name, const void *req); - probe eval__reqint__fragment__hit(const char *type, const char *name); - - probe guest__hostingport(void *host, mach_port_t hostingPort); - probe guest__locate__generic(void *host, uint32_t *guestPath, uint32_t guestPathLength, mach_port_t subport); - probe guest__identify__process(void *guest, uint32_t guestPid, void *code); - probe guest__cdhash__process(void *code, const void *cdhash, uint32_t length); - probe guest__identify__generic(void *guest, uint32_t guestRef, void *code); - probe guest__cdhash__generic(void *code, const void *cdhash, uint32_t length); - - probe allocate__validate(const char *path, uint32_t pid); - probe allocate__arch(const char *arch, uint32_t size); - probe allocate__archn(uint32_t cputype, uint32_t cpusubtype, uint32_t size); - probe allocate__write(const char *arch, off_t offset, uint32_t length, uint32_t available); - - probe sign__dep__macho(void *me, const char *name, const void *requirement); - probe sign__dep__interp(void *me, const char *name, const void *requirement); - - probe load__antlr(); -}; - - -provider syspolicy { - probe assess_api(const char *path, int type, uint64_t flags); - - probe assess__outcome__accept(const char *path, int type, const char *label, const void *cdhash); - probe assess__outcome__deny(const char *path, int type, const char *label, const void *cdhash); - probe assess__outcome__default(const char *path, int type, const char *label, const void *cdhash); - probe assess__outcome__unsigned(const char *path, int type); - probe assess__outcome__broken(const char *path, int type, bool exception_made); - - probe recorder_mode(const char *path, int type, const char *label, const void *cdhash, int flags); - probe recorder_mode_adhoc_path(const char *path, int type, const char *sig_path); // path containing adhoc signature recorded - - probe assess_cache_hit(); - probe assess_local(); - probe assess_remote(); -}; diff --git a/OSX/include/security_codesigning/security_codesigning.exp b/OSX/include/security_codesigning/security_codesigning.exp deleted file mode 100644 index 7a907d31..00000000 --- a/OSX/include/security_codesigning/security_codesigning.exp +++ /dev/null @@ -1,176 +0,0 @@ -# -# Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. -# -# @APPLE_LICENSE_HEADER_START@ -# -# This file contains Original Code and/or Modifications of Original Code -# as defined in and that are subject to the Apple Public Source License -# Version 2.0 (the 'License'). You may not use this file except in -# compliance with the License. Please obtain a copy of the License at -# http://www.opensource.apple.com/apsl/ and read it before using this -# file. -# -# The Original Code and all software distributed under the License are -# distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER -# EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, -# INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. -# Please see the License for the specific language governing rights and -# limitations under the License. -# -# @APPLE_LICENSE_HEADER_END@ -# -_SecCodeGetTypeID -_SecCodeCopySelf -_SecCodeCopyInternalRequirement -_SecCodeGetStatus -_SecCodeSetStatus -_SecCodeCopyStaticCode -_SecCodeCopyHost -_SecCodeCopyGuestWithAttributes -_SecCodeCreateWithPID -_SecCodeCheckValidity -_SecCodeCheckValidityWithErrors -_SecCodeCopyPath -_SecCodeCopyDesignatedRequirement -_SecCodeCopySigningInformation -_SecCodeMapMemory -_SecCodeSetDetachedSignature -_kSecCodeAttributeArchitecture -_kSecCodeAttributeBundleVersion -_kSecCodeAttributeSubarchitecture -_kSecCodeAttributeUniversalFileOffset -_SecStaticCodeGetTypeID -_SecStaticCodeCreateWithPath -_SecStaticCodeCreateWithPathAndAttributes -_SecStaticCodeCheckValidity -_SecStaticCodeCheckValidityWithErrors -_SecRequirementGetTypeID -_SecRequirementCreateWithData -_SecRequirementCreateWithResource -_SecRequirementCreateWithString -_SecRequirementCreateWithStringAndErrors -_SecRequirementCreateGroup -_SecRequirementCopyData -_SecRequirementCopyString -_SecRequirementEvaluate -_SecRequirementsCreateFromRequirements -_SecRequirementsCopyRequirements -_SecRequirementsCreateWithString -_SecRequirementsCopyString -_SecCodeSignerGetTypeID -_SecCodeSignerCreate -_SecCodeSignerAddSignature -_SecCodeSignerAddSignatureWithErrors -_SecHostCreateGuest -_SecHostRemoveGuest -_SecHostSetGuestStatus -_SecHostSelectGuest -_SecHostSelectedGuest -_SecHostSetHostingPort -_kSecCodeDirectoryFlagTable -_kSecCodeSignerApplicationData -_kSecCodeSignerDetached -_kSecCodeSignerDigestAlgorithm -_kSecCodeSignerDryRun -_kSecCodeSignerEntitlements -_kSecCodeSignerFlags -_kSecCodeSignerIdentifier -_kSecCodeSignerIdentifierPrefix -_kSecCodeSignerIdentity -_kSecCodeSignerTimestampAuthentication -_kSecCodeSignerRequireTimestamp -_kSecCodeSignerTimestampServer -_kSecCodeSignerTimestampOmitCertificates -_kSecCodeSignerPageSize -_kSecCodeSignerRequirements -_kSecCodeSignerResourceRules -_kSecCodeSignerSDKRoot -_kSecCodeSignerSigningTime -_kSecCodeInfoCertificates -_kSecCodeInfoChangedFiles -_kSecCodeInfoCMS -_kSecCodeInfoTime -_kSecCodeInfoDesignatedRequirement -_kSecCodeInfoEntitlements -_kSecCodeInfoEntitlementsDict -_kSecCodeInfoFlags -_kSecCodeInfoFormat -_kSecCodeInfoDigestAlgorithm -_kSecCodeInfoIdentifier -_kSecCodeInfoImplicitDesignatedRequirement -_kSecCodeInfoMainExecutable -_kSecCodeInfoPList -_kSecCodeInfoRequirements -_kSecCodeInfoRequirementData -_kSecCodeInfoSource -_kSecCodeInfoStatus -_kSecCodeInfoTrust -_kSecCodeInfoUnique -_kSecCodeInfoCodeDirectory -_kSecCodeInfoCodeOffset -_kSecCodeInfoResourceDirectory -_kSecGuestAttributeCanonical -_kSecGuestAttributeHash -_kSecGuestAttributeMachPort -_kSecGuestAttributePid -_kSecRequirementKeyInfoPlist -_kSecRequirementKeyEntitlements -_kSecCFErrorArchitecture -_kSecCFErrorPattern -_kSecCFErrorResourceSeal -_kSecCFErrorResourceAdded -_kSecCFErrorResourceAltered -_kSecCFErrorResourceMissing -_kSecCFErrorInfoPlist -_kSecCFErrorGuestAttributes -_kSecCFErrorRequirementSyntax -_kSecCFErrorPath - -# Entitlements -_SecTaskGetTypeID -_SecTaskCreateWithAuditToken -_SecTaskCreateFromSelf -_SecTaskCopyValueForEntitlement -_SecTaskCopyValuesForEntitlements -_SecTaskEntitlementsValidated -_SecTaskValidateForRequirement - -# Assessments -_SecAssessmentCreate -_SecAssessmentCopyResult -_SecAssessmentUpdate -_SecAssessmentControl -_kSecAssessmentContextKeyOperation -_kSecAssessmentOperationTypeExecute -_kSecAssessmentOperationTypeInstall -_kSecAssessmentOperationTypeOpenDocument -_kSecAssessmentContextKeyUpdate -_kSecAssessmentUpdateOperationAddFile -_kSecAssessmentUpdateOperationRemoveFile -_kSecAssessmentUpdateOperationAdd -_kSecAssessmentUpdateOperationRemove -_kSecAssessmentUpdateKeyAllow -_kSecAssessmentUpdateKeyExpires -_kSecAssessmentUpdateKeyLabel -_kSecAssessmentUpdateKeyPriority -_kSecAssessmentUpdateKeyRemarks -_kSecAssessmentAssessmentAuthority -_kSecAssessmentAssessmentAuthorityRow -_kSecAssessmentAssessmentFromCache -_kSecAssessmentAssessmentOriginator -_kSecAssessmentAssessmentAuthorityOverride -_kSecAssessmentAssessmentOriginalVerdict -_kSecAssessmentAssessmentSource -_kSecAssessmentAssessmentVerdict -_kSecAssessmentAssessmentWeakSignature -_kSecAssessmentAssessmentCodeSigningError - -# gatekeeper logging - -_GKBIS_DS_Store_Present -_GKBIS_Dot_underbar_Present -_GKBIS_Num_localizations -_GKBIS_Num_files -_GKBIS_Num_dirs -_GKBIS_Num_symlinks diff --git a/OSX/include/security_codesigning/sigblob.cpp b/OSX/include/security_codesigning/sigblob.cpp deleted file mode 100644 index 619986a1..00000000 --- a/OSX/include/security_codesigning/sigblob.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2006,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// sigblob - signature (Super)Blob types -// -#include "sigblob.h" -#include "CSCommon.h" - - -namespace Security { -namespace CodeSigning { - - -CFDataRef EmbeddedSignatureBlob::component(CodeDirectory::SpecialSlot slot) const -{ - if (const BlobCore *blob = this->find(slot)) { - if (CodeDirectory::slotAttributes(slot) & cdComponentIsBlob) { - return makeCFData(*blob); // is a native Blob - } else if (const BlobWrapper *wrap = BlobWrapper::specific(blob)) { - return makeCFData(*wrap); - } else { - MacOSError::throwMe(errSecCSSignatureInvalid); - } - } - return NULL; -} - - -void EmbeddedSignatureBlob::Maker::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - if (CodeDirectory::slotAttributes(slot) & cdComponentIsBlob) - add(slot, reinterpret_cast(CFDataGetBytePtr(data))->clone()); - else - add(slot, BlobWrapper::alloc(CFDataGetBytePtr(data), CFDataGetLength(data))); -} - - -CFDictionaryRef EntitlementBlob::entitlements() const -{ - return makeCFDictionaryFrom(this->at(sizeof(EntitlementBlob)), - this->length() - sizeof(EntitlementBlob)); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/sigblob.h b/OSX/include/security_codesigning/sigblob.h deleted file mode 100644 index 50d8d21d..00000000 --- a/OSX/include/security_codesigning/sigblob.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2006,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// sigblob - signature (Super)Blob types -// -#ifndef _H_SIGBLOB -#define _H_SIGBLOB - -#include "codedirectory.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// An EmbeddedSignatureBlob is a SuperBlob indexed by component slot number. -// This is what we embed in Mach-O images. It is also what we use for detached -// signatures for non-Mach-O binaries. -// -class EmbeddedSignatureBlob : public SuperBlobCore { - typedef SuperBlobCore _Core; -public: - CFDataRef component(CodeDirectory::SpecialSlot slot) const; - - class Maker : public _Core::Maker { - public: - void component(CodeDirectory::SpecialSlot type, CFDataRef data); - }; -}; - - -// -// A DetachedSignatureBlob collects multiple architectures' worth of -// EmbeddedSignatureBlobs into one, well, Super-SuperBlob. -// This is what we use for Mach-O detached signatures. -// -typedef SuperBlob<0xfade0cc1> DetachedSignatureBlob; // indexed by main architecture - - -// -// The linkers produces a superblob of dependency records from its dylib inputs -// -typedef SuperBlob<0xfade0c05> LibraryDependencyBlob; // indexed sequentially from 0 - - -// -// An entitlement blob is used for embedding entitlement configuration data -// -class EntitlementBlob : public Blob { -public: - CFDictionaryRef entitlements() const; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_SIGBLOB diff --git a/OSX/include/security_codesigning/signer.cpp b/OSX/include/security_codesigning/signer.cpp deleted file mode 100644 index daa2dac7..00000000 --- a/OSX/include/security_codesigning/signer.cpp +++ /dev/null @@ -1,670 +0,0 @@ -/* - * Copyright (c) 2006-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// signer - Signing operation supervisor and controller -// -#include "signer.h" -#include "resources.h" -#include "signerutils.h" -#include "SecCodeSigner.h" -#include -#include -#include -#include -#include -#include "resources.h" -#include "machorep.h" -#include "reqparser.h" -#include "reqdumper.h" -#include "csutilities.h" -#include -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// Sign some code. -// -void SecCodeSigner::Signer::sign(SecCSFlags flags) -{ - rep = code->diskRep()->base(); - this->prepare(flags); - - PreSigningContext context(*this); - - /* If an explicit teamID was passed in it must be - the same as what came from the cert */ - std::string teamIDFromCert = state.getTeamIDFromSigner(context.certs); - - if (state.mPreserveMetadata & kSecCodeSignerPreserveTeamIdentifier) { - /* If preserving the team identifier, teamID is set previously when the - code object is still available */ - if (!teamIDFromCert.empty() && teamID != teamIDFromCert) - MacOSError::throwMe(errSecCSInvalidFlags); - } else { - if (teamIDFromCert.empty()) { - /* state.mTeamID is an explicitly passed teamID */ - teamID = state.mTeamID; - } else if (state.mTeamID.empty() || (state.mTeamID == teamIDFromCert)) { - /* If there was no explicit team ID set, or the explicit team ID matches - what is in the cert, use the team ID from the certificate */ - teamID = teamIDFromCert; - } else { - /* The caller passed in an explicit team ID that does not match what is - in the signing cert, which is an invalid usage */ - MacOSError::throwMe(errSecCSInvalidFlags); - } - } - - if (Universal *fat = state.mNoMachO ? NULL : rep->mainExecutableImage()) { - signMachO(fat, context); - } else { - signArchitectureAgnostic(context); - } -} - - -// -// Remove any existing code signature from code -// -void SecCodeSigner::Signer::remove(SecCSFlags flags) -{ - // can't remove a detached signature - if (state.mDetached) - MacOSError::throwMe(errSecCSNotSupported); - - rep = code->diskRep(); - if (Universal *fat = state.mNoMachO ? NULL : rep->mainExecutableImage()) { - // architecture-sensitive removal - MachOEditor editor(rep->writer(), *fat, kSecCodeSignatureNoHash, rep->mainExecutablePath()); - editor.allocate(); // create copy - editor.commit(); // commit change - } else { - // architecture-agnostic removal - RefPointer writer = rep->writer(); - writer->remove(); - writer->flush(); - } -} - - -// -// Contemplate the object-to-be-signed and set up the Signer state accordingly. -// -void SecCodeSigner::Signer::prepare(SecCSFlags flags) -{ - // make sure the rep passes strict validation - if (strict) - rep->strictValidate(NULL, MacOSErrorSet()); - - // initialize progress/cancellation state - code->prepareProgress(0); // totally fake workload - we don't know how many files we'll encounter - - // get the Info.plist out of the rep for some creative defaulting - CFRef infoDict; - if (CFRef infoData = rep->component(cdInfoSlot)) - infoDict.take(makeCFDictionaryFrom(infoData)); - - uint32_t inherit = code->isSigned() ? state.mPreserveMetadata : 0; - - // work out the canonical identifier - identifier = state.mIdentifier; - if (identifier.empty() && (inherit & kSecCodeSignerPreserveIdentifier)) - identifier = code->identifier(); - if (identifier.empty()) { - identifier = rep->recommendedIdentifier(state); - if (identifier.find('.') == string::npos) - identifier = state.mIdentifierPrefix + identifier; - if (identifier.find('.') == string::npos && state.isAdhoc()) - identifier = identifier + "-" + uniqueName(); - secdebug("signer", "using default identifier=%s", identifier.c_str()); - } else - secdebug("signer", "using explicit identifier=%s", identifier.c_str()); - - teamID = state.mTeamID; - if (teamID.empty() && (inherit & kSecCodeSignerPreserveTeamIdentifier)) { - const char *c_id = code->teamID(); - if (c_id) - teamID = c_id; - } - - entitlements = state.mEntitlementData; - if (!entitlements && (inherit & kSecCodeSignerPreserveEntitlements)) - entitlements = code->component(cdEntitlementSlot); - - // work out the CodeDirectory flags word - bool haveCdFlags = false; - if (!haveCdFlags && state.mCdFlagsGiven) { - cdFlags = state.mCdFlags; - secdebug("signer", "using explicit cdFlags=0x%x", cdFlags); - haveCdFlags = true; - } - if (!haveCdFlags) { - cdFlags = 0; - if (infoDict) - if (CFTypeRef csflags = CFDictionaryGetValue(infoDict, CFSTR("CSFlags"))) { - if (CFGetTypeID(csflags) == CFNumberGetTypeID()) { - cdFlags = cfNumber(CFNumberRef(csflags)); - secdebug("signer", "using numeric cdFlags=0x%x from Info.plist", cdFlags); - } else if (CFGetTypeID(csflags) == CFStringGetTypeID()) { - cdFlags = cdTextFlags(cfString(CFStringRef(csflags))); - secdebug("signer", "using text cdFlags=0x%x from Info.plist", cdFlags); - } else - MacOSError::throwMe(errSecCSBadDictionaryFormat); - haveCdFlags = true; - } - } - if (!haveCdFlags && (inherit & kSecCodeSignerPreserveFlags)) { - cdFlags = code->codeDirectory(false)->flags & ~kSecCodeSignatureAdhoc; - secdebug("signer", "using inherited cdFlags=0x%x", cdFlags); - haveCdFlags = true; - } - if (!haveCdFlags) - cdFlags = 0; - if (state.mSigner == SecIdentityRef(kCFNull)) // ad-hoc signing requested... - cdFlags |= kSecCodeSignatureAdhoc; // ... so note that - - // prepare the internal requirements input - if (state.mRequirements) { - if (CFGetTypeID(state.mRequirements) == CFDataGetTypeID()) { // binary form - const Requirements *rp = (const Requirements *)CFDataGetBytePtr(state.mRequirements.as()); - if (!rp->validateBlob()) - MacOSError::throwMe(errSecCSReqInvalid); - requirements = rp->clone(); - } else if (CFGetTypeID(state.mRequirements) == CFStringGetTypeID()) { // text form - CFRef reqText = CFStringCreateMutableCopy(NULL, 0, state.mRequirements.as()); - // substitute $ variable tokens - CFRange range = { 0, CFStringGetLength(reqText) }; - CFStringFindAndReplace(reqText, CFSTR("$self.identifier"), CFTempString(identifier), range, 0); - requirements = parseRequirements(cfString(reqText)); - } else - MacOSError::throwMe(errSecCSInvalidObjectRef); - } else if (inherit & kSecCodeSignerPreserveRequirements) - if (const Requirements *rp = code->internalRequirements()) - requirements = rp->clone(); - - // prepare the resource directory, if any - string rpath = rep->resourcesRootPath(); - if (!rpath.empty()) { - // explicitly given resource rules always win - CFCopyRef resourceRules = state.mResourceRules; - - // inherited rules come next (overriding embedded ones!) - if (!resourceRules && (inherit & kSecCodeSignerPreserveResourceRules)) - if (CFDictionaryRef oldRules = code->resourceDictionary(false)) - resourceRules = oldRules; - - // embedded resource rules come next - if (!resourceRules && infoDict) - if (CFTypeRef spec = CFDictionaryGetValue(infoDict, _kCFBundleResourceSpecificationKey)) { - if (CFGetTypeID(spec) == CFStringGetTypeID()) - if (CFRef data = cfLoadFile(rpath + "/" + cfString(CFStringRef(spec)))) - if (CFDictionaryRef dict = makeCFDictionaryFrom(data)) - resourceRules.take(dict); - if (!resourceRules) // embedded rules present but unacceptable - MacOSError::throwMe(errSecCSResourceRulesInvalid); - } - - // if we got one from anywhere (but the defaults), sanity-check it - if (resourceRules) { - CFTypeRef rules = CFDictionaryGetValue(resourceRules, CFSTR("rules")); - if (!rules || CFGetTypeID(rules) != CFDictionaryGetTypeID()) - MacOSError::throwMe(errSecCSResourceRulesInvalid); - } - - // finally, ask the DiskRep for its default - if (!resourceRules) - resourceRules.take(rep->defaultResourceRules(state)); - - // resource root can optionally be the canonical bundle path, - // but sealed resource paths are always relative to rpath - string root = rpath; - if (state.signingFlags() & kSecCSSignBundleRoot) - root = cfStringRelease(rep->copyCanonicalPath()); - - // build the resource directory - buildResources(root, rpath, resourceRules); - } - - // screen and set the signing time - CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); - if (state.mSigningTime == CFDateRef(kCFNull)) { - signingTime = 0; // no time at all - } else if (!state.mSigningTime) { - signingTime = now; // default - } else { - CFAbsoluteTime time = CFDateGetAbsoluteTime(state.mSigningTime); - if (time > now) // not allowed to post-date a signature - MacOSError::throwMe(errSecCSBadDictionaryFormat); - signingTime = time; - } - - pagesize = state.mPageSize ? cfNumber(state.mPageSize) : rep->pageSize(state); - - // Timestamping setup - CFRef mTSAuth; // identity for client-side authentication to the Timestamp server -} - - -// -// Collect the resource seal for a program. -// This includes both sealed resources and information about nested code. -// -void SecCodeSigner::Signer::buildResources(std::string root, std::string relBase, CFDictionaryRef rulesDict) -{ - typedef ResourceBuilder::Rule Rule; - - secdebug("codesign", "start building resource directory"); - __block CFRef result = makeCFMutableDictionary(); - - CFDictionaryRef rules = cfget(rulesDict, "rules"); - assert(rules); - - if (this->state.mLimitedAsync == NULL) { - this->state.mLimitedAsync = - /* rdar://problem/20299541: Async workers (i.e. parallelization) are currently - * turned off, because the paths for signing code are not ready for it yet. */ - // new LimitedAsync(rep->fd().mediumType() == kIOPropertyMediumTypeSolidStateKey); - new LimitedAsync(false); - } - - CFDictionaryRef files2 = NULL; - if (!(state.signingFlags() & kSecCSSignV1)) { - CFCopyRef rules2 = cfget(rulesDict, "rules2"); - if (!rules2) { - // Clone V1 rules and add default nesting rules at weight 0 (overridden by anything in rules). - // V1 rules typically do not cover these places so we'll prevail, but if they do, we defer to them. - rules2 = cfmake("{+%O" - "'^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/' = {nested=#T, weight=0}" // exclude dynamic repositories - "}", rules); - } - - Dispatch::Group group; - Dispatch::Group &groupRef = group; // (into block) - - // build the modern (V2) resource seal - __block CFRef files = makeCFMutableDictionary(); - CFMutableDictionaryRef filesRef = files.get(); // (into block) - ResourceBuilder resourceBuilder(root, relBase, rules2, digestAlgorithm(), strict, MacOSErrorSet()); - ResourceBuilder &resources = resourceBuilder; // (into block) - rep->adjustResources(resources); - - resources.scan(^(FTSENT *ent, uint32_t ruleFlags, const std::string relpath, Rule *rule) { - bool isSymlink = (ent->fts_info == FTS_SL); - const std::string path(ent->fts_path); - const std::string accpath(ent->fts_accpath); - this->state.mLimitedAsync->perform(groupRef, ^{ - CFRef seal; - if (ruleFlags & ResourceBuilder::nested) { - seal.take(signNested(path, relpath)); - } else if (isSymlink) { - char target[PATH_MAX]; - ssize_t len = ::readlink(accpath.c_str(), target, sizeof(target)-1); - if (len < 0) - UnixError::check(-1); - target[len] = '\0'; - seal.take(cfmake("{symlink=%s}", target)); - } else { - seal.take(cfmake("{hash=%O}", - CFRef(resources.hashFile(accpath.c_str())).get())); - } - if (ruleFlags & ResourceBuilder::optional) - CFDictionaryAddValue(seal, CFSTR("optional"), kCFBooleanTrue); - CFTypeRef hash; - StLock _(resourceLock); - if ((hash = CFDictionaryGetValue(seal, CFSTR("hash"))) && CFDictionaryGetCount(seal) == 1) // simple form - CFDictionaryAddValue(filesRef, CFTempString(relpath).get(), hash); - else - CFDictionaryAddValue(filesRef, CFTempString(relpath).get(), seal.get()); - code->reportProgress(); - }); - }); - group.wait(); - CFDictionaryAddValue(result, CFSTR("rules2"), resourceBuilder.rules()); - files2 = files; - CFDictionaryAddValue(result, CFSTR("files2"), files2); - } - - CFDictionaryAddValue(result, CFSTR("rules"), rules); // preserve V1 rules in any case - if (!(state.signingFlags() & kSecCSSignNoV1)) { - // build the legacy (V1) resource seal - __block CFRef files = makeCFMutableDictionary(); - ResourceBuilder resourceBuilder(root, relBase, rules, digestAlgorithm(), strict, MacOSErrorSet()); - ResourceBuilder &resources = resourceBuilder; - rep->adjustResources(resources); // DiskRep-specific adjustments - resources.scan(^(FTSENT *ent, uint32_t ruleFlags, std::string relpath, Rule *rule) { - if (ent->fts_info == FTS_F) { - CFRef hash; - if (files2) // try to get the hash from a previously-made version - if (CFTypeRef seal = CFDictionaryGetValue(files2, CFTempString(relpath))) { - if (CFGetTypeID(seal) == CFDataGetTypeID()) - hash = CFDataRef(seal); - else - hash = CFDataRef(CFDictionaryGetValue(CFDictionaryRef(seal), CFSTR("hash"))); - } - if (!hash) - hash.take(resources.hashFile(ent->fts_accpath)); - if (ruleFlags == 0) { // default case - plain hash - cfadd(files, "{%s=%O}", relpath.c_str(), hash.get()); - secdebug("csresource", "%s added simple (rule %p)", relpath.c_str(), rule); - } else { // more complicated - use a sub-dictionary - cfadd(files, "{%s={hash=%O,optional=%B}}", - relpath.c_str(), hash.get(), ruleFlags & ResourceBuilder::optional); - secdebug("csresource", "%s added complex (rule %p)", relpath.c_str(), rule); - } - } - }); - CFDictionaryAddValue(result, CFSTR("files"), files.get()); - } - - resourceDirectory = result.get(); - resourceDictData.take(makeCFData(resourceDirectory.get())); -} - - -// -// Deal with one piece of nested code -// -CFMutableDictionaryRef SecCodeSigner::Signer::signNested(const std::string &path, const std::string &relpath) -{ - // sign nested code and collect nesting information - try { - SecPointer code = new SecStaticCode(DiskRep::bestGuess(path)); - if (state.signingFlags() & kSecCSSignNestedCode) - this->state.sign(code, state.signingFlags()); - std::string dr = Dumper::dump(code->designatedRequirement()); - return cfmake("{requirement=%s,cdhash=%O}", - Dumper::dump(code->designatedRequirement()).c_str(), - code->cdHash()); - } catch (const CommonError &err) { - CSError::throwMe(err.osStatus(), kSecCFErrorPath, CFTempURL(relpath, false, this->code->resourceBase())); - } -} - - -// -// Sign a Mach-O binary, using liberal dollops of that special Mach-O magic sauce. -// Note that this will deal just fine with non-fat Mach-O binaries, but it will -// treat them as architectural binaries containing (only) one architecture - that -// interpretation is courtesy of the Universal/MachO support classes. -// -void SecCodeSigner::Signer::signMachO(Universal *fat, const Requirement::Context &context) -{ - // Mach-O executable at the core - perform multi-architecture signing - auto_ptr editor(state.mDetached - ? static_cast(new BlobEditor(*fat, *this)) - : new MachOEditor(rep->writer(), *fat, this->digestAlgorithm(), rep->mainExecutablePath())); - assert(editor->count() > 0); - if (!editor->attribute(writerNoGlobal)) // can store architecture-common components - populate(*editor); - - // pass 1: prepare signature blobs and calculate sizes - for (MachOEditor::Iterator it = editor->begin(); it != editor->end(); ++it) { - MachOEditor::Arch &arch = *it->second; - arch.source.reset(fat->architecture(it->first)); - - // library validation is not compatible with i386 - if (arch.architecture.cpuType() == CPU_TYPE_I386) { - if (cdFlags & kSecCodeSignatureLibraryValidation) { - MacOSError::throwMe(errSecCSBadLVArch); - } - } - - arch.ireqs(requirements, rep->defaultRequirements(&arch.architecture, state), context); - if (editor->attribute(writerNoGlobal)) // can't store globally, add per-arch - populate(arch); - populate(arch.cdbuilder, arch, arch.ireqs, - arch.source->offset(), arch.source->signingExtent()); - - // add identification blob (made from this architecture) only if we're making a detached signature - if (state.mDetached) { - CFRef identification = MachORep::identificationFor(arch.source.get()); - arch.add(cdIdentificationSlot, BlobWrapper::alloc( - CFDataGetBytePtr(identification), CFDataGetLength(identification))); - } - - // prepare SuperBlob size estimate - size_t cdSize = arch.cdbuilder.size(CodeDirectory::currentVersion); - arch.blobSize = arch.size(cdSize, state.mCMSSize, 0); - } - - editor->allocate(); - - // pass 2: Finish and generate signatures, and write them - for (MachOEditor::Iterator it = editor->begin(); it != editor->end(); ++it) { - MachOEditor::Arch &arch = *it->second; - editor->reset(arch); - - // finish CodeDirectory (off new binary) and sign it - CodeDirectory *cd = arch.cdbuilder.build(); - CFRef signature = signCodeDirectory(cd); - - // complete the SuperBlob - arch.add(cdCodeDirectorySlot, cd); // takes ownership - arch.add(cdSignatureSlot, BlobWrapper::alloc( - CFDataGetBytePtr(signature), CFDataGetLength(signature))); - if (!state.mDryRun) { - EmbeddedSignatureBlob *blob = arch.make(); - editor->write(arch, blob); // takes ownership of blob - } - } - - // done: write edit copy back over the original - if (!state.mDryRun) - editor->commit(); -} - - -// -// Sign a binary that has no notion of architecture. -// That currently means anything that isn't Mach-O format. -// -void SecCodeSigner::Signer::signArchitectureAgnostic(const Requirement::Context &context) -{ - // non-Mach-O executable - single-instance signing - RefPointer writer = state.mDetached ? - (new DetachedBlobWriter(*this)) : rep->writer(); - CodeDirectory::Builder builder(state.mDigestAlgorithm); - InternalRequirements ireqs; - ireqs(requirements, rep->defaultRequirements(NULL, state), context); - populate(*writer); - populate(builder, *writer, ireqs, rep->signingBase(), rep->signingLimit()); - - // add identification blob (made from this architecture) only if we're making a detached signature - if (state.mDetached) { - CFRef identification = rep->identification(); - writer->component(cdIdentificationSlot, identification); - } - - CodeDirectory *cd = builder.build(); - CFRef signature = signCodeDirectory(cd); - if (!state.mDryRun) { - writer->codeDirectory(cd); - writer->signature(signature); - writer->flush(); - } - ::free(cd); -} - - -// -// Global populate - send components to destination buffers ONCE -// -void SecCodeSigner::Signer::populate(DiskRep::Writer &writer) -{ - if (resourceDirectory && !state.mDryRun) - writer.component(cdResourceDirSlot, resourceDictData); -} - - -// -// Per-architecture populate - send components to per-architecture buffers -// and populate the CodeDirectory for an architecture. In architecture-agnostic -// signing operations, the non-architectural binary is considered one (arbitrary) architecture -// for the purposes of this call. -// -void SecCodeSigner::Signer::populate(CodeDirectory::Builder &builder, DiskRep::Writer &writer, - InternalRequirements &ireqs, size_t offset /* = 0 */, size_t length /* = 0 */) -{ - // fill the CodeDirectory - builder.executable(rep->mainExecutablePath(), pagesize, offset, length); - builder.flags(cdFlags); - builder.identifier(identifier); - builder.teamID(teamID); - builder.platform(state.mPlatform); - - if (CFRef data = rep->component(cdInfoSlot)) - builder.specialSlot(cdInfoSlot, data); - if (ireqs) { - CFRef data = makeCFData(*ireqs); - writer.component(cdRequirementsSlot, data); - builder.specialSlot(cdRequirementsSlot, data); - } - if (resourceDirectory) - builder.specialSlot(cdResourceDirSlot, resourceDictData); -#if NOT_YET - if (state.mApplicationData) - builder.specialSlot(cdApplicationSlot, state.mApplicationData); -#endif - if (entitlements) { - writer.component(cdEntitlementSlot, entitlements); - builder.specialSlot(cdEntitlementSlot, entitlements); - } - - writer.addDiscretionary(builder); -} - -#include - -// -// Generate the CMS signature for a (finished) CodeDirectory. -// -CFDataRef SecCodeSigner::Signer::signCodeDirectory(const CodeDirectory *cd) -{ - assert(state.mSigner); - CFRef defaultTSContext = NULL; - - // a null signer generates a null signature blob - if (state.mSigner == SecIdentityRef(kCFNull)) - return CFDataCreate(NULL, NULL, 0); - - // generate CMS signature - CFRef cms; - MacOSError::check(CMSEncoderCreate(&cms.aref())); - MacOSError::check(CMSEncoderSetCertificateChainMode(cms, kCMSCertificateChainWithRoot)); - CMSEncoderAddSigners(cms, state.mSigner); - CMSEncoderSetSignerAlgorithm(cms, kCMSEncoderDigestAlgorithmSHA256); - MacOSError::check(CMSEncoderSetHasDetachedContent(cms, true)); - - if (signingTime) { - MacOSError::check(CMSEncoderAddSignedAttributes(cms, kCMSAttrSigningTime)); - MacOSError::check(CMSEncoderSetSigningTime(cms, signingTime)); - } - - MacOSError::check(CMSEncoderUpdateContent(cms, cd, cd->length())); - - // Set up to call Timestamp server if requested - - if (state.mWantTimeStamp) - { - CFRef error = NULL; - defaultTSContext = SecCmsTSAGetDefaultContext(&error.aref()); - if (error) - MacOSError::throwMe(errSecDataNotAvailable); - - if (state.mNoTimeStampCerts || state.mTimestampService) { - if (state.mTimestampService) - CFDictionarySetValue(defaultTSContext, kTSAContextKeyURL, state.mTimestampService); - if (state.mNoTimeStampCerts) - CFDictionarySetValue(defaultTSContext, kTSAContextKeyNoCerts, kCFBooleanTrue); - } - - CmsMessageSetTSAContext(cms, defaultTSContext); - } - - CFDataRef signature; - MacOSError::check(CMSEncoderCopyEncodedContent(cms, &signature)); - - return signature; -} - - -// -// Parse a text of the form -// flag,...,flag -// where each flag is the canonical name of a signable CodeDirectory flag. -// No abbreviations are allowed, and internally set flags are not accepted. -// -uint32_t SecCodeSigner::Signer::cdTextFlags(std::string text) -{ - uint32_t flags = 0; - for (string::size_type comma = text.find(','); ; text = text.substr(comma+1), comma = text.find(',')) { - string word = (comma == string::npos) ? text : text.substr(0, comma); - const SecCodeDirectoryFlagTable *item; - for (item = kSecCodeDirectoryFlagTable; item->name; item++) - if (item->signable && word == item->name) { - flags |= item->value; - break; - } - if (!item->name) // not found - MacOSError::throwMe(errSecCSInvalidFlags); - if (comma == string::npos) // last word - break; - } - return flags; -} - - -// -// Generate a unique string from our underlying DiskRep. -// We could get 90%+ of the uniquing benefit by just generating -// a random string here. Instead, we pick the (hex string encoding of) -// the source rep's unique identifier blob. For universal binaries, -// this is the canonical local architecture, which is a bit arbitrary. -// This provides us with a consistent unique string for all architectures -// of a fat binary, *and* (unlike a random string) is reproducible -// for identical inputs, even upon resigning. -// -std::string SecCodeSigner::Signer::uniqueName() const -{ - CFRef identification = rep->identification(); - const UInt8 *ident = CFDataGetBytePtr(identification); - const CFIndex length = CFDataGetLength(identification); - string result; - for (CFIndex n = 0; n < length; n++) { - char hex[3]; - snprintf(hex, sizeof(hex), "%02x", ident[n]); - result += hex; - } - return result; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/signer.h b/OSX/include/security_codesigning/signer.h deleted file mode 100644 index 3902d5bb..00000000 --- a/OSX/include/security_codesigning/signer.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2006-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// signer - Signing operation supervisor and controller -// -#ifndef _H_SIGNER -#define _H_SIGNER - -#include "CodeSigner.h" -#include "cdbuilder.h" -#include "signerutils.h" -#include "StaticCode.h" -#include - -namespace Security { -namespace CodeSigning { - - -// -// The signer driver class. -// This is a workflow object, containing all the data needed for the various -// signing stages to cooperate. It is not meant to be API visible; that is -// SecCodeSigner's job. -// -class SecCodeSigner::Signer { -public: - Signer(SecCodeSigner &s, SecStaticCode *c) : state(s), code(c), requirements(NULL) - { strict = state.signingFlags() & kSecCSSignStrictPreflight; } - ~Signer() { ::free((Requirements *)requirements); } - - void sign(SecCSFlags flags); - void remove(SecCSFlags flags); - - SecCodeSigner &state; - SecStaticCode * const code; - - CodeDirectory::HashAlgorithm digestAlgorithm() const { return state.mDigestAlgorithm; } - - std::string path() const { return cfStringRelease(rep->copyCanonicalPath()); } - SecIdentityRef signingIdentity() const { return state.mSigner; } - std::string signingIdentifier() const { return identifier; } - -protected: - void prepare(SecCSFlags flags); // set up signing parameters - void signMachO(Universal *fat, const Requirement::Context &context); // sign a Mach-O binary - void signArchitectureAgnostic(const Requirement::Context &context); // sign anything else - - void populate(DiskRep::Writer &writer); // global - void populate(CodeDirectory::Builder &builder, DiskRep::Writer &writer, - InternalRequirements &ireqs, size_t offset = 0, size_t length = 0); // per-architecture - CFDataRef signCodeDirectory(const CodeDirectory *cd); - - uint32_t cdTextFlags(std::string text); // convert text CodeDirectory flags - std::string uniqueName() const; // derive unique string from rep - -protected: - void buildResources(std::string root, std::string relBase, CFDictionaryRef rules); - CFMutableDictionaryRef signNested(const std::string &path, const std::string &relpath); - CFDataRef hashFile(const char *path); - -private: - RefPointer rep; // DiskRep of Code being signed - CFRef resourceDirectory; // resource directory - CFRef resourceDictData; // XML form of resourceDirectory - std::string identifier; // signing identifier - std::string teamID; // team identifier - CFRef entitlements; // entitlements - uint32_t cdFlags; // CodeDirectory flags - const Requirements *requirements; // internal requirements ready-to-use - size_t pagesize; // size of main executable pages - CFAbsoluteTime signingTime; // signing time for CMS signature (0 => none) - bool strict; // strict validation - -private: - Mutex resourceLock; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_CODESIGNER diff --git a/OSX/include/security_codesigning/signerutils.cpp b/OSX/include/security_codesigning/signerutils.cpp deleted file mode 100644 index eb19d2d3..00000000 --- a/OSX/include/security_codesigning/signerutils.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (c) 2006-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// signerutils - utilities for signature generation -// -#include "signerutils.h" -#include "signer.h" -#include "SecCodeSigner.h" -#include -#include -#include "resources.h" -#include "csutilities.h" -#include "drmaker.h" -#include -#include -#include - -// for helper validation -#include "Code.h" -#include -#include - - -namespace Security { -namespace CodeSigning { - - -// -// About the Mach-O allocation helper -// -static const char helperName[] = "codesign_allocate"; -static const char helperPath[] = "/usr/bin/codesign_allocate"; -static const char helperOverride[] = "CODESIGN_ALLOCATE"; -static const size_t csAlign = 16; - - -// -// BlobWriters -// -void BlobWriter::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - return EmbeddedSignatureBlob::Maker::component(slot, data); -} - - -void DetachedBlobWriter::flush() -{ - EmbeddedSignatureBlob *blob = this->make(); - signer.code->detachedSignature(CFTempData(*blob)); - signer.state.returnDetachedSignature(blob, signer); - ::free(blob); -} - - -// -// ArchEditor -// -ArchEditor::ArchEditor(Universal &code, CodeDirectory::HashAlgorithm hashType, uint32_t attrs) - : DiskRep::Writer(attrs) -{ - Universal::Architectures archList; - code.architectures(archList); - for (Universal::Architectures::const_iterator it = archList.begin(); - it != archList.end(); ++it) - architecture[*it] = new Arch(*it, hashType); -} - - -ArchEditor::~ArchEditor() -{ - for (ArchMap::iterator it = begin(); it != end(); ++it) - delete it->second; -} - - -// -// BlobEditor -// -BlobEditor::BlobEditor(Universal &fat, SecCodeSigner::Signer &s) - : ArchEditor(fat, s.digestAlgorithm(), 0), signer(s) -{ } - - -void BlobEditor::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - mGlobal.component(slot, data); -} - -void BlobEditor::write(Arch &arch, EmbeddedSignatureBlob *blob) -{ - mMaker.add(arch.architecture.cpuType(), blob); -} - - -void BlobEditor::commit() -{ - // create the architecture-global blob and store it into the superblob - mMaker.add(0, mGlobal.make()); // takes ownership of blob - - // finish up the superblob and deliver it - DetachedSignatureBlob *blob = mMaker.make(); - signer.state.returnDetachedSignature(blob, signer); - ::free(blob); -} - - -// -// MachOEditor's allocate() method spawns the codesign_allocate helper tool to -// "drill up" the Mach-O binary for insertion of Code Signing signature data. -// After the tool succeeds, we open the new file and are ready to write it. -// -MachOEditor::MachOEditor(DiskRep::Writer *w, Universal &code, CodeDirectory::HashAlgorithm hashType, std::string srcPath) - : ArchEditor(code, hashType, w->attributes()), - writer(w), - sourcePath(srcPath), - tempPath(srcPath + ".cstemp"), - mNewCode(NULL), - mTempMayExist(false) -{ - if (const char *path = getenv(helperOverride)) { - mHelperPath = path; - mHelperOverridden = true; - } else { - mHelperPath = helperPath; - mHelperOverridden = false; - } -} - -MachOEditor::~MachOEditor() -{ - delete mNewCode; - if (mTempMayExist) - ::remove(tempPath.c_str()); // ignore error (can't do anything about it) - this->kill(); -} - - -void MachOEditor::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - writer->component(slot, data); -} - - -void MachOEditor::allocate() -{ - // note that we may have a temporary file from now on (for cleanup in the error case) - mTempMayExist = true; - - // run codesign_allocate to make room in the executable file - fork(); - wait(); - if (!Child::succeeded()) - MacOSError::throwMe(errSecCSHelperFailed); - - // open the new (temporary) Universal file - { - UidGuard guard(0); - mFd.open(tempPath, O_RDWR); - } - mNewCode = new Universal(mFd); -} - -static const unsigned char appleReq[] = { - // anchor apple and info["Application-Group"] = "com.apple.tool.codesign_allocate" - 0xfa, 0xde, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, - 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x11, 0x41, 0x70, 0x70, 0x6c, - 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2d, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x70, 0x70, 0x6c, - 0x65, 0x2e, 0x74, 0x6f, 0x6f, 0x6c, 0x2e, 0x63, 0x6f, 0x64, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x5f, - 0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x65, -}; - -void MachOEditor::parentAction() -{ - if (mHelperOverridden) { - CODESIGN_ALLOCATE_VALIDATE((char*)mHelperPath, this->pid()); - // check code identity of an overridden allocation helper - SecPointer code = new SecStaticCode(DiskRep::bestGuess(mHelperPath)); - code->staticValidate(kSecCSDefaultFlags, NULL); - code->validateRequirement((const Requirement *)appleReq, errSecCSReqFailed); - } -} - -void MachOEditor::childAction() -{ - vector arguments; - arguments.push_back(helperName); - arguments.push_back("-i"); - arguments.push_back(sourcePath.c_str()); - arguments.push_back("-o"); - arguments.push_back(tempPath.c_str()); - - for (Iterator it = architecture.begin(); it != architecture.end(); ++it) { - size_t size = LowLevelMemoryUtilities::alignUp(it->second->blobSize, csAlign); - char *ssize; // we'll leak this (execv is coming soon) - asprintf(&ssize, "%zd", size); - - if (const char *arch = it->first.name()) { - CODESIGN_ALLOCATE_ARCH((char*)arch, (unsigned int)size); - arguments.push_back("-a"); - arguments.push_back(arch); - } else { - CODESIGN_ALLOCATE_ARCHN(it->first.cpuType(), it->first.cpuSubtype(), (unsigned int)size); - arguments.push_back("-A"); - char *anum; - asprintf(&anum, "%d", it->first.cpuType()); - arguments.push_back(anum); - asprintf(&anum, "%d", it->first.cpuSubtype()); - arguments.push_back(anum); - } - arguments.push_back(ssize); - } - arguments.push_back(NULL); - - if (mHelperOverridden) - ::csops(0, CS_OPS_MARKKILL, NULL, 0); // force code integrity - ::seteuid(0); // activate privilege if caller has it; ignore error if not - execv(mHelperPath, (char * const *)&arguments[0]); -} - -void MachOEditor::reset(Arch &arch) -{ - arch.source.reset(mNewCode->architecture(arch.architecture)); - arch.cdbuilder.reopen(tempPath, - arch.source->offset(), arch.source->signingOffset()); -} - - -// -// MachOEditor's write() method actually writes the blob into the CODESIGNING section -// of the executable image file. -// -void MachOEditor::write(Arch &arch, EmbeddedSignatureBlob *blob) -{ - if (size_t offset = arch.source->signingOffset()) { - size_t signingLength = arch.source->signingLength(); - CODESIGN_ALLOCATE_WRITE((char*)arch.architecture.name(), offset, (unsigned)blob->length(), (unsigned)signingLength); - if (signingLength < blob->length()) - MacOSError::throwMe(errSecCSCMSTooLarge); - arch.source->seek(offset); - arch.source->writeAll(*blob); - ::free(blob); // done with it - } else { - secdebug("signer", "%p cannot find CODESIGNING section", this); - MacOSError::throwMe(errSecCSInternalError); - } -} - - -// -// Commit the edit. -// This moves the temporary editor copy over the source image file. -// Note that the Universal object returned by allocate() is still open -// and valid; the caller owns it. -// -void MachOEditor::commit() -{ - // if the file's owned by someone else *and* we can become root... - struct stat st; - UnixError::check(::stat(sourcePath.c_str(), &st)); - - // copy over all the *other* stuff - Copyfile copy; - int fd = mFd; - copy.set(COPYFILE_STATE_DST_FD, &fd); - { - // perform copy under root or file-owner privileges if available - UidGuard guard; - if (!guard.seteuid(0)) - guard.seteuid(st.st_uid); - - // copy metadata from original file... - copy(sourcePath.c_str(), NULL, COPYFILE_SECURITY | COPYFILE_METADATA); - - // ... but explicitly update the timestamps since we did change the file - char buf; - mFd.read(&buf, sizeof(buf), 0); - mFd.write(&buf, sizeof(buf), 0); - - // move the new file into place - UnixError::check(::rename(tempPath.c_str(), sourcePath.c_str())); - mTempMayExist = false; // we renamed it away - } -} - - -// -// InternalRequirements -// -void InternalRequirements::operator () (const Requirements *given, const Requirements *defaulted, const Requirement::Context &context) -{ - // first add the default internal requirements - if (defaulted) { - this->add(defaulted); - ::free((void *)defaulted); // was malloc(3)ed by DiskRep - } - - // now override them with any requirements explicitly given by the signer - if (given) - this->add(given); - - // now add the Designated Requirement, if we can make it and it's not been provided - if (!this->contains(kSecDesignatedRequirementType)) { - DRMaker maker(context); - if (Requirement *dr = maker.make()) { - this->add(kSecDesignatedRequirementType, dr); // takes ownership of dr - } - } - - // return the result - mReqs = this->make(); -} - - -// -// Pre-Signing contexts -// -PreSigningContext::PreSigningContext(const SecCodeSigner::Signer &signer) -{ - // construct a cert chain - if (signer.signingIdentity() != SecIdentityRef(kCFNull)) { - CFRef signingCert; - MacOSError::check(SecIdentityCopyCertificate(signer.signingIdentity(), &signingCert.aref())); - CFRef policy = SecPolicyCreateWithOID(kSecPolicyAppleCodeSigning); - CFRef trust; - MacOSError::check(SecTrustCreateWithCertificates(CFArrayRef(signingCert.get()), policy, &trust.aref())); - SecTrustResultType result; - MacOSError::check(SecTrustEvaluate(trust, &result)); - CSSM_TP_APPLE_EVIDENCE_INFO *info; - MacOSError::check(SecTrustGetResult(trust, &result, &mCerts.aref(), &info)); - this->certs = mCerts; - } - - // other stuff - this->identifier = signer.signingIdentifier(); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/signerutils.h b/OSX/include/security_codesigning/signerutils.h deleted file mode 100644 index 906be1ea..00000000 --- a/OSX/include/security_codesigning/signerutils.h +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2006-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// signerutils - utilities for signature generation -// -#ifndef _H_SIGNERUTILS -#define _H_SIGNERUTILS - -#include "CodeSigner.h" -#include "sigblob.h" -#include "cdbuilder.h" -#include -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// A helper to deal with the magic merger logic of internal requirements -// -class InternalRequirements : public Requirements::Maker { -public: - InternalRequirements() : mReqs(NULL) { } - ~InternalRequirements() { ::free((void *)mReqs); } - void operator () (const Requirements *given, const Requirements *defaulted, const Requirement::Context &context); - operator const Requirements * () const { return mReqs; } - -private: - const Requirements *mReqs; -}; - - -// -// A DiskRep::Writer that assembles data in a SuperBlob (in memory) -// -class BlobWriter : public DiskRep::Writer, public EmbeddedSignatureBlob::Maker { -public: - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); -}; - - -class DetachedBlobWriter : public BlobWriter { -public: - DetachedBlobWriter(SecCodeSigner::Signer &s) : signer(s) { } - - SecCodeSigner::Signer &signer; - - void flush(); -}; - - -// -// A multi-architecture editing assistant. -// ArchEditor collects (Mach-O) architectures in use, and maintains per-archtitecture -// data structures. It must be subclassed to express a particular way to handle the signing -// data. -// -class ArchEditor : public DiskRep::Writer { -public: - ArchEditor(Universal &fat, CodeDirectory::HashAlgorithm hashType, uint32_t attrs); - virtual ~ArchEditor(); - -public: - // - // One architecture's signing construction element. - // This also implements DispRep::Writer so generic writing code - // can work with both Mach-O and other files. - // - struct Arch : public BlobWriter { - Architecture architecture; // our architecture - auto_ptr source; // Mach-O object to be signed - CodeDirectory::Builder cdbuilder; // builder for CodeDirectory - InternalRequirements ireqs; // consolidated internal requirements - size_t blobSize; // calculated SuperBlob size - - Arch(const Architecture &arch, CodeDirectory::HashAlgorithm hashType) - : architecture(arch), cdbuilder(hashType) { } - }; - - // - // Our callers access the architectural universe through a map - // from Architectures to Arch objects. - // - typedef std::map ArchMap; - typedef ArchMap::iterator Iterator; - ArchMap::iterator begin() { return architecture.begin(); } - ArchMap::iterator end() { return architecture.end(); } - unsigned count() const { return (unsigned)architecture.size(); } - - // methods needed for an actual implementation - virtual void allocate() = 0; // interpass allocations - virtual void reset(Arch &arch) = 0; // pass 2 prep - virtual void write(Arch &arch, EmbeddedSignatureBlob *blob) = 0; // takes ownership of blob - virtual void commit() = 0; // write/flush result - -protected: - ArchMap architecture; -}; - - -// -// An ArchEditor that collects all architectures into a single SuperBlob, -// usually for writing a detached multi-architecture signature. -// -class BlobEditor : public ArchEditor { -public: - BlobEditor(Universal &fat, SecCodeSigner::Signer &s); - - SecCodeSigner::Signer &signer; - - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); - void allocate() { } - void reset(Arch &arch) { } - void write(Arch &arch, EmbeddedSignatureBlob *blob); - void commit(); - -private: - DetachedSignatureBlob::Maker mMaker; - EmbeddedSignatureBlob::Maker mGlobal; -}; - - -// -// An ArchEditor that writes its signatures into a (fat) binary file. -// We do this by forking a helper tool (codesign_allocate) and asking -// it to make a copy with suitable space "opened up" in the right spots. -// -class MachOEditor : public ArchEditor, private UnixPlusPlus::Child { -public: - MachOEditor(DiskRep::Writer *w, Universal &code, CodeDirectory::HashAlgorithm hashType, std::string srcPath); - ~MachOEditor(); - - const RefPointer writer; - const std::string sourcePath; - const std::string tempPath; - - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); - void allocate(); - void reset(Arch &arch); - void write(Arch &arch, EmbeddedSignatureBlob *blob); - void commit(); - -private: - // fork operation - void childAction(); - void parentAction(); - - // controlling the temporary file copy - Universal *mNewCode; - UnixPlusPlus::AutoFileDesc mFd; - bool mTempMayExist; - - // finding and managing the helper tool - const char *mHelperPath; - bool mHelperOverridden; -}; - - -// -// A Requirement::Context populated from a signing request. -// We use this to help generate the explicit Designated Requirement -// during signing ops, and thus this must be constructed BEFORE we -// actually have a signed object. -// -class PreSigningContext : public Requirement::Context { -public: - PreSigningContext(const SecCodeSigner::Signer &signer); - -private: - CFRef mCerts; // hold cert chain -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_SIGNERUTILS diff --git a/OSX/include/security_codesigning/singlediskrep.cpp b/OSX/include/security_codesigning/singlediskrep.cpp deleted file mode 100644 index 5b01b138..00000000 --- a/OSX/include/security_codesigning/singlediskrep.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2006-2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// singlediskrep - semi-abstract diskrep for a single file of some kind -// -#include "singlediskrep.h" -#include "csutilities.h" -#include -#include - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Construct a SingleDiskRep -// -SingleDiskRep::SingleDiskRep(const std::string &path) - : mPath(path) -{ -} - - -// -// The default binary identification of a SingleDiskRep is the (SHA-1) hash -// of the entire file itself. -// -CFDataRef SingleDiskRep::identification() -{ - SHA1 hash; - this->fd().seek(0); - hashFileData(this->fd(), &hash); - SHA1::Digest digest; - hash.finish(digest); - return makeCFData(digest, sizeof(digest)); -} - - -// -// Both the canonical and main executable path of a SingleDiskRep is, well, its path. -// -CFURLRef SingleDiskRep::copyCanonicalPath() -{ - return makeCFURL(mPath); -} - -string SingleDiskRep::mainExecutablePath() -{ - return mPath; -} - - -// -// The default signing limit is the size of the file. -// This will do unless the signing data gets creatively stuck in there somewhere. -// -size_t SingleDiskRep::signingLimit() -{ - return fd().fileSize(); -} - -// -// A lazily opened read-only file descriptor for the path. -// -FileDesc &SingleDiskRep::fd() -{ - if (!mFd) - mFd.open(mPath, O_RDONLY); - - return mFd; -} - -// -// Flush cached state -// -void SingleDiskRep::flush() -{ - mFd.close(); -} - - -// -// The recommended identifier of a SingleDiskRep is, absent any better clue, -// the basename of its path. -// -string SingleDiskRep::recommendedIdentifier(const SigningContext &) -{ - return canonicalIdentifier(mPath); -} - - -// -// Paranoid validation -// -void SingleDiskRep::strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated) -{ - // code limit must cover (exactly) the entire file - if (cd && cd->codeLimit != signingLimit()) - MacOSError::throwMe(errSecCSSignatureInvalid); -} - - - -// -// Prototype Writers -// -FileDesc &SingleDiskRep::Writer::fd() -{ - if (!mFd) - mFd.open(rep->path(), O_RDWR); - return mFd; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/singlediskrep.h b/OSX/include/security_codesigning/singlediskrep.h deleted file mode 100644 index 1992dc16..00000000 --- a/OSX/include/security_codesigning/singlediskrep.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2007,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// singlediskrep - semi-abstract diskrep for a single file of some kind -// -#ifndef _H_SINGLEDISKREP -#define _H_SINGLEDISKREP - -#include "diskrep.h" -#include - -namespace Security { -namespace CodeSigning { - - -// -// A slight specialization of DiskRep that knows that it's working with a single -// file at a path that is both the canonical and main executable path. This is a common -// pattern. -// -// A SingleDiskRep is not a fully formed DiskRep in its own right. It must be further -// subclassed. -// -class SingleDiskRep : public DiskRep { -public: - SingleDiskRep(const std::string &path); - - CFDataRef identification(); // partial file hash - std::string mainExecutablePath(); // base path - CFURLRef copyCanonicalPath(); // base path - size_t signingLimit(); // size of file - UnixPlusPlus::FileDesc &fd(); // readable fd for this file - void flush(); // close cached fd - - std::string recommendedIdentifier(const SigningContext &ctx); // basename(path) - - void strictValidate(const CodeDirectory* cd, const ToleratedErrors& tolerated); - -public: - class Writer; - -protected: - std::string path() const { return mPath; } - -private: - std::string mPath; - UnixPlusPlus::AutoFileDesc mFd; // open file (cached) -}; - - -// -// A Writer for a SingleDiskRep -// -class SingleDiskRep::Writer : public DiskRep::Writer { -public: - Writer(SingleDiskRep *r, uint32_t attrs = 0) : DiskRep::Writer(attrs), rep(r) { } - - UnixPlusPlus::FileDesc &fd(); - -private: - RefPointer rep; // underlying SingleDiskRep - UnixPlusPlus::AutoFileDesc mFd; // cached writable fd -}; - - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_SINGLEDISKREP diff --git a/OSX/include/security_codesigning/slcrep.cpp b/OSX/include/security_codesigning/slcrep.cpp deleted file mode 100644 index 8a0ecbd4..00000000 --- a/OSX/include/security_codesigning/slcrep.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2009,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// slcrep - DiskRep representing the Mac OS Shared Library Cache -// -#include "slcrep.h" - - -namespace Security { -namespace CodeSigning { - -using namespace UnixPlusPlus; - - -// -// Object management. -// We open the file lazily, so nothing much happens on constructions. -// We can construct directly from a file path, or from an architecture -// (represented by Context), which will find the file in its usual -// location on disk. -// -DYLDCacheRep::DYLDCacheRep(const char *path) - : SingleDiskRep(path), mCache(path) -{ - this->setup(); -} - -DYLDCacheRep::DYLDCacheRep(const Context *ctx) - : SingleDiskRep(DYLDCache::pathFor(((ctx && ctx->arch) ? ctx->arch : Architecture::local()))), - mCache(this->path()) -{ - this->setup(); -} - -void DYLDCacheRep::setup() -{ - mSigningData = NULL; - if (mCache.totalSize() >= mCache.mapSize() + sizeof(BlobCore)) { - const EmbeddedSignatureBlob *blob = mCache.at((uint32_t)mCache.mapSize()); - if (mCache.totalSize() >= mCache.mapSize() + blob->length()) // entire blob fits in file - mSigningData = blob; - } - CODESIGN_DISKREP_CREATE_SLC(this, (char*)this->mainExecutablePath().c_str()); -} - - -// -// Sniffer function for "plausible shared library cache file". -// -bool DYLDCacheRep::candidate(FileDesc &fd) -{ - return DYLDCache::validate(fd); -} - - -// -// Default to system page size for segmented (paged) signatures -// -size_t DYLDCacheRep::pageSize(const SigningContext &) -{ - return segmentedPageSize; -} - - -// -// Signing limit is the start of the (trailing) signature -// -size_t DYLDCacheRep::signingLimit() -{ - return mCache.mapSize(); -} - - -// -// Retrieve a component from the executable. -// Our mCache has mapped the entire file, so we just fish the contents out of -// the mapped area as needed. -// -CFDataRef DYLDCacheRep::component(CodeDirectory::SpecialSlot slot) -{ - return mSigningData ? mSigningData->component(slot) : NULL; -} - - -// -// Provide a (vaguely) human readable characterization of this code -// -string DYLDCacheRep::format() -{ - if (const char *name = mCache.architecture().name()) { - char result[100]; - snprintf(result, sizeof(result), "OS X Shared Library Cache (%s @ 0x%llx)", - name, mCache.baseAddress()); - return result; - } else - return "OS X Shared Library Cache (unknown type)"; -} - - -// -// DYLDCacheRep::Writers -// -DiskRep::Writer *DYLDCacheRep::writer() -{ - return new Writer(this); -} - - -// -// Write a component. -// -void DYLDCacheRep::Writer::component(CodeDirectory::SpecialSlot slot, CFDataRef data) -{ - EmbeddedSignatureBlob::Maker::component(slot, data); -} - - -// -// Append the superblob we built to the cache file. -// -void DYLDCacheRep::Writer::flush() -{ - delete mSigningData; // ditch previous blob just in case - mSigningData = Maker::make(); // assemble new signature SuperBlob - fd().seek(rep->mCache.mapSize()); // end of impage proper - fd().writeAll(*mSigningData); -} - - -// -// The discretionary additions insert a Scatter vector describing the file's mapping table. -// -void DYLDCacheRep::Writer::addDiscretionary(CodeDirectory::Builder &builder) -{ - unsigned count = rep->mCache.mappingCount(); - builder.scatter(count); - for (unsigned n = 0; n < count; n++) { - const DYLDCache::Mapping dmap = rep->mCache.mapping(n); - CodeDirectory::Scatter *scatter = builder.scatter() + n; - scatter->targetOffset = dmap.address(); - scatter->base = (uint32_t)(dmap.offset() / segmentedPageSize); - assert(dmap.offset() % segmentedPageSize == 0); - scatter->count = (uint32_t)(dmap.size() / segmentedPageSize); - assert(dmap.size() % segmentedPageSize == 0); - } -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/slcrep.h b/OSX/include/security_codesigning/slcrep.h deleted file mode 100644 index d1b2a554..00000000 --- a/OSX/include/security_codesigning/slcrep.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2009,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// slcrep - DiskRep representing the Mac OS Shared Library Cache -// -#ifndef _H_SLCREP -#define _H_SLCREP - -#include "singlediskrep.h" -#include "sigblob.h" -#include -#include -#include - -namespace Security { -namespace CodeSigning { - - -// -// DYLDCacheRep implements the on-disk format for the Mac OS X -// Shared Library Cache, which coalesces a set of system libraries -// and frameworks into one big (mappable) code blob in the sky. -// -class DYLDCacheRep : public SingleDiskRep { -public: - DYLDCacheRep(const Context *ctx = NULL); - DYLDCacheRep(const char *path); - - CFDataRef component(CodeDirectory::SpecialSlot slot); - size_t pageSize(const SigningContext &ctx); - size_t signingLimit(); - std::string format(); - - static bool candidate(UnixPlusPlus::FileDesc &fd); - -public: - static CFDataRef identificationFor(MachO *macho); - -public: - DiskRep::Writer *writer(); - class Writer; - friend class Writer; - -private: - void setup(); - -private: - DYLDCache mCache; - const EmbeddedSignatureBlob *mSigningData; // pointer to signature SuperBlob (in mapped memory) -}; - - -// -// The write side of a FileDiskRep -// -class DYLDCacheRep::Writer : public SingleDiskRep::Writer, private EmbeddedSignatureBlob::Maker { - friend class FileDiskRep; -public: - Writer(DYLDCacheRep *r) : SingleDiskRep::Writer(r, writerNoGlobal), rep(r), mSigningData(NULL) { } - void component(CodeDirectory::SpecialSlot slot, CFDataRef data); - void flush(); - void addDiscretionary(CodeDirectory::Builder &builder); - -private: - DYLDCacheRep *rep; - EmbeddedSignatureBlob *mSigningData; -}; - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_SLCREP diff --git a/OSX/include/security_codesigning/syspolicy.sql b/OSX/include/security_codesigning/syspolicy.sql deleted file mode 100644 index 745533f6..00000000 --- a/OSX/include/security_codesigning/syspolicy.sql +++ /dev/null @@ -1,204 +0,0 @@ --- --- Copyright (c) 2011-2012 Apple Inc. All Rights Reserved. --- --- @APPLE_LICENSE_HEADER_START@ --- --- This file contains Original Code and/or Modifications of Original Code --- as defined in and that are subject to the Apple Public Source License --- Version 2.0 (the 'License'). You may not use this file except in --- compliance with the License. Please obtain a copy of the License at --- http://www.opensource.apple.com/apsl/ and read it before using this --- file. --- --- The Original Code and all software distributed under the License are --- distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER --- EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, --- INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, --- FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. --- Please see the License for the specific language governing rights and --- limitations under the License. --- --- @APPLE_LICENSE_HEADER_END@ --- --- --- System Policy master database - file format and initial contents --- --- This is currently for sqlite3 --- --- NOTES: --- Dates are uniformly in julian form. We use 5000000 as the canonical "never" expiration --- value; that's a day in the year 8977. --- -PRAGMA user_version = 1; -PRAGMA foreign_keys = true; -PRAGMA legacy_file_format = false; -PRAGMA recursive_triggers = true; - - --- --- The feature table hold configuration features and options --- -CREATE TABLE feature ( - id INTEGER PRIMARY KEY, -- canononical - name TEXT NOT NULL UNIQUE, -- name of option - value TEXT NULL, -- value of option, if any - remarks TEXT NULL -- optional remarks string -); - - --- --- The primary authority. This table is conceptually scanned --- in priority order, with the highest-priority matching enabled record --- determining the outcome. --- -CREATE TABLE authority ( - id INTEGER PRIMARY KEY AUTOINCREMENT, -- canonical - version INTEGER NOT NULL DEFAULT (1) -- semantic version of this rule - CHECK (version > 0), - type INTEGER NOT NULL, -- operation type - requirement TEXT NULL -- code requirement - CHECK ((requirement IS NULL) = ((flags & 1) != 0)), - allow INTEGER NOT NULL DEFAULT (1) -- allow (1) or deny (0) - CHECK (allow = 0 OR allow = 1), - disabled INTEGER NOT NULL DEFAULT (0) -- disable count (stacks; enabled if zero) - CHECK (disabled >= 0), - expires FLOAT NOT NULL DEFAULT (5000000), -- expiration of rule authority (Julian date) - priority REAL NOT NULL DEFAULT (0), -- rule priority (full float) - label TEXT NULL, -- text label for authority rule - filter_unsigned TEXT NULL, -- prescreen for handling unsigned code - flags INTEGER NOT NULL DEFAULT (0), -- amalgamated binary flags - -- following fields are for documentation only - ctime FLOAT NOT NULL DEFAULT (JULIANDAY('now')), -- rule creation time (Julian) - mtime FLOAT NOT NULL DEFAULT (JULIANDAY('now')), -- time rule was last changed (Julian) - user TEXT NULL, -- user requesting this rule (NULL if unknown) - remarks TEXT NULL -- optional remarks string -); - --- index -CREATE INDEX authority_type ON authority (type); -CREATE INDEX authority_priority ON authority (priority); -CREATE INDEX authority_expires ON authority (expires); - --- update mtime if a record is changed -CREATE TRIGGER authority_update AFTER UPDATE ON authority -BEGIN - UPDATE authority SET mtime = JULIANDAY('now') WHERE id = old.id; -END; - --- rules that are actively considered -CREATE VIEW active_authority AS -SELECT * from authority -WHERE disabled = 0 AND JULIANDAY('now') < expires AND (flags & 1) = 0; - --- rules subject to priority scan: active_authority but including disabled rules -CREATE VIEW scan_authority AS -SELECT * from authority -WHERE JULIANDAY('now') < expires AND (flags & 1) = 0; - - --- --- A table to carry (potentially large-ish) filesystem data stored as a bookmark blob. --- -CREATE TABLE bookmarkhints ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - bookmark BLOB NOT NULL, - authority INTEGER NOT NULL - REFERENCES authority(id) ON DELETE CASCADE -); - - --- --- Upgradable features already contained in this baseline. --- See policydatabase.cpp for upgrade code. --- -INSERT INTO feature (name, value, remarks) - VALUES ('bookmarkhints', 'present', 'builtin'); -INSERT INTO feature (name, value, remarks) - VALUES ('codesignedpackages', 'present', 'builtin'); -INSERT INTO feature (name, value, remarks) - VALUES ('filter_unsigned', 'present', 'builtin'); - - --- --- Initial canonical contents of a fresh database --- - --- virtual rule anchoring negative cache entries (no rule found) -insert into authority (type, allow, priority, flags, label) - values (1, 0, -1.0E100, 1, 'No Matching Rule'); - --- any "genuine Apple-signed" installers -insert into authority (type, allow, priority, flags, label, requirement) - values (2, 1, -1, 2, 'Apple Installer', 'anchor apple generic and certificate 1[subject.CN] = "Apple Software Update Certification Authority"'); - --- Apple code signing -insert into authority (type, allow, flags, label, requirement) - values (1, 1, 2, 'Apple System', 'anchor apple'); - --- Mac App Store code signing -insert into authority (type, allow, flags, label, requirement) - values (1, 1, 2, 'Mac App Store', 'anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.9] exists'); - --- Mac App Store installer signing -insert into authority (type, allow, flags, label, requirement) - values (2, 1, 2, 'Mac App Store', 'anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.10] exists'); - --- Caspian code and archive signing -insert into authority (type, allow, flags, label, requirement) - values (1, 1, 2, 'Developer ID', 'anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists'); -insert into authority (type, allow, flags, label, requirement) - values (2, 1, 2, 'Developer ID', 'anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and (certificate leaf[field.1.2.840.113635.100.6.1.14] or certificate leaf[field.1.2.840.113635.100.6.1.13])'); - - --- --- The cache table lists previously determined outcomes --- for individual objects (by object hash). Entries come from --- full evaluations of authority records, or by explicitly inserting --- override rules that preempt the normal authority. --- EACH object record must have a parent authority record from which it is derived; --- this may be a normal authority rule or an override rule. If the parent rule is deleted, --- all objects created from it are automatically removed (by sqlite itself). --- -CREATE TABLE object ( - id INTEGER PRIMARY KEY, -- canonical - type INTEGER NOT NULL, -- operation type - hash CDHASH NOT NULL, -- canonical hash of object - allow INTEGER NOT NULL, -- allow (1) or deny (0) - expires FLOAT NOT NULL DEFAULT (5000000), -- expiration of object entry - authority INTEGER NOT NULL -- governing authority rule - REFERENCES authority(id) ON DELETE CASCADE, - -- following fields are for documentation only - path TEXT NULL, -- path of object at record creation time - ctime FLOAT NOT NULL DEFAULT (JULIANDAY('now')), -- record creation time - mtime FLOAT NOT NULL DEFAULT (JULIANDAY('now')), -- record modification time - remarks TEXT NULL -- optional remarks string -); - --- index -CREATE INDEX object_type ON object (type); -CREATE INDEX object_expires ON object (expires); -CREATE UNIQUE INDEX object_hash ON object (hash); - --- update mtime if a record is changed -CREATE TRIGGER object_update AFTER UPDATE ON object -BEGIN - UPDATE object SET mtime = JULIANDAY('now') WHERE id = old.id; -END; - - --- --- Some useful views on objects. These are for administration; they are not used by the assessor. --- -CREATE VIEW object_state AS -SELECT object.id, object.type, object.allow, - CASE object.expires WHEN 5000000 THEN NULL ELSE STRFTIME('%Y-%m-%d %H:%M:%f', object.expires, 'localtime') END AS expiration, - (object.expires - JULIANDAY('now')) * 86400 as remaining, - authority.label, - object.authority, - object.path, - object.ctime, - authority.requirement, - authority.disabled, - object.remarks -FROM object, authority -WHERE object.authority = authority.id; diff --git a/OSX/include/security_codesigning/xar++.cpp b/OSX/include/security_codesigning/xar++.cpp deleted file mode 100644 index 3029c5bb..00000000 --- a/OSX/include/security_codesigning/xar++.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// xar++ - interface to XAR-format archive files -// -#include "xar++.h" -#include -#include - - -namespace Security { -namespace CodeSigning { - - -Xar::Xar(const char *path) -{ - mXar = 0; - mSigCMS = 0; - mSigClassic = 0; - if (path) - open(path); -} - -void Xar::open(const char *path) -{ - if ((mXar = ::xar_open(path, READ)) == NULL) - return; - - xar_signature_t sig = ::xar_signature_first(mXar); - // read signatures until we find a CMS signature - while (sig && mSigCMS == NULL) { - const char *type = ::xar_signature_type(sig); - if (strcmp(type, "CMS") == 0) { - mSigCMS = sig; - } else if (strcmp(type, "RSA") == 0) { - mSigClassic = sig; - } - sig = ::xar_signature_next(sig); - } -} - -Xar::~Xar() -{ - if (mXar) - ::xar_close(mXar); -} - -static CFArrayRef copyCertChainFromSignature(xar_signature_t sig) -{ - unsigned count = xar_signature_get_x509certificate_count(sig); - CFRef certs = makeCFMutableArray(0); - for (unsigned ix = 0; ix < count; ix++) { - const uint8_t *data; - uint32_t length; - if (xar_signature_get_x509certificate_data(sig, ix, &data, &length) == 0) { - CFTempData cdata(data, length); - CFRef cert = SecCertificateCreateWithData(NULL, cdata); - CFArrayAppendValue(certs, cert.get()); - } - } - return certs.yield(); -} - -CFArrayRef Xar::copyCertChain() -{ - if (mSigCMS) - return copyCertChainFromSignature(mSigCMS); - else if (mSigClassic) - return copyCertChainFromSignature(mSigClassic); - return NULL; -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/xar++.h b/OSX/include/security_codesigning/xar++.h deleted file mode 100644 index 8d9dccff..00000000 --- a/OSX/include/security_codesigning/xar++.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// xar++ - interface to XAR-format archive files -// -#ifndef _H_XARPLUSPLUS -#define _H_XARPLUSPLUS - -#include -#include - -extern "C" { -#include -} - -namespace Security { -namespace CodeSigning { - - -// -// A XAR-format file on disk -// -class Xar { -public: - Xar(const char *path = NULL); - virtual ~Xar(); - void open(const char *path); - - operator bool() const { return mXar != 0; } - bool isSigned() const { return mSigClassic != 0 || mSigCMS != 0; } - - CFArrayRef copyCertChain(); - -private: - xar_t mXar; - xar_signature_t mSigClassic; - xar_signature_t mSigCMS; -}; - - - -} // end namespace CodeSigning -} // end namespace Security - -#endif // !_H_XARPLUSPLUS diff --git a/OSX/include/security_codesigning/xpcengine.cpp b/OSX/include/security_codesigning/xpcengine.cpp deleted file mode 100644 index 2da4e67f..00000000 --- a/OSX/include/security_codesigning/xpcengine.cpp +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#include "xpcengine.h" -#include -#include -#include -#include -#include - - -namespace Security { -namespace CodeSigning { - - -static void doProgress(xpc_object_t msg); - - -static const char serviceName[] = "com.apple.security.syspolicy"; - - -static dispatch_once_t dispatchInit; // one-time init marker -static xpc_connection_t service; // connection to spd -static dispatch_queue_t queue; // dispatch queue for service - -static void init() -{ - dispatch_once(&dispatchInit, ^void(void) { - const char *name = serviceName; - if (const char *env = getenv("SYSPOLICYNAME")) - name = env; - queue = dispatch_queue_create("spd-client", 0); - service = xpc_connection_create_mach_service(name, queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED); - xpc_connection_set_event_handler(service, ^(xpc_object_t msg) { - if (xpc_get_type(msg) == XPC_TYPE_DICTIONARY) { - const char *function = xpc_dictionary_get_string(msg, "function"); - if (!strcmp(function, "progress")) { - doProgress(msg); - } - } - }); - xpc_connection_resume(service); - }); -} - - -// -// Your standard XPC client-side machinery -// -class Message { -public: - xpc_object_t obj; - - Message(const char *function) - { - init(); - obj = xpc_dictionary_create(NULL, NULL, 0); - xpc_dictionary_set_string(obj, "function", function); - } - ~Message() - { - if (obj) - xpc_release(obj); - } - operator xpc_object_t () { return obj; } - - void send() - { - xpc_object_t reply = xpc_connection_send_message_with_reply_sync(service, obj); - xpc_release(obj); - obj = NULL; - xpc_type_t type = xpc_get_type(reply); - if (type == XPC_TYPE_DICTIONARY) { - obj = reply; - if (int64_t error = xpc_dictionary_get_int64(obj, "error")) - MacOSError::throwMe((int)error); - } else if (type == XPC_TYPE_ERROR) { - const char *s = xpc_copy_description(reply); - printf("Error returned: %s\n", s); - free((char*)s); - MacOSError::throwMe(errSecCSInternalError); - } else { - const char *s = xpc_copy_description(reply); - printf("Unexpected type of return object: %s\n", s); - free((char*)s); - } - } -}; - - - -static void copyCFDictionary(const void *key, const void *value, void *ctx) -{ - CFMutableDictionaryRef target = CFMutableDictionaryRef(ctx); - if (CFGetTypeID(value) == CFURLGetTypeID()) { - CFRef path = CFURLCopyFileSystemPath(CFURLRef(value), kCFURLPOSIXPathStyle); - CFDictionaryAddValue(target, key, path); - } else if (CFEqual(key, kSecAssessmentContextKeyFeedback)) { - CFDictionaryAddValue(target, key, CFTempNumber(uint64_t(value))); - } else { - CFDictionaryAddValue(target, key, value); - } -} - -void xpcEngineAssess(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result) -{ - Message msg("assess"); - xpc_dictionary_set_string(msg, "path", cfString(path).c_str()); - xpc_dictionary_set_int64(msg, "flags", flags); - CFRef ctx = makeCFMutableDictionary(); - if (context) - CFDictionaryApplyFunction(context, copyCFDictionary, ctx); - CFRef contextData = makeCFData(CFDictionaryRef(ctx)); - xpc_dictionary_set_data(msg, "context", CFDataGetBytePtr(contextData), CFDataGetLength(contextData)); - - msg.send(); - - if (int64_t error = xpc_dictionary_get_int64(msg, "error")) - MacOSError::throwMe((int)error); - - size_t resultLength; - const void *resultData = xpc_dictionary_get_data(msg, "result", &resultLength); - CFRef resultDict = makeCFDictionaryFrom(resultData, resultLength); - CFDictionaryApplyFunction(resultDict, copyCFDictionary, result); - CFDictionaryAddValue(result, CFSTR("assessment:remote"), kCFBooleanTrue); -} - -static void doProgress(xpc_object_t msg) -{ - uint64_t current = xpc_dictionary_get_uint64(msg, "current"); - uint64_t total = xpc_dictionary_get_uint64(msg, "total"); - uint64_t ref = xpc_dictionary_get_uint64(msg, "ref"); - const char *token = xpc_dictionary_get_string(msg, "token"); - SecAssessmentFeedback feedback = SecAssessmentFeedback(ref); - CFTemp info("{current=%d,total=%d}", current, total); - Boolean proceed = feedback(kSecAssessmentFeedbackProgress, info); - if (!proceed) { - xpc_connection_t connection = xpc_dictionary_get_remote_connection(msg); - xpc_object_t cancelRequest = xpc_dictionary_create(NULL, NULL, 0); - xpc_dictionary_set_string(cancelRequest, "function", "cancel"); - xpc_dictionary_set_string(cancelRequest, "token", token); - xpc_connection_send_message(connection, cancelRequest); - xpc_release(cancelRequest); - } -} - - -CFDictionaryRef xpcEngineUpdate(CFTypeRef target, SecAssessmentFlags flags, CFDictionaryRef context) -{ - Message msg("update"); - // target can be NULL, a CFURLRef, a SecRequirementRef, or a CFNumberRef - if (target) { - if (CFGetTypeID(target) == CFNumberGetTypeID()) - xpc_dictionary_set_uint64(msg, "rule", cfNumber(CFNumberRef(target))); - else if (CFGetTypeID(target) == CFURLGetTypeID()) - xpc_dictionary_set_string(msg, "url", cfString(CFURLRef(target)).c_str()); - else if (CFGetTypeID(target) == SecRequirementGetTypeID()) { - CFRef data; - MacOSError::check(SecRequirementCopyData(SecRequirementRef(target), kSecCSDefaultFlags, &data.aref())); - xpc_dictionary_set_data(msg, "requirement", CFDataGetBytePtr(data), CFDataGetLength(data)); - } else - MacOSError::throwMe(errSecCSInvalidObjectRef); - } - xpc_dictionary_set_int64(msg, "flags", flags); - CFRef ctx = makeCFMutableDictionary(); - if (context) - CFDictionaryApplyFunction(context, copyCFDictionary, ctx); - AuthorizationRef localAuthorization = NULL; - if (CFDictionaryGetValue(ctx, kSecAssessmentUpdateKeyAuthorization) == NULL) { // no caller-provided authorization - MacOSError::check(AuthorizationCreate(NULL, NULL, kAuthorizationFlagDefaults, &localAuthorization)); - AuthorizationExternalForm extForm; - MacOSError::check(AuthorizationMakeExternalForm(localAuthorization, &extForm)); - CFDictionaryAddValue(ctx, kSecAssessmentUpdateKeyAuthorization, CFTempData(&extForm, sizeof(extForm))); - } - CFRef contextData = makeCFData(CFDictionaryRef(ctx)); - xpc_dictionary_set_data(msg, "context", CFDataGetBytePtr(contextData), CFDataGetLength(contextData)); - - msg.send(); - - if (localAuthorization) - AuthorizationFree(localAuthorization, kAuthorizationFlagDefaults); - - if (int64_t error = xpc_dictionary_get_int64(msg, "error")) - MacOSError::throwMe((int)error); - - size_t resultLength; - const void *resultData = xpc_dictionary_get_data(msg, "result", &resultLength); - return makeCFDictionaryFrom(resultData, resultLength); -} - - -bool xpcEngineControl(const char *control) -{ - Message msg("control"); - xpc_dictionary_set_string(msg, "control", control); - msg.send(); - return true; -} - - -void xpcEngineRecord(CFDictionaryRef info) -{ - Message msg("record"); - CFRef infoData = makeCFData(CFDictionaryRef(info)); - xpc_dictionary_set_data(msg, "info", CFDataGetBytePtr(infoData), CFDataGetLength(infoData)); - - msg.send(); -} - - -} // end namespace CodeSigning -} // end namespace Security diff --git a/OSX/include/security_codesigning/xpcengine.h b/OSX/include/security_codesigning/xpcengine.h deleted file mode 100644 index cd70387d..00000000 --- a/OSX/include/security_codesigning/xpcengine.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2011-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ -#ifndef _H_XPCENGINE -#define _H_XPCENGINE - -#include "SecAssessment.h" -#include "policydb.h" -#include -#include - -namespace Security { -namespace CodeSigning { - - -void xpcEngineAssess(CFURLRef path, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result); -CFDictionaryRef xpcEngineUpdate(CFTypeRef target, SecAssessmentFlags flags, CFDictionaryRef context) - CF_RETURNS_RETAINED; -bool xpcEngineControl(const char *name); -void xpcEngineRecord(CFDictionaryRef info); - - -} // end namespace CodeSigning -} // end namespace Security - -#endif //_H_XPCENGINE diff --git a/OSX/include/security_comcryption b/OSX/include/security_comcryption new file mode 120000 index 00000000..cbcdf214 --- /dev/null +++ b/OSX/include/security_comcryption @@ -0,0 +1 @@ +./libsecurity_comcryption/lib \ No newline at end of file diff --git a/OSX/include/security_comcryption/comDebug.h b/OSX/include/security_comcryption/comDebug.h deleted file mode 100644 index efc823d9..00000000 --- a/OSX/include/security_comcryption/comDebug.h +++ /dev/null @@ -1,212 +0,0 @@ -/* Copyright (c) 1997,2011,2014 Apple Inc. - * - * comDebug.h - */ - -#ifndef _COM_DEBUG_H_ -#define _COM_DEBUG_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * enable general debugging printfs and error checking. - */ -#define COM_DEBUG 0 -#if COM_DEBUG -#include - -#define ddprintf(x) printf x -#else -#define ddprintf(x) -#endif - -/* - * block parsing debug - */ -#define COM_SCAN_DEBUG 0 -#if COM_SCAN_DEBUG -#define scprintf(x) printf x -#else -#define scprintf(x) -#endif - -/* - * 2nd-level comcrypt debug - */ -#define LEVEL2_DEBUG 0 -#if LEVEL2_DEBUG -#include - -#define l2printf(x) printf x -#else -#define l2printf(x) -#endif - -/* - * lookahead queue debug - */ -#define COM_LA_DEBUG 0 -#define COM_LA_PRINTF 0 -#if COM_LA_PRINTF -#define laprintf(x) printf x -#else -#define laprintf(x) -#endif - -/* - * Statistics measurements. This is a private API. - */ -#if COM_DEBUG -#define COM_STATS 0 -#else -#define COM_STATS 0 -#endif - -#if COM_STATS - -/* - * Info obtained via a call to getComStats() - */ -typedef struct { - unsigned level1blocks; - unsigned plaintextBytes; - unsigned ciphertextBytes; - unsigned oneByteFrags; // 1st level only - unsigned twoByteFrags; // ditto - unsigned level2oneByteFrags; // second level only - unsigned level2twoByteFrags; // ditto - unsigned level2byteCode; // bytes, pre-encrypted - unsigned level2cipherText; // bytes, post-encrypt - unsigned level2blocks; // 2nd-level blocks - unsigned level2jmatch; // total jmatch (at first level) of - // 2nd level blocks -} comStats; - -extern comStats _comStats; -#define incrComStat(stat, num) _comStats.stat += num; - -#define incr1byteFrags(recursLevel) { \ - if(recursLevel == 1) { \ - incrComStat(level2oneByteFrags, 1); \ - } \ - else { \ - incrComStat(oneByteFrags, 1); \ - } \ -} -#define incr2byteFrags(recursLevel) { \ - if(recursLevel == 1) { \ - incrComStat(level2twoByteFrags, 1); \ - } \ - else { \ - incrComStat(twoByteFrags, 1); \ - } \ -} - -extern void resetComStats(); -extern void getComStats(comStats *stats); - -#else -#define incrComStat(stat, num) -#define incr1byteFrags(recursLevel) -#define incr2byteFrags(recursLevel) -#endif - -/* - * Profiling measurement. A private API when enabled. - */ -#if COM_DEBUG -#define COM_PROFILE 0 -#else -#define COM_PROFILE 0 -#endif - -#if COM_PROFILE - -#include - -/* - * Global profiling enable. It turns out the the cost of doing the - * kern_timestamp() call twice per codeword is way more expensive - * than the actual comcryption code. Setting this variable to zero - * avoids the cost of all the timestamps for reference without - * rebuilding. Also, the cmcPerWordOhead calibrates the actual - * cost of the two kern_timestamp() calls per word. - */ -extern unsigned comProfEnable; - -/* - * Profiling accumulators. - */ -typedef unsigned comprof_t; - -extern comprof_t cmcTotal; -extern comprof_t cmcQueSearch; -extern comprof_t cmcQueMatchMove; -extern comprof_t cmcQueMissMove; -extern comprof_t cmcPerWordOhead; -extern comprof_t cmcLevel2; - - -/* - * Place one of these in the local variable declaration list of each routine - * which will do profiling. - */ -#define COMPROF_LOCALS \ - struct tsval _profStartTime; \ - struct tsval _profEndTime; - -/* - * Start the clock. - */ -#define COMPROF_START \ - if(comProfEnable) { \ - kern_timestamp(&_profStartTime); \ - } - -/* - * Stop the clock and gather elapsed time to specified accumulator. - */ -#define COMPROF_END(accum) \ - if(comProfEnable) { \ - kern_timestamp(&_profEndTime); \ - accum += (_profEndTime.low_val - _profStartTime.low_val); \ - } - - -#else - -#define COMPROF_LOCALS -#define COMPROF_START -#define COMPROF_END(accum) - -#endif /* COM_PROFILE */ - -/* - * Get/set parameter API, private, for debug only. - */ -#if COM_DEBUG -#define COM_PARAM_ENABLE 1 -#else -#define COM_PARAM_ENABLE 0 -#endif /*COM_DEBUG*/ - -#if COM_PARAM_ENABLE - -extern unsigned getF1(comcryptObj cobj); -extern void setF1(comcryptObj cobj, unsigned f1); -extern unsigned getF2(comcryptObj cobj); -extern void setF2(comcryptObj cobj, unsigned f2); -extern unsigned getJmatchThresh(comcryptObj cobj); -extern void setJmatchThresh(comcryptObj cobj, unsigned jmatchThresh); -extern unsigned getMinByteCode(comcryptObj cobj); -extern void setMinByteCode(comcryptObj cobj, unsigned minByteCode); - -#endif /*COM_PARAM_ENABLE*/ - -#ifdef __cplusplus -} -#endif - -#endif /*_COM_DEBUG_H_*/ diff --git a/OSX/include/security_comcryption/comcryptPriv.c b/OSX/include/security_comcryption/comcryptPriv.c deleted file mode 100644 index 873b32c8..00000000 --- a/OSX/include/security_comcryption/comcryptPriv.c +++ /dev/null @@ -1,540 +0,0 @@ -/* - * Copyright (c) 1997,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#include "comcryptPriv.h" -#include -#include -#include -#ifdef macintosh -#include -#endif - -/* if NULL, use our own */ -comMallocExternFcn *comMallocExt = NULL; -comFreeExternFcn *comFreeExt = NULL; - -#if COM_STATS -comStats _comStats; - -void resetComStats() -{ - memset(&_comStats, 0, sizeof(comStats)); -} - -void getComStats(comStats *stats) -{ - *stats = _comStats; -} - -#else /*COM_STATS*/ - -#define incrComStat(stat, num) - -#endif /*COM_STATS*/ - -/* - * Generate a symbol permutation from the key. - */ -void key_perm( - const unsigned char *key, - int keybytes, - unsigned char *map, - unsigned char *invmap) -{ - int i, j, tmp, sum; - - for(sum = 0, j = 0; j < keybytes; j++) { - sum += key[j]; - } - for(j=0; j < 256; j++) { - map[j] = j; - } - for(j=0; j < 255; j++) { - i = (key[j % keybytes] + j*sum) & 0xff; - tmp = map[i]; - map[i] = map[j]; - map[j] = tmp; - } - for(j=0; j<256; j++) { - invmap[map[j]] = j; - } -} - -int keybyte( - const unsigned char *key, - int keybytes, - int index) -{ - return((int) key[index % keybytes]); -} - -int keynybble( - const unsigned char *key, - int keybytes, - int index) -{ - int i = index % (2*keybytes); - int j; - - j = key[i>>1]; /* Which byte. */ - if(i & 1) j >>= 4; /* Which nybble. */ - return(j & 0xf); -} - -/* - * Hash a key array. - */ - -#define HASH_SEED 3 -#define HASH_REDUCE 1023 - -static unsigned keyHash(const unsigned char *key, unsigned keylen) -{ - unsigned x = HASH_SEED; /* Any seed in [1,p-1]. Like SEED = 3. */ - unsigned ctr; - - for(ctr=0; ctrcodeBufSize = comcryptMaxOutBufSize(NULL, - CC_BLOCK_SIZE, - CCOP_COMCRYPT, - 1); - cbuf->codeBuf = (unsigned char *)ascMalloc(cbuf->codeBufSize); - - /* - * max size needed for level2Buf is the MaxOutBufSize of comcrypting - * a whole block of byte code. Note we assume that MaxOutBufSize(n) >= n. - */ - cbuf->level2BufSize = comcryptMaxOutBufSize(NULL, - MAX_TOKENS, // one byte per token - CCOP_COMCRYPT, - 1); - cbuf->level2Buf = (unsigned char *)ascMalloc(cbuf->level2BufSize); - - cbuf->queue = (queueElt *)ascMalloc(sizeof(queueElt) * QLEN); - - #if QUEUE_LOOKAHEAD - /* - * Might want to do this dynamically, though that requires the malloc - * of the lookAhead buffer to be done in initCodeBufs(), not here (at - * comcryptAlloc() time). - * - * FIXME : should do the malloc of lookAhead buffer lazily for - * non-Mac platforms. - */ - cbuf->lookAhead = (unsigned char *)ascMalloc(LOOKAHEAD_SIZE); - #else /* QUEUE_LOOKAHEAD */ - cbuf->lookAhead = NULL; - #endif /* QUEUE_LOOKAHEAD */ - - /* - * This maybe should also be done dynamically, lazily... - */ - cbuf->sigArray = (unsigned *)ascMalloc((MAX_TOKENS + 1) * sizeof(unsigned)); -} - -void initCodeBufs( - comcryptBuf *cbuf, - const unsigned char *key, - unsigned keyLen, - unsigned char laEnable, - unsigned char sigSeqEnable) -{ - unsigned ct; - unsigned qval; - unsigned char khash = (unsigned char)keyHash(key, keyLen); - - cbuf->nybbleDex = khash; - - if(laEnable) { - memset(cbuf->lookAhead, 0, LOOKAHEAD_SIZE); - } - - laprintf(("initing queue and lookahead\n")); - - for(ct=0; ctqueue[ct] = qval; - if(laEnable) { - markInQueue(cbuf, qval, 1); - } - } - // note cbuf->nybbleDex = khash on return... - - cbuf->f1 = F1_DEFAULT; - cbuf->f2 = F2_DEFAULT; - cbuf->jmatchThresh = THRESH_2LEVEL_JMATCH_DEF; - cbuf->minByteCode = THRESH_2LEVEL_NUMBYTECODES_DEF; - if(sigSeqEnable) { - initSigSequence(cbuf, key, keyLen); - } -} - -void freeCodeBufs(comcryptBuf *cbuf) -{ - if(cbuf->queue != NULL) { - ascFree(cbuf->queue); - } - if(cbuf->codeBuf != NULL) { - ascFree(cbuf->codeBuf); - } - if(cbuf->level2Buf != NULL) { - ascFree(cbuf->level2Buf); - } - if(cbuf->nextBuf != NULL) { - freeCodeBufs(cbuf->nextBuf); - ascFree(cbuf->nextBuf); - cbuf->nextBuf = NULL; - } - if(cbuf->lookAhead != NULL) { - ascFree(cbuf->lookAhead); - } - if(cbuf->sigArray != NULL) { - ascFree(cbuf->sigArray); - } -} - -void serializeInt( - unsigned i, - unsigned char *buf) -{ - buf[0] = (unsigned char)(i >> 24); - buf[1] = (unsigned char)(i >> 16); - buf[2] = (unsigned char)(i >> 8); - buf[3] = (unsigned char)(i & 0xff); -} - -unsigned deserializeInt(unsigned char *buf) -{ - unsigned i; - - i = ((unsigned)buf[0]) << 24; - i |= ((unsigned)buf[1]) << 16; - i |= ((unsigned)buf[2]) << 8; - i |= buf[3]; - return i; -} - -#if COM_PARAM_ENABLE - -unsigned getF1(comcryptObj cobj) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - return cpriv->cbuf.f1; -} - -void setF1(comcryptObj cobj, unsigned f1) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - cpriv->cbuf.f1 = f1; - if(cpriv->cbuf.nextBuf != NULL) { - cpriv->cbuf.nextBuf->f1 = f1; - } -} - -unsigned getF2(comcryptObj cobj) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - return cpriv->cbuf.f2; -} - -void setF2(comcryptObj cobj, unsigned f2) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - cpriv->cbuf.f2 = f2; - if(cpriv->cbuf.nextBuf != NULL) { - cpriv->cbuf.nextBuf->f2 = f2; - } -} - -unsigned getJmatchThresh(comcryptObj cobj) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - return cpriv->cbuf.jmatchThresh; -} - -void setJmatchThresh(comcryptObj cobj, unsigned jmatchThresh) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - cpriv->cbuf.jmatchThresh = jmatchThresh; - if(cpriv->cbuf.nextBuf != NULL) { - cpriv->cbuf.nextBuf->jmatchThresh = jmatchThresh; - } -} - -unsigned getMinByteCode(comcryptObj cobj) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - return cpriv->cbuf.minByteCode; -} - -void setMinByteCode(comcryptObj cobj, unsigned minByteCode) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - cpriv->cbuf.minByteCode = minByteCode; - if(cpriv->cbuf.nextBuf != NULL) { - cpriv->cbuf.nextBuf->minByteCode = minByteCode; - } -} - -#endif /*COM_PARAM_ENABLE*/ - - -#if COM_LA_DEBUG - -/* - * Verify integrity of lookahead w.r.t. queue. - */ -int testLookAhead(comcryptBuf *cbuf, int i1, int i2) -{ - unsigned i; - - if(!cbuf->laEnable) { - return 0; - } - for(i=0; iqueue[i])) { - printf("aaagh, corrupted lookahead - in queue[], !inQueue()\n"); - printf("i=0x%x i1=0x%x i2=0x%x\n", - i, i1, i2); - printf("\n"); - exit(1); - } - } - //return initTestLookAhead(cbuf); - return 0; -} - -int initTestLookAhead(comcryptBuf *cbuf) -{ - #if QUEUE_LOOKAHEAD_BIT - - unsigned codeWord = 0; - unsigned char bit; - unsigned short byte; - unsigned char *la = cbuf->lookAhead; - - for(byte=0; bytequeue[i] == codeWord) { - found = 1; - break; - } - } - if(!found) { - printf("***corrupted init lookahead - in l.a., " - "not in queue[]\n"); - printf("codeWord 0x%x\n", codeWord); - printf("\n"); - exit(1); - } - } - codeWord++; - } - } - - #endif /* QUEUE_LOOKAHEAD_BIT */ - return 0; -} - -#endif /* COM_LA_DEBUG */ - -void initSigSequence(comcryptBuf *cbuf, - const unsigned char *key, - unsigned keyLen) -{ - unsigned seed = IN_OFFSET; - unsigned j; - - for(j=0; jsigArray[0] = (unsigned short)seed; -} - -#if 0 -/* - * Called once per token bit, after processing the token. - */ -void nextSigWord(comcryptBuf *cbuf, - unsigned sigDex, // same as tokenDex - unsigned match, - unsigned above) // jabove, keyabove -{ - unsigned offset; - unsigned short *sigArray = cbuf->sigArray; - - #if COM_DEBUG - if(sigDex == 0) { - printf("nextSigWord underflow\n"); - exit(1); - } - if(sigDex > MAX_TOKENS) { - printf("nextSigWord overflow\n"); - exit(1); - } - #endif - - if(match) { - offset = IN_OFFSET; - } - else { - offset = OUT_OFFSET; - } -#if 1 - sigArray[sigDex] = (sigArray[sigDex-1] * (above + offset)) % HASH_PRIME; -#endif -} -#endif - -/* - * Obfuscate a block of ciphertext. - */ -void sigMunge(comcryptBuf *cbuf, - const unsigned char *tokenPtr, - unsigned numTokens, - unsigned char *byteCodePtr, - unsigned char *longCodePtr) -{ - unsigned char tokenBit = 0x01; - unsigned token; - unsigned short sig; - - for(token=0; tokensigArray[token]; - if(*tokenPtr & tokenBit) { - /* no match - munge longCode - written MSB first */ - *longCodePtr++ ^= (unsigned char)(sig >> 8); - *longCodePtr++ ^= (unsigned char)sig; - } - else { - /* match - munge byteCode */ - *byteCodePtr++ ^= (unsigned char)sig; - } - tokenBit <<= 1; - if(tokenBit == 0) { - tokenBit = 0x01; - tokenPtr++; - } - } -} - - -/* - * All this can be optimized and tailored to specific platforms, of course... - */ - -void *ascMalloc(unsigned size) -{ - #ifdef macintosh - - Handle h; - OSErr err; - Ptr p; - - #endif /* mac */ - - if(comMallocExt != NULL) { - return (comMallocExt)(size); - } - - #ifdef macintosh - - h = nil; - err = errSecSuccess; - - h = NewHandleSys(size); // system heap is not paged - do{ - HLockHi(h); // will move low in system heap - err = MemError(); - if( err != errSecSuccess ) break; - p = *h; - }while(0); - if( err != errSecSuccess ){ - return NULL; - } - return p; - - #else /* others...*/ - return malloc(size); - #endif -} - -void ascFree(void *data) -{ - #ifdef macintosh - Handle h; - #endif - - if(comFreeExt != NULL) { - (comFreeExt)(data); - return; - } - - #ifdef macintosh - if( data != nil ){ - h = RecoverHandle((Ptr) data); - DisposeHandle(h); - } - - #else /* others */ - free(data); - #endif -} diff --git a/OSX/include/security_comcryption/comcryptPriv.h b/OSX/include/security_comcryption/comcryptPriv.h deleted file mode 100644 index d99c9637..00000000 --- a/OSX/include/security_comcryption/comcryptPriv.h +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright (c) 1997,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#ifndef _COMCRYPT_PRIV_H_ -#define _COMCRYPT_PRIV_H_ - -#include "comcryption.h" -#include "comDebug.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern comMallocExternFcn *comMallocExt; -extern comFreeExternFcn *comFreeExt; - -/* - * type of element in comcryptBuf.queue[]. Making this an unsigned int gives - * a slight performance improvement on the i486 platform, but it does use up - * more memory. - */ -typedef unsigned queueElt; - -/* - * Enable queue lookahead via comcryptBuf.lookAhead[]. This is currently - * just the default value for comcryptBuf.laEnable. - */ -#define QUEUE_LOOKAHEAD 1 - -/* - * lookahead queue is bit array if 1, else byte array. - * FIXME - this will most likely be a hard-coded 1 for Mac and - * dynamically configurable for other platforms. - */ -#define QUEUE_LOOKAHEAD_BIT 1 - -/* - * Size of lookAhead buffer in bytes. - */ -#if QUEUE_LOOKAHEAD_BIT -/* - * 1 bit per potential queueElt value. - */ -#define LOOKAHEAD_SIZE (1 << ((2 * 8) - 3)) -#else /* QUEUE_LOOKAHEAD_BIT */ -/* - * One byte per queueElt value; avoids shifts and masks in accessing - * array elements at the cost of additional memory. - */ -#define LOOKAHEAD_SIZE (1 << (2 * 8)) -#endif /* QUEUE_LOOKAHEAD_BIT */ - -/* - * When true, optimize away the cost of the keynybble() call on a hit - * on queue[0]. - */ -#define SKIP_NIBBLE_ON_QUEUE_0 1 - -/* - * pre-malloc'd buffers, one per level of comcryption. This allows each level - * to maintain its own queue state machine as well as its own comcryption - * parameters. - */ -typedef struct _comcryptBuf { - queueElt *queue; // mallocd, QLEN elements - unsigned nybbleDex; // index for keynybble() - struct _comcryptBuf *nextBuf; // for recursion - - /* - * Used to temporarily store bytecode fragments during comcryption and - * partial blocks during decomcryption. - */ - unsigned char *codeBuf; - unsigned codeBufSize; // malloc'd size of codeBuf - unsigned codeBufLength; // valid bytes in codeBuf - - /* - * Buffer for two-level comcryption. During comcryption, 2nd level - * comcrypted bytecode is placed here. During decomcryption, the result - * of decomcrytping the 2nd level bytecode is placed here. - */ - unsigned char *level2Buf; - unsigned level2BufSize; // malloc'd size of level2Buf - - /* - * comcryption parameters, may (eventually) be different for different - * levels. Tweakable, for now, only via private API in comDebug.h. - */ - unsigned f1; - unsigned f2; - unsigned jmatchThresh; // max avg jmatch for 2 level - unsigned minByteCode; // min numByteCodes for 2 level - - /* - * Bit map, one bit per potential value in queue[]; 1 means "this value - * is somewhere in queue[]" - */ - unsigned char *lookAhead; - - /* - * Signature Sequence array - to be Xord with ciphertext - * size = MAX_TOKENS - */ - unsigned *sigArray; -} comcryptBuf; - - -/* - * Private struct associated with client's comcryptObj. - */ -typedef struct { - unsigned char *key; - unsigned keybytes; // valid bytes in *key - comcryptOptimize optimize; // CCO_SIZE, etc. - unsigned char *map; - unsigned char *invmap; - unsigned version; // from ciphertext - unsigned versionBytes; // valid bytes in version; - // also nonzero on comcrypt - // means version has been - // written - unsigned spareBytes; // # ciphertext header spare - // bytes skipped - comcryptBuf cbuf; - - /* - * To save a tiny bit of memory, these could/should be bits, but - * we examine some of them on every code word, so we'll expand them into - * bytes... - */ - unsigned char laEnable; // lookahead enable - unsigned char sigSeqEnable; // signature sequence enable - unsigned char level2enable; // 2-level comcryption - -} comcryptPriv; - - -/* - * Block and buffer sizes. Subject to tweaking... - */ -#define CC_BLOCK_SIZE 256 /* bytes of plaintext */ - -/* - * For comcryptMaxInBufSize(CCOP_COMCRYPT), if outBufSize exceeds this - * threshhold, truncate the max inBufSize so that - * inBufSize = 0 mod CC_BLOCK_SIZE. - */ -#define INBUF_TRUNC_THRESH (16 * 1024) - -/* - * Macros to calculate number of token bits and bytes associated with - * a quantity of plaintext (in bytes) - */ -#define TOKEN_BITS_FROM_PTEXT(pt) ((pt + 1) >> 1) -#define TOKEN_BYTES_FROM_PTEXT(pt) ((pt + 15) >> 4) -#define TOKEN_BYTES_FROM_TOKEN_BITS(tb) ((tb + 7) >> 3) - -/* - * Max number of token bits or code fragments in a block - */ -#define MAX_TOKENS (CC_BLOCK_SIZE / 2) - -/* - * Size of comcryptBuf.queue[]. - */ -#define QLEN 256 - -/* - * FIXME - some info on these constants? - */ -#define F1_DEFAULT 12 -#define F2_DEFAULT 12 -#define ABOVE(F2) ((F2 * QLEN) >> 4) - -/* - * Constants for obfuscation via signature sequence. - */ -#define HASH_Q 19 -#define HASH_PRIME ((1< HASH_PRIME) { \ - x = (x >> HASH_Q) + (x & HASH_PRIME); \ - } \ -} - -/* - * Haven't gotten this to work for the Mac yet... - */ -#ifdef NeXT -#define SIG_WORD_INLINE 1 -#else /*NeXT*/ -#define SIG_WORD_INLINE 0 -#endif - -#if SIG_WORD_INLINE - -static inline void nextSigWord(comcryptBuf *cbuf, - unsigned sigDex, // same as tokenDex - unsigned match, - unsigned above) // (jabove, keyabove) + nibbleDex -{ - unsigned offset; - unsigned *sigArray = cbuf->sigArray; - - #if COM_DEBUG - if(sigDex == 0) { - printf("nextSigWord underflow\n"); - exit(1); - } - if(sigDex > MAX_TOKENS) { - printf("nextSigWord overflow\n"); - exit(1); - } - #endif - - if(match) { - offset = IN_OFFSET; - } - else { - offset = OUT_OFFSET; - } - sigArray[sigDex] = sigArray[sigDex-1] * (above + offset); - MOD_HASH(sigArray[sigDex]); -} - -#else /*SIG_WORD_INLINE*/ - -#define nextSigWord(cbuf, sigDex, match, above) { \ - unsigned offset = (match ? IN_OFFSET : OUT_OFFSET); \ - unsigned *sigArray = cbuf->sigArray; \ - unsigned result = (sigArray[sigDex-1] * (above + offset)); \ - MOD_HASH(result); \ - sigArray[sigDex] = result; \ -} - -#endif /*SIG_WORD_INLINE*/ - -/* - * Inline serializeShort(), deserializeShort() - */ -#define serializeShort(s, buf) \ - buf[0] = (unsigned char)(s >> 8); \ - buf[1] = (unsigned char)(s); \ - -#define deserializeShort(s, buf) \ - s = ((unsigned short)buf[0]) << 8; \ - s |= buf[1]; \ - - -/* - * General purpose macros for accessing bit arrays. Used for accessing - * token bits and lookahead array bits if QUEUE_LOOKAHEAD_BIT = 1. - */ -#define MARK_BIT_ARRAY(cp, index, val) { \ - unsigned char bit = 1 << (index & 7); \ - unsigned char *bytePtr = &cp[index>>3]; \ - if(val) { \ - *bytePtr |= bit; \ - } \ - else { \ - *bytePtr &= ~bit; \ - } \ -} -#define GET_BIT_ARRAY(cp, index) \ - (cp[index >> 3] & (1 << (index & 7))) - -#define getToken(tokenPtr, tokenDex) \ - GET_BIT_ARRAY(tokenPtr, tokenDex) - -#define updateToken(tokenPtr, tokenDex, tokenBit) \ - MARK_BIT_ARRAY(tokenPtr, tokenDex, tokenBit) - -/* - * Macros for accessing lookahead array elements - */ - -#if QUEUE_LOOKAHEAD_BIT -/* - * This way saves memory - */ -#define markInQueue(cbuf, codeWord, val) \ - MARK_BIT_ARRAY(cbuf->lookAhead, codeWord, val) - -#define inQueue(cbuf, codeWord) \ - GET_BIT_ARRAY(cbuf->lookAhead, codeWord) - -#else /* QUEUE_LOOKAHEAD_BIT */ - -/* - * This way saves time - */ -#define markInQueue(cbuf, codeWord, val) { \ - cbuf->lookAhead[codeWord] = val; \ -} -#define inQueue(cbuf, codeWord) (cbuf->lookAhead[codeWord]) - -#endif /* QUEUE_LOOKAHEAD_BIT */ - -void *ascMalloc(unsigned size); -void ascFree(void *data); - -#ifdef __cplusplus -} -#endif - -#endif /*_COMCRYPT_PRIV_H_*/ diff --git a/OSX/include/security_comcryption/comcryption.c b/OSX/include/security_comcryption/comcryption.c deleted file mode 100644 index a7d23e95..00000000 --- a/OSX/include/security_comcryption/comcryption.c +++ /dev/null @@ -1,1438 +0,0 @@ -/* - * Copyright (c) 1997,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#include -#include -#include -#include "comcryption.h" -#include "comDebug.h" -#include "comcryptPriv.h" - -#if COM_PROFILE - -unsigned comProfEnable; -comprof_t cmcTotal; -comprof_t cmcQueSearch; -comprof_t cmcQueMatchMove; -comprof_t cmcQueMissMove; -comprof_t cmcLevel2; -comprof_t cmcPerWordOhead; - -#endif /*COM_PROFILE*/ - -void comMallocRegister(comMallocExternFcn *mallocExtern, - comFreeExternFcn *freeExtern) -{ - comMallocExt = mallocExtern; - comFreeExt = freeExtern; -} - -/* - * Call once at startup. The resulting comcryptObj can be reused multiple - * times. - */ -comcryptObj comcryptAlloc(void) -{ - comcryptPriv *cpriv = (comcryptPriv *) ascMalloc(sizeof(comcryptPriv)); - - if(cpriv == NULL) { - return NULL; - } - memset(cpriv, 0, sizeof(comcryptPriv)); - -#if COMCRYPT_EXPORT_ONLY - cpriv->key = (unsigned char *)ascMalloc(EXPORT_KEY_SIZE); -#else /*COMCRYPT_EXPORT_ONLY*/ - cpriv->key = (unsigned char *)ascMalloc(COMCRYPT_MAX_KEYLENGTH); -#endif /*COMCRYPT_EXPORT_ONLY*/ - - if(cpriv->key == NULL) { - return NULL; - } - cpriv->map = (unsigned char *)ascMalloc(256); - cpriv->invmap = (unsigned char *)ascMalloc(256); - if((cpriv->map == NULL) || (cpriv->invmap == NULL)) { - return NULL; - } - mallocCodeBufs(&cpriv->cbuf); - if((cpriv->cbuf.codeBuf == NULL) || - (cpriv->cbuf.level2Buf == NULL)) { - return NULL; - } - #if QUEUE_LOOKAHEAD - if(cpriv->cbuf.lookAhead == NULL) { - return NULL; - } - #endif - - /* - * Hard coded limit of two levels of comcryption - */ - cpriv->cbuf.nextBuf = (comcryptBuf *)ascMalloc(sizeof(comcryptBuf)); - if(cpriv->cbuf.nextBuf == NULL) { - return NULL; - } - mallocCodeBufs(cpriv->cbuf.nextBuf); - if((cpriv->cbuf.nextBuf->codeBuf == NULL) || - (cpriv->cbuf.nextBuf->level2Buf == NULL)) { - return NULL; - } - #if QUEUE_LOOKAHEAD - if(cpriv->cbuf.nextBuf->lookAhead == NULL) { - return NULL; - } - #endif - - cpriv->cbuf.nextBuf->nextBuf = NULL; - return cpriv; -} - -/* - * Call this before starting every stream process - */ -comcryptReturn comcryptInit( - comcryptObj cobj, - const unsigned char *key, - unsigned keyLen, - comcryptOptimize optimize) // CCO_SIZE, etc. -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - unsigned maxKeySize; - -#if COMCRYPT_EXPORT_ONLY - /* - * FIXME - NSA might not be satisfied with this, may have to enforce - * elsewhere - */ - maxKeySize = EXPORT_KEY_SIZE; -#else /*COMCRYPT_EXPORT_ONLY*/ - maxKeySize = COMCRYPT_MAX_KEYLENGTH; -#endif /*COMCRYPT_EXPORT_ONLY*/ - - if(keyLen > maxKeySize) { - keyLen = maxKeySize; - } - memmove(cpriv->key, key, keyLen); - cpriv->keybytes = keyLen; - cpriv->cbuf.codeBufLength = 0; - cpriv->cbuf.nextBuf->codeBufLength = 0; - cpriv->version = 0; - cpriv->versionBytes = 0; - cpriv->spareBytes = 0; - cpriv->optimize = optimize; - - /* - * Derive feature enable bits from optimize arg. This is highly likely - * to change.... - */ - cpriv->level2enable = 1; - cpriv->sigSeqEnable = 1; - switch(optimize) { - case CCO_TIME: - cpriv->level2enable = 0; - break; - case CCO_TIME_SIZE: - cpriv->sigSeqEnable = 0; - break; - default: - break; - } -#if QUEUE_LOOKAHEAD - cpriv->laEnable = 1; -#else /* QUEUE_LOOKAHEAD */ - cpriv->laEnable = 0; -#endif /* QUEUE_LOOKAHEAD */ - - /* - * init queue and maps - */ - initCodeBufs(&cpriv->cbuf, key, keyLen, cpriv->laEnable, - cpriv->sigSeqEnable); - initCodeBufs(cpriv->cbuf.nextBuf, key, keyLen, cpriv->laEnable, - cpriv->sigSeqEnable); - key_perm(key, keyLen, cpriv->map, cpriv->invmap); - return CCR_SUCCESS; -} - -/* - * Free a comcryptObj object obtained via comcryptAlloc() - */ -void comcryptObjFree(comcryptObj cobj) -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - if(cpriv->key != NULL) { - ascFree(cpriv->key); - } - if(cpriv->map != NULL) { - ascFree(cpriv->map); - } - if(cpriv->invmap != NULL) { - ascFree(cpriv->invmap); - } - freeCodeBufs(&cpriv->cbuf); - ascFree(cpriv); -} - -/* - * Return the maximum input buffer size allowed for for specified - * output buffer size. Note that for both comcrypt and decomcrypt, - * to cover the worst case, the output buffer always has to be - * larger than the input buffer. - */ -unsigned comcryptMaxInBufSize(comcryptObj cobj, - unsigned outBufSize, - comcryptOp op) -{ - unsigned fullBlocks; - unsigned minCblockSize; - unsigned resid; - unsigned rtn; - unsigned tokenBytes; - comcryptPriv *cpriv = (comcryptPriv *)cobj; - unsigned ptextFromCodeBuf; - - switch(op) { - case CCOP_COMCRYPT: - /* - * Worst case: no compression. Also, establish a minimum - * ciphertext size to accomodate header and one block. - */ - minCblockSize = MIN_CBLOCK_SIZE; - if(cpriv->versionBytes == 0) { - minCblockSize += CTEXT_HDR_SIZE; - } - if(outBufSize < (minCblockSize)) { - return 0; - } - if(cpriv->versionBytes == 0) { - outBufSize -= CTEXT_HDR_SIZE; - } - fullBlocks = outBufSize / MAX_CBLOCK_SIZE; - rtn = (fullBlocks * CC_BLOCK_SIZE); // bytes of ptext - - /* - * code must be even aligned, then chop off one for odd ptext - */ - rtn &= 0xfffffffe; - rtn--; - if(rtn <= 0) { - return 0; - } - resid = outBufSize % MAX_CBLOCK_SIZE; - if(resid) { - rtn += resid; - - /* - * Account for resid block overhead - */ - if(rtn < MIN_CBLOCK_SIZE) { - return 0; - } - rtn -= MIN_CBLOCK_SIZE; - - tokenBytes = TOKEN_BYTES_FROM_PTEXT(resid); - if(rtn <= tokenBytes) { - return 0; - } - rtn -= tokenBytes; - } - if(rtn > INBUF_TRUNC_THRESH) { - /* - * Truncate to even block size to minimize partial cipherblocks - */ - rtn &= ~(CC_BLOCK_SIZE - 1); - } - return rtn; - - case CCOP_DECOMCRYPT: - /* - * Worst case - 4:1 compression and an almost full block in - * codeBuf. Note 4:1 is a super-conservative, easy arithmetic - * version of (9/16) squared... - */ - ptextFromCodeBuf = cpriv->cbuf.codeBufLength * 4; - if(outBufSize < ptextFromCodeBuf) { - /* decrypting codeBuf might overflow output (plaintext) - * buffer - won't be able to move anything */ - rtn = 0; - } - else { - /* can decrypt (this much plainText - ptextFromCodeBuf) / 4 */ - rtn = (outBufSize - ptextFromCodeBuf) / 4; - } - - /* may be able to handle a bit extra for initial decrypt... */ - if(cpriv->versionBytes < VERSION_BYTES) { - rtn += (VERSION_BYTES - cpriv->versionBytes); - } - if(cpriv->spareBytes < SPARE_BYTES) { - rtn += (SPARE_BYTES - cpriv->spareBytes); - } - return rtn; - - default: - ddprintf(("bogus op (%d) in comcryptMaxInBufSize()\n", op)); - return 0; - } -} - -/* - * Return the maximum output buffer size for specified input buffer size. - * Output buffer size will always be larger than input buffer size. - */ -unsigned comcryptMaxOutBufSize(comcryptObj cobj, - unsigned inBufSize, - comcryptOp op, - char final) -{ - unsigned fullBlocks; - unsigned resid; - unsigned rtn; - comcryptPriv *cpriv = (comcryptPriv *)cobj; - - switch(op) { - case CCOP_COMCRYPT: - fullBlocks = inBufSize / CC_BLOCK_SIZE; - rtn = fullBlocks * MAX_CBLOCK_SIZE; - resid = inBufSize % CC_BLOCK_SIZE; - if(resid != 0) { - /* - * partial block - */ - unsigned tokenBytes = TOKEN_BYTES_FROM_PTEXT(resid); - - rtn += MIN_CBLOCK_SIZE; - rtn += tokenBytes; - rtn += resid; // no compression - if(resid & 1) { - rtn++; // oddByte uses extra - } - } - if((cpriv == NULL) || // i.e., we're being called from mallocCodeBufs - (cpriv->versionBytes == 0)) { - rtn += CTEXT_HDR_SIZE; // first of a stream - } - return rtn; - - case CCOP_DECOMCRYPT: - /* - * Here assume max compression, including resid block in codeBuf - */ - inBufSize += cpriv->cbuf.codeBufLength; - if(inBufSize) { - /* may be able to handle a bit extra for initial decrypt... */ - unsigned delta; - if(cpriv->versionBytes < VERSION_BYTES) { - delta = VERSION_BYTES - cpriv->versionBytes; - if(inBufSize > delta) { - inBufSize -= delta; - } - else { - inBufSize = 0; - } - } - if(cpriv->spareBytes < SPARE_BYTES) { - delta = SPARE_BYTES - cpriv->spareBytes; - if(inBufSize > delta) { - inBufSize -= delta; - } - else { - inBufSize = 0; - } - } - } - rtn = 4 * inBufSize; - return rtn; - - default: - ddprintf(("bogus op (%d) in comcryptMaxOutBufSize()\n", op)); - return 0; - } -} - -/* - * Threshold for using memmove() rather than hard-coded loop for - * moving queue segment. This was derived empirically on a Pentium; - * we should do similar measurements on PPC. - */ -#define QUEUE_MEMMOVE_THRESH 3 - -/* - * peek at queue[0] before search. This appears to only be a win for - * constant plaintext, i.e., the codeword is almost always at queue[0]. - */ -#define QUEUE_PEEK 0 - -/* - * Comcrypt one block. - */ -static comcryptReturn comcryptBlock( - comcryptPriv *cpriv, - comcryptBuf *cbuf, // not necessarily cpriv->cbuf - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // IN/OUT - unsigned recursLevel) -{ - unsigned char *byteCodePtr; - unsigned char *destByteCodePtr; - unsigned char *longCodePtr; - unsigned char *startLongCodePtr; - unsigned char *tokenPtr; - unsigned char *startTokenPtr; - unsigned char *startCtextPtr = cipherText; - unsigned numTokenBytes; // in bytes, constant - unsigned short codeWord; - unsigned oddByte = 0; - unsigned match; - unsigned jmatch=0; - unsigned tokenDex = 0; // index into array of token bits - unsigned j; - unsigned numLongCodes = 0; - unsigned numByteCodes = 0; - unsigned totalCipherTextLen; - unsigned above; - unsigned jmatchTotal = 0; - unsigned jmatchAvg; - comcryptReturn crtn; - unsigned char blockDesc = CBD_MAGIC; - unsigned fullBlock = 0; - int len; - queueElt *src; - queueElt *dst; - queueElt *cbufq = &cbuf->queue[0]; - - /* - * 'nibble' is added to 'above' in the call to nextSigWord() for - * additional security. - * - * Normal case : nibble = keynybble() - * last word on odd byte : nibble = nibbleDex - * hit on queue q : nibble = nibbleDex (optimize to avoid keynybble() - * call) - */ - unsigned char nibble; - - COMPROF_LOCALS; - - #if COM_LA_DEBUG - if(testLookAhead(cbuf, 0, 0)) { - return CCR_INTERNAL; - } - #endif - - laprintf(("comcryptBlock recurs level %d\n", recursLevel)); - - /* - * Set up ptrs for the three arrays we'll be writing - */ - tokenPtr = cipherText + CTBO_NUM_TOKENS + 1; - if(plainTextLen >= (CC_BLOCK_SIZE - 1)) { - /* - * Optimized for full block - no token count in block. Note - * that plainTextLen == (CC_BLOCK_SIZE - 1) is also a full block - * in that it uses up a full block's worth of tokens! - */ - numTokenBytes = CC_BLOCK_SIZE >> 4; - tokenPtr--; - blockDesc |= CBD_FULL_BLOCK; - fullBlock = 1; - } - else { - numTokenBytes = (plainTextLen + 15) >> 4; - } - longCodePtr = tokenPtr + numTokenBytes; - startLongCodePtr = longCodePtr; - byteCodePtr = cbuf->codeBuf; - startTokenPtr = tokenPtr; - - if((unsigned)(longCodePtr - cipherText) > *cipherTextLen) { - ddprintf(("comcryptBlock: short block (1)\n")); - return CCR_OUTBUFFER_TOO_SMALL; - } - memset(tokenPtr, 0, numTokenBytes); - - /* - * Entering time-critical region. This loop executes once for every - * 2 bytes of plaintext. Make every attempt to streamline the code - * here; avoid function calls in favor of macros; etc. - */ - while(plainTextLen != 0) { - - /* - * assemble a 16-bit word from two bytes if possible - */ - if(plainTextLen == 1) { - /* - * Odd byte case - */ - codeWord = ((unsigned short)(cpriv->map[*plainText]) << 8) | - cpriv->map[0]; // a bit of obfuscation - mapped zero - oddByte = 1; - blockDesc |= CBD_ODD; - plainTextLen--; - } - else { - codeWord = ((unsigned short)(cpriv->map[*plainText]) << 8) | - (unsigned short)(cpriv->map[plainText[1]]); - plainText += 2; - plainTextLen -= 2; - } - - /* - * Calibrate how much profiling is costing us. - */ - COMPROF_START; - COMPROF_END(cmcPerWordOhead); - - /* - * See if this word is in queue[]. Skip if oddByte; we'll force - * a 16-bit word in that case. Also skip the search if we know - * via lookahead that a search would be fruitless. - */ - COMPROF_START; /* cmcQueSearch */ - match = 0; - do { /* while 0 - for easy breaks w/o goto */ - - /* - * First handle some optimizations and special cases - */ - if(oddByte) { - break; // force longcode - } - -#if QUEUE_PEEK - if(cbufq[0] == codeWord) { - match = 1; - jmatch = 0; - break; - - } -#endif /*QUEUE_PEEK*/ - - if(cpriv->laEnable && !inQueue(cbuf, codeWord)) { - break; - } - - /* - * OK, do the gruntwork search - */ - for(j=0; j < QLEN; j++) { - if(cbufq[j] == codeWord) { - match = 1; - jmatch = j; - break; - } - } - -#if COM_LA_DEBUG - if(cpriv->laEnable && !match) { - printf("inQueue, not found in queue!\n"); - return CCR_INTERNAL; - } - - /* - * Search for duplicates. - */ - if(match) { - for(j=jmatch+1; jkey, cpriv->keybytes, - (cbuf->nybbleDex)++); -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - - COMPROF_START; - if(match) { - /* - * 16-bit symbol is in queue. 8 bits of ciphertext, token bit is 0. - */ - if(jmatch == 0) { - /* - * Optimization: jmatch = 0. Keep state machine in sync, - * but skip queue update. - */ - above = 0; - laprintf(("...queue hit at queue[0]\n")); -#if SKIP_NIBBLE_ON_QUEUE_0 - nibble = (cbuf->nybbleDex)++; -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - } - else { -#if SKIP_NIBBLE_ON_QUEUE_0 - nibble = keynybble(cpriv->key, cpriv->keybytes, - (cbuf->nybbleDex)++); -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - - above = (cbuf->f1 * jmatch * (16 + nibble)) >> 9; - - /* - * queue[above..(jmatch-1)] move one element towards end - * queue[above] = this codeWord - */ - laprintf(("...queue hit, moving 0x%x from 0x%x to 0x%x\n", - codeWord, jmatch, above)); - - len = (int)jmatch - (int)above; - if(len > QUEUE_MEMMOVE_THRESH) { - src = &cbufq[above]; - dst = src + 1; - len *= sizeof(queueElt); - memmove(dst, src, len); - } - else { - for(j = jmatch; j>above; j--) { - cbufq[j] = cbufq[j-1]; - } - } - - cbufq[above] = codeWord; -#if COM_LA_DEBUG - if(testLookAhead(cbuf, above, jmatch)) { - return CCR_INTERNAL; - } -#endif /*COM_LA_DEBUG*/ - } - COMPROF_END(cmcQueMatchMove); - - codeWord = jmatch; - incr1byteFrags(recursLevel); - jmatchTotal += jmatch; - } - else if(oddByte == 0) { - /* - * 16-bit symbol is not in queue. 16 bits of ciphertext. - * Token bit is 1. - * - * queue[above...QLEN-1] move one element toward end - * queue[QLEN-1] discarded - * queue[above] = new codeword - * - * Note we skip this queue manipulation in the oddbyte case, since - * we don't really know (or care) if the current code word is in - * the queue or not. - */ -#if SKIP_NIBBLE_ON_QUEUE_0 - nibble = keynybble(cpriv->key, cpriv->keybytes, - (cbuf->nybbleDex)++); -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - - above = ABOVE(cbuf->f2) + nibble; - -#if COM_DEBUG - if(above > QLEN) { - printf("Hey Doug! above %d QLEN %d\n", above, QLEN); - return CCR_INTERNAL; - } -#endif - - laprintf(("...queue miss, adding 0x%x at 0x%x, deleting 0x%x\n", - codeWord, above, cbufq[QLEN-1])); - - if(cpriv->laEnable) { - markInQueue(cbuf, codeWord, 1); // new entry - markInQueue(cbuf, cbufq[QLEN-1], 0); // bumped out - } - - len = QLEN - 1 - (int)above; - if(len > QUEUE_MEMMOVE_THRESH) { - src = &cbufq[above]; - dst = src + 1; - len *= sizeof(queueElt); - memmove(dst, src, len); - } - else { - for(j=QLEN-1; j > above; j--) { - cbufq[j] = cbufq[j-1]; - } - } - - cbufq[above] = codeWord; - -#if COM_LA_DEBUG - if(testLookAhead(cbuf, above, 0)) { - return CCR_INTERNAL; - } -#endif /*COM_LA_DEBUG*/ - - COMPROF_END(cmcQueMissMove); - incr2byteFrags(recursLevel); - } - else { - /* - * Odd byte case, at least gather stats. - */ - incr2byteFrags(recursLevel); - - /* - * ...and keep this in sync for signature sequence - */ - above = 0; -#if SKIP_NIBBLE_ON_QUEUE_0 - nibble = (cbuf->nybbleDex)++; -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - } - - updateToken(tokenPtr, tokenDex, !match); - tokenDex++; - - if(match) { - *byteCodePtr++ = codeWord & 0xff; - numByteCodes++; - } - else { - serializeShort(codeWord, longCodePtr); - longCodePtr += 2; - numLongCodes++; - } - if(cpriv->sigSeqEnable) { - nextSigWord(cbuf, tokenDex, match, (above + nibble)); - } - } - -#if COM_DEBUG - if(numTokenBytes != ((tokenDex + 7) >> 3)) { - ddprintf(("comcryptBlock: numTokenBytes (%d), tokenDex (%d)\n", - numTokenBytes, tokenDex)); - } -#endif /*COM_DEBUG*/ - - /* - * We already wrote tokens and longcode to cipherText; verify we - * didn't overrun - */ - totalCipherTextLen = (unsigned)(longCodePtr - startCtextPtr); - if(*cipherTextLen < totalCipherTextLen) { - ddprintf(("comcryptBlock: short block (2)\n")); - return CCR_OUTBUFFER_TOO_SMALL; - } - if(!fullBlock) { - cipherText[CTBO_NUM_TOKENS] = tokenDex; - } - cipherText[CTBO_NUM_LONG_CODES] = numLongCodes; - -#if COM_DEBUG - if(tokenDex > MAX_TOKENS) { - ddprintf(("comcryptBlock: counter overflow!\n")); - return CCR_INTERNAL; - } - if((numByteCodes + numLongCodes) != tokenDex) { - ddprintf(("comcryptBlock: counter mismatch!\n")); - return CCR_INTERNAL; - } -#endif /*COM_DEBUG*/ - - /* - * See if doing a second level comcryption makes sense. - */ - destByteCodePtr = startLongCodePtr + (numLongCodes * 2); - if(numByteCodes > 0) { - jmatchAvg = jmatchTotal / numByteCodes; - } - else { - jmatchAvg = cbuf->jmatchThresh + 1; - } - if((recursLevel == 0) && // hard coded recursion limit - (cpriv->level2enable) && // enabled by caller - (numByteCodes >= cbuf->minByteCode) && // meaningful # of bytecodes - (jmatchAvg <= cbuf->jmatchThresh)) { // reasonable compression - // already achieved - - unsigned thisCtext = cbuf->level2BufSize; - - COMPROF_START; - crtn = comcryptBlock(cpriv, - cbuf->nextBuf, - cbuf->codeBuf, - numByteCodes, - cbuf->level2Buf, - &thisCtext, - recursLevel + 1); - if(crtn) { - return crtn; - } - - /* - * Write level2Buf to cipherText (as byteCodeArray). - * Size of 2nd level comcrypted byte code follows longcode array, - * then the bytecode itself. - * First bump totalCipherTextLen by the size of the comcrypted array - * plus one (for the size byte itself), and verify no overflow - */ - totalCipherTextLen += (thisCtext + 1); - if(*cipherTextLen < totalCipherTextLen) { - ddprintf(("comcryptBlock: short block (3)\n")); - return CCR_OUTBUFFER_TOO_SMALL; - } - *destByteCodePtr++ = thisCtext; - COMPROF_END(cmcLevel2); - memmove(destByteCodePtr, cbuf->level2Buf, thisCtext); - blockDesc |= CBD_DOUBLE; - - l2printf(("***2nd-level comcrypt: numByteCodes %d encrypted " - "size %d\n", numByteCodes, thisCtext)); - incrComStat(level2byteCode, numByteCodes); - incrComStat(level2cipherText, thisCtext); - incrComStat(level2jmatch, jmatchTotal); - incrComStat(level2blocks, 1); - } - else { - /* - * Normal one-level comcryption. Write byteCodes to ciphertext. - * numByteCodes is inferred. - */ - totalCipherTextLen += numByteCodes; - if(*cipherTextLen < totalCipherTextLen) { - ddprintf(("comcryptBlock: short block (3)\n")); - return CCR_OUTBUFFER_TOO_SMALL; - } - memmove(destByteCodePtr, cbuf->codeBuf, numByteCodes); - blockDesc |= CBD_SINGLE; - if(recursLevel == 0) { - incrComStat(level1blocks, 1); - } - /* else this is a 2nd-level, our caller will count */ - - /* - * obfuscate via sigArray (only when we're NOT doing 2nd level - * comcrypt) - */ - if(cpriv->sigSeqEnable) { - sigMunge(cbuf, startTokenPtr, tokenDex, - destByteCodePtr, startLongCodePtr); - - /* - * Prime sigArray state machine for next block. Note in the case - * of 2nd level, we skip this step, so the next block starts from - * the same state as this one did. - */ - cbuf->sigArray[0] = cbuf->sigArray[tokenDex]; - } - } - cipherText[CTBO_BLOCK_DESC] = blockDesc; - *cipherTextLen = totalCipherTextLen; - return CCR_SUCCESS; -} - -/* - * Main public encrypt function. - */ -comcryptReturn comcryptData( - comcryptObj cobj, - unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, // malloc'd by caller - unsigned *cipherTextLen, // IN/OUT - comcryptEos endOfStream) // CCE_END_OF_STREAM, etc. -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - unsigned ctextLen = *cipherTextLen; - comcryptReturn crtn; - unsigned thisPtext; - unsigned thisCtext; - COMPROF_LOCALS; - - COMPROF_START; - incrComStat(plaintextBytes, plainTextLen); - if(cpriv->versionBytes == 0) { - /* - * First, put header (version, spare) into head of ciphertext. - */ - if(ctextLen < CTEXT_HDR_SIZE) { - ddprintf(("comcryptData: overflow (0)\n")); - return CCR_OUTBUFFER_TOO_SMALL; - } - serializeInt(VERSION_3_Dec_97, cipherText); - cipherText += VERSION_BYTES; - cpriv->versionBytes = VERSION_BYTES; - serializeInt(0, cipherText); // spares - cipherText += SPARE_BYTES; - ctextLen -= CTEXT_HDR_SIZE; - } - - /* - * OK, grind it out, one block at a time. - */ - while (plainTextLen != 0) { - thisPtext = CC_BLOCK_SIZE; - if(thisPtext > plainTextLen) { - thisPtext = plainTextLen; - } - thisCtext = ctextLen; - crtn = comcryptBlock(cpriv, - &cpriv->cbuf, - plainText, - thisPtext, - cipherText, - &thisCtext, - 0); // recurs level - if(crtn) { - return crtn; - } - plainText += thisPtext; - plainTextLen -= thisPtext; - if(thisCtext > ctextLen) { - ddprintf(("comcryptData: undetected ciphertext overlow\n")); - return CCR_OUTBUFFER_TOO_SMALL; - } - cipherText += thisCtext; - ctextLen -= thisCtext; - } - *cipherTextLen = *cipherTextLen - ctextLen; - incrComStat(ciphertextBytes, *cipherTextLen); - COMPROF_END(cmcTotal); - return CCR_SUCCESS; -} - -/* - * Return values from deComcryptBlock(). - */ -typedef enum { - DCB_SUCCESS, // OK - DCB_SHORT, // incomplete block, try again with more ciphertext - DCB_PARSE_ERROR, // bad block - DCB_OUTBUFFER_TOO_SMALL -} dcbReturn; - -/* - * Assumes exactly one block of ciphertext, error otherwise. - */ -static dcbReturn deComcryptBlock( - comcryptPriv *cpriv, - comcryptBuf *cbuf, // not necessarily cpriv->cbuf - unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // IN/OUT - comcryptEos endOfStream, // CCE_END_OF_STREAM, etc. - unsigned *blockSize) // RETURNED on DCB_SUCCESS -{ - unsigned char *tokenPtr; - unsigned numTokenBits; // constant, from ciphertext - unsigned numTokenBytes; - unsigned char *longCodePtr; - unsigned numLongCodes; - unsigned char *byteCodePtr; - unsigned numByteCodes; - unsigned tokenDex; - unsigned oddByte = 0; - unsigned short codeWord; - unsigned char codeByte; - unsigned ptextLen = *plainTextLen; // bytes REMAINING - unsigned above; - unsigned j; - unsigned char blockDesc; - dcbReturn drtn; - int len; - queueElt *src; - queueElt *dst; - int lastWord = 0; - queueElt *cbufq = &cbuf->queue[0]; - int level2 = 0; // 2nd level comcrypted block - unsigned match; - unsigned char sigSeq; // signature sequence enable - unsigned char nibble; - - blockDesc = cipherText[CTBO_BLOCK_DESC]; - if((blockDesc & CBD_MAGIC_MASK) != CBD_MAGIC) { - ddprintf(("deComcryptBlock: bad CBD_MAGIC\n")); - return DCB_PARSE_ERROR; - } - - /* - * Min block size - blockDesc, numLongCodes, numTokens, one token byte, - * one bytecode - */ - if(cipherTextLen < 5) { - return DCB_SHORT; - } - if((blockDesc & CBD_FULL_BLOCK_MASK) == CBD_FULL_BLOCK) { - /* - * # of token bits implied for full block - */ - numTokenBits = TOKEN_BITS_FROM_PTEXT(CC_BLOCK_SIZE); - numTokenBytes = TOKEN_BYTES_FROM_PTEXT(CC_BLOCK_SIZE); - tokenPtr = cipherText + CTBO_NUM_TOKENS; - } - else { - numTokenBits = cipherText[CTBO_NUM_TOKENS]; - numTokenBytes = TOKEN_BYTES_FROM_TOKEN_BITS(numTokenBits); - tokenPtr = cipherText + CTBO_NUM_TOKENS + 1; - } - longCodePtr = tokenPtr + numTokenBytes; - numLongCodes = cipherText[CTBO_NUM_LONG_CODES]; - - byteCodePtr = longCodePtr + (numLongCodes * 2); // may increment... - if((blockDesc & CBD_BLOCK_TYPE_MASK) == CBD_SINGLE) { - /* - * # of bytecodes implied from numTokenBits and numLongCodes - */ - numByteCodes = numTokenBits - numLongCodes; - } - else { - /* - * size of 2nd level comcrypted bytecode specified after longCode - * array (and before the bytecode itself). - * Careful, verify that we can read numByteCodes first... - */ - if((unsigned)(byteCodePtr - cipherText) > cipherTextLen) { - return DCB_SHORT; - } - numByteCodes = *byteCodePtr++; - level2 = 1; - } - *blockSize = (unsigned)(byteCodePtr - cipherText) + numByteCodes; - if(*blockSize > cipherTextLen) { - return DCB_SHORT; - } - - /* - * We now know that we have a complete cipherblock. Go for it. - */ - if(level2) { - /* - * this block's bytecode array contains 2nd level comcrypted bytecodes. - */ - unsigned thisPtext = cbuf->level2BufSize; - unsigned level1CodeSize; - - if(cbuf->nextBuf == NULL) { - ddprintf(("2-level comcypt, no nextBuf available!\n")); - return DCB_PARSE_ERROR; - } - drtn = deComcryptBlock(cpriv, - cbuf->nextBuf, - byteCodePtr, - numByteCodes, - cbuf->level2Buf, - &thisPtext, - CCE_END_OF_STREAM, - &level1CodeSize); - switch(drtn) { - case DCB_SHORT: - ddprintf(("CBT_DOUBLE block, incomplete cipherblock in " - "2nd level code\n")); - return DCB_PARSE_ERROR; - - case DCB_OUTBUFFER_TOO_SMALL: // not our fault! - case DCB_PARSE_ERROR: - default: - ddprintf(("2nd-level decomcrypt error (%d)\n", drtn)); - return drtn; - - case DCB_SUCCESS: - /* - * Supposedly we passed in exactly one cipherblock... - */ - if(numByteCodes != level1CodeSize) { - ddprintf(("2nd-level decomcrypt: " - "numByteCodes != level1CodeSize\n")); - return DCB_PARSE_ERROR; - } - l2printf(("2nd-level decomcrypt: ciphertext %d " - "numByteCodes %d\n", numByteCodes, thisPtext)); - break; - } - byteCodePtr = cbuf->level2Buf; - numByteCodes = thisPtext; - } - - if((blockDesc & CBD_ODD_MASK) == CBD_ODD) { - oddByte = 1; - } - - /* - * Skip signature sequence if this was a 2nd level comcrypted block - */ - sigSeq = cpriv->sigSeqEnable && !level2; - - for(tokenDex=0; tokenDexkey, cpriv->keybytes, - (cbuf->nybbleDex)++); - - if(match) { - codeByte = *byteCodePtr++; - - if(sigSeq) { - codeByte ^= (unsigned char)(cbuf->sigArray[tokenDex]); - } - - /* - * dynamically process the queue for match - 8 bits - * of ciphercode, 16 bits of plaintext - */ - codeWord = cbufq[codeByte]; - above = (cbuf->f1 * codeByte * (16 + nibble)) >> 9; - -#if SKIP_NIBBLE_ON_QUEUE_0 - if(codeByte == 0) { - /* - * Special case for top of queue optimization during - * comcrypt - */ - nibble = cbuf->nybbleDex - 1; - } -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - - /* - * queue[above..codeByte] move one element towards end - * queue[above] = this codeWord - */ - len = (int)codeByte - (int)above; - if(len > QUEUE_MEMMOVE_THRESH) { - src = &cbufq[above]; - dst = src + 1; - len *= sizeof(queueElt); - memmove(dst, src, len); - } - else { - for(j = codeByte; j > above; j--) { - cbufq[j] = cbufq[j-1]; - } - } - cbufq[above] = codeWord; - } - else { - /* - * !match, 16 bits of code - */ - deserializeShort(codeWord, longCodePtr); - if(sigSeq) { - codeWord ^= cbuf->sigArray[tokenDex]; - } - - if(oddByte && (tokenDex == (numTokenBits - 1))) { - lastWord = 1; - above = 0; -#if SKIP_NIBBLE_ON_QUEUE_0 - nibble = cbuf->nybbleDex - 1; -#endif /*SKIP_NIBBLE_ON_QUEUE_0*/ - } - else { - longCodePtr += 2; - - /* - * dynamically process the queue for unmatch; skip if this - * is an oddByte codeword. - * queue[above...QLEN-1] move one element toward end - * queue[above] = new codeWord - */ - above = ABOVE(cbuf->f2) + nibble; - len = QLEN - 1 - (int)above; - if(len > QUEUE_MEMMOVE_THRESH) { - src = &cbufq[above]; - dst = src + 1; - len *= sizeof(queueElt); - memmove(dst, src, len); - } - else { - for(j=QLEN-1; j > above; j--) { - cbufq[j] = cbufq[j-1]; - } - } - cbufq[above] = codeWord; - } - } - - if(sigSeq) { - /* - * Advance signature sequence state machine. - */ - nextSigWord(cbuf, tokenDex+1, match, (above + nibble)); - } - - /* - * cook up a byte or two of plainText from code word and invmap[] - */ - if(ptextLen < 1) { - ddprintf(("decryptBlock: ptext overflow (1)\n")); - return DCB_OUTBUFFER_TOO_SMALL; - } - *plainText++ = cpriv->invmap[(codeWord >> 8) & 0xff]; - ptextLen--; - if(lastWord) { - /* - * end of oddByte block. - */ - tokenDex++; // for sigArray maintenance - break; // out of main loop - } - else { - if(ptextLen < 1) { - ddprintf(("decryptBlock: ptext overflow (2)\n")); - return DCB_OUTBUFFER_TOO_SMALL; - } - *plainText++ = cpriv->invmap[(codeWord) & 0xff]; - ptextLen--; - } - } - - /* - * Prime sigArray state machine for next block. - */ - if(sigSeq) { - cbuf->sigArray[0] = cbuf->sigArray[tokenDex]; - } - *plainTextLen = *plainTextLen - ptextLen; - return DCB_SUCCESS; -} - -comcryptReturn deComcryptData( - comcryptObj cobj, - unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // IN/OUT - comcryptEos endOfStream) // CCE_END_OF_STREAM, etc. - -{ - comcryptPriv *cpriv = (comcryptPriv *)cobj; - unsigned char *outorigin = plainText; - unsigned ptextLen = *plainTextLen; - unsigned thisPtext; // per block - unsigned blockSize; - dcbReturn drtn; - unsigned ctextUsed; - - /* - * Snag version from ciphertext, or as much as we can get - */ - while((cpriv->versionBytes < VERSION_BYTES) && cipherTextLen) { - cpriv->version <<= 8; - cpriv->version |= *cipherText; - cpriv->versionBytes++; - cipherText++; - cipherTextLen--; - } - - /* - * Then skip over the remainder of the header (currently spares) - */ - if((cpriv->spareBytes < SPARE_BYTES) && cipherTextLen) { - unsigned toSkip = SPARE_BYTES - cpriv->spareBytes; - - if(toSkip > cipherTextLen) { - toSkip = cipherTextLen; - } - cpriv->spareBytes += toSkip; - cipherText += toSkip; - cipherTextLen -= toSkip; - } - - if(cipherTextLen == 0) { - *plainTextLen = 0; - return CCR_SUCCESS; - } - - if(cpriv->version != VERSION_3_Dec_97) { - ddprintf(("Incompatible version.\n")); - return CCR_BAD_CIPHERTEXT; - } - - while(cipherTextLen != 0) { - - /* - * Main loop. First deal with possible existing partial block. - */ - if(cpriv->cbuf.codeBufLength != 0) { - unsigned toCopy = - cpriv->cbuf.codeBufSize - cpriv->cbuf.codeBufLength; - unsigned origBufSize = cpriv->cbuf.codeBufLength; - - if(toCopy > cipherTextLen) { - toCopy = cipherTextLen; - } - memmove(cpriv->cbuf.codeBuf + cpriv->cbuf.codeBufLength, - cipherText, toCopy); - cpriv->cbuf.codeBufLength += toCopy; - - thisPtext = ptextLen; - drtn = deComcryptBlock(cpriv, - &cpriv->cbuf, - cpriv->cbuf.codeBuf, - cpriv->cbuf.codeBufLength, - plainText, - &thisPtext, - endOfStream, - &blockSize); - switch(drtn) { - case DCB_SHORT: - /* - * Incomplete block in codeBuf - */ - if(endOfStream == CCE_END_OF_STREAM) { - /* - * Caller thinks this is the end, but we need more - */ - ddprintf(("deComcryptData(): CCE_END_OF_STREAM, " - "not end of block\n")); - return CCR_BAD_CIPHERTEXT; - } - cipherTextLen -= toCopy; - if(cipherTextLen != 0) { - /* - * i.e., codeBuf overflow - could be s/w error? Do - * we need a bigger buffer? - */ - ddprintf(("deComcryptData: full codeBuf, incomplete " - "block\n")); - return CCR_BAD_CIPHERTEXT; - } - else { - /* - * OK, stash it and try again - */ - scprintf(("====incomplete codeBuf, codeBufLength %d, " - "cipherTextLen %d\n", - cpriv->cbuf.codeBufLength, toCopy)); - break; // out of main loop (after this switch) - } - - case DCB_OUTBUFFER_TOO_SMALL: - ddprintf(("codeBuf decomcrypt error short buf\n")); - return CCR_OUTBUFFER_TOO_SMALL; - - case DCB_PARSE_ERROR: - default: - ddprintf(("codeBuf decomcrypt error (%d)\n", drtn)); - return CCR_BAD_CIPHERTEXT; - - case DCB_SUCCESS: - /* - * ctextUsed is how much of caller's ciphertext we used - * in this buffered block - */ - ctextUsed = blockSize - origBufSize; - scprintf(("====decrypted block in codeBuf, blockSize %d, " - "ctextUsed %d, thisPtext %d\n", - blockSize, ctextUsed, thisPtext)); - cipherText += ctextUsed; - cipherTextLen -= ctextUsed; - plainText += thisPtext; - ptextLen -= thisPtext; - cpriv->cbuf.codeBufLength = 0; - break; - } - - /* - * We might have used up all of caller's cipherText processing - * codeBuf... - */ - if(cipherTextLen == 0) { - break; // out of main loop - } - - } /* buffered ciphertext in codeBuf */ - - /* - * Snarf ciphertext, one block at a time. - */ - - thisPtext = ptextLen; - drtn = deComcryptBlock(cpriv, - &cpriv->cbuf, - cipherText, - cipherTextLen, - plainText, - &thisPtext, - endOfStream, - &blockSize); - switch(drtn) { - case DCB_SHORT: - /* - * Incomplete block - */ - if(endOfStream == CCE_END_OF_STREAM) { - ddprintf(("deComcryptData(): CCE_END_OF_STREAM, not end of " - "block (2)\n")); - return CCR_BAD_CIPHERTEXT; - } - if(cipherTextLen > - (cpriv->cbuf.codeBufSize - cpriv->cbuf.codeBufLength)) { - ddprintf(("deComcryptData(): codeBuf overflow!\n")); - return CCR_BAD_CIPHERTEXT; - } - memmove(cpriv->cbuf.codeBuf + cpriv->cbuf.codeBufLength, - cipherText, cipherTextLen); - cpriv->cbuf.codeBufLength += cipherTextLen; - cipherTextLen = 0; - scprintf(("====Incomplete block, cipherTextLen %d " - "codeBufLength %d\n", cipherTextLen, - cpriv->cbuf.codeBufLength)); - break; // actually out of main loop - - case DCB_PARSE_ERROR: - case DCB_OUTBUFFER_TOO_SMALL: - default: - return CCR_BAD_CIPHERTEXT; - - case DCB_SUCCESS: - if(ptextLen < thisPtext) { - /* - * Software error - */ - ddprintf(("deComcryptData: undetected ptext " - "overflow (2)\n")); - return CCR_BAD_CIPHERTEXT; - } - plainText += thisPtext; - ptextLen -= thisPtext; - cipherText += blockSize; - cipherTextLen -= blockSize; - scprintf(("====decrypted one block, blockSize %d " - "thisPtext %d\n", blockSize, thisPtext)); - break; - } - } /* main loop */ - - *plainTextLen = (unsigned)(plainText - outorigin); - return CCR_SUCCESS; -} diff --git a/OSX/include/security_comcryption/comcryption.h b/OSX/include/security_comcryption/comcryption.h deleted file mode 100644 index fd10934f..00000000 --- a/OSX/include/security_comcryption/comcryption.h +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 1997,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#ifndef _COMCRYPTION_H_ -#define _COMCRYPTION_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Return values. - */ -typedef enum { - CCR_SUCCESS = 0, // normal result - CCR_OUTBUFFER_TOO_SMALL, // caller needs to alloc more out buffer - CCR_MEMORY_ERROR, // internal error - CCR_WRONG_VERSION, // compatibility error - CCR_BAD_CIPHERTEXT, // can't decrypt ciphertext stream - CCR_INTERNAL // internal library error -} comcryptReturn; - -/* - * Used to specify optimization in ComcryptInit(). May be ignored in - * early implementation. - */ -typedef enum { - CCO_DEFAULT, // let the low-level code decide - CCO_SIZE, // optimize for max compression - CCO_SECURITY, // optimize for max crypto security - CCO_TIME, // optimize for minimum runtime; implies no - // second-level comcryption; security not - // compromised - CCO_TIME_SIZE, // minimum runtime with second-level - // comcryption enabled; implies loss of - // security - CCO_ASCII, // optimize for max compression for ASCII - // plaintext - CCO_OTHER // TBD -} comcryptOptimize; - -/* - * Used to specify operation type. - */ -typedef enum { - CCOP_COMCRYPT, - CCOP_DECOMCRYPT -} comcryptOp; - -/* - * Used to specify End of stream. - */ -typedef enum { - CCE_MORE_TO_COME, // more ops to follow - CCE_END_OF_STREAM // end of stream, close output strem -} comcryptEos; - -/* - * Maximum key length in bytes. - */ -#define COMCRYPT_MAX_KEYLENGTH 64 - -/* - * Clients can *optionally* register external memory alloc/free functions here. - */ -typedef void *(comMallocExternFcn)(unsigned size); -typedef void (comFreeExternFcn)(void *data); -void comMallocRegister(comMallocExternFcn *mallocExtern, - comFreeExternFcn *freeExtern); - -/* - * Opaque data type for ComCryptData() and DeComCryptData() - */ -typedef void *comcryptObj; - -/* - * Call once at startup. The resulting comcryptObj can be reused multiple - * times. - */ -comcryptObj comcryptAlloc(void); - -/* - * Use this before starting every stream process - */ -comcryptReturn comcryptInit( - comcryptObj cobj, - const unsigned char *key, - unsigned keyLen, - comcryptOptimize optimize); // CCO_SIZE, etc. - -/* - * Free a comcryptObj object obtained via comcryptAlloc() - */ -void comcryptObjFree(comcryptObj cobj); - -/* - * Return the maximum input buffer size allowed for for specified - * output buffer size. Note that for both comcrypt and decomcrypt, - * to cover the worst case, the output buffer always has to be - * larger that the input buffer. - */ -unsigned comcryptMaxInBufSize(comcryptObj cobj, - unsigned outBufSize, - comcryptOp op); // CCOP_COMCRYPT, etc. - -/* - * Return the maximum output buffer size for specified input buffer size. - * Output buffer size will always be larger than input buffer size. - */ -unsigned comcryptMaxOutBufSize(comcryptObj cobj, - unsigned inBufSize, - comcryptOp op, // CCOP_COMCRYPT, etc. - char final); // nonzero for last op - // only used for CCOP_DECOMCRYPT - -/* - * the one-function-fits-all comcrypt routine - - * call it multiple times for one ComcryptObj if - * you want, or just once to do a whole stream - * in one shot. - * - * NOTE: in the current implementation, the endOfStream is not used; - * no "final" call is necessary on comcryption. - */ -comcryptReturn comcryptData( - comcryptObj cobj, - unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, // malloc'd by caller - unsigned *cipherTextLen, // IN/OUT - comcryptEos endOfStream); // CCE_END_OF_STREAM, etc. - -/* - * decomcrypt routine - call it multiple times for - * one comcryptObj, or just once to do a whole stream - * in one shot. Boundaries of ciphertext segments - - * across calls to this function - are arbitrary. - * - * NOTE: in the current implementation, the final call to this (when - * endOfStrem == CCE_END_OF_STREAM) must contain a nonzero amount of - * ciphertext. - */ -comcryptReturn deComcryptData( - comcryptObj cobj, - unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // IN/OUT - comcryptEos endOfStream); // CCE_END_OF_STREAM, etc. - -#ifdef __cplusplus -} -#endif - -#endif /*_COMCRYPTION_H_*/ diff --git a/OSX/include/security_cryptkit b/OSX/include/security_cryptkit new file mode 120000 index 00000000..609dcc3b --- /dev/null +++ b/OSX/include/security_cryptkit @@ -0,0 +1 @@ +./libsecurity_cryptkit/lib \ No newline at end of file diff --git a/OSX/include/security_cryptkit/ByteRep.txt b/OSX/include/security_cryptkit/ByteRep.txt deleted file mode 100644 index 2ed46109..00000000 --- a/OSX/include/security_cryptkit/ByteRep.txt +++ /dev/null @@ -1,293 +0,0 @@ - FEE Portable Byte Representation of Public Key Strings and Signatures - Last Modified 15 March 2001 - -This defines portable data formats shared by the C and Java implementation of FEE. This definition supercedes formats used prior to 20 Feb 2001. - - -Primitive Data Types --------------------- - - int, unsigned int: - 4 bytes, M.S. byte first - - short, feeUnichar, Java char: - 2 bytes, M.S. byte first - - giant, GiantInteger: - - type contents comment - ------ -------- --------------------------------------- - int numBytes abs(numBytes) indicates size of n[] to - follow, in BYTES - sign of numBytes is sign bit of result - byte data n[0], MSB first for each element - - -Curve Parameters (curveParams, Java CurveParams) ------------------------------------------------- - - CURVE_PARAM_VERSION = 1: - - type contents - ------ -------- - int CURVE_PARAM_VERSION = 1 - int minVersion of code to parse this struct = 1 - unsigned q - int k - int spare - giant a - giant b - giant c - giant x1Plus - giant x1Minus - giant cOrderPlus - giant cOrderMinus - giant x1OrderPlus - giant x1OrderMinus - - The last four fields are not always known; a value of (giant)0 - indicates a "not known" condition. In this case, 4 bytes of - zero are written, indicating a giant with a length of zero. - - CURVE_PARAM_VERSION = 2 (20 Jan 1998) - - type contents - ------ -------- - int CURVE_PARAM_VERSION = 2 - int minVersion of code to parse this struct = 2 - byte primeType /* new for version 2 */ - unsigned q - int k - unsigned m /* new for version 2 */ - int spare - giant a - giant b - giant c - giant x1Plus - giant x1Minus - giant cOrderPlus - giant cOrderMinus - giant x1OrderPlus - giant x1OrderMinus - giant basePrime, if primeType == PT_GENERAL /* new */ - - Note that as of version 2, the cOrder* and x1Order* fields are always - known. - - CURVE_PARAM_VERSION = 3 (1 Sep 1998) - - type contents - ------ -------- - int CURVE_PARAM_VERSION = 3 - int minVersion of code to parse this struct = 3 - byte primeType - byte curveType /* new for version 3 */ - unsigned q - int k - unsigned m - int spare - giant a - giant b - giant c - giant x1Plus - giant x1Minus - giant cOrderPlus - giant cOrderMinus - giant x1OrderPlus - giant x1OrderMinus - giant basePrime, if primeType == PT_GENERAL - - -Public Key String ------------------ - - PUBLIC_KEY_STRING_VERSION = 3: - - A public key string is always encoded via enc64(); the raw data before - enc64() is as follows. - - type contents - ------ -------- - int PUBLIC_KEY_STRING_MAGIC (0xfeeddeef) - int PUBLIC_KEY_STRING_VERSION = 3 - int minVersion of code to parse this key = 3 - int spare - curveParams curve parameters - giant plusX (public key, plus curve) - giant minusX (public key, minus curve) - int usageName length in unichars - feeUnichar[] usageName as array of unichars - - PUBLIC_KEY_BLOB_VERSION = 4 (23 Mar 1998) - - New for version 4 - exported blobs for both public and private keys. - Public key strings are merely enc64() encoded versions of public - key blobs and are identical to PUBLIC_KEY_STRING_VERSION 3 public - key strings. - - PUBLIC_KEY_BLOB_MAGIC : 0xfeeddeef - public - 0xfeeddeed - private - minVersion : 3 for public, 4 for private - - type contents - ------ -------- - int PUBLIC_KEY_BLOB_MAGIC - int PUBLIC_KEY_BLOB_VERSION = 4 - int minVersion of code to parse this key = 3 or 4 - int spare - curveParams curve parameters - - public key blob: - giant plusX (public key, plus curve) - giant minusX (public key, minus curve) - private key blob: - int privDataLen - unsigned char privData[] - - both private and public: - - int usageName length in unichars - feeUnichar[] usageName as array of unichars - - PUBLIC_KEY_BLOB_VERSION = 5 (2 Sep 1998) - - Added plusY. - minVersion = 5. - - type contents - ------ -------- - int PUBLIC_KEY_BLOB_MAGIC_{PRIV,PUB} - int PUBLIC_KEY_BLOB_VERSION = 5 - int minVersion of code to parse this key = 5 - int spare - curveParams curve parameters - - public key blob: - giant plusX (public key, plus curve) - giant plusY (y-coord of public key, plus curve, may be zero) - giant minusX (public key, minus curve) - private key blob: - giant privGiant - - both private and public: - - int usageName length in unichars - feeUnichar[] usageName as array of unichars - - PUBLIC_KEY_BLOB_VERSION = 6 (14 Mar 2001) - - Deleted usageName. - - type contents - ------ -------- - int PUBLIC_KEY_BLOB_MAGIC_{PRIV,PUB} - int PUBLIC_KEY_BLOB_VERSION = 5 - int minVersion of code to parse this key = 5 - int spare - curveParams curve parameters - - public key blob: - giant plusX (public key, plus curve) - giant plusY (y-coord of public key, plus curve, may be zero) - giant minusX (public key, minus curve) - private key blob: - giant privGiant - - -Digital Signature, ElGamal style --------------------------------- - - type contents - ------ -------- - int FEE_SIG_MAGIC (0xfee00516) - int FEE_SIG_VERSION = 3 - int minVersion of code to parse this signature = 3 - int spare - int signer length in unichars (DELETED 2/20/01) - feeUnichar[] signer as array of unichars (DELETED 2/20/01) - giant u - giant Pm.x - - FEE_SIG_VERSION = 4 (15 March 2001) - Deleted signer. - - type contents - ------ -------- - int FEE_SIG_MAGIC (0xfee00516) - int FEE_SIG_VERSION = 4 - int minVersion of code to parse this signature = 4 - int spare - giant u - giant Pm.x - -Digital Signature, ECDSA style --------------------------------- - - type contents - ------ -------- - int FEE_ECDSA_MAGIC (0xfee00517) - int FEE_ECDSA_VERSION = 1 - int minVersion of code to parse this signature = 1 - int spare - int signer length in unichars (DELETED 2/20/01) - feeUnichar[] signer as array of unichars (DELETED 2/20/01) - giant s - giant x0 - - FEE_ECDSA_VERSION = 2 (15 March 2001) - Deleted signer. - - type contents - ------ -------- - int FEE_ECDSA_MAGIC (0xfee00517) - int FEE_ECDSA_VERSION = 2 - int minVersion of code to parse this signature = 2 - int spare - giant s - giant x0 - - - -FEED (2:1) CipherText ---------------------- - -This data type uses an optimized form of Giants in that the sign, and hence -the number of 16-bit shorts (i.e., the size of n[]), is implied by the size -of p used in encryption and decryption. For a given curve parameter q (as -in p = 2**q - k), the number of shorts per giant transmitted is ((q/8 + 1)/2). -As in normal giants, the n[] array is transmitted m.s. byte first. During -encoding, unused elements in n[] - i.e., those appearing after -n[abs(sign) - 1] - are zero. Upon decoding, the sign of an incoming n[] -array can be inferred from the number of non-zero shorts. - -One block of ciphertext is formatted as follows. See "Fast Elliptic -Encryption (FEE) Algorithms", by Richard E. Crandall, July 1996, for -descriptions of Xm, Xc, and g. - - type contents - --------------- ----------------- - optimized giant Xm - optimized giant Xc - byte g - - -FEED (1:1) CipherText ---------------------- - -The first cipherblock is a FEED(2:1) encrypted copy of the initial -R and S arrays; this is basically a bunch of random bytes which are -used to cook up the giants R and S at both encrypt and decrypt time. -In 1:1 FEED ciphertext, this is encrypted with the recipient's public -key; the result is padded out to one 1:1 FEED Cipherblock. - -Subsequent cipherblocks are: - - type contents - --------------- ----------------- - optimized giant Xm - byte clueByte - - clueByte contents: - bit 0 : 0 ==> minus - 1 ==> plus - bit 1 : 's' arg to elliptic_add() diff --git a/OSX/include/security_cryptkit/CipherFileDES.c b/OSX/include/security_cryptkit/CipherFileDES.c deleted file mode 100644 index f4554ea9..00000000 --- a/OSX/include/security_cryptkit/CipherFileDES.c +++ /dev/null @@ -1,586 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * CipherFileDES.c - DES-related cipherfile support - * - * Revision History - * ---------------- - * 24 Jun 97 at Apple - * Fixed memory leaks via sigData - * 18 Feb 97 at Apple - * Split off from feeCipherFile.c - */ - -#include "ckconfig.h" - -#if CRYPTKIT_CIPHERFILE_ENABLE - -#include "Crypt.h" -#include "CipherFileDES.h" -#include "falloc.h" -#include "feeDebug.h" -#include - -/* - * These functions are only called from feeCipherFile.c. - */ -feeReturn createRandDES(feePubKey sendPrivKey, // for sig only - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile) // RETURNED if successful -{ - feeRand frand = NULL; - feeReturn frtn; - unsigned char desKey[FEE_DES_MIN_STATE_SIZE]; - unsigned char *encrDesKey = NULL; // FEED encrypted desKey - unsigned encrDesKeyLen; - feeDES des = NULL; - feeFEEDExp feed = NULL; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - unsigned char *sigData = NULL; - unsigned sigDataLen = 0; - feeCipherFile cfile = NULL; - unsigned char *pubKeyString = NULL; // of sendPrivKey - unsigned pubKeyStringLen = 0; - - if(recvPubKey == NULL) { - return FR_BadPubKey; - } - - /* - * Cons up random DES key and a feeDES object with it - */ - frand = feeRandAlloc(); - if(frand == NULL) { - frtn = FR_Internal; - goto out; - } - feeRandBytes(frand, desKey, FEE_DES_MIN_STATE_SIZE); - des = feeDESNewWithState(desKey, FEE_DES_MIN_STATE_SIZE); - if(des == NULL) { - frtn = FR_Internal; - goto out; - } - - /* - * Encrypt the DES key via FEEDExp - */ - feed = feeFEEDExpNewWithPubKey(recvPubKey, NULL, NULL); - if(feed == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feeFEEDExpEncrypt(feed, - desKey, - FEE_DES_MIN_STATE_SIZE, - &encrDesKey, - &encrDesKeyLen); - if(frtn) { - goto out; - } - - /* - * Encrypt the plaintext via DES - */ - frtn = feeDESEncrypt(des, - plainText, - plainTextLen, - &cipherText, - &cipherTextLen); - if(frtn) { - goto out; - } - - if(genSig) { - /* - * We generate signature on ciphertext by convention. - */ - if(sendPrivKey == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feePubKeyCreateSignature(sendPrivKey, - cipherText, - cipherTextLen, - &sigData, - &sigDataLen); - if(frtn) { - goto out; - } - /* - * Sender's public key string - */ - frtn = feePubKeyCreateKeyString(sendPrivKey, - (char **)&pubKeyString, - &pubKeyStringLen); - if(frtn) { - /* - * Huh? - */ - frtn = FR_BadPubKey; - goto out; - } - } - - /* - * Cons up a cipherfile - */ - cfile = feeCFileNewFromCipherText(CFE_RandDES, - cipherText, - cipherTextLen, - pubKeyString, - pubKeyStringLen, - encrDesKey, - encrDesKeyLen, - sigData, - sigDataLen, - userData); - if(cfile == NULL) { - frtn = FR_Internal; - goto out; - } - -out: - /* free alloc'd stuff */ - - if(cipherText) { - ffree(cipherText); - } - if(feed) { - feeFEEDExpFree(feed); - } - if(frand) { - feeRandFree(frand); - } - if(des) { - feeDESFree(des); - } - if(sigData) { - ffree(sigData); - } - if(encrDesKey) { - ffree(encrDesKey); - } - if(pubKeyString) { - ffree(pubKeyString); - } - memset(desKey, 0, FEE_DES_MIN_STATE_SIZE); - *cipherFile = cfile; - return frtn; - -} - -feeReturn decryptRandDES(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, // optional - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus) // RETURNED -{ - feeReturn frtn = FR_Success; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - feeFEEDExp feed = NULL; // to decrypt desKey - feeDES des = NULL; // to decrypt cipherText - unsigned char *desKey; - unsigned desKeyLen; - unsigned char *encrDesKey = NULL; // FEED encrypted desKey - unsigned encrDesKeyLen; - unsigned char *sigData = NULL; - unsigned sigDataLen; - unsigned char *sendPubKeyStr = NULL; - unsigned sendPubKeyStrLen = 0; - feePubKey parsedSendPubKey = NULL; - - if(feeCFileEncrType(cipherFile) != CFE_RandDES) { - frtn = FR_Internal; - goto out; - } - - /* - * Get ciphertext and encrypted DES key from cipherFile - */ - cipherText = feeCFileCipherText(cipherFile, &cipherTextLen); - if(cipherText == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - encrDesKey = feeCFileOtherKeyData(cipherFile, &encrDesKeyLen); - if(encrDesKey == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - - /* - * FEED decrypt to get DES key - */ - feed = feeFEEDExpNewWithPubKey(recvPrivKey, NULL, NULL); - if(feed == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feeFEEDExpDecrypt(feed, - encrDesKey, - encrDesKeyLen, - &desKey, - &desKeyLen); - if(frtn) { - goto out; - } - - /* - * Now DES decrypt the ciphertext - */ - if(desKeyLen != FEE_DES_MIN_STATE_SIZE) { - frtn = FR_BadCipherFile; - goto out; - } - des = feeDESNewWithState(desKey, desKeyLen); - if(des == NULL) { - frtn = FR_Internal; - goto out; - } - frtn = feeDESDecrypt(des, - cipherText, - cipherTextLen, - plainText, - plainTextLen); - if(frtn) { - goto out; - } - - sigData = feeCFileSigData(cipherFile, &sigDataLen); - if(sigData) { - feeReturn sigFrtn; - - if(sendPubKey == NULL) { - /* - * Obtain sender's public key from cipherfile - */ - sendPubKeyStr = feeCFileSendPubKeyData(cipherFile, - &sendPubKeyStrLen); - if(sendPubKeyStr == NULL) { - /* - * Hmm..shouldn't really happen, but let's - * press on. - */ - *sigStatus = SS_PresentNoKey; - goto out; - } - parsedSendPubKey = feePubKeyAlloc(); - frtn = feePubKeyInitFromKeyString(parsedSendPubKey, - (char *)sendPubKeyStr, sendPubKeyStrLen); - if(frtn) { - dbgLog(("parseRandDES: bad sendPubKeyStr\n")); - *sigStatus = SS_PresentNoKey; - goto out; - } - sendPubKey = parsedSendPubKey; - } - sigFrtn = feePubKeyVerifySignature(sendPubKey, - cipherText, - cipherTextLen, - sigData, - sigDataLen); - switch(sigFrtn) { - case FR_Success: - *sigStatus = SS_PresentValid; - break; - default: - *sigStatus = SS_PresentInvalid; - break; - } - } - else { - *sigStatus = SS_NotPresent; - } -out: - if(cipherText) { - ffree(cipherText); - } - if(feed) { - feeFEEDExpFree(feed); - } - if(des) { - feeDESFree(des); - } - if(desKey) { - memset(desKey, 0, desKeyLen); - ffree(desKey); - } - if(encrDesKey) { - ffree(encrDesKey); - } - if(sigData) { - ffree(sigData); - } - if(parsedSendPubKey) { - feePubKeyFree(parsedSendPubKey); - } - if(sendPubKeyStr) { - ffree(sendPubKeyStr); - } - return frtn; -} - -feeReturn createPubDES(feePubKey sendPrivKey, // required - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile) // RETURNED if successful -{ - feeRand frand = NULL; - feeReturn frtn; - unsigned char *desKey; - unsigned desKeyLen; - feeDES des = NULL; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - unsigned char *sigData = NULL; - unsigned sigDataLen = 0; - feeCipherFile cfile = NULL; - unsigned char *pubKeyString = NULL; - unsigned pubKeyStringLen; - - if((sendPrivKey == NULL) || (recvPubKey == NULL)) { - return FR_BadPubKey; - } - - /* - * Get the public string version of sendPrivKey for embedding in - * cipherfile - */ - frtn = feePubKeyCreateKeyString(sendPrivKey, - (char **)&pubKeyString, - &pubKeyStringLen); - if(frtn) { - goto out; - } - - /* - * Obtain DES key via key exchange and get a feeDES object with it - */ - frtn = feePubKeyCreatePad(sendPrivKey, - recvPubKey, - &desKey, - &desKeyLen); - if(frtn) { - goto out; - } - des = feeDESNewWithState(desKey, desKeyLen); - if(des == NULL) { - frtn = FR_Internal; - goto out; - } - - /* - * Encrypt the plaintext via DES - */ - frtn = feeDESEncrypt(des, - plainText, - plainTextLen, - &cipherText, - &cipherTextLen); - if(frtn) { - goto out; - } - - if(genSig) { - /* - * We generate signature on ciphertext by convention. - */ - frtn = feePubKeyCreateSignature(sendPrivKey, - cipherText, - cipherTextLen, - &sigData, - &sigDataLen); - if(frtn) { - goto out; - } - } - - /* - * Cons up a cipherfile - */ - cfile = feeCFileNewFromCipherText(CFE_PublicDES, - cipherText, - cipherTextLen, - pubKeyString, - pubKeyStringLen, - NULL, // otherKey - 0, - sigData, - sigDataLen, - userData); - if(cfile == NULL) { - frtn = FR_Internal; - goto out; - } - -out: - /* free alloc'd stuff */ - - if(cipherText) { - ffree(cipherText); - } - if(frand) { - feeRandFree(frand); - } - if(des) { - feeDESFree(des); - } - if(desKey) { - ffree(desKey); - } - if(sigData) { - ffree(sigData); - } - if(pubKeyString) { - ffree(pubKeyString); - } - *cipherFile = cfile; - return frtn; - -} - -feeReturn decryptPubDES(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus) // RETURNED -{ - feeReturn frtn = FR_Success; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - feeDES des = NULL; // to decrypt cipherText - unsigned char *desKey; - unsigned desKeyLen; - unsigned char *sigData = NULL; - unsigned sigDataLen; - unsigned char *pubKeyString = NULL; - unsigned pubKeyStringLen; - feePubKey decryptPubKey = NULL; // from cipherfile - - if(feeCFileEncrType(cipherFile) != CFE_PublicDES) { - frtn = FR_Internal; - goto out; - } - - /* - * Get ciphertext and sender's public key from cipherFile - */ - cipherText = feeCFileCipherText(cipherFile, &cipherTextLen); - if(cipherText == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - pubKeyString = feeCFileSendPubKeyData(cipherFile, &pubKeyStringLen); - if(pubKeyString == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - decryptPubKey = feePubKeyAlloc(); - frtn = feePubKeyInitFromKeyString(decryptPubKey, - (char *)pubKeyString, - pubKeyStringLen); - if(frtn) { - goto out; - } - - /* - * key exchange to get DES key - */ - frtn = feePubKeyCreatePad(recvPrivKey, - decryptPubKey, - &desKey, - &desKeyLen); - if(frtn) { - goto out; - } - - /* - * Now DES decrypt the ciphertext - */ - if(desKeyLen < FEE_DES_MIN_STATE_SIZE) { - frtn = FR_BadCipherFile; - goto out; - } - des = feeDESNewWithState(desKey, desKeyLen); - if(des == NULL) { - frtn = FR_Internal; - goto out; - } - frtn = feeDESDecrypt(des, - cipherText, - cipherTextLen, - plainText, - plainTextLen); - if(frtn) { - goto out; - } - - sigData = feeCFileSigData(cipherFile, &sigDataLen); - if(sigData) { - feeReturn sigFrtn; - - if(sendPubKey == NULL) { - /* - * Use key embedded in cipherfile - */ - sendPubKey = decryptPubKey; - } - sigFrtn = feePubKeyVerifySignature(sendPubKey, - cipherText, - cipherTextLen, - sigData, - sigDataLen); - switch(sigFrtn) { - case FR_Success: - *sigStatus = SS_PresentValid; - break; - default: - *sigStatus = SS_PresentInvalid; - break; - } - } - else { - *sigStatus = SS_NotPresent; - } -out: - if(cipherText) { - ffree(cipherText); - } - if(des) { - feeDESFree(des); - } - if(desKey) { - ffree(desKey); - } - if(pubKeyString) { - ffree(pubKeyString); - } - if(sigData) { - ffree(sigData); - } - if(decryptPubKey) { - feePubKeyFree(decryptPubKey); - } - return frtn; -} - -#endif /* CRYPTKIT_CIPHERFILE_ENABLE */ - diff --git a/OSX/include/security_cryptkit/CipherFileDES.h b/OSX/include/security_cryptkit/CipherFileDES.h deleted file mode 100644 index 78139888..00000000 --- a/OSX/include/security_cryptkit/CipherFileDES.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * CipherFileDES.h - DES-related cipherfile support - * - * Revision History - * ---------------- - * 18 Feb 97 at Apple - * Created. - */ - -#ifndef _CK_CFILEDES_H_ -#define _CK_CFILEDES_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_CIPHERFILE_ENABLE - -#include "Crypt.h" -#include "feeCipherFile.h" -#include "CipherFileTypes.h" - -#ifdef __cplusplus -extern "C" { -#endif - -feeReturn createRandDES(feePubKey sendPrivKey, - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile); // RETURNED if successful -feeReturn decryptRandDES(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus); // RETURNED -feeReturn createPubDES(feePubKey sendPrivKey, // required - feePubKey recvPubKey, // required - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile); // RETURNED if successful -feeReturn decryptPubDES(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, // optional - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus); // RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_CIPHERFILE_ENABLE*/ - -#endif /*_CK_CFILEDES_H_*/ diff --git a/OSX/include/security_cryptkit/CipherFileFEED.c b/OSX/include/security_cryptkit/CipherFileFEED.c deleted file mode 100644 index ce9e075a..00000000 --- a/OSX/include/security_cryptkit/CipherFileFEED.c +++ /dev/null @@ -1,460 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * CipherFileFEED.c - FEED and FEEDExp related cipherfile support - * - * Revision History - * ---------------- - * 24 Jun 97 at Apple - * Fixed memory leaks via sigData - * 18 Feb 97 at Apple - * Split off from feeCipherFile.c - */ - -#include "ckconfig.h" - -#if CRYPTKIT_CIPHERFILE_ENABLE - -#include "Crypt.h" -#include "CipherFileFEED.h" -#include "falloc.h" -#include "feeDebug.h" - -feeReturn createFEED(feePubKey sendPrivKey, // required - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile) // RETURNED if successful -{ - feeReturn frtn; - feeFEED feed = NULL; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - unsigned char *sigData = NULL; - unsigned sigDataLen = 0; - feeCipherFile cfile = NULL; - unsigned char *pubKeyString = NULL; // of sendPrivKey - unsigned pubKeyStringLen = 0; - - if((sendPrivKey == NULL) || (recvPubKey == NULL)) { - return FR_BadPubKey; - } - - /* - * FEED encrypt plaintext - */ - feed = feeFEEDNewWithPubKey(sendPrivKey, recvPubKey, FF_ENCRYPT, NULL, NULL); - if(feed == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feeFEEDEncrypt(feed, - plainText, - plainTextLen, - &cipherText, - &cipherTextLen); - if(frtn) { - goto out; - } - - /* - * Sender's public key string - */ - frtn = feePubKeyCreateKeyString(sendPrivKey, - (char **)&pubKeyString, - &pubKeyStringLen); - if(frtn) { - /* - * Huh? - */ - frtn = FR_BadPubKey; - goto out; - } - - if(genSig) { - /* - * We generate signature on ciphertext by convention. - */ - frtn = feePubKeyCreateSignature(sendPrivKey, - cipherText, - cipherTextLen, - &sigData, - &sigDataLen); - if(frtn) { - goto out; - } - } - - /* - * Cons up a cipherfile - */ - cfile = feeCFileNewFromCipherText(CFE_FEED, - cipherText, - cipherTextLen, - pubKeyString, - pubKeyStringLen, - NULL, - 0, - sigData, - sigDataLen, - userData); - if(cfile == NULL) { - frtn = FR_Internal; - goto out; - } - -out: - /* free alloc'd stuff */ - - if(cipherText) { - ffree(cipherText); - } - if(feed) { - feeFEEDFree(feed); - } - if(pubKeyString) { - ffree(pubKeyString); - } - if(sigData) { - ffree(sigData); - } - *cipherFile = cfile; - return frtn; - -} - -feeReturn decryptFEED(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, // optional - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus) // RETURNED -{ - feeReturn frtn = FR_Success; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - feeFEED feed = NULL; - unsigned char *sigData = NULL; - unsigned sigDataLen; - unsigned char *sendPubKeyStr = NULL; - unsigned sendPubKeyStrLen = 0; - feePubKey parsedSendPubKey = NULL; - - if(feeCFileEncrType(cipherFile) != CFE_FEED) { - frtn = FR_Internal; - goto out; - } -//printf("decryptFEED\n"); -//printf("privKey:\n"); printPubKey(recvPrivKey); -//printf("pubKey:\n"); printPubKey(sendPubKey); - /* - * Get ciphertext and sender's public key from cipherFile - */ - cipherText = feeCFileCipherText(cipherFile, &cipherTextLen); - if(cipherText == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - sendPubKeyStr = feeCFileSendPubKeyData(cipherFile, &sendPubKeyStrLen); - if(sendPubKeyStr == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - parsedSendPubKey = feePubKeyAlloc(); - frtn = feePubKeyInitFromKeyString(parsedSendPubKey, - (char *)sendPubKeyStr, - sendPubKeyStrLen); - if(frtn) { - frtn = FR_BadCipherFile; - goto out; - } -//printf("parsedSendPubKey:\n"); printPubKey(parsedSendPubKey); - - /* - * FEED decrypt - */ - feed = feeFEEDNewWithPubKey(recvPrivKey, parsedSendPubKey, FF_DECRYPT, NULL, NULL); - if(feed == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feeFEEDDecrypt(feed, - cipherText, - cipherTextLen, - plainText, - plainTextLen); - if(frtn) { - goto out; - } - - sigData = feeCFileSigData(cipherFile, &sigDataLen); - if(sigData) { - feeReturn sigFrtn; - - if(sendPubKey == NULL) { - /* - * use embedded sender's public key - */ - sendPubKey = parsedSendPubKey; - } - sigFrtn = feePubKeyVerifySignature(sendPubKey, - cipherText, - cipherTextLen, - sigData, - sigDataLen); - switch(sigFrtn) { - case FR_Success: - *sigStatus = SS_PresentValid; - break; - default: - *sigStatus = SS_PresentInvalid; - break; - } - } - else { - *sigStatus = SS_NotPresent; - } -out: - if(cipherText) { - ffree(cipherText); - } - if(feed) { - feeFEEDFree(feed); - } - if(sigData) { - ffree(sigData); - } - if(parsedSendPubKey) { - feePubKeyFree(parsedSendPubKey); - } - if(sendPubKeyStr) { - ffree(sendPubKeyStr); - } - return frtn; -} - -feeReturn createFEEDExp(feePubKey sendPrivKey, // for sig only - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile) // RETURNED if successful -{ - feeReturn frtn; - feeFEEDExp feed = NULL; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - unsigned char *sigData = NULL; - unsigned sigDataLen = 0; - feeCipherFile cfile = NULL; - unsigned char *pubKeyString = NULL; // of sendPrivKey, for sig - unsigned pubKeyStringLen = 0; - - if(recvPubKey == NULL) { - return FR_BadPubKey; - } - - /* - * FEEDExp encrypt plaintext - */ - feed = feeFEEDExpNewWithPubKey(recvPubKey, NULL, NULL); - if(feed == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feeFEEDExpEncrypt(feed, - plainText, - plainTextLen, - &cipherText, - &cipherTextLen); - if(frtn) { - goto out; - } - - if(genSig) { - if(sendPrivKey == NULL) { - frtn = FR_IllegalArg; - goto out; - } - /* - * We generate signature on ciphertext by convention. - */ - frtn = feePubKeyCreateSignature(sendPrivKey, - cipherText, - cipherTextLen, - &sigData, - &sigDataLen); - if(frtn) { - goto out; - } - /* - * Sender's public key string - */ - frtn = feePubKeyCreateKeyString(sendPrivKey, - (char **)&pubKeyString, - &pubKeyStringLen); - if(frtn) { - /* - * Huh? - */ - frtn = FR_BadPubKey; - goto out; - } - } - - /* - * Cons up a cipherfile - */ - cfile = feeCFileNewFromCipherText(CFE_FEEDExp, - cipherText, - cipherTextLen, - pubKeyString, - pubKeyStringLen, - NULL, - 0, - sigData, - sigDataLen, - userData); - if(cfile == NULL) { - frtn = FR_Internal; - goto out; - } - -out: - /* free alloc'd stuff */ - - if(cipherText) { - ffree(cipherText); - } - if(feed) { - feeFEEDExpFree(feed); - } - if(sigData) { - ffree(sigData); - } - if(pubKeyString) { - ffree(pubKeyString); - } - *cipherFile = cfile; - return frtn; - -} - -feeReturn decryptFEEDExp(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, // optional - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus) // RETURNED -{ - feeReturn frtn = FR_Success; - unsigned char *cipherText = NULL; - unsigned cipherTextLen; - feeFEEDExp feed = NULL; - unsigned char *sigData = NULL; - unsigned sigDataLen; - unsigned char *sendPubKeyStr = NULL; - unsigned sendPubKeyStrLen = 0; - feePubKey parsedSendPubKey = NULL; - - if(feeCFileEncrType(cipherFile) != CFE_FEEDExp) { - frtn = FR_Internal; - goto out; - } - - /* - * Get ciphertext from cipherFile - */ - cipherText = feeCFileCipherText(cipherFile, &cipherTextLen); - if(cipherText == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - - /* - * FEEDExp decrypt - */ - feed = feeFEEDExpNewWithPubKey(recvPrivKey, NULL, NULL); - if(feed == NULL) { - frtn = FR_BadPubKey; - goto out; - } - frtn = feeFEEDExpDecrypt(feed, - cipherText, - cipherTextLen, - plainText, - plainTextLen); - if(frtn) { - goto out; - } - - sigData = feeCFileSigData(cipherFile, &sigDataLen); - if(sigData) { - feeReturn sigFrtn; - - if(sendPubKey == NULL) { - /* - * use embedded sender's public key - */ - sendPubKeyStr = feeCFileSendPubKeyData(cipherFile, - &sendPubKeyStrLen); - if(sendPubKeyStr == NULL) { - frtn = FR_BadCipherFile; - goto out; - } - parsedSendPubKey = feePubKeyAlloc(); - frtn = feePubKeyInitFromKeyString(parsedSendPubKey, - (char *)sendPubKeyStr, sendPubKeyStrLen); - if(frtn) { - frtn = FR_BadCipherFile; - goto out; - } - sendPubKey = parsedSendPubKey; - } - sigFrtn = feePubKeyVerifySignature(sendPubKey, - cipherText, - cipherTextLen, - sigData, - sigDataLen); - switch(sigFrtn) { - case FR_Success: - *sigStatus = SS_PresentValid; - break; - default: - *sigStatus = SS_PresentInvalid; - break; - } - } - else { - *sigStatus = SS_NotPresent; - } -out: - if(cipherText) { - ffree(cipherText); - } - if(feed) { - feeFEEDExpFree(feed); - } - if(sigData) { - ffree(sigData); - } - if(parsedSendPubKey) { - feePubKeyFree(parsedSendPubKey); - } - if(sendPubKeyStr) { - ffree(sendPubKeyStr); - } - return frtn; -} - -#endif /* CRYPTKIT_CIPHERFILE_ENABLE */ diff --git a/OSX/include/security_cryptkit/CipherFileFEED.h b/OSX/include/security_cryptkit/CipherFileFEED.h deleted file mode 100644 index 5e6890bc..00000000 --- a/OSX/include/security_cryptkit/CipherFileFEED.h +++ /dev/null @@ -1,69 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * CipherFileFEED.h - FEED and FEEDExp related cipherfile support - * - * Revision History - * ---------------- - * 18 Feb 97 at Apple - * Created. - */ - -#ifndef _CK_CFILEFEED_H_ -#define _CK_CFILEFEED_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_CIPHERFILE_ENABLE - -#include "Crypt.h" -#include "feeCipherFile.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Private functions. - */ -feeReturn createFEED(feePubKey sendPrivKey, - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile); // RETURNED if successful -feeReturn decryptFEED(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus); // RETURNED -feeReturn createFEEDExp(feePubKey sendPrivKey, - feePubKey recvPubKey, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - unsigned userData, // for caller's convenience - feeCipherFile *cipherFile); // RETURNED if successful -feeReturn decryptFEEDExp(feeCipherFile cipherFile, - feePubKey recvPrivKey, - feePubKey sendPubKey, // optional - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus); // RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_CIPHERFILE_ENABLE */ - -#endif /*_CK_CFILEFEED_H_*/ diff --git a/OSX/include/security_cryptkit/CipherFileTypes.h b/OSX/include/security_cryptkit/CipherFileTypes.h deleted file mode 100644 index e0307dc9..00000000 --- a/OSX/include/security_cryptkit/CipherFileTypes.h +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * CipherFileTypes.h - * - * Revision History - * ---------------- - * 8/24/98 ap - * Added tags around #endif comment. - * 19 Feb 97 at NeXT - * Created. - */ - -#ifndef _CK_CFILETYPES_H_ -#define _CK_CFILETYPES_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_CIPHERFILE_ENABLE - -#include "feeCipherFile.h" - -/* - * Type of encryption used in a CipherFile. - */ -typedef enum { - - /* - * DES encryption using pad created via public key exchange; sender's - * public key is embedded. - */ - CFE_PublicDES = 1, - - /* - * Random DES key used for encryption. The DES key is encrypted via - * FEEDExp using recipient's public key; the result is embedded in the - * CipherFile. Sender's public key is embedded only if - * signature is generated. - */ - CFE_RandDES = 2, - - /* - * 1:1 FEED encryption. Sender's public key is embedded. - */ - CFE_FEED = 3, - - /* - * 2:1 FEED encryption. Sender's public key is embedded only if signature - * is generated. - */ - CFE_FEEDExp = 4, - - /* - * User-defined cipherfile. - */ - CFE_Other = 5 - -} cipherFileEncrType; - - -/* - * Signature status upon decryption of a CipherFile. - */ -typedef enum { - - SS_NotPresent = 0, // Signature not present. - SS_PresentValid = 1, // Signature present and valid. - SS_PresentNoKey = 2, // Signature present, but no public key - // available to validate it. - SS_PresentInvalid = 3 // Signature present and invalid. - -} feeSigStatus; - -#endif /* CRYPTKIT_CIPHERFILE_ENABLE */ - -#endif /* _CK_CFILETYPES_H_ */ diff --git a/OSX/include/security_cryptkit/Crypt.h b/OSX/include/security_cryptkit/Crypt.h deleted file mode 100644 index 29a47d58..00000000 --- a/OSX/include/security_cryptkit/Crypt.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * Crypt.h - top-level header for FEE library. - * - * Revision History - * ---------------- - * 8/24/98 ap - * Added tags around #endif comment. - * 28 May 1996 at Apple - * Added falloc.h, newly exported API. - * 27 Aug 1996 at NeXT - * Created. - */ - -#ifndef _CK_CRYPT_H_ -#define _CK_CRYPT_H_ - -#ifdef macintosh - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#else - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif - -#endif /* _CK_CRYPT_H_ */ diff --git a/OSX/include/security_cryptkit/CryptKit.def b/OSX/include/security_cryptkit/CryptKit.def deleted file mode 100644 index b4a73bb4..00000000 --- a/OSX/include/security_cryptkit/CryptKit.def +++ /dev/null @@ -1,113 +0,0 @@ -LIBRARY CryptKit.dll - -EXPORTS - - feePubKeyAlloc - feePubKeyFree - feePubKeyInitFromPrivData - feePubKeyInitFromKey - feePubKeyInitFromKeyString - feePubKeyCreateKeyString - feePubKeyIsEqual - feePubKeyCreatePad - feePubKeyCreateSignature - feePubKeyVerifySignature - feePubKeyUsageName - feePubKeyAlgorithmName - feePubKeyBitsize - feeDESNewWithState - feeDESFree - feeDESSetState - feeDESSetBlockMode - feeDESSetChainMode - feeDESPlainBlockSize - feeDESCipherBlockSize - feeDESCipherBufSize - - feeDESCipherTextSize - - feeDESEncryptBlock - feeDESDecryptBlock - feeDESEncrypt - feeDESDecrypt - feeSigNewWithKey - feeSigFree - feeSigPm - feeSigSign - feeSigData - feeSigParse - feeSigVerify - feeSigSigner - feeHashAlloc - feeHashReinit - feeHashFree - feeHashAddData - feeHashDigest - feeHashDigestLen - feeRandAllocWithSeed - feeRandAlloc - feeRandFree - feeRandNextNum - feeRandBytes - feeReturnString - feeFEEDNewWithPubKey - feeFEEDFree - feeFEEDPlainBlockSize - feeFEEDCipherBlockSize - feeFEEDCipherBufSize - - feeFEEDCipherTextSize - feeFEEDEncryptBlock - feeFEEDDecryptBlock - feeFEEDEncrypt - feeFEEDDecrypt - - feeFEEDExpNewWithPubKey - - feeFEEDExpFree - - feeFEEDExpPlainBlockSize - - feeFEEDExpCipherBlockSize - - feeFEEDExpCipherBufSize - - feeFEEDExpCipherTextSize - - feeFEEDExpEncryptBlock - - feeFEEDExpDecryptBlock - - feeFEEDExpEncrypt - - feeFEEDExpDecrypt - dec64 - enc64 - isValidEnc64 - feeCFileNewFromCipherText - feeCFileDataRepresentation - feeCFileNewFromDataRep - feeCFileFree - feeCFileEncrType - feeCFileCipherText - feeCFileSendPubKeyData - feeCFileOtherKeyData - feeCFileSigData - parseCipherFile - - createCipherFile - fmalloc - fmallocWithData - ffree - - .objc_class_name_NSFEEPublicKey CONSTANT - - .objc_category_name_NSFEEPublicKey_Private CONSTANT - - .objc_class_name_NSRandomNumberGenerator CONSTANT - - .objc_class_name_NSDESCryptor CONSTANT - - .objc_class_name_NSCipherFile CONSTANT - - diff --git a/OSX/include/security_cryptkit/CryptKit.h b/OSX/include/security_cryptkit/CryptKit.h deleted file mode 100644 index 6c6f2bc5..00000000 --- a/OSX/include/security_cryptkit/CryptKit.h +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * CryptKit.h created by blaine on Thu 22-Feb-1996 - */ - -// Encryption related protocols and types -#include -#include - -// Classes -#include -#include -#include -#include -#include - -// Misc. Functions -#include -#include -#include diff --git a/OSX/include/security_cryptkit/CryptKitAsn1.cpp b/OSX/include/security_cryptkit/CryptKitAsn1.cpp deleted file mode 100644 index d67478b2..00000000 --- a/OSX/include/security_cryptkit/CryptKitAsn1.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * CryptKitAsn1.cpp - ASN1 templates for FEE keys and signatures - */ - -#include "CryptKitAsn1.h" -#include - -/* - * Unlike RSA, DSA, and Diffie-Hellman, the integers in these - * objects are indeed signed. - */ -#define SEC_ASN1_SIGNED (SEC_ASN1_SIGNED_INT | SEC_ASN1_INTEGER) - -/* FEECurveParametersASN1 */ -const SecAsn1Template FEECurveParametersASN1Template[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(FEECurveParametersASN1) }, - { SEC_ASN1_INTEGER, offsetof(FEECurveParametersASN1,primeType) }, - { SEC_ASN1_INTEGER, offsetof(FEECurveParametersASN1,curveType) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,q) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,k) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,m) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,a) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,b_) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,c) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,x1Plus) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,x1Minus) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,cOrderPlus) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,cOrderMinus) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,x1OrderPlus) }, - { SEC_ASN1_SIGNED, offsetof(FEECurveParametersASN1,x1OrderMinus) }, - { SEC_ASN1_SIGNED | SEC_ASN1_OPTIONAL, - offsetof(FEECurveParametersASN1,basePrime) }, - { 0, } -}; - -/* FEEElGamalSignatureASN1 */ -const SecAsn1Template FEEElGamalSignatureASN1Template[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(FEEElGamalSignatureASN1) }, - { SEC_ASN1_SIGNED, offsetof(FEEElGamalSignatureASN1,u) }, - { SEC_ASN1_SIGNED, offsetof(FEEElGamalSignatureASN1,pmX) }, - { 0, } -}; - -/* FEEECDSASignatureASN1 */ -const SecAsn1Template FEEECDSASignatureASN1Template[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(FEEECDSASignatureASN1) }, - { SEC_ASN1_SIGNED, offsetof(FEEECDSASignatureASN1,c) }, - { SEC_ASN1_SIGNED, offsetof(FEEECDSASignatureASN1,d) }, - { 0, } -}; - -/* FEEPublicKeyASN1 */ -const SecAsn1Template FEEPublicKeyASN1Template[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(FEEPublicKeyASN1) }, - { SEC_ASN1_SIGNED, offsetof(FEEPublicKeyASN1,version) }, - { SEC_ASN1_INLINE, - offsetof(FEEPublicKeyASN1,curveParams), - FEECurveParametersASN1Template }, - { SEC_ASN1_SIGNED, offsetof(FEEPublicKeyASN1,plusX) }, - { SEC_ASN1_SIGNED, offsetof(FEEPublicKeyASN1,minusX) }, - { SEC_ASN1_SIGNED | SEC_ASN1_OPTIONAL, - offsetof(FEEPublicKeyASN1,plusY) }, - { 0, } -}; - -/* FEEPrivateKeyASN1 */ -const SecAsn1Template FEEPrivateKeyASN1Template[] = { - { SEC_ASN1_SEQUENCE, - 0, NULL, sizeof(FEEPrivateKeyASN1) }, - { SEC_ASN1_SIGNED, offsetof(FEEPrivateKeyASN1,version) }, - { SEC_ASN1_INLINE, - offsetof(FEEPrivateKeyASN1,curveParams), - FEECurveParametersASN1Template }, - { SEC_ASN1_SIGNED, offsetof(FEEPrivateKeyASN1,privData) }, - { 0, } -}; - - diff --git a/OSX/include/security_cryptkit/CryptKitAsn1.h b/OSX/include/security_cryptkit/CryptKitAsn1.h deleted file mode 100644 index a4bfc299..00000000 --- a/OSX/include/security_cryptkit/CryptKitAsn1.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * CryptKitAsn1.h - ASN1 templates for FEE objects - */ - -#ifndef _CRYPT_KIT_ASN1_H_ -#define _CRYPT_KIT_ASN1_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_DER_ENABLE - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - -- FEE Curve parameters (defined in ) - FEEPrimeType ::= INTEGER { FPT_Mersenne(0), FPT_FEE(1), FPT_General(2) } - FEECurveType ::= INTEGER { FCT_Montgomery(0), FCT_Weierstrass(1), - FCT_General(2) } - */ - -/* - FEECurveParameters ::= SEQUENCE - { - primeType FEEPrimeType, - curveType FEECurveType, - q INTEGER, -- unsigned - k INTEGER, -- signed - m INTEGER, - a BigIntegerStr, - bb BigIntegerStr, -- can't use variable/field b - c BigIntegerStr, - x1Plus BigIntegerStr, - x1Minus BigIntegerStr, - cOrderPlus BigIntegerStr, - cOrderMinus BigIntegerStr, - x1OrderPlus BigIntegerStr, - x1OrderMinus BigIntegerStr, - basePrime BigIntegerStr OPTIONAL - -- iff FEEPrimeType == CT_GENERAL -} -*/ -typedef struct { - CSSM_DATA primeType; - CSSM_DATA curveType; - CSSM_DATA q; - CSSM_DATA k; - CSSM_DATA m; - CSSM_DATA a; - CSSM_DATA b_; // can't use variable/field b - CSSM_DATA c; - CSSM_DATA x1Plus; - CSSM_DATA x1Minus; - CSSM_DATA cOrderPlus; - CSSM_DATA cOrderMinus; - CSSM_DATA x1OrderPlus; - CSSM_DATA x1OrderMinus; - CSSM_DATA basePrime; // OPTIONAL -} FEECurveParametersASN1; - -extern const SecAsn1Template FEECurveParametersASN1Template[]; - -/* - -- FEE ElGamal-style signature - FEEElGamalSignature ::= SEQUENCE { - u BigIntegerStr, - pmX BigIntegerStr - } -*/ -typedef struct { - CSSM_DATA u; - CSSM_DATA pmX; -} FEEElGamalSignatureASN1; - -extern const SecAsn1Template FEEElGamalSignatureASN1Template[]; - -/* - -- FEE ECDSA-style signature - FEEECDSASignature ::= SEQUENCE { - c BigIntegerStr, - d BigIntegerStr - } -*/ -typedef struct { - CSSM_DATA c; - CSSM_DATA d; -} FEEECDSASignatureASN1; - -extern const SecAsn1Template FEEECDSASignatureASN1Template[]; - -/* - FEEPublicKey ::= SEQUENCE - { - version INTEGER, - curveParams FEECurveParameters, - plusX BigIntegerStr, - minusX BigIntegerStr, - plusY BigIntegerStr OPTIONAL - -- iff FEECurveType == ct-weierstrass -} -*/ -typedef struct { - CSSM_DATA version; - FEECurveParametersASN1 curveParams; - CSSM_DATA plusX; - CSSM_DATA minusX; - CSSM_DATA plusY; // OPTIONAL -} FEEPublicKeyASN1; - -extern const SecAsn1Template FEEPublicKeyASN1Template[]; - -/* - FEEPrivateKey ::= SEQUENCE - { - version INTEGER, - curveParams FEECurveParameters, - privData BigIntegerStr - } -*/ -typedef struct { - CSSM_DATA version; - FEECurveParametersASN1 curveParams; - CSSM_DATA privData; -} FEEPrivateKeyASN1; - -extern const SecAsn1Template FEEPrivateKeyASN1Template[]; - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_DER_ENABLE */ - -#endif /* _CRYPT_KIT_ASN1_H_ */ diff --git a/OSX/include/security_cryptkit/CryptKitDER.cpp b/OSX/include/security_cryptkit/CryptKitDER.cpp deleted file mode 100644 index f8cabe31..00000000 --- a/OSX/include/security_cryptkit/CryptKitDER.cpp +++ /dev/null @@ -1,1244 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -/* - * CryptKitDER.h - snacc-based routines to create and parse DER-encoded FEE - * keys and signatures - * - */ - -#include "ckconfig.h" - -#if CRYPTKIT_DER_ENABLE - -#include -#include -#include -#include -#include -#include "CryptKitAsn1.h" -#include -#include -#include -#include -#include - -#define PRINT_SIG_GIANTS 0 -#define PRINT_CURVE_PARAMS 0 -#define PRINT_SIZES 0 -#if PRINT_SIZES -#define szprint(s) printf s -#else -#define szprint(s) -#endif - -/* - * Trivial exception class associated with a feeReturn. - */ -class feeException -{ -protected: - feeException(feeReturn frtn, const char *op); -public: - ~feeException() throw() {} - feeReturn frtn() const throw() { return mFrtn; } - static void throwMe(feeReturn frtn, const char *op = NULL) __attribute__((noreturn)); -private: - feeReturn mFrtn; -}; - -feeException::feeException( - feeReturn frtn, - const char *op) - : mFrtn(frtn) -{ - if(op) { - dbgLog(("%s: %s\n", op, feeReturnString(frtn))); - } -} - -void feeException::throwMe(feeReturn frtn, const char *op /*= NULL*/) { throw feeException(frtn, op); } - -/* - * ASN1 encoding rules specify that an integer's sign is indicated by the MSB - * of the first (MS) content byte. For a non-negative number, if the MSB of - * the MS byte (of the unencoded number) is one, then the encoding starts with - * a byte of zeroes to indicate positive sign. For a negative number, the first - * nine bits can not be all 1 - if they are (in the undecoded number), leading - * bytes of 0xff are trimmed off until the first nine bits are something other - * than one. Also, the first nine bits of the encoded number can not all be - * zero. - * - * CryptKit giants express their sign as part of the giantstruct.sign field. - * The giantDigit array (giantstruct.n[]) is stored l.s. digit first. - * - * These routines are independent of platform, endianness, and giatn digit size. - */ - -/* routines to guess maximum size of DER-encoded objects */ -static unsigned feeSizeOfSnaccGiant( - giant g) -{ - unsigned rtn = abs(g->sign) * GIANT_BYTES_PER_DIGIT; - szprint(("feeSizeOfSnaccGiant: sign %d size %d\n", g->sign, rtn + 4)); - return rtn + 4; -} - -/* PUBLIC... */ -unsigned feeSizeOfDERSig( - giant g1, - giant g2) -{ - unsigned rtn = feeSizeOfSnaccGiant(g1); - rtn += feeSizeOfSnaccGiant(g2); - szprint(("feeSizeOfDERSig: size %d\n", rtn + 4)); - return rtn + 4; -} - -/* perform 2's complement of byte array, expressed MS byte first */ -static void twosComplement( - unsigned char *bytePtr, // points to MS byte - unsigned numBytes) -{ - unsigned char *outp = bytePtr + numBytes - 1; - unsigned char carry = 1; // first time thru, carry = 1 to add one to 1's comp - for(unsigned byteDex=0; byteDex unsigned int - */ -static unsigned cssmDataToInt( - const CSSM_DATA &cdata) -{ - if((cdata.Length == 0) || (cdata.Data == NULL)) { - return 0; - } - unsigned len = (unsigned)cdata.Length; - if(len > sizeof(int)) { - feeException::throwMe(FR_BadKeyBlob, "cssmDataToInt"); - } - - unsigned rtn = 0; - uint8 *cp = cdata.Data; - for(unsigned i=0; i CSSM_DATA, mallocing from an SecNssCoder - */ -static void intToCssmData( - unsigned num, - CSSM_DATA &cdata, - SecNssCoder &coder) -{ - unsigned len = 0; - - if(num < 0x100) { - len = 1; - } - else if(num < 0x10000) { - len = 2; - } - else if(num < 0x1000000) { - len = 3; - } - else { - len = 4; - } - cdata.Data = (uint8 *)coder.malloc(len); - cdata.Length = len; - uint8 *cp = &cdata.Data[len - 1]; - for(unsigned i=0; i>= 8; - } -} - -/* - * Convert a decoded ASN integer, as a CSSM_DATA, to a (mallocd) giant. - * Only known exception is a feeException. - */ -static giant cssmDataToGiant( - const CSSM_DATA &cdata) -{ - char *rawOcts = (char *)cdata.Data; - unsigned numBytes = (unsigned)cdata.Length; - unsigned numGiantDigits; - int sign = 1; - giant grtn; - feeReturn frtn = FR_Success; - unsigned char *inp = NULL; - unsigned digitDex; // index into g->giantDigit[] - - /* handle degenerate case (value of zero) */ - if((numBytes == 0) || ((numBytes == 1) && rawOcts[0] == 0)) { - grtn = newGiant(1); - if(grtn == NULL) { - feeException::throwMe(FR_Memory, "newGiant(1)"); - } - int_to_giant(0, grtn); - return grtn; - } - - /* make a copy of raw octets if we have to do two's complement */ - unsigned char *byteArray = NULL; - bool didMalloc = false; - if(rawOcts[0] & 0x80) { - sign = -1; - numBytes++; - byteArray = (unsigned char *)fmalloc(numBytes); - didMalloc = true; - byteArray[0] = 0xff; - memmove(byteArray + 1, rawOcts, numBytes-1); - twosComplement(byteArray, numBytes); - } - else { - /* no copy */ - char *foo = rawOcts; - byteArray = (unsigned char *)foo; - } - - /* cook up a new giant */ - numGiantDigits = (numBytes + GIANT_BYTES_PER_DIGIT - 1) / - GIANT_BYTES_PER_DIGIT; - grtn = newGiant(numGiantDigits); - if(grtn == NULL) { - frtn = FR_Memory; - goto abort; - } - - /* - * Convert byteArray to array of giantDigits - * inp - raw input bytes, LSB last - * grtn->n[] - output array of giantDigits, LSD first - * Start at LS byte and LD digit - */ - digitDex = 0; // index into g->giantDigit[] - giantDigit thisDigit; - inp = byteArray + numBytes - 1; - unsigned dex; // total byte counter - unsigned byteDex; // index into one giantDigit - unsigned shiftCount; - for(dex=0; dexn[digitDex++] = thisDigit; - } - grtn->sign = (int)numGiantDigits * sign; - - /* trim leading (MS) zeroes */ - gtrimSign(grtn); -abort: - if(didMalloc) { - ffree(byteArray); - } - if(frtn) { - feeException::throwMe(frtn, "bigIntStrToGiant"); - } - return grtn; -} - -/* - * Convert a giant to an CSSM_DATA, mallocing using specified coder. - * Only known exception is a feeException. - */ - static void giantToCssmData( - giant g, - CSSM_DATA &cdata, - SecNssCoder &coder) -{ - unsigned char doPrepend = 0; - unsigned numGiantDigits = abs(g->sign); - unsigned numBytes = numGiantDigits * GIANT_BYTES_PER_DIGIT; - giantDigit msGiantBit = 0; - if(isZero(g)) { - /* special degenerate case */ - intToCssmData(0, cdata, coder); - return; - } - else { - msGiantBit = g->n[numGiantDigits - 1] >> (GIANT_BITS_PER_DIGIT - 1); - } - - /* prepend a byte of zero if necessary */ - if((g->sign < 0) || // negative - to handle 2's complement - ((g->sign > 0) && msGiantBit)) { // ensure MS byte is zero - doPrepend = 1; - numBytes++; - } - - unsigned char *rawBytes = (unsigned char *)fmalloc(numBytes); - if(rawBytes == NULL) { - feeException::throwMe(FR_Memory, "giantToCssmData fmalloc(rawBytes)"); - } - unsigned char *outp = rawBytes; - if(doPrepend) { - *outp++ = 0; - } - - /* - * Convert array of giantDigits to bytes. - * outp point to MS output byte. - */ - int digitDex; // index into g->giantDigit[] - unsigned byteDex; // byte index into a giantDigit - for(digitDex=numGiantDigits-1; digitDex>=0; digitDex--) { - /* one loop per giantDigit, starting at MS end */ - giantDigit thisDigit = g->n[digitDex]; - unsigned char *bp = outp + GIANT_BYTES_PER_DIGIT - 1; - for(byteDex=0; byteDex>= 8; - } - outp += GIANT_BYTES_PER_DIGIT; - } - - /* do two's complement for negative giants */ - if(g->sign < 0) { - twosComplement(rawBytes, numBytes); - } - - /* strip off redundant leading bits (nine zeroes or nine ones) */ - outp = rawBytes; - unsigned char *endp = outp + numBytes - 1; - while((*outp == 0) && // m.s. byte zero - (outp < endp) && // more bytes exist - (!(outp[1] & 0x80))) { // 9th bit is 0 - outp++; - numBytes--; - } - while((*outp == 0xff) && // m.s. byte all ones - (outp < endp) && // more bytes exist - (outp[1] & 0x80)) { // 9th bit is 1 - outp++; - numBytes--; - } - cdata.Data = (uint8 *)coder.malloc(numBytes); - memmove(cdata.Data, outp, numBytes); - cdata.Length = numBytes; - ffree(rawBytes); - return; -} - -/* curveParams : CryptKit <--> FEECurveParametersASN1 */ -/* Only known exception is a feeException */ -static void feeCurveParamsToASN1( - const curveParams *cp, - FEECurveParametersASN1 &asnCp, - SecNssCoder &coder) -{ - #if PRINT_CURVE_PARAMS - printf("===encoding curveParams; cp:\n"); printCurveParams(cp); - #endif - memset(&asnCp, 0, sizeof(asnCp)); - try { - intToCssmData(cp->primeType, asnCp.primeType, coder); - intToCssmData(cp->curveType, asnCp.curveType, coder); - intToCssmData(cp->q, asnCp.q, coder); - intToCssmData(cp->k, asnCp.k, coder); - intToCssmData(cp->m, asnCp.m, coder); - giantToCssmData(cp->a, asnCp.a, coder); - giantToCssmData(cp->b, asnCp.b_, coder); - giantToCssmData(cp->c, asnCp.c, coder); - giantToCssmData(cp->x1Plus, asnCp.x1Plus, coder); - giantToCssmData(cp->x1Minus, asnCp.x1Minus, coder); - giantToCssmData(cp->cOrderPlus, asnCp.cOrderPlus, coder); - giantToCssmData(cp->cOrderMinus, asnCp.cOrderMinus, coder); - giantToCssmData(cp->x1OrderPlus, asnCp.x1OrderPlus, coder); - giantToCssmData(cp->x1OrderMinus, asnCp.x1OrderMinus, coder); - if(cp->primeType == FPT_General) { - giantToCssmData(cp->basePrime, asnCp.basePrime, coder); - } - } - catch(const feeException &ferr) { - throw; - } - catch(...) { - feeException::throwMe(FR_Memory, "feeCurveParamsToSnacc catchall"); // ??? - } -} - -static curveParams *feeCurveParamsFromAsn1( - const FEECurveParametersASN1 &asnCp) -{ - curveParams *cp = newCurveParams(); - if(cp == NULL) { - feeException::throwMe(FR_Memory, "feeCurveParamsFromSnacc alloc cp"); - } - cp->primeType = (feePrimeType)cssmDataToInt(asnCp.primeType); - cp->curveType = (feeCurveType)cssmDataToInt(asnCp.curveType); - cp->q = cssmDataToInt(asnCp.q); - cp->k = cssmDataToInt(asnCp.k); - cp->m = cssmDataToInt(asnCp.m); - cp->a = cssmDataToGiant(asnCp.a); - cp->b = cssmDataToGiant(asnCp.b_); - cp->c = cssmDataToGiant(asnCp.c); - cp->x1Plus = cssmDataToGiant(asnCp.x1Plus); - cp->x1Minus = cssmDataToGiant(asnCp.x1Minus); - cp->cOrderPlus = cssmDataToGiant(asnCp.cOrderPlus); - cp->cOrderMinus = cssmDataToGiant(asnCp.cOrderMinus); - cp->x1OrderPlus = cssmDataToGiant(asnCp.x1OrderPlus); - cp->x1OrderMinus = cssmDataToGiant(asnCp.x1OrderMinus); - if(asnCp.basePrime.Data != NULL) { - cp->basePrime = cssmDataToGiant(asnCp.basePrime); - } - - /* remaining fields inferred */ - curveParamsInferFields(cp); - allocRecipGiants(cp); - #if PRINT_CURVE_PARAMS - printf("===decoding curveParams; cp:\n"); printCurveParams(cp); - #endif - return cp; -} - -/*** - *** Public routines. These are usable from C code; they never throw. - ***/ - -/* - * Encode/decode the two FEE signature types. We malloc returned data via - * fmalloc(); caller must free via ffree(). - */ -feeReturn feeDEREncodeElGamalSignature( - giant u, - giant PmX, - unsigned char **encodedSig, // fmallocd and RETURNED - unsigned *encodedSigLen) // RETURNED -{ - /* convert to FEEElGamalSignatureASN1 */ - FEEElGamalSignatureASN1 asnSig; - SecNssCoder coder; - - try { - giantToCssmData(u, asnSig.u, coder); - giantToCssmData(PmX, asnSig.pmX, coder); - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - - /* DER encode */ - PRErrorCode perr; - CSSM_DATA encBlob; // mallocd by coder - perr = coder.encodeItem(&asnSig, FEEElGamalSignatureASN1Template, encBlob); - if(perr) { - return FR_Memory; - } - - /* copy out to caller */ - *encodedSig = (unsigned char *)fmalloc((unsigned)encBlob.Length); - *encodedSigLen = (unsigned)encBlob.Length; - memmove(*encodedSig, encBlob.Data, encBlob.Length); - - #if PRINT_SIG_GIANTS - printf("feeEncodeElGamalSignature:\n"); - printf(" u : "); printGiantHex(u); - printf(" PmX : "); printGiantHex(PmX); - #endif - - return FR_Success; -} - -/* - * Encode a DER formatted ECDSA signature - */ -feeReturn feeDEREncodeECDSASignature( - giant c, - giant d, - unsigned char **encodedSig, // fmallocd and RETURNED - unsigned *encodedSigLen) // RETURNED -{ - /* convert to FEEECDSASignatureASN1 */ - FEEECDSASignatureASN1 asnSig; - SecNssCoder coder; - - try { - giantToCssmData(c, asnSig.c, coder); - giantToCssmData(d, asnSig.d, coder); - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - - /* DER encode */ - PRErrorCode perr; - CSSM_DATA encBlob; // mallocd by coder - perr = coder.encodeItem(&asnSig, FEEECDSASignatureASN1Template, encBlob); - if(perr) { - return FR_Memory; - } - - /* copy out to caller */ - *encodedSig = (unsigned char *)fmalloc((unsigned)encBlob.Length); - *encodedSigLen = (unsigned)encBlob.Length; - memmove(*encodedSig, encBlob.Data, encBlob.Length); - - #if PRINT_SIG_GIANTS - printf("feeDEREncodeECDSASignature:\n"); - printf(" c : "); printGiantHex(c); - printf(" d : "); printGiantHex(d); - #endif - return FR_Success; - -} - -#if PRINT_SIG_GIANTS -static void printHex( - const unsigned char *buf, - unsigned len, - unsigned maxLen) -{ - bool doEllipsis = false; - unsigned dex; - if(len > maxLen) { - len = maxLen; - doEllipsis = true; - } - for(dex=0; dex>1))) { - return FR_BadSignatureFormat; - } - - try { - *c = giant_with_data((uint8_t*)encodedSig,(int)groupBytesLen); - *d = giant_with_data((uint8_t*)encodedSig+groupBytesLen, (int)groupBytesLen); - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - catch(...) { - /* FIXME - bad sig? memory? */ - return FR_Memory; - } -#if PRINT_SIG_GIANTS - printf("feeRAWDecodeECDSASignature:\n"); - printf(" c : "); printGiantHex(*c); - printf(" d : "); printGiantHex(*d); -#endif - return FR_Success; -} - -/* - * Encode/decode the FEE private and public keys. We malloc returned data via - * falloc(); caller must free via ffree(). Public C functions which never throw. - */ -feeReturn feeDEREncodePublicKey( - int version, - const curveParams *cp, - giant plusX, - giant minusX, - giant plusY, // may be NULL - unsigned char **keyBlob, // fmallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - FEEPublicKeyASN1 asnKey; - SecNssCoder coder; - - memset(&asnKey, 0, sizeof(asnKey)); - intToCssmData(version, asnKey.version, coder); - - try { - feeCurveParamsToASN1(cp, asnKey.curveParams, coder); - giantToCssmData(plusX, asnKey.plusX, coder); - giantToCssmData(minusX, asnKey.minusX, coder); - if(plusY != NULL) { - giantToCssmData(plusY, asnKey.plusY, coder); - } - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - - /* DER encode */ - PRErrorCode perr; - CSSM_DATA encBlob; // mallocd by coder - perr = coder.encodeItem(&asnKey, FEEPublicKeyASN1Template, encBlob); - if(perr) { - return FR_Memory; - } - - /* copy out */ - *keyBlob = (unsigned char *)fmalloc((unsigned)encBlob.Length); - *keyBlobLen = (unsigned)encBlob.Length; - memmove(*keyBlob, encBlob.Data, encBlob.Length); - return FR_Success; -} - -feeReturn feeDEREncodePrivateKey( - int version, - const curveParams *cp, - const giant privData, - unsigned char **keyBlob, // fmallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - FEEPrivateKeyASN1 asnKey; - SecNssCoder coder; - - memset(&asnKey, 0, sizeof(asnKey)); - intToCssmData(version, asnKey.version, coder); - - try { - feeCurveParamsToASN1(cp, asnKey.curveParams, coder); - giantToCssmData(privData, asnKey.privData, coder); - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - - /* DER encode */ - PRErrorCode perr; - CSSM_DATA encBlob; // mallocd by coder - perr = coder.encodeItem(&asnKey, FEEPrivateKeyASN1Template, encBlob); - if(perr) { - return FR_Memory; - } - - /* copy out */ - *keyBlob = (unsigned char *)fmalloc((unsigned)encBlob.Length); - *keyBlobLen = (unsigned)encBlob.Length; - memmove(*keyBlob, encBlob.Data, encBlob.Length); - return FR_Success; -} - -feeReturn feeDERDecodePublicKey( - const unsigned char *keyBlob, - unsigned keyBlobLen, - int *version, // this and remainder RETURNED - curveParams **cp, - giant *plusX, - giant *minusX, - giant *plusY) // may be NULL -{ - FEEPublicKeyASN1 asnKey; - SecNssCoder coder; - - memset(&asnKey, 0, sizeof(asnKey)); - PRErrorCode perr = coder.decode(keyBlob, keyBlobLen, - FEEPublicKeyASN1Template, &asnKey); - if(perr) { - return FR_BadKeyBlob; - } - - try { - *version = cssmDataToInt(asnKey.version); - *cp = feeCurveParamsFromAsn1(asnKey.curveParams); - *plusX = cssmDataToGiant(asnKey.plusX); - *minusX = cssmDataToGiant(asnKey.minusX); - if(asnKey.plusY.Data != NULL) { - /* optional */ - *plusY = cssmDataToGiant(asnKey.plusY); - } - else { - *plusY = newGiant(1); - int_to_giant(0, *plusY); - } - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - catch(...) { - /* FIXME - bad sig? memory? */ - return FR_Memory; - } - return FR_Success; -} - -feeReturn feeDERDecodePrivateKey( - const unsigned char *keyBlob, - unsigned keyBlobLen, - int *version, // this and remainder RETURNED - curveParams **cp, - giant *privData) // RETURNED -{ - FEEPrivateKeyASN1 asnKey; - SecNssCoder coder; - - memset(&asnKey, 0, sizeof(asnKey)); - PRErrorCode perr = coder.decode(keyBlob, keyBlobLen, - FEEPrivateKeyASN1Template, &asnKey); - if(perr) { - return FR_BadKeyBlob; - } - - try { - *version = cssmDataToInt(asnKey.version); - *cp = feeCurveParamsFromAsn1(asnKey.curveParams); - *privData = cssmDataToGiant(asnKey.privData); - } - catch(const feeException &ferr) { - return ferr.frtn(); - } - catch(...) { - /* FIXME - bad sig? memory? */ - return FR_Memory; - } - return FR_Success; -} - -#pragma mark --- ECDSA support --- - -/* convert between feeDepth and curve OIDs */ -static const CSSM_OID *depthToOid( - feeDepth depth) -{ - switch(depth) { - case FEE_DEPTH_secp192r1: - return &CSSMOID_secp192r1; - case FEE_DEPTH_secp256r1: - return &CSSMOID_secp256r1; - case FEE_DEPTH_secp384r1: - return &CSSMOID_secp384r1; - case FEE_DEPTH_secp521r1: - return &CSSMOID_secp521r1; - default: - dbgLog(("depthToOid needs work\n")); - return NULL; - } -} - -static feeReturn curveOidToFeeDepth( - const CSSM_OID *curveOid, - feeDepth *depth) /* RETURNED */ -{ - if(nssCompareCssmData(curveOid, &CSSMOID_secp192r1)) { - *depth = FEE_DEPTH_secp192r1; - } - else if(nssCompareCssmData(curveOid, &CSSMOID_secp256r1)) { - *depth = FEE_DEPTH_secp256r1; - } - else if(nssCompareCssmData(curveOid, &CSSMOID_secp384r1)) { - *depth = FEE_DEPTH_secp384r1; - } - else if(nssCompareCssmData(curveOid, &CSSMOID_secp521r1)) { - *depth = FEE_DEPTH_secp521r1; - } - else { - dbgLog(("curveOidToFeeDepth: unknown curve OID\n")); - return FR_BadKeyBlob; - } - return FR_Success; -} - - -/* - * Validate a decoded CSSM_X509_ALGORITHM_IDENTIFIER and infer - * depth from its algorith.parameter - */ -static feeReturn feeAlgIdToDepth( - const CSSM_X509_ALGORITHM_IDENTIFIER *algId, - feeDepth *depth) -{ - const CSSM_OID *oid = &algId->algorithm; - /* FIXME what's the value here for a private key!? */ - if(!nssCompareCssmData(oid, &CSSMOID_ecPublicKey)) { - dbgLog(("feeAlgIdToDepth: bad OID")); - return FR_BadKeyBlob; - } - - /* - * AlgId.params is curve OID, still encoded since it's an ASN_ANY. - * First two bytes of encoded OID are (06, length) - */ - const CSSM_DATA *param = &algId->parameters; - if((param->Length <= 2) || (param->Data[0] != BER_TAG_OID)) { - dbgLog(("feeAlgIdToDepth: no curve params\n")); - return FR_BadKeyBlob; - } - - CSSM_OID decOid = {param->Length-2, algId->parameters.Data+2}; - return curveOidToFeeDepth(&decOid, depth); -} - -/* - * Prepare an CSSM_X509_ALGORITHM_IDENTIFIER for encoding. - */ -static feeReturn feeSetupAlgId( - feeDepth depth, - SecNssCoder &coder, - CSSM_X509_ALGORITHM_IDENTIFIER &algId) -{ - algId.algorithm = CSSMOID_ecPublicKey; - const CSSM_OID *curveOid = depthToOid(depth); - if(curveOid == NULL) { - return FR_IllegalDepth; - } - - /* quick & dirty encode of the parameter OID; it's an ASN_ANY in the template */ - coder.allocItem(algId.parameters, curveOid->Length + 2); - algId.parameters.Data[0] = BER_TAG_OID; - algId.parameters.Data[1] = curveOid->Length; - memmove(algId.parameters.Data+2, curveOid->Data, curveOid->Length); - return FR_Success; -} - -#pragma mark --- ECDSA public key, X.509 format --- - -/* - * Encode/decode public key in X.509 format. - */ -feeReturn feeDEREncodeX509PublicKey( - const unsigned char *pubBlob, /* x and y octet string */ - unsigned pubBlobLen, - curveParams *cp, - unsigned char **x509Blob, /* fmallocd and RETURNED */ - unsigned *x509BlobLen) /* RETURNED */ -{ - SecNssCoder coder; - CSSM_X509_SUBJECT_PUBLIC_KEY_INFO nssPubKeyInfo; - - memset(&nssPubKeyInfo, 0, sizeof(nssPubKeyInfo)); - - /* The x/y string, to be encoded in a bit string */ - nssPubKeyInfo.subjectPublicKey.Data = (uint8 *)pubBlob; - nssPubKeyInfo.subjectPublicKey.Length = pubBlobLen * 8; - - feeDepth depth; - feeReturn frtn = curveParamsDepth(cp, &depth); - if(frtn) { - dbgLog(("feeDEREncodePKCS8PrivateKey: curveParamsDepth error\n")); - return frtn; - } - - CSSM_X509_ALGORITHM_IDENTIFIER &algId = nssPubKeyInfo.algorithm; - frtn = feeSetupAlgId(depth, coder, algId); - if(frtn) { - return frtn; - } - - /* DER encode */ - CSSM_DATA encBlob; // mallocd by coder - PRErrorCode perr = coder.encodeItem(&nssPubKeyInfo, kSecAsn1SubjectPublicKeyInfoTemplate, encBlob); - if(perr) { - return FR_Memory; - } - - /* copy out */ - *x509Blob = (unsigned char *)fmalloc((unsigned)encBlob.Length); - *x509BlobLen = (unsigned)encBlob.Length; - memmove(*x509Blob, encBlob.Data, encBlob.Length); - return FR_Success; -} - -feeReturn feeDERDecodeX509PublicKey( - const unsigned char *x509Blob, - unsigned x509BlobLen, - feeDepth *depth, /* RETURNED */ - unsigned char **pubBlob, /* x and y octet string RETURNED */ - unsigned *pubBlobLen) /* RETURNED */ -{ - SecNssCoder coder; - CSSM_X509_SUBJECT_PUBLIC_KEY_INFO nssPubKeyInfo; - PRErrorCode perr; - - memset(&nssPubKeyInfo, 0, sizeof(nssPubKeyInfo)); - perr = coder.decode(x509Blob, x509BlobLen, kSecAsn1SubjectPublicKeyInfoTemplate, - &nssPubKeyInfo); - if(perr) { - dbgLog(("decode(SubjectPublicKeyInfo) error")); - return FR_BadKeyBlob; - } - - /* verify alg identifier & depth */ - feeReturn frtn = feeAlgIdToDepth(&nssPubKeyInfo.algorithm, depth); - if(frtn) { - return frtn; - } - - /* copy public key string - it's in bits here */ - CSSM_DATA *pubKey = &nssPubKeyInfo.subjectPublicKey; - unsigned keyLen =(unsigned) (pubKey->Length + 7) / 8; - *pubBlob = (unsigned char *)fmalloc(keyLen); - if(*pubBlob == NULL) { - return FR_Memory; - } - memmove(*pubBlob, pubKey->Data, keyLen); - *pubBlobLen = keyLen; - return FR_Success; -} - -#pragma mark --- ECDSA keys, OpenSSL format --- - -/* - * Encode private, and decode private or public key, in unencrypted OpenSSL format. - */ -feeReturn feeDEREncodeOpenSSLPrivateKey( - const unsigned char *privBlob, /* private data octet string */ - unsigned privBlobLen, - const unsigned char *pubBlob, /* public key, optional */ - unsigned pubBlobLen, - curveParams *cp, - unsigned char **openBlob, /* fmallocd and RETURNED */ - unsigned *openBlobLen) /* RETURNED */ -{ - feeDepth depth; - const CSSM_OID *curveOid; - SecNssCoder coder; - - NSS_ECDSA_PrivateKey ecdsaPrivKey; - memset(&ecdsaPrivKey, 0, sizeof(ecdsaPrivKey)); - uint8 vers = 1; - ecdsaPrivKey.version.Data = &vers; - ecdsaPrivKey.version.Length = 1; - ecdsaPrivKey.privateKey.Data = (uint8 *)privBlob; - ecdsaPrivKey.privateKey.Length = privBlobLen; - - /* Params - ASN_ANY - actually the curve OID */ - if(curveParamsDepth(cp, &depth)) { - dbgLog(("feeDEREncodeOpenSSLPrivateKey: bad depth")); - return FR_BadKeyBlob; - } - curveOid = depthToOid(depth); - if(curveOid == NULL) { - return FR_BadKeyBlob; - } - - /* quickie DER-encode of the curve OID */ - try { - coder.allocItem(ecdsaPrivKey.params, curveOid->Length + 2); - } - catch(...) { - return FR_Memory; - } - ecdsaPrivKey.params.Data[0] = BER_TAG_OID; - ecdsaPrivKey.params.Data[1] = curveOid->Length; - memmove(ecdsaPrivKey.params.Data+2, curveOid->Data, curveOid->Length); - - /* public key - optional - bit string, length in bits */ - if(pubBlob) { - ecdsaPrivKey.pubKey.Data = (uint8 *)pubBlob; - ecdsaPrivKey.pubKey.Length = pubBlobLen * 8; - } - - CSSM_DATA encPriv = {0, NULL}; - PRErrorCode perr = coder.encodeItem(&ecdsaPrivKey, kSecAsn1ECDSAPrivateKeyInfoTemplate, encPriv); - if(perr) { - return FR_Memory; - } - - /* copy out */ - *openBlob = (unsigned char *)fmalloc((unsigned)encPriv.Length); - *openBlobLen = (unsigned)encPriv.Length; - memmove(*openBlob, encPriv.Data, encPriv.Length); - return FR_Success; -} - -feeReturn feeDERDecodeOpenSSLKey( - const unsigned char *osBlob, - unsigned osBlobLen, - feeDepth *depth, /* RETURNED */ - unsigned char **privBlob, /* private data octet string RETURNED */ - unsigned *privBlobLen, /* RETURNED */ - unsigned char **pubBlob, /* public data octet string optionally RETURNED */ - unsigned *pubBlobLen) -{ - SecNssCoder coder; - NSS_ECDSA_PrivateKey ecdsaPrivKey; - memset(&ecdsaPrivKey, 0, sizeof(ecdsaPrivKey)); - if(coder.decode(osBlob, osBlobLen, - kSecAsn1ECDSAPrivateKeyInfoTemplate, &ecdsaPrivKey)) { - dbgLog(("Error decoding openssl priv key\n")); - return FR_BadKeyBlob; - } - - unsigned keyLen = (unsigned)ecdsaPrivKey.privateKey.Length; - if(keyLen == 0) { - dbgLog(("NULL priv key data in PKCS8\n")); - } - *privBlob = (unsigned char *)fmalloc(keyLen); - if(*privBlob == NULL) { - return FR_Memory; - } - *privBlobLen = keyLen; - memmove(*privBlob, ecdsaPrivKey.privateKey.Data, keyLen); - - /* curve OID --> depth */ - if(ecdsaPrivKey.params.Data != NULL) { - /* quickie decode */ - const CSSM_DATA *param = &ecdsaPrivKey.params; - if((param->Data[0] != BER_TAG_OID) || (param->Length <= 2)) { - dbgLog(("feeDERDecodeOpenSSLKey: bad curve params\n")); - return FR_BadKeyBlob; - } - CSSM_OID decOid = {param->Length-2, param->Data+2}; - if(curveOidToFeeDepth(&decOid, depth)) { - return FR_BadKeyBlob; - } - } - - /* Public key, if it's there and caller wants it */ - if((ecdsaPrivKey.pubKey.Length != 0) && (pubBlob != NULL)) { - *pubBlobLen = (unsigned)(ecdsaPrivKey.pubKey.Length + 7) / 8; - *pubBlob = (unsigned char *)fmalloc(*pubBlobLen); - memmove(*pubBlob, ecdsaPrivKey.pubKey.Data, *pubBlobLen); - } - return FR_Success; -} - -#pragma mark --- ECDSA public key, PKCS8 format --- - -/* - * Encode/decode private key in unencrypted PKCS8 format. - */ -feeReturn feeDEREncodePKCS8PrivateKey( - const unsigned char *privBlob, /* private data octet string */ - unsigned privBlobLen, - const unsigned char *pubBlob, /* public blob, optional */ - unsigned pubBlobLen, - curveParams *cp, - unsigned char **pkcs8Blob, /* fmallocd and RETURNED */ - unsigned *pkcs8BlobLen) /* RETURNED */ -{ - /* First encode a NSS_ECDSA_PrivateKey */ - unsigned char *encPriv = NULL; - unsigned encPrivLen = 0; - feeReturn frtn = feeDEREncodeOpenSSLPrivateKey(privBlob, privBlobLen, - pubBlob, pubBlobLen, cp, &encPriv, &encPrivLen); - if(frtn) { - return frtn; - } - - /* That encoding goes into NSS_PrivateKeyInfo.private key */ - SecNssCoder coder; - NSS_PrivateKeyInfo nssPrivKeyInfo; - CSSM_X509_ALGORITHM_IDENTIFIER &algId = nssPrivKeyInfo.algorithm; - memset(&nssPrivKeyInfo, 0, sizeof(nssPrivKeyInfo)); - nssPrivKeyInfo.privateKey.Data = (uint8 *)encPriv; - nssPrivKeyInfo.privateKey.Length = encPrivLen; - uint8 vers = 0; - - feeDepth depth; - frtn = curveParamsDepth(cp, &depth); - if(frtn) { - dbgLog(("feeDEREncodePKCS8PrivateKey: curveParamsDepth error\n")); - goto errOut; - } - frtn = feeSetupAlgId(depth, coder, algId); - if(frtn) { - goto errOut; - } - - nssPrivKeyInfo.version.Data = &vers; - nssPrivKeyInfo.version.Length = 1; - - /* DER encode */ - CSSM_DATA encPrivInfo; // mallocd by coder - if(coder.encodeItem(&nssPrivKeyInfo, kSecAsn1PrivateKeyInfoTemplate, encPrivInfo)) { - frtn = FR_Memory; - goto errOut; - } - - /* copy out */ - *pkcs8Blob = (unsigned char *)fmalloc((unsigned)encPrivInfo.Length); - *pkcs8BlobLen = (unsigned)encPrivInfo.Length; - memmove(*pkcs8Blob, encPrivInfo.Data, encPrivInfo.Length); -errOut: - if(encPriv) { - ffree(encPriv); - } - return frtn; -} - -feeReturn feeDERDecodePKCS8PrivateKey( - const unsigned char *pkcs8Blob, - unsigned pkcs8BlobLen, - feeDepth *depth, /* RETURNED */ - unsigned char **privBlob, /* private data octet string RETURNED */ - unsigned *privBlobLen, /* RETURNED */ - unsigned char **pubBlob, /* optionally returned, if it's there */ - unsigned *pubBlobLen) -{ - NSS_PrivateKeyInfo nssPrivKeyInfo; - PRErrorCode perr; - SecNssCoder coder; - - memset(&nssPrivKeyInfo, 0, sizeof(nssPrivKeyInfo)); - perr = coder.decode(pkcs8Blob, pkcs8BlobLen, kSecAsn1PrivateKeyInfoTemplate, &nssPrivKeyInfo); - if(perr) { - dbgLog(("Error decoding top level PKCS8\n")); - return FR_BadKeyBlob; - } - - /* verify alg identifier & depth */ - feeReturn frtn = feeAlgIdToDepth(&nssPrivKeyInfo.algorithm, depth); - if(frtn) { - return frtn; - } - - /* - * nssPrivKeyInfo.privateKey is an octet string containing an encoded - * NSS_ECDSA_PrivateKey. - */ - frtn = feeDERDecodeOpenSSLKey((const unsigned char *)nssPrivKeyInfo.privateKey.Data, - (unsigned)nssPrivKeyInfo.privateKey.Length, depth, - privBlob, privBlobLen, - pubBlob, pubBlobLen); - - return frtn; -} - -#endif /* CRYPTKIT_DER_ENABLE */ diff --git a/OSX/include/security_cryptkit/CryptKitDER.h b/OSX/include/security_cryptkit/CryptKitDER.h deleted file mode 100644 index 28b6ed03..00000000 --- a/OSX/include/security_cryptkit/CryptKitDER.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2001,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#ifndef _CRYPTKIT_DER_H_ -#define _CRYPTKIT_DER_H_ - -#include - -#if CRYPTKIT_DER_ENABLE - -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Encode/decode the two FEE signature types. We malloc returned data via - * falloc(); caller must free via ffree(). - */ -feeReturn feeDEREncodeElGamalSignature( - giant u, - giant PmX, - unsigned char **encodedSig, // fallocd and RETURNED - unsigned *encodedSigLen); // RETURNED - -feeReturn feeDEREncodeECDSASignature( - giant c, - giant d, - unsigned char **encodedSig, // fallocd and RETURNED - unsigned *encodedSigLen); // RETURNED - -feeReturn feeDERDecodeElGamalSignature( - const unsigned char *encodedSig, - size_t encodedSigLen, - giant *u, // newGiant'd and RETURNED - giant *PmX); // newGiant'd and RETURNED - -feeReturn feeDERDecodeECDSASignature( - const unsigned char *encodedSig, - size_t encodedSigLen, - giant *c, // newGiant'd and RETURNED - giant *d); // newGiant'd and RETURNED - -/* - * RAW format for ECDSA signatures - */ -feeReturn feeRAWEncodeECDSASignature( - unsigned groupBytesLen, - giant c, - giant d, - unsigned char **encodedSig, // fallocd and RETURNED - unsigned *encodedSigLen); // RETURNED - -feeReturn feeRAWDecodeECDSASignature( - unsigned groupBytesLen, - const unsigned char *encodedSig, - size_t encodedSigLen, - giant *c, // newGiant'd and RETURNED - giant *d); // newGiant'd and RETURNED - - - -/* - * Encode/decode the FEE private and public keys. We malloc returned data via - * falloc(); caller must free via ffree(). - * These use a DER format which is custom to this module. - */ -feeReturn feeDEREncodePublicKey( - int version, - const curveParams *cp, - giant plusX, - giant minusX, - giant plusY, // may be NULL - unsigned char **keyBlob, // fmallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feeDEREncodePrivateKey( - int version, - const curveParams *cp, - const giant privData, - unsigned char **keyBlob, // fmallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feeDERDecodePublicKey( - const unsigned char *keyBlob, - unsigned keyBlobLen, - int *version, // this and remainder RETURNED - curveParams **cp, - giant *plusX, - giant *minusX, - giant *plusY); // always valid, may be (giant)0 - -feeReturn feeDERDecodePrivateKey( - const unsigned char *keyBlob, - unsigned keyBlobLen, - int *version, // this and remainder RETURNED - curveParams **cp, - giant *privData); // RETURNED - -/* obtain the max size of a DER-encoded signature (either ElGamal or ECDSA) */ -unsigned feeSizeOfDERSig( - giant g1, - giant g2); - -/* - * Encode/decode public key in X.509 format. - */ -feeReturn feeDEREncodeX509PublicKey( - const unsigned char *pubBlob, /* x and y octet string */ - unsigned pubBlobLen, - curveParams *cp, - unsigned char **x509Blob, /* fmallocd and RETURNED */ - unsigned *x509BlobLen); /* RETURNED */ - -feeReturn feeDERDecodeX509PublicKey( - const unsigned char *x509Blob, - unsigned x509BlobLen, - feeDepth *depth, /* RETURNED */ - unsigned char **pubBlob, /* x and y octet string RETURNED */ - unsigned *pubBlobLen); /* RETURNED */ - -/* - * Encode private, and decode private or public key, in unencrypted OpenSSL format. - */ -feeReturn feeDEREncodeOpenSSLPrivateKey( - const unsigned char *privBlob, /* private data octet string */ - unsigned privBlobLen, - const unsigned char *pubBlob, /* public key, optional */ - unsigned pubBlobLen, - curveParams *cp, - unsigned char **openBlob, /* fmallocd and RETURNED */ - unsigned *openBlobLen); /* RETURNED */ - -feeReturn feeDERDecodeOpenSSLKey( - const unsigned char *osBlob, - unsigned osBlobLen, - feeDepth *depth, /* RETURNED */ - unsigned char **privBlob, /* private data octet string RETURNED */ - unsigned *privBlobLen, /* RETURNED */ - unsigned char **pubBlob, /* public data octet string optionally RETURNED */ - unsigned *pubBlobLen); - -/* - * Encode/decode private key in unencrypted PKCS8 format. - */ -feeReturn feeDEREncodePKCS8PrivateKey( - const unsigned char *privBlob, /* private data octet string */ - unsigned privBlobLen, - const unsigned char *pubBlob, /* public blob, optional */ - unsigned pubBlobLen, - curveParams *cp, - unsigned char **pkcs8Blob, /* fmallocd and RETURNED */ - unsigned *pkcs8BlobLen); /* RETURNED */ - -feeReturn feeDERDecodePKCS8PrivateKey( - const unsigned char *pkcs8Blob, - unsigned pkcs8BlobLen, - feeDepth *depth, /* RETURNED */ - unsigned char **privBlob, /* private data octet string RETURNED */ - unsigned *privBlobLen, /* RETURNED */ - unsigned char **pubBlob, /* optionally returned, if it's there */ - unsigned *pubBlobLen); - - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_DER_ENABLE */ -#endif /* _CRYPTKIT_DER_H_ */ - - diff --git a/OSX/include/security_cryptkit/CryptKitSA.h b/OSX/include/security_cryptkit/CryptKitSA.h deleted file mode 100644 index b5a902c8..00000000 --- a/OSX/include/security_cryptkit/CryptKitSA.h +++ /dev/null @@ -1,23 +0,0 @@ -/* Copyright (c) 1998-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - ***************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include diff --git a/OSX/include/security_cryptkit/CurveParamDocs/FEEDaffine.nb b/OSX/include/security_cryptkit/CurveParamDocs/FEEDaffine.nb deleted file mode 100644 index 19592d36..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/FEEDaffine.nb +++ /dev/null @@ -1,253 +0,0 @@ -(*********************************************************************** - - Mathematica-Compatible Notebook - -This notebook can be used on any computer system with Mathematica 3.0, -MathReader 3.0, or any compatible application. The data for the notebook -starts with the line of stars above. - -To get the notebook into a Mathematica-compatible application, do one of -the following: - -* Save the data starting with the line of stars above into a file - with a name ending in .nb, then open the file inside the application; - -* Copy the data starting with the line of stars above to the - clipboard, then use the Paste menu command inside the application. - -Data for notebooks contains only printable 7-bit ASCII and can be -sent directly in email or through ftp in text mode. Newlines can be -CR, LF or CRLF (Unix, Macintosh or MS-DOS style). - -NOTE: If you modify the data for this notebook not in a Mathematica- -compatible application, you must delete the line below containing the -word CacheID, otherwise Mathematica-compatible applications may try to -use invalid cache data. - -For more information on notebooks and Mathematica-compatible -applications, contact Wolfram Research: - web: http://www.wolfram.com - email: info@wolfram.com - phone: +1-217-398-0700 (U.S.) - -Notebook reader applications are available free of charge from -Wolfram Research. -***********************************************************************) - -(*CacheID: 232*) - - -(*NotebookFileLineBreakTest -NotebookFileLineBreakTest*) -(*NotebookOptionsPosition[ 10630, 213]*) -(*NotebookOutlinePosition[ 11308, 238]*) -(* CellTagsIndexPosition[ 11264, 234]*) -(*WindowFrame->Normal*) - - - -Notebook[{ -Cell[BoxData[ - \(\( (*\n\ - Algorithm\ 8.1 .10\ - \((Direct - embedding\ ECC\ encryption)\) . \t\t\t\n\ Support\ code\ - for\n\ R . \ Crandall\ and\ C . \ Pomerance, \n\ - "\"\n\ Springer - - Verlag\ 2001. \n\ c . \ 2000\ Perfectly\ Scientific, \ - Inc . \n\ All\ Rights\ Reserved . \n\t\n\t20\ Apr\ 2001\ RC\ - \((revamped\ for\ simplicity)\)\n\ 10\ Dec\ 2000\ AH\ - \((Formatting)\)\n\t14\ Sep\ 2000\ RT\ \((Creation)\)\n*) \n\)\)], - "Input"], - -Cell[BoxData[{ - \( (*\ CODE\ *) \n - \[IndentingNewLine] (*\ - We\ include\ functions\ from\ algorithm\ 7.2 .2\ for\ performing\ - elliptic\ \n\(arithmetic . \)\ *) \n - \n (*\ Next, \ - a\ function\ that\ negates\ a\ point\ pt\ on\ an\ elliptic\ - \(curve . \)\ *) \n - ellneg[pt_]\ := \ Mod[pt\ *\ {1, \(-1\), \ 1}, \ p]; \n - \n (*\ Next, \ elliptic\ subtraction\ pt1 - \(pt2 . \)\ *) \n - \(ellsub[pt1_, \ pt2_]\ := \ elladd[pt1, \ ellneg[pt2]]; \)\n - \n (*\ Next, \ the\ double\ of\ a\ \(point . \)\ *) \), - \(elldouble[pt_]\ := \ elladd[pt, pt]; \n - \n (*\ Next, \ elliptic\ addition\ pt1 + \(pt2 . \)\ *) \n\n\n - \(elladd[pt1_, \ pt2_]\ := \ \n\t - Block[{x1, y1, x2, y2, x3, y3, m}, \n\t\t - If[pt1[\([3]\)]\ == \ 0, \ Return[pt2]]; \n\t\t - If[pt2[\([3]\)]\ == \ 0, \ Return[pt1]]; \n\t\t - x1\ = \ pt1[\([1]\)]; \ y1\ = \ pt1[\([2]\)]; \n\t\t - x2\ = \ pt2[\([1]\)]; \ y2\ = \ pt2[\([2]\)]; \n\t\t - If[x1\ == \ x2, \ \n\t\t\t - If[Mod[y1 + y2, p] == 0, \ Return[{1, 1, 0}]]; \n\t\t\t - m\ = \ Mod[\((3\ x1^2\ + \ a)\)\ *\ PowerMod[2 y1, \(-1\), p], \ - p], \n\t\t\t - m\ = \ Mod[\((y2 - y1)\)\ PowerMod[x2 - x1, \(-1\), p], p]\n\t\t]; - \n\t\tx3\ = \ Mod[m^2\ - \ x1\ - \ x2, p]; \n\t\t - y3\ = \ Mod[m \((x1 - x3)\)\ - \ y1, \ p]; \n\t\t - Return[{x3, y3, 1}]\n\t]; \)\n\ \ - \n (*\ Next, \ elliptic - multiply\ a\ point\ pt\ by\ \(k . \)\ *) \), - \(\n\nelliptic[pt_, \ k_]\ := \ \n\t - Block[{hh, \ kk, pt2, lenh, \ lenk, \ hb, \ kb}, \n\t\t - If[k == 0, \ Return[{1, 1, 0}]]; \n\t\t - hh\ = \ Reverse[IntegerDigits[3 k, 2]]; \n\t\t - kk\ = \ Reverse[IntegerDigits[k, 2]]; \n\t\tpt2\ = \ pt; \n\t\t - lenh\ = \ Length[hh]; \n\t\tlenk\ = \ Length[kk]; \n\t\t - Do[\n\t\t\tpt2\ = \ elldouble[pt2]; \n\t\t\thb\ = \ hh[\([b]\)]; \n - \t\t\tIf[b\ <= \ lenk, \ kb\ = \ kk[\([b]\)], \ kb\ = \ 0]; \n - \t\t\tIf[{hb, kb}\ == \ {1, 0}, \n\t\t\t\t - pt2\ = \ elladd[pt2, \ pt], \n\t\t\t\t - If[{hb, \ kb}\ == \ {0, 1}, \n\t\t\t\t - pt2\ = \ ellsub[pt2, \ pt]]\n\t\t\t]\n\t\t\t, \n - \t\t\t{b, \ lenh - 1, \ 2, \(-1\)}\n\t\t\ ]; \n\tReturn[pt2]\n]\n - \n (*\ Next, \ - we\ include\ algorithm\ 2.3 .8\ for\ finding\ square\ roots\ \nmodulo\ - a\ prime\ p, \ - to\ be\ used\ to\ seek\ out\ valid\ y - - coordinates\ on\ \(curves . \)\ *) \n\), - \(sqrtmod[b_, p_] := \ \n\t - Module[{a, x, c, d, cd, m, t, tst}, \n\ \ \ \t\ta\ = \ Mod[b, p]; \n - \ \ \ \t\tIf[p\ == \ 2, \ Return[a]]; \n\ \ \ \ \t - If[MemberQ[{3, 7}, Mod[p, 8]], \n\ \ \ \ \ \ \t\t - Return[PowerMod[a, \((p + 1)\)/4, p]]\n\ \ \ \ \ \ \t]; \n\ \ \ \ \t - If[Mod[p, 8]\ == \ 5, \n\ \ \ \ \ \ \t\t - x\ = \ PowerMod[a, \((p + 3)\)/8, p]; \n\ \ \ \ \ \ \t\t - c\ = \ Mod[x^2, p]; \n\ \ \ \ \ \ \t\t - If[Not[c\ == \ a], \n\ \ \ \ \ \ \ \ \t\t - Return[Mod[x\ PowerMod[2, \((p - 1)\)/4, p], \ p]]\n - \ \ \ \ \ \ \ \ \t]; \n\ \ \ \ \ \ \t]; \n\ \ \ \ \t\n - \ \ \ \ \t (*\ Here, \ p\ = \ 1\ \(\((mod\ 8)\) . \)\ *) \n - \ \ \ \ \ \ \ttst\ = \ 1; \n\ \ \ \ \ \ \t - While[Not[tst\ == \ \(-1\)], \n\ \ \ \ \ \ \ \ \t - d\ = \ Random[Integer, {1, p}]; \n\ \ \ \ \ \ \ \ \t - tst\ = \ JacobiSymbol[d, p]\n\ \ \ \ \ \ \ \ ]; \n\ \ \ \ \ \ \t - t\ = \ \((p - 1)\)/2; \ s\ = \ 1; \n\ \ \ \ \ \ \t - While[EvenQ[t], \ t\ = \ t/2; \ \(++s\)]; \n\ \ \ \ \ \ \t - ca\ = \ PowerMod[a, t, p]; \n\ \ \ \ \ \ \t - cd\ = \ PowerMod[d, t, p]; \n\ \ \ \ \ \ \tm\ = \ 0; \n - \ \ \ \ \ \ \t - Do[\n\ \ \ \ \ \ \t\ \ \ - If[PowerMod[Mod[ca\ PowerMod[cd, \ m, \ p], p], \ - 2^\((s - 1 - i)\), \ p]\n\ \ \ \ \ \ \t\ \ \ \t\t == \ p - 1, - \ m\ += \ 2^i]\n\ \ \ \ \ \ \t\ \ \ , {i, 0, s - 1}\n - \ \ \ \ \ \ \t]; \ \ \ \ \ \ \t\ \ \ \ \n\ \ \ \ \ \ \t - Return[Mod[PowerMod[a, \ \((t + 1)\)/2, p]\ PowerMod[cd, \ m/2, p], - p]]; \ \n\t]; \n\n - \n (*\ Now, \ - the\ main\ routine . \ Parameters\ are\ given\ for\ 161 - - bit\ prime\ field\n\t\t\tand\ specific\ curve; \n\t\ \ - direct\ embedding\ proceeds\ on\ "\"\ integers\ x\ - \((mod\ p)\) . \ \n\ \ \ We\ start\ with\ relevant\ global\ - \((and\ public, \ except\ for\ kb)\)\n\ \ \ parameters\n\ *) \n - \[IndentingNewLine]p\ = \ - 1654338658923174831024422729553880293604080853451; \nA\ = \ \(-152\); - \nB\ = \ 722; \ng\ = \ \(-1\); - \ \ (*\ Quadratic\ nonresidue\ \((mod\ p)\)\ for\ this\ case, \ - as\ p\ = \ 3\ \(\((mod\ 4)\) . \)\ *) \n - Atwist\ = \ Mod[A\ \ Mod[h\ = \ g^2, p], \ p]; \n - Btwist\ = \ Mod[B\ \ Mod[h\ g, p], p]; \n - \n (*\ Next, \ - create\ public\ point\ P\ of\ prime\ order\ on\ main\ \(curve . \)\ *) - \nx1 = \ 124590448755381588517063157600522073397838354227; \ \ \n - pubpoint\ = - \ {x1, \ sqrtmod[Mod[x1\ Mod[x1^2\ + \ A, p]\ + \ B, p], \ p], 1}; \n - \n (*\ Next, \ - create\ public\ point\ P'\ of\ prime\ order\ on\ twist\ - \(curve . \)\ *) \n - x1twist\ = \ 480775151193986876474195670157924389403361833567; \n - pubpointtwist\ = - \ {x1twist, \ - sqrtmod[Mod[x1twist\ Mod[x1twist^2\ + \ Atwist, p]\ + \ Btwist, p], - \ p], 1}; \n\nkb\ = \ 968525826201321079923232842886222248; - \ \ (*\ Private\ key\ \(K_B . \)\ *) \n\n{a, b}\ = \ {A, B}; - \ \ (*\ Prepare\ elliptic\ algebra\ for\ main\ \(curve . \)\ *) \n - pubkey\ = \ \ \ elliptic[pubpoint, \ kb]; - \ \ \ \ \ \ \ \ (*\ Public\ key\ \(P_B . \)\ *) \n\ - \n{a, b}\ = \ {Atwist, \ Btwist}; - \ \ \ (*\ Prepare\ elliptic\ algebra\ for\ twist\ \(curve . \)\ *) \n - pubkeytwist\ = \ \telliptic[pubpointtwist, \ kb]; - \ \ \ \ \ (*\ Public\ key\ \(P_B' . \)\ *) \n\ \n\t\t\n - encryptEmbed[x_] := \ - Module[{cubic, \ curve, \ X\ = \ x, \ Y, \ pbk, \ X1}, - \[IndentingNewLine] (*\ First, \ - let\ us\ determine\ which\ curve . \ \n\t\t\ \ \ EITHER\ X\ lies\ in - \ the\ curve\ y^2\ = \ X^3\ + \ A\ X\ + \ B, \n\t\t\ \ \ - or\ Xt\ := \ - \(g\ X\ lies\ on\ y^2\ = \ - Xt^3\ + \ Atwist\ Xt\ + \ Btwist\)\ *) \n\t\t\ - cubic\ = \ Mod[X\ Mod[X^2\ + \ A, p]\ + \ B, p]; \n\t\t\ - If[JacobiSymbol[cubic, \ p]\ > \ \(-1\), \ \n\t\t\t\ \ \ \ \ \ - curve\ = \ 1; \ {a, b}\ = \ {A, B}; \ pbk\ = \ pubkey; \ - pbp\ = \ pubpoint, \t\t\t\ \ \ \ \ \ \n\t\t\t\t\ \ \ \ \ - curve\ = \ \(-1\); \ {a, b}\ = \ {Atwist, \ Btwist}; \ - pbk\ = \ pubkeytwist; \ pbp\ = \ pubpointtwist; \ \n - \t\t\t\t\t\t\t\t\tX\ = \ g\ X; \ \n\t\t\ \ \ \ \ \ \ - cubic\ = \ Mod[X\ Mod[X^2\ + \ Atwist, p]\ + \ Btwist, p]\n - \t\t\ \ ]; \n\t\t\ \ Y\ = \ sqrtmod[cubic, \ p]; \ \ \n - \t\t\t (*\ - Now\ we\ \(have : \ \n\t\t\t\t\t\t\ \ - \((X\ = \ x, Y)\)\ or\ \((X\ = \ g\ x, \ Y)\) lies\ on\ the\ - respective\ curve\); \n\t\t\t\t\ \ \ \ - \((a, b)\)\ parameters\ are\ set\ up\ for\ respective\ - \(curve . \)\ *) \n\t\t\t\ \n\t\t\t - r\ = \ Random[Integer, \ {2, p - 2}]; \n\t\t\t - u\ = \ elladd[elliptic[pbk, \ r], \ {X, \ Y, 1}]; \n\t\t\t - c\ = \ elliptic[pbp, \ r]; \n - \t\t\ \ {u, \ c, \ curve}\[IndentingNewLine]]; \[IndentingNewLine]\n - decryptEmbed[cipherList_] := \ - Module[{u\ = \ cipherList[\([1]\)], \ c\ = \ cipherList[\([2]\)], \ - curve\ = \ cipherList[\([3]\)]}, - \[IndentingNewLine]If[curve\ == \ 1, \n - \t\t\t\t{a, b}\ = \ {A, \ B}, \n - \t\t\t\ \ {a, b}\ = \ {Atwist, \ Btwist}\n\t\t\ \ \ ]; \n\t\t - X\ = \ \(ellsub[u, \ elliptic[c, \ kb]]\)[\([1]\)]; \n\t\t - If[curve\ != \ 1, \ X\ = \ Mod[X\ PowerMod[g, \(-1\), \ p], p]]; \n - \t\t\tX\[IndentingNewLine]]; \[IndentingNewLine]\n\)}], "Input"], - -Cell[BoxData[{ - \( (*\ EXAMPLE\ *) \ \n\n - \[IndentingNewLine]ciph\ = \ - encryptEmbed[plain\ = \ 1324578918324567]\), - \(decryptEmbed[ciph]\)}], "Input"] -}, -FrontEndVersion->"NeXT 3.0", -ScreenRectangle->{{0, 957}, {0, 768}}, -WindowToolbars->{}, -WindowSize->{762, 676}, -WindowMargins->{{Automatic, 45}, {Automatic, 0}}, -ShowCellLabel->False -] - - -(*********************************************************************** -Cached data follows. If you edit this Notebook file directly, not using -Mathematica, you must remove the line containing CacheID at the top of -the file. The cache data will then be recreated when you save this file -from within Mathematica. -***********************************************************************) - -(*CellTagsOutline -CellTagsIndex->{} -*) - -(*CellTagsIndex -CellTagsIndex->{} -*) - -(*NotebookFileOutline -Notebook[{ -Cell[1709, 49, 546, 10, 202, "Input"], -Cell[2258, 61, 8194, 144, 2206, "Input"], -Cell[10455, 207, 171, 4, 78, "Input"] -} -] -*) - - - - -(*********************************************************************** -End of Mathematica Notebook file. -***********************************************************************) - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/FEEDsansY.nb b/OSX/include/security_cryptkit/CurveParamDocs/FEEDsansY.nb deleted file mode 100644 index 386f29ae..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/FEEDsansY.nb +++ /dev/null @@ -1,324 +0,0 @@ -(*********************************************************************** - - Mathematica-Compatible Notebook - -This notebook can be used on any computer system with Mathematica 3.0, -MathReader 3.0, or any compatible application. The data for the notebook -starts with the line of stars above. - -To get the notebook into a Mathematica-compatible application, do one of -the following: - -* Save the data starting with the line of stars above into a file - with a name ending in .nb, then open the file inside the application; - -* Copy the data starting with the line of stars above to the - clipboard, then use the Paste menu command inside the application. - -Data for notebooks contains only printable 7-bit ASCII and can be -sent directly in email or through ftp in text mode. Newlines can be -CR, LF or CRLF (Unix, Macintosh or MS-DOS style). - -NOTE: If you modify the data for this notebook not in a Mathematica- -compatible application, you must delete the line below containing the -word CacheID, otherwise Mathematica-compatible applications may try to -use invalid cache data. - -For more information on notebooks and Mathematica-compatible -applications, contact Wolfram Research: - web: http://www.wolfram.com - email: info@wolfram.com - phone: +1-217-398-0700 (U.S.) - -Notebook reader applications are available free of charge from -Wolfram Research. -***********************************************************************) - -(*CacheID: 232*) - - -(*NotebookFileLineBreakTest -NotebookFileLineBreakTest*) -(*NotebookOptionsPosition[ 12180, 264]*) -(*NotebookOutlinePosition[ 12859, 289]*) -(* CellTagsIndexPosition[ 12815, 285]*) -(*WindowFrame->Normal*) - - - -Notebook[{ -Cell[BoxData[ - \(\( (*\n\tNo - Y - coordinate\ version\ of\ Algorithm\ 8.1 .10; \n\t - see\ program\ 8.1 .10 . directembed . nb\n\t\t\t\n\n\ Support\ code\ - for\n\ R . \ Crandall\ and\ C . \ Pomerance, \n\ - "\"\n\ Springer - - Verlag\ 2001. \n\ c . \ 2000\ Perfectly\ Scientific, \ - Inc . \n\ All\ Rights\ Reserved . \n\t\n\t20\ Apr\ 2001\ RC\ - \((revamped\ for\ simplicity)\)\n\ 10\ Dec\ 2000\ AH\ - \((Formatting)\)\n\t14\ Sep\ 2000\ RT\ \((Creation)\)\n*) \n\)\)], - "Input"], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(\( (*\ CODE\ *) \n - \n (*\ First, \ a\ function\ for\ inverting\ n\ mod\ \(p . \)\ *) \n - ellinv[n_]\ := \ If[n == 0, 0, PowerMod[n, \(-1\), p]]; \n - \n (*\ Next, \ - a\ function\ for\ normalizing\ the\ x\ \(coordinate . \)\ *) \n - ex[pt_]\ := \ Mod[pt[\([1]\)]\ *\ ellinv[pt[\([2]\)]], \ p]; \n - \n (*\ Next, \ - the\ doubleh \(()\)\ function\ for\ doubling\ a\ \(point . \)\ *) \n - elleven[pt_]\ := \ \n\t - Block[{x1\ = \ pt[\([1]\)], \ z1\ = \ pt[\([2]\)], \ e, \ f\ }, \n - \ \ \t\te\ = \ - Mod[\((x1^2\ - \ a\ z1^2)\)^2\ - \ - 4\ b\ \((2\ x1\ + \ c\ z1)\)\ z1^3, \ p]; \n\ \ \t\t - f\ = \ Mod[ - 4\ z1\ \((x1^3\ + \ c\ x1^2\ z1\ + \ a\ x1\ z1^2\ + \ b\ z1^3) - \), \ p]; \n\ \ \t\t{e, f}\n\t]; \n - \n (*\ Next, \ - the\ addh \(()\)\ function\ for\ adding\ pt\ and\ pu\ with\ pv\ = \ - pt - pu\ known\ \n - \(\((x\ and\ z\ coordinates\ only\ of\ course)\) . \)\ *) \n - ellodd[pt_, \ pu_, \ pv_]\ := \ \n\t - Block[\n\t\t{x1\ = \ pt[\([1]\)], \ z1\ = \ pt[\([2]\)], \n\t\t\ - x2\ = \ pu[\([1]\)], \ z2\ = \ pu[\([2]\)], \n\t\t\ - xx\ = \ pv[\([1]\)], \ zz\ = \ pv[\([2]\)], \ i, \ j\n\t\t\ }, \n - \ \ \t\ \ \ \ \ - i\ = \ Mod[ - zz\ \((\((x1\ x2\ - \ a\ z1\ z2)\)^2\ - \n - \ \ \t\ \ \ \ \ \ \ \ \ \ \t - 4\ b \((x1\ z2\ + \ x2\ z1\ + \ c\ z1\ z2)\)\ z1\ z2)\), - \ \n\ \ \t\ \ \ \ \ \ \ \ \ \ \tp\n\ \ \t\ \ \ \ \ \ \ \ \ ]; \n - \ \ \t\ \ \ \ \ j\ = \ Mod[xx\ \((x1\ z2\ - \ x2\ z1)\)^2, \ p]; \n - \ \ \t\t\ {i, j}\n\t]; \n - \n (*\ Now, \ the\ main\ routine, \ elliptic\ multiply\ [k] \(pt . \)\ *) - \nelliptic[pt_, \ k_]\ := \ \n\t - Block[{porg, \ ps, \ pp, \ q}, \n\t\tIf[k\ == 1, \ Return[pt]]; \n\t\t - If[k\ == 2, \ Return[elleven[pt]]]; \n\t\tporg\ = \ pt; \n\t\t - ps\ = \ elleven[pt]; \n\t\tpp\ = \ pt; \n\t\t - bitlist\ = \ Reverse[IntegerDigits[k, 2]]; \n\t\t - Do[\t\ \ \ \n\t\ \ \ \t\t - If[bitlist[\([q]\)]\ == \ 1, \n\t\ \ \ \t\ \ \ \t\t - pp\ = \ ellodd[ps, \ pp, \ porg]; \n\t\ \ \ \t\ \ \ \t\t - ps\ = \ elleven[ps]\n\t\ \ \ \t\ \ \ \t\t, \n - \t\ \ \ \t\ \ \ \ \ \ \tps\ = \ ellodd[pp, \ ps, \ porg]; \n - \t\t\ \ \ \ \ \tpp\ = \ elleven[pp]\n\t\ \ \ \t\t]\n - \t\ \ \ \t\t, \n - \t\ \ \ \t\t{q, \ Length[bitlist] - 1, \ 1, \ \(-1\)}\n\ \ \ \ \t]; - \n\ \ \ \ \tReturn[Mod[pp, p]]\n\t]; \n - \n (*\ Next, \ - we\ include\ algorithm\ 2.3 .8\ for\ finding\ square\ roots\ \nmodulo\ - a\ prime\ \(p . \)\ *) \n\n - sqrtmod[b_, p_] := \ \n\t - Module[{a, x, c, d, cd, m, t, tst}, \n\ \ \ \t\ta\ = \ Mod[b, p]; \n - \ \ \ \t\tIf[p\ == \ 2, \ Return[a]]; \n\ \ \ \ \t - If[MemberQ[{3, 7}, Mod[p, 8]], \n\ \ \ \ \ \ \t\t - Return[PowerMod[a, \((p + 1)\)/4, p]]\n\ \ \ \ \ \ \t]; \n\ \ \ \ \t - If[Mod[p, 8]\ == \ 5, \n\ \ \ \ \ \ \t\t - x\ = \ PowerMod[a, \((p + 3)\)/8, p]; \n\ \ \ \ \ \ \t\t - c\ = \ Mod[x^2, p]; \n\ \ \ \ \ \ \t\t - If[Not[c\ == \ a], \n\ \ \ \ \ \ \ \ \t\t - Return[Mod[x\ PowerMod[2, \((p - 1)\)/4, p], \ p]]\n - \ \ \ \ \ \ \ \ \t]; \n\ \ \ \ \ \ \t]; \n\ \ \ \ \t\n - \ \ \ \ \t (*\ Here, \ p\ = \ 1\ \(\((mod\ 8)\) . \)\ *) \n - \ \ \ \ \ \ \ttst\ = \ 1; \n\ \ \ \ \ \ \t - While[Not[tst\ == \ \(-1\)], \n\ \ \ \ \ \ \ \ \t - d\ = \ Random[Integer, {1, p}]; \n\ \ \ \ \ \ \ \ \t - tst\ = \ JacobiSymbol[d, p]\n\ \ \ \ \ \ \ \ ]; \n\ \ \ \ \ \ \t - t\ = \ \((p - 1)\)/2; \ s\ = \ 1; \n\ \ \ \ \ \ \t - While[EvenQ[t], \ t\ = \ t/2; \ \(++s\)]; \n\ \ \ \ \ \ \t - ca\ = \ PowerMod[a, t, p]; \n\ \ \ \ \ \ \t - cd\ = \ PowerMod[d, t, p]; \n\ \ \ \ \ \ \tm\ = \ 0; \n - \ \ \ \ \ \ \t - Do[\n\ \ \ \ \ \ \t\ \ \ - If[PowerMod[Mod[ca\ PowerMod[cd, \ m, \ p], p], \ - 2^\((s - 1 - i)\), \ p]\n\ \ \ \ \ \ \t\ \ \ \t\t == \ p - 1, - \ m\ += \ 2^i]\n\ \ \ \ \ \ \t\ \ \ , {i, 0, s - 1}\n - \ \ \ \ \ \ \t]; \ \ \ \ \ \ \t\ \ \ \ \n\ \ \ \ \ \ \t - Return[Mod[PowerMod[a, \ \((t + 1)\)/2, p]\ PowerMod[cd, \ m/2, p], - p]]; \ \n\t]; \n - \n (*\ Next, \ a\ function\ relevant\ to\ Algorithm\ 7.2 \( .8 . \)\ *) \n - \nellXadd[x1_, x2_] := \n\t - Module[{u2, v, g}, \[IndentingNewLine]\t\tg = x1 - x2; - \[IndentingNewLine]\t\tden = PowerMod[g, \(-2\), p]; - \[IndentingNewLine]\t\t - alpha = Mod[ - \((\((x1\ x2 + a)\) \((x1 + x2)\) + 2 c\ x1\ x2 + 2 b)\), p]; - \[IndentingNewLine]\t\t - beta = Mod[\((\((x1\ x2 - a)\)^2 - 4 b \((x1 + x2 + c)\))\), p]; - \[IndentingNewLine]\t\tdisc = Mod[alpha^2 - beta\ g^2, p]; - \[IndentingNewLine]\t\t{\ \ - Mod[\ den*\((alpha + sqrtmod[disc, p])\), p], \ \n\t\t\ \ \ \ - Mod[den*\((alpha - sqrtmod[disc, p])\), p]\n\t\t} - \[IndentingNewLine]\t]; \n - \n (*\ Now, \ - the\ main\ routine . \ Parameters\ are\ given\ for\ 161 - - bit\ prime\ field\n\t\t\tand\ specific\ curve; \n\t\ \ - direct\ embedding\ proceeds\ on\ "\"\ integers\ x\ - \((mod\ p)\) . \ \n\ \ \ We\ start\ with\ relevant\ global\ - \((and\ public, \ except\ for\ kb)\)\n\ \ \ \(parameters . \)\n\ *) \n - \[IndentingNewLine]p\ = \ - 1654338658923174831024422729553880293604080853451; \na\ = \ \(-152\); - \nb = \ 722; \nc\ = \ 0; \ \ (*\ Montgomery\ \(parameter . \)\ *) \n - \n (*\ Next, \ - create\ public\ point\ P\ of\ prime\ order\ on\ main\ \(curve . \)\ *) - \npubpoint\ = - \ {124590448755381588517063157600522073397838354227, \ 1}; \ \ \n - pubpointtwist\ = - \ {1173563507729187954550227059395955904200719019884, 1}; \n\n - kb\ = \ 968525826201321079923232842886222248; - \ \ (*\ Private\ key\ \(K_B . \)\ *) \n\n - pubkey\ = \ \ \ elliptic[pubpoint, \ kb]; - \ \ \ \ \ \ \ \ (*\ Public\ key\ \(P_B . \)\ *) \n - pubkeytwist\ = \ \telliptic[pubpointtwist, \ kb]; - \ \ \ \ \ (*\ Public\ key\ \(P_B' . \)\ *) \n\ \n\t\t\n - encryptEmbed[x_] := \ - Module[{cubic, \ curve, \ X\ = \ x, \ pbk, \ pbp, \ clueX, \ X2, \ uX, - \n\t\t\ \ piece, \ try, \ sign}, - \[IndentingNewLine] (*\ First, \ - let\ us\ determine\ which\ curve . \ \n\t\t\ \ \ EITHER\ X\ lies\ in - \ the\ curve\ y^2\ = \ X^3\ + \ c\ X^2\ + \ a\ X\ + \ b, \n - \t\t\ \ \ - or\ on\ g\ y^2\ = \ X^3\ + \ c\ X^2\ + \ a\ X\ + \ b\ *) \n - \t\t\ cubic\ = \ Mod[X\ Mod[X^2\ + c\ X\ + \ \ a, p]\ + \ b, p]; - \n\t\t\ If[JacobiSymbol[cubic, \ p]\ > \ \(-1\), \ \n - \t\t\t\ \ \ \ \ \ curve\ = \ 1; \ pbk\ = \ pubkey; \ - pbp\ = \ pubpoint, \t\t\t\ \ \ \ \ \ \n\t\t\t\t\ \ \ \ \ - curve\ = \ \(-1\)\ ; \ pbk\ = \ pubkeytwist; \ - pbp\ = \ pubpointtwist; \ \n\t\t\ \ ]; \n\t\t\n\t\t\t - r\ = \ Random[Integer, \ {2, p - 2}]; \t\t\ \ \n\t\t\t - clueX\ = \ ex[elliptic[pbp, \ r]]; \n\t\t\ \ - X2\ = \ ex[elliptic[pbk, \ r]]; - \ (*\ We\ shall\ be\ adding\ the\ points\ having\ X, \ X2, \ - and\n\t\t\t\t\t\ \ \ there\ is\ a\ sign\ ambiguity\ a\ la\ Algorithm - \ 7.2 .8\ because\ Y - - coordinates\n\t\t\t\t\t\t\ \ are\ being\ \(avoided . \)\ *) \ \n - \t\t\ \ \ uX\ = \ \(ellXadd[X, \ X2]\)[\([1]\)]; \n\t\t\n - \t\t (*\ Next, \ - feedback\ loop\ to\ determine\ which\ value\ of\ sign\ recovers\ - \(plaintext . \)\ *) \n\t\t\n\t\t\ \ \ - piece\ = \ ex[elliptic[{clueX, 1}, \ kb]]; \t\t\ \n\t\t\ \ \ - try\ = \ ellXadd[uX, \ piece]; \n\n\t\t\t\ - If[\ttry[\([1]\)]\ == \ X, \ sign\ = \ 1, \n - \t\t\t\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ - If[try[\([2]\)]\ == \ X, \ sign\ = \ \(-1\), \ Print["\"]] - \n\t\t\t]; \t\t\t\t\ \ \ \ \ \ \ \ \n - \t\t\ \ {uX, \ clueX, \ curve, \ sign}\[IndentingNewLine]]; - \[IndentingNewLine]\n - decryptEmbed[cipherList_] := \ - Module[{uX\ = \ cipherList[\([1]\)], \ - clueX\ = \ cipherList[\([2]\)], \ curve\ = \ cipherList[\([3]\)], - \ sign\ = \ cipherList[\([4]\)]}, \n\t\t\ \ \ - piece\ = \ ex[elliptic[{clueX, 1}, \ kb]]; \t\t\ \n\t\t\ \ \ - try\ = \ ellXadd[uX, \ piece]; \n\t\t\ \ \ - X\ = \ try[\([\((3 - sign)\)/2]\)]; \n\t\t\tX\[IndentingNewLine]]; - \[IndentingNewLine]\n\)\)], "Input"], - -Cell[BoxData[ - \(General::"spell1" \( : \ \) - "Possible spelling error: new symbol name \"\!\(beta\)\" is similar to \ -existing symbol \"\!\(Beta\)\"."\)], "Message"], - -Cell[BoxData[ - \(General::"spell1" \( : \ \) - "Possible spelling error: new symbol name \"\!\(sign\)\" is similar to \ -existing symbol \"\!\(Sign\)\"."\)], "Message"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(\( (*\ EXAMPLE\ *) \ \n\n - ciph\ = \ encryptEmbed[plain\ = \ Random[Integer, p - 1]]; \n - If[decryptEmbed[ciph]\ != \ plain, \ Print["\"]], {ct, 1, 10}] - \)\)], "Input"], - -Cell[BoxData[ - \(General::"spell1" \( : \ \) - "Possible spelling error: new symbol name \"\!\(plain\)\" is similar to \ -existing symbol \"\!\(Plain\)\"."\)], "Message"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(p\)], "Input"], - -Cell[BoxData[ - \(1654338658923174831024422729553880293604080853451\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(CC\)], "Input"], - -Cell[BoxData[ - \(CC\)], "Output"] -}, Open ]], - -Cell[BoxData[ - \(6277101735386680763835789423207666416083908700390324961279\)], "Input"] -}, -FrontEndVersion->"NeXT 3.0", -ScreenRectangle->{{0, 957}, {0, 768}}, -WindowToolbars->{}, -WindowSize->{762, 676}, -WindowMargins->{{Automatic, 11}, {Automatic, 24}}, -ShowCellLabel->False -] - - -(*********************************************************************** -Cached data follows. If you edit this Notebook file directly, not using -Mathematica, you must remove the line containing CacheID at the top of -the file. The cache data will then be recreated when you save this file -from within Mathematica. -***********************************************************************) - -(*CellTagsOutline -CellTagsIndex->{} -*) - -(*CellTagsIndex -CellTagsIndex->{} -*) - -(*NotebookFileOutline -Notebook[{ -Cell[1709, 49, 576, 9, 242, "Input"], - -Cell[CellGroupData[{ -Cell[2310, 62, 8704, 154, 2269, "Input"], -Cell[11017, 218, 175, 3, 33, "Message"], -Cell[11195, 223, 175, 3, 33, "Message"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[11407, 231, 215, 4, 65, "Input"], -Cell[11625, 237, 177, 3, 33, "Message"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[11839, 245, 34, 1, 25, "Input"], -Cell[11876, 248, 83, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[11996, 254, 35, 1, 24, "Input"], -Cell[12034, 257, 36, 1, 24, "Output"] -}, Open ]], -Cell[12085, 261, 91, 1, 24, "Input"] -} -] -*) - - - - -(*********************************************************************** -End of Mathematica Notebook file. -***********************************************************************) - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/README b/OSX/include/security_cryptkit/CurveParamDocs/README deleted file mode 100644 index a5b938c2..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/README +++ /dev/null @@ -1,62 +0,0 @@ -TOOLS for Apple-CryptKit curve generation/testing. -24 Apr 2001 REC - -The state-of-the-art in ECC (elliptic-curve cryptography) -is in a well known mode of imperfection. For example, -it is very easy to generate CM (complex-multiplication) -curves, with known order and parameters; yet, it is suspected -by some (though unproven in any sense of rigor) -that better security accrues if curves are entirely -"random" in the sense of random base prime p, and random (a,b) -under minimal constraints such as prime curve order, etc. -Thus the collection of this Directory is a potpourri of -various tools, including a Schoof implementation (schoof.c, -schoofs.c) for arbitrary curves. As expected, said implementation -is very slow, yet we have used it for some of the current -CryptKit curves, while for other curves we have used the -fast CM methods, and for yet other curves we have borrowed -recommended parameters from other investigators. - -Contained in this Directory are various C sources: - -* curvegen.c, curvegenFEE.c - Utility for generating CM curves, links to other sources - as shown in comment atop source. - -* factor.c - Utility for factoring such as curve orders; - see comment atop source. - -* giants.c, ellproj.c, fmodule.c, tools.c - Number-theoretical library sources, having standard and - some ECC-specific tools. - -* schoof.c, shoofs.c - Curve-order finder, using the celebratd Schoof algorithm - When run, you input p, a, b (Weierstrass parameterization) - and out comes the curve order, sometimes after a very long - wait. The source schoofs.c is a "sieving Schoof" method - as explained in the References below, for finding curves - of prime-or-nearly-prime order (along with the same constraint - for twists). - -together with Mathematica sources: - -* curverecords.nb - A program to test current CryptKit points/orders. - -* FEED affine.nb, FEEDsansY.nb - Programs for testing FEED, in particular the integrity of - any choice for x1Minus (a coordinate for the twist curve). - -References - -Crandall R and Pomerance C, "Prime numbers: a computational perspective," Springer-Verlag, 2001. - -Crandall, R. E., U.S. Patents #5159632 (1992), #5271061 (1993), - #5463690 (1994), "Method and apparatus for public key exchange in - a cryptographic system." - -Crandall, R. E. 1996 U. S. Patent #5581616, "Method and apparatus - for Digital Signature Authentication." - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/curvegen.c b/OSX/include/security_cryptkit/CurveParamDocs/curvegen.c deleted file mode 100644 index fe3b8aa9..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/curvegen.c +++ /dev/null @@ -1,105 +0,0 @@ -/************************************************************** - * - * curvegen.c - * - * CM curve generator. - * - * Compile with: - * - * % cc -O curvegen.c tools.c giants.c ellproj.c -lm -o curvegen - * - * Updates: - * 27 Sep 98 REC - Creation - * - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -/* include files */ - -#include -#include -#include -#include -#ifdef _WIN32 - -#include - -#endif - -#include -#include "giants.h" -#include "tools.h" - -#define DCOUNT 27 - -int disc12[DCOUNT] = {-3, -4, -7, -8, -11, -19, -43, -67, -163, -15, -20, -24, -35, -40, -51, -52, -88, -91, -115, -123, -148, -187, -232, -235, -267, -403, -427}; /* All discriminants of class number 1,2. */ - -/************************************************************** - * - * Main Function - * - **************************************************************/ - -#define CM_SHORTS 4096 - -main(int argc, char **argv) { - giant p = newgiant(CM_SHORTS); - giant u = newgiant(CM_SHORTS); - giant v = newgiant(CM_SHORTS); - giant g[6]; - giant plus_order = newgiant(CM_SHORTS); - giant minus_order = newgiant(CM_SHORTS); - giant a = newgiant(CM_SHORTS); - giant b = newgiant(CM_SHORTS); - int d, dc, olen, k; - - init_tools(CM_SHORTS); /* Basic algorithms. */ - printf("Give base prime p:\n"); fflush(stdout); - gin(p); - for(dc=0; dc < 6; dc++) g[dc] = newgiant(CM_SHORTS); - for(dc = 0; dc < DCOUNT; dc++) { - d = disc12[dc]; - /* Next, seek representation 4N = u^2 + |d| v^2. */ - if(cornacchia4(p, d, u, v) == 0) continue; -/* Here, (u,v) give the quadratic representation of 4p. */ - printf("D: %d\n", d); fflush(stdout); - gtog(u, g[0]); - switch(d) { - case -3: olen = 3; /* Six orders: p + 1 +- g[0,1,2]. */ - gtog(u, g[1]); gtog(v, g[2]); - addg(g[2], g[2]); addg(v, g[2]); /* g[2] := 3v. */ - addg(g[2], g[1]); gshiftright(1, g[1]); /* g[1] = (u + 3v)/2. */ - subg(u, g[2]); gshiftright(1, g[2]); absg(g[2]); /* g[2] = |u-3v|/2. */ - break; - case -4: olen = 2; /* Four orders: p + 1 +- g[0,1]. */ - gtog(v, g[1]); addg(g[1], g[1]); /* g[1] = 2v. */ - break; - default: olen = 1; /* Two orders: p + 1 +- g[0]. */ - } - for(k=0; k < olen; k++) { - gtog(p, plus_order); iaddg(1, plus_order); - gtog(p, minus_order); iaddg(1, minus_order); - addg(g[k], plus_order); - subg(g[k], minus_order); - printf("curve orders: \n"); - printf("(%d) ", prime_probable(plus_order)); - gout(plus_order); - printf("(%d) ", prime_probable(minus_order)); - gout(minus_order); - } - } -} - - - - - - - - - - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/curverecords.nb b/OSX/include/security_cryptkit/CurveParamDocs/curverecords.nb deleted file mode 100644 index f66f4f8d..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/curverecords.nb +++ /dev/null @@ -1,898 +0,0 @@ -(*********************************************************************** - - Mathematica-Compatible Notebook - -This notebook can be used on any computer system with Mathematica 3.0, -MathReader 3.0, or any compatible application. The data for the notebook -starts with the line of stars above. - -To get the notebook into a Mathematica-compatible application, do one of -the following: - -* Save the data starting with the line of stars above into a file - with a name ending in .nb, then open the file inside the application; - -* Copy the data starting with the line of stars above to the - clipboard, then use the Paste menu command inside the application. - -Data for notebooks contains only printable 7-bit ASCII and can be -sent directly in email or through ftp in text mode. Newlines can be -CR, LF or CRLF (Unix, Macintosh or MS-DOS style). - -NOTE: If you modify the data for this notebook not in a Mathematica- -compatible application, you must delete the line below containing the -word CacheID, otherwise Mathematica-compatible applications may try to -use invalid cache data. - -For more information on notebooks and Mathematica-compatible -applications, contact Wolfram Research: - web: http://www.wolfram.com - email: info@wolfram.com - phone: +1-217-398-0700 (U.S.) - -Notebook reader applications are available free of charge from -Wolfram Research. -***********************************************************************) - -(*CacheID: 232*) - - -(*NotebookFileLineBreakTest -NotebookFileLineBreakTest*) -(*NotebookOptionsPosition[ 18376, 710]*) -(*NotebookOutlinePosition[ 19227, 740]*) -(* CellTagsIndexPosition[ 19183, 736]*) -(*WindowFrame->Normal*) - - - -Notebook[{ -Cell["\<\ -(* curverecords - - Recorded data for Apple ECC curves. - - R. Crandall - 3 Apr 2001 - - - *) - -pointQ[x_] := (JacobiSymbol[x^3 + c x^2 + a x + b, p] > -1); - -(* Next, binary expansion for very old M'ca versions, - otherwise use IntegerDigits[.,2]. *) -bitList[k_] := Block[{li = {}, j = k}, -\tWhile[j > 0, -\t li = Append[li, Mod[j,2]]; -\t j = Floor[j/2]; -\t]; -\tReturn[Reverse[li]]; -\t]; -\t -ellinv[n_] := PowerMod[n,-1,p]; -(* Next, obtain actual x,y coords via normalization: - {x,y,z} := {X/Z^2, Y/Z^3, 1}. *) -normalize[pt_] := Block[{z,z2,z3}, -\t\tIf[pt[[3]] == 0, Return[pt]]; -\t\tz = ellinv[pt[[3]]]; -\t\tz2 = Mod[z^2,p]; -\t\tz3 = Mod[z z2,p]; -\t\tReturn[{Mod[pt[[1]] z2, p], Mod[pt[[2]] z3, p], 1}]; -\t\t]; - -ellneg[pt_] := Mod[pt * {1,-1,1}, p]; -ellsub[pt1_, pt2_] := elladd[pt1, ellneg[pt2]]; -elldouble[pt_] := Block[{x,y,z,m,y2,s}, -\tx = pt[[1]]; y = pt[[2]]; z = pt[[3]]; -\tIf[(y==0) || (z==0), Return[{1,1,0}]]; -\tm = Mod[3 x^2 + a Mod[Mod[z^2,p]^2,p],p]; -\tz = Mod[2 y z, p]; -\ty2 = Mod[y^2,p]; -\ts = Mod[4 x y2,p]; -\tx = Mod[m^2 - 2s,p]; -\ty = Mod[m(s - x) - 8 y2^2,p]; -\tReturn[{x,y,z}]; -]; - -elladd[pt0_, pt1_] := Block[ -\t{x0,y0,z0,x1,y1,z1, -\tt1,t2,t3,t4,t5,t6,t7}, -\tx0 = pt0[[1]]; y0 = pt0[[2]]; z0 = pt0[[3]]; -\tx1 = pt1[[1]]; y1 = pt1[[2]]; z1 = pt1[[3]]; -\tIf[z0 == 0, Return[pt1]]; -\tIf[z1 == 0, Return[pt0]]; - -\tt1 = x0; -\tt2 = y0; -\tt3 = z0; -\tt4 = x1; -\tt5 = y1; -\tIf[(z1 != 1), -\t\tt6 = z1; -\t\tt7 = Mod[t6^2, p]; -\t\tt1 = Mod[t1 t7, p]; -\t\tt7 = Mod[t6 t7, p]; -\t\tt2 = Mod[t2 t7, p]; -\t]; -\tt7 = Mod[t3^2, p]; -\tt4 = Mod[t4 t7, p]; -\tt7 = Mod[t3 t7, p]; -\tt5 = Mod[t5 t7, p]; -\tt4 = Mod[t1-t4, p]; -\tt5 = Mod[t2 - t5, p]; -\tIf[t4 == 0, If[t5 == 0, -\t\t\t\t Return[elldouble[pt0]], -\t \t\t\t\tReturn[{1,1,0}] -\t \t\t\t] -\t]; -\tt1 = Mod[2t1 - t4,p]; -\tt2 = Mod[2t2 - t5, p]; -\tIf[z1 != 1, t3 = Mod[t3 t6, p]]; -\tt3 = Mod[t3 t4, p]; -\tt7 = Mod[t4^2, p]; -\tt4 = Mod[t4 t7, p]; -\tt7 = Mod[t1 t7, p]; -\tt1 = Mod[t5^2, p]; -\tt1 = Mod[t1-t7, p]; -\tt7 = Mod[t7 - 2t1, p]; -\tt5 = Mod[t5 t7, p]; -\tt4 = Mod[t2 t4, p]; -\tt2 = Mod[t5-t4, p]; -\tIf[EvenQ[t2], t2 = t2/2, t2 = (p+t2)/2]; -\tReturn[{t1, t2, t3}]; -]; -\t\t -(* Next, elliptic-multiply a normalized pt by k. *) -elliptic[pt_, k_] := Block[{pt2, hh, kk, hb, kb, lenh, lenk}, -\tIf[k==0, Return[{1,1,0}]]; -\thh = Reverse[bitList[3k]]; -\tkk = Reverse[bitList[k]]; -\tpt2 = pt; -\tlenh = Length[hh]; -\tlenk = Length[kk]; -\tDo[ -\t\tpt2 = elldouble[pt2]; -\t\thb = hh[[b]]; -\t\tIf[b <= lenk, kb = kk[[b]], kb = 0]; -\t\tIf[{hb,kb} == {1,0}, -\t\t\tpt2 = elladd[pt2, pt], -\t\t\tIf[{hb, kb} == {0,1}, -\t\t\tpt2 = ellsub[pt2, pt]] -\t\t] -\t ,{b, lenh-1, 2,-1} -\t ]; -\tReturn[pt2]; -]; - -(* Next, provide point-finding functions. *) - -(* Next, perform (a + b w)^n (mod p), where pair = {a,b}, w2 = w^2. *) -pow[pair_, w2_, n_, p_] := Block[{bitlist, z}, - bitlist = bitList[n]; - z = pair; -\tDo[\t -\t zi = Mod[z[[2]]^2,p]; -\t z = {Mod[z[[1]]^2 + w2 zi, p], Mod[2 z[[1]] z[[2]], p]}; -\t If[bitlist[[q]] == 1, -\t zi = Mod[pair[[2]] z[[2]], p]; -\t \t z = {Mod[pair[[1]] z[[1]] + w2 zi, p], -\t \t Mod[pair[[1]] z[[2]] + pair[[2]] z[[1]], p]}; -\t ], -\t {q,2,Length[bitlist]} - ]; - Return[z] -]; - - -sqrt[x_, p_] := Module[{t, b, w2}, - If[Mod[x,p] == 0, Return[0]]; -\tIf[Mod[p,4] == 3, Return[PowerMod[x, (p+1)/4, p]]]; -\tIf[Mod[p,8] == 5, -\t\tb = PowerMod[x, (p-1)/4, p]; -\t\tIf[b==1, Return[PowerMod[x, (p+3)/8, p]], -\t\t\tReturn[Mod[2x PowerMod[4x, (p-5)/8,p],p]] -\t\t] -\t]; -\tt = 2; - While[True, - w2 = Mod[t^2 - x, p]; - If[JacobiSymbol[w2,p] == -1, Break[]]; - ++t - ]; - (* Next, raise (t + Sqrt[w2])^((p+1)/2). *) - t = pow[{t,1},w2, (p+1)/2, p]; - Return[t[[1]]]; - ]; - -findpoint[start_] := Block[{x = start, y, s}, -\tWhile[True, -\t s = Mod[x(Mod[x^2+a,p]) + b, p]; -\t y = sqrt[s, p]; -\t If[Mod[y^2, p] == s, Break[]]; -\t ++x; -\t]; -\tReturn[{x, y, 1}] -]; - -report[a_] := Module[{ia = IntegerDigits[a,65536]}, - Prepend[Reverse[ia], Length[ia]] - ]; - \ -\>", "Input", - AspectRatioFixed->True], - -Cell[CellGroupData[{ - -Cell["\<\ - - - -report[a_] := Module[{ia = IntegerDigits[a,65536]}, - Prepend[Reverse[ia], Length[ia]] - ]; - - -(* Case of Weierstrass/feemod curve. *) -p = 2^127 + 57675 -report[p] -r = 512000; s = 512001; - -a = Mod[-3 r s^3, p] -report[a] -b = Mod[-2 r s^5, p] -report[b] -pt = findpoint[3]; -pt -plusOrd = 170141183460469231756943134065055014407 -report[plusOrd] -PrineQ[plusOrd] -minusOrd = 170141183460469231706431473366713312401 -report[minusOrd] -PrimeQ[minusOrd] -elliptic[pt, plusOrd] -elliptic[pt, minusOrd]\ -\>", "Input", - AspectRatioFixed->True], - -Cell[BoxData[ - \(170141183460469025572049133804586627403\)], "Output"], - -Cell[BoxData[ - \({8, 29003, 44777, 29962, 4169, 54360, 65535, 65535, 32767}\)], "Output"], - -Cell[BoxData[ - \(170105154311605172483148226534443139403\)], "Output"], - -Cell[BoxData[ - \({8, 16715, 42481, 16221, 60523, 56573, 13644, 4000, 32761}\)], "Output"], - -Cell[BoxData[ - \(Reverse::"normal" \( : \ \) - "Nonatomic expression expected at position \!\(1\) in \ -\!\(Reverse[ib]\)."\)], "Message"], - -Cell[BoxData[ - \(Join::"heads" \( : \ \) - "Heads \!\(List\) and \!\(Reverse\) at positions \!\(1\) and \!\(2\) \ -are expected to be the same."\)], "Message"], - -Cell[BoxData[ - \(Join[{0}, Reverse[ib]]\)], "Output"], - -Cell[BoxData[ - \({6, 30690820274365139284340271178980469693, 1}\)], "Output"], - -Cell[BoxData[ - \({1, 1, 0}\)], "Output"], - -Cell[BoxData[ - \({29855379595419734109449938959593549451, - 71894799143021275114012027736812077762, - 78629090074833058028405436736324079039}\)], "Output"], - -Cell[CellGroupData[{ - -Cell[BoxData[{ - \( (*\ Case\ of\ Weierstrass/gen . \ mod\ \(curve . \)\ *) \n - p\ = \ 1654338658923174831024422729553880293604080853451; \n - Mod[p, 4]\), - \(Length[IntegerDigits[p, 2]]\), - \(report[p]\), - \(PrimeQ[p]\n\n\), - \(a\ = \ \(-152\); \nreport[a]\), - \(b\ = \ Mod[722, \ p]\), - \(report[b]\), - \(ptplus\ = \ - findpoint[1245904487553815885170631576005220733978383542270]\), - \(ptminus\ = \ - findpoint[1173563507729187954550227059395955904200719019884]\), - \(plusOrd\ = \ \ 1654338658923174831024425147405519522862430265804; \n - report[plusOrd]\), - \(PrimeQ[plusOrd]\), - \(minusOrd\ = \ 2 p + 2\ - \ plusOrd\), - \(report[minusOrd]\), - \(PrimeQ[minusOrd]\n\), - \(pt2\ = \ - elliptic[ptplus, \ plusOrd/\((2^2\ *\ 23\ *\ 359\ *\ 479\ *\ 102107)\)] - \), - \(pt3\ = \ elliptic[ptminus, \ minusOrd/\((2^2\ *\ 5^2\ *\ 17^2)\)]\)}], - "Input"], - -Cell[BoxData[ - \(3\)], "Output"], - -Cell[BoxData[ - \(161\)], "Output"], - -Cell[BoxData[ - \({11, 41419, 58349, 36408, 14563, 25486, 9098, 29127, 50972, 7281, 8647, - 1}\)], "Output"], - -Cell[BoxData[ - \(True\)], "Output"], - -Cell[BoxData[ - \({1, 152}\)], "Output"], - -Cell[BoxData[ - \(722\)], "Output"], - -Cell[BoxData[ - \({1, 722}\)], "Output"], - -Cell[BoxData[ - \({1245904487553815885170631576005220733978383542270, - 560361014661268580786436670038204012763093444403, 1}\)], "Output"], - -Cell[BoxData[ - \({1173563507729187954550227059395955904200719019885, - 1175039848591896005104837959278049495835875105211, 1}\)], "Output"], - -Cell[BoxData[ - \({11, 41420, 58349, 36408, 14563, 25486, 9100, 29127, 50972, 7281, 8647, - 1}\)], "Output"], - -Cell[BoxData[ - \(False\)], "Output"], - -Cell[BoxData[ - \(1654338658923174831024420311702241064345731441100\)], "Output"], - -Cell[BoxData[ - \({11, 41420, 58349, 36408, 14563, 25486, 9096, 29127, 50972, 7281, 8647, - 1}\)], "Output"], - -Cell[BoxData[ - \(False\)], "Output"], - -Cell[BoxData[ - \({1, 1, 0}\)], "Output"], - -Cell[BoxData[ - \({1190583420013022954017374261618382173651469909929, - 629194203259568943908951973353992532594049316627, - 1243063853191133727091858197899695654928311311960}\)], "Output"] -}, Open ]] -}, Open ]], - -Cell[CellGroupData[{ - -Cell["\<\ - - -(* Case of Weierstrass/feemod curve. *) -p = 2^160 + 5875 -report[p] -PrimeQ[p] -r = 512; s = 513; - -a = Mod[-3 r s^3, p] -report[a] -b = Mod[2 r s^5, p] -report[b] -pt = findpoint[3]; -pt -plusOrd = 1461501637330902918203687223801810245920805144027 -report[plusOrd] -PrimeQ[plusOrd] -minusOrd = 1461501637330902918203682441630755793391059953677 -report[minusOrd] -PrimeQ[minusOrd] - -elliptic[pt, plusOrd] -elliptic[pt, minusOrd]\ -\>", "Input", - AspectRatioFixed->True], - -Cell[BoxData[ - \(1461501637330902918203684832716283019655932548851\)], "Output"], - -Cell[BoxData[ - \({11, 5875, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}\)], "Output"], - -Cell[BoxData[ - \(True\)], "Output"], - -Cell[BoxData[ - \(1461501637330902918203684832716283019448563798259\)], "Output"], - -Cell[BoxData[ - \({11, 4339, 47068, 65487, 65535, 65535, 65535, 65535, 65535, 65535, - 65535, 0}\)], "Output"], - -Cell[BoxData[ - \(36382017816364032\)], "Output"], - -Cell[BoxData[ - \({4, 1024, 41000, 16704, 129}\)], "Output"], - -Cell[BoxData[ - \({7, 1141381147330837701163756056508811445797829159301, 1}\)], "Output"], - -Cell[BoxData[ - \(1461501637330902918203687223801810245920805144027\)], "Output"], - -Cell[BoxData[ - \({11, 50651, 30352, 49719, 403, 64085, 1, 0, 0, 0, 0, 1}\)], "Output"], - -Cell[BoxData[ - \(True\)], "Output"], - -Cell[BoxData[ - \(1461501637330902918203682441630755793391059953677\)], "Output"], - -Cell[BoxData[ - \({11, 26637, 35183, 15816, 65132, 1450, 65534, 65535, 65535, 65535, - 65535, 0}\)], "Output"], - -Cell[BoxData[ - \(True\)], "Output"], - -Cell[BoxData[ - \({1, 1, 0}\)], "Output"], - -Cell[BoxData[ - \({626678646813931825585362114548610779332932369721, - 425645027836716936906396416648647850487040622280, - 374678203163702432662589149043052098374578486466}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[{ - \( (*\ Case\ of\ NIST\ P - 192. \ *) \n - p\ = \ 6277101735386680763835789423207666416083908700390324961279; \n - Mod[p, 4]\), - \(Length[IntegerDigits[p, 2]]\), - \(report[p]\), - \(PrimeQ[p]\n\n\), - \(a\ = \ \(-3\); \nreport[a]\), - \(b\ = \ - Mod[\(-2455155546008943817740293915197451784769108058161191238065\), \ - p]\), - \(report[b]\), - \(pt\ = \ findpoint[3]; \npt\), - \(plusOrd\ = \ \ - 6277101735386680763835789423176059013767194773182842284081\), - \(report[plusOrd]\), - \(PrimeQ[plusOrd]\), - \(minusOrd\ = \ 2 p + 2\ - \ plusOrd\), - \(report[minusOrd]\), - \(PrimeQ[minusOrd]\), - \(elliptic[pt, \ plusOrd]\), - \(pt2\ = \ elliptic[pt, \ 23]\), - \(pt\ = \ elliptic[pt2, \ minusOrd/23]\), - \(report[minusOrd/23]\)}], "Input"], - -Cell[BoxData[ - \(3\)], "Output"], - -Cell[BoxData[ - \(192\)], "Output"], - -Cell[BoxData[ - \({12, 65535, 65535, 65535, 65535, 65534, 65535, 65535, 65535, 65535, - 65535, 65535, 65535}\)], "Output"], - -Cell[BoxData[ - \(True\)], "Output"], - -Cell[BoxData[ - \({1, 3}\)], "Output"], - -Cell[BoxData[ - \(3821946189377736946095495508010214631314800642229133723214\)], "Output"], - -Cell[BoxData[ - \({12, 17998, 16057, 8467, 327, 53173, 36315, 5716, 61528, 32536, 6755, - 64230, 39902}\)], "Output"], - -Cell[BoxData[ - \({3, 2573760116079900500718205355717584033158714840310676461950, 1}\)], - "Output"], - -Cell[BoxData[ - \(6277101735386680763835789423176059013767194773182842284081\)], "Output"], - -Cell[BoxData[ - \({12, 10289, 46290, 51633, 5227, 63542, 39390, 65535, 65535, 65535, - 65535, 65535, 65535}\)], "Output"], - -Cell[BoxData[ - \(True\)], "Output"], - -Cell[BoxData[ - \(6277101735386680763835789423239273818400622627597807638479\)], "Output"], - -Cell[BoxData[ - \({12, 55247, 19245, 13902, 60308, 1991, 26145, 0, 0, 0, 0, 0, 0}\)], - "Output"], - -Cell[BoxData[ - \(False\)], "Output"], - -Cell[BoxData[ - \({1974979226733528697945860683178722101664119564992975891016, - 4098724835649872426757510355842063594543191498480025032993, - 6276809135556566751199297417037505266020088100630063387404}\)], "Output"], - -Cell[BoxData[ - \({4331701396234773295967464070295991827703321716502384917379, - 6038875199291747318091498070766965234564517946489302751105, - 2975197300407214290225034931542769825877023149833302700493}\)], "Output"], - -Cell[BoxData[ - \({1, 1, 0}\)], "Output"], - -Cell[BoxData[ - \({12, 16649, 40728, 9152, 53911, 59923, 9684, 22795, 17096, 45590, - 34192, 25644, 2849}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(normalize[pt2]\)], "Input"], - -Cell[BoxData[ - \({572757471182948021179439097275935071491066938838024362853, - 1582598775998321197887787208733859332485461160705858323879, 1}\)], - "Output"], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(report[%[\([1]\)]]\)], "Input"], - -Cell[BoxData[ - \({12, 39781, 2122, 19172, 23122, 40686, 43699, 10062, 14682, 25122, - 55271, 56820, 5979}\)], "Output"] -}, Open ]] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[{ - \(minusOrd\), - \(plusOrd\)}], "Input"], - -Cell[BoxData[ - \(6277101735386680763835789423239273818400622627597807638479\)], "Output"], - -Cell[BoxData[ - \(6277101735386680763835789423176059013767194773182842284081\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(IntegerDigits[13, 2]\)], "Input"], - -Cell[BoxData[ - \({1, 1, 0, 1}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[{ - \(minusOrd/23\), - \(\treport[minusOrd/23]\)}], "Input"], - -Cell[BoxData[ - \(272917466755942641905903887966924948626114027286861201673\)], "Output"], - -Cell[BoxData[ - \({12, 16649, 40728, 9152, 53911, 59923, 9684, 22795, 17096, 45590, - 34192, 25644, 2849}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(ord\ = \ 1024120625531724089187207582052247831; \n - Floor[4^Length[IntegerDigits[plusOrd, \ 2]]/plusOrd]\)], "Input"], - -Cell[BoxData[ - \(5846006549323611672814729766523023173564239767715\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(report[%]\)], "Input"], - -Cell[BoxData[ - \({11, 59555, 9660, 63266, 63920, 5803, 65528, 65535, 65535, 65535, - 65535, 3}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(IntegerDigits[ - 6277101735386680763835789423207666416083908700390324961279, 2]\)], - "Input"], - -Cell[BoxData[ - \({1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[{ - \(a\), - \(b\), - \(JacobiSymbol[3^3\ + \ a\ *\ 3\ - \ b, \ p]\)}], "Input"], - -Cell[BoxData[ - \(\(-3\)\)], "Output"], - -Cell[BoxData[ - \(3821946189377736946095495508010214631314800642229133723214\)], "Output"], - -Cell[BoxData[ - \(1\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(minusOrd\)], "Input"], - -Cell[BoxData[ - \(6277101735386680763835789423239273818400622627597807638479\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(o\ = 272917466755942641905903887966924948626114027286861201673; \n - Floor[4^Length[IntegerDigits[o, 2]]/o]\)], "Input"], - -Cell[BoxData[ - \(563958359038647099875871705988474052021461054728890671516\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(report[%]\)], "Input"], - -Cell[BoxData[ - \({12, 57756, 63294, 44830, 2517, 2125, 63187, 65535, 65535, 65535, - 65535, 65535, 5887}\)], "Output"] -}, Open ]], - -Cell[CellGroupData[{ - -Cell[BoxData[ - \(IntegerDigits[1654338658923174831024422729553880293604080853451, 2]\)], - "Input"], - -Cell[BoxData[ - \({1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, - 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, - 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, - 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, - 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, - 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, - 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1}\)], "Output"] -}, Open ]] -}, -FrontEndVersion->"NeXT 3.0", -ScreenRectangle->{{0, 957}, {0, 768}}, -WindowToolbars->{}, -CellGrouping->Manual, -WindowSize->{520, 600}, -WindowMargins->{{Automatic, 44}, {-10, Automatic}}, -PrivateNotebookOptions->{"ColorPalette"->{RGBColor, -1}}, -ShowCellLabel->True, -ShowCellTags->False, -RenderingOptions->{"ObjectDithering"->True, -"RasterDithering"->False} -] - - -(*********************************************************************** -Cached data follows. If you edit this Notebook file directly, not using -Mathematica, you must remove the line containing CacheID at the top of -the file. The cache data will then be recreated when you save this file -from within Mathematica. -***********************************************************************) - -(*CellTagsOutline -CellTagsIndex->{} -*) - -(*CellTagsIndex -CellTagsIndex->{} -*) - -(*NotebookFileOutline -Notebook[{ -Cell[1709, 49, 4062, 173, 2136, "Input"], - -Cell[CellGroupData[{ -Cell[5796, 226, 556, 29, 336, "Input"], -Cell[6355, 257, 73, 1, 24, "Output"], -Cell[6431, 260, 92, 1, 24, "Output"], -Cell[6526, 263, 73, 1, 24, "Output"], -Cell[6602, 266, 92, 1, 24, "Output"], -Cell[6697, 269, 145, 3, 33, "Message"], -Cell[6845, 274, 166, 3, 33, "Message"], -Cell[7014, 279, 56, 1, 24, "Output"], -Cell[7073, 282, 80, 1, 24, "Output"], -Cell[7156, 285, 43, 1, 24, "Output"], -Cell[7202, 288, 168, 3, 50, "Output"], - -Cell[CellGroupData[{ -Cell[7395, 295, 949, 24, 381, "Input"], -Cell[8347, 321, 35, 1, 24, "Output"], -Cell[8385, 324, 37, 1, 24, "Output"], -Cell[8425, 327, 115, 2, 37, "Output"], -Cell[8543, 331, 38, 1, 24, "Output"], -Cell[8584, 334, 42, 1, 24, "Output"], -Cell[8629, 337, 37, 1, 24, "Output"], -Cell[8669, 340, 42, 1, 24, "Output"], -Cell[8714, 343, 145, 2, 37, "Output"], -Cell[8862, 347, 146, 2, 37, "Output"], -Cell[9011, 351, 115, 2, 37, "Output"], -Cell[9129, 355, 39, 1, 24, "Output"], -Cell[9171, 358, 83, 1, 24, "Output"], -Cell[9257, 361, 115, 2, 37, "Output"], -Cell[9375, 365, 39, 1, 24, "Output"], -Cell[9417, 368, 43, 1, 24, "Output"], -Cell[9463, 371, 200, 3, 50, "Output"] -}, Open ]] -}, Open ]], - -Cell[CellGroupData[{ -Cell[9712, 380, 469, 25, 312, "Input"], -Cell[10184, 407, 83, 1, 24, "Output"], -Cell[10270, 410, 74, 1, 24, "Output"], -Cell[10347, 413, 38, 1, 24, "Output"], -Cell[10388, 416, 83, 1, 24, "Output"], -Cell[10474, 419, 117, 2, 37, "Output"], -Cell[10594, 423, 51, 1, 24, "Output"], -Cell[10648, 426, 62, 1, 24, "Output"], -Cell[10713, 429, 91, 1, 24, "Output"], -Cell[10807, 432, 83, 1, 24, "Output"], -Cell[10893, 435, 89, 1, 24, "Output"], -Cell[10985, 438, 38, 1, 24, "Output"], -Cell[11026, 441, 83, 1, 24, "Output"], -Cell[11112, 444, 117, 2, 37, "Output"], -Cell[11232, 448, 38, 1, 24, "Output"], -Cell[11273, 451, 43, 1, 24, "Output"], -Cell[11319, 454, 198, 3, 50, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[11554, 462, 844, 23, 420, "Input"], -Cell[12401, 487, 35, 1, 24, "Output"], -Cell[12439, 490, 37, 1, 24, "Output"], -Cell[12479, 493, 129, 2, 37, "Output"], -Cell[12611, 497, 38, 1, 24, "Output"], -Cell[12652, 500, 40, 1, 24, "Output"], -Cell[12695, 503, 92, 1, 24, "Output"], -Cell[12790, 506, 124, 2, 37, "Output"], -Cell[12917, 510, 103, 2, 50, "Output"], -Cell[13023, 514, 92, 1, 24, "Output"], -Cell[13118, 517, 128, 2, 37, "Output"], -Cell[13249, 521, 38, 1, 24, "Output"], -Cell[13290, 524, 92, 1, 24, "Output"], -Cell[13385, 527, 100, 2, 24, "Output"], -Cell[13488, 531, 39, 1, 24, "Output"], -Cell[13530, 534, 228, 3, 89, "Output"], -Cell[13761, 539, 228, 3, 89, "Output"], -Cell[13992, 544, 43, 1, 24, "Output"], -Cell[14038, 547, 126, 2, 37, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[14201, 554, 47, 1, 25, "Input"], -Cell[14251, 557, 166, 3, 63, "Output"], - -Cell[CellGroupData[{ -Cell[14442, 564, 51, 1, 25, "Input"], -Cell[14496, 567, 127, 2, 37, "Output"] -}, Open ]] -}, Open ]], - -Cell[CellGroupData[{ -Cell[14672, 575, 61, 2, 38, "Input"], -Cell[14736, 579, 92, 1, 24, "Output"], -Cell[14831, 582, 92, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[14960, 588, 53, 1, 25, "Input"], -Cell[15016, 591, 46, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[15099, 597, 78, 2, 38, "Input"], -Cell[15180, 601, 91, 1, 24, "Output"], -Cell[15274, 604, 126, 2, 37, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[15437, 611, 141, 2, 38, "Input"], -Cell[15581, 615, 83, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[15701, 621, 42, 1, 25, "Input"], -Cell[15746, 624, 116, 2, 37, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[15899, 631, 119, 3, 51, "Input"], -Cell[16021, 636, 666, 9, 128, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[16724, 650, 103, 3, 51, "Input"], -Cell[16830, 655, 40, 1, 24, "Output"], -Cell[16873, 658, 92, 1, 24, "Output"], -Cell[16968, 661, 35, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[17040, 667, 41, 1, 24, "Input"], -Cell[17084, 670, 92, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[17213, 676, 143, 2, 64, "Input"], -Cell[17359, 680, 91, 1, 24, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[17487, 686, 42, 1, 25, "Input"], -Cell[17532, 689, 126, 2, 37, "Output"] -}, Open ]], - -Cell[CellGroupData[{ -Cell[17695, 696, 103, 2, 38, "Input"], -Cell[17801, 700, 559, 7, 115, "Output"] -}, Open ]] -} -] -*) - - - - -(*********************************************************************** -End of Mathematica Notebook file. -***********************************************************************) - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/disc.h b/OSX/include/security_cryptkit/CurveParamDocs/disc.h deleted file mode 100644 index 09461933..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/disc.h +++ /dev/null @@ -1,312 +0,0 @@ - -#define DISC_COUNT 1666 /* All fundamental (negatuve) D with - |D| <= 20000, h(D) <= 20. */ - -/* Next, list of fundamental discriminants |D| <= 20000, h(D) <= 20. */ -int disc[DISC_COUNT] = {-3, -4, -7, -8, -11, -19, -43, -67, -163, -15, -20, -24, -35, -40, -51, -52, - - -88, -91, -115, -123, -148, -187, -232, -235, -267, -403, -427, -23, -31, -59, - - -83, -107, -139, -211, -283, -307, -331, -379, -499, -547, -643, -883, -907, - - -39, -55, -56, -68, -84, -120, -132, -136, -155, -168, -184, -195, -203, -219, - - -228, -259, -280, -291, -292, -312, -323, -328, -340, -355, -372, -388, -408, - - -435, -483, -520, -532, -555, -568, -595, -627, -667, -708, -715, -723, -760, - - -763, -772, -795, -955, -1003, -1012, -1027, -1227, -1243, -1387, -1411, - - -1435, -1507, -1555, -47, -79, -103, -127, -131, -179, -227, -347, -443, -523, - - -571, -619, -683, -691, -739, -787, -947, -1051, -1123, -1723, -1747, -1867, - - -2203, -2347, -2683, -87, -104, -116, -152, -212, -244, -247, -339, -411, - - -424, -436, -451, -472, -515, -628, -707, -771, -808, -835, -843, -856, -1048, - - -1059, -1099, -1108, -1147, -1192, -1203, -1219, -1267, -1315, -1347, -1363, - - -1432, -1563, -1588, -1603, -1843, -1915, -1963, -2227, -2283, -2443, -2515, - - -2563, -2787, -2923, -3235, -3427, -3523, -3763, -71, -151, -223, -251, -463, - - -467, -487, -587, -811, -827, -859, -1163, -1171, -1483, -1523, -1627, -1787, - - -1987, -2011, -2083, -2179, -2251, -2467, -2707, -3019, -3067, -3187, -3907, - - -4603, -5107, -5923, -95, -111, -164, -183, -248, -260, -264, -276, -295, - - -299, -308, -371, -376, -395, -420, -452, -456, -548, -552, -564, -579, -580, - - -583, -616, -632, -651, -660, -712, -820, -840, -852, -868, -904, -915, -939, - - -952, -979, -987, -995, -1032, -1043, -1060, -1092, -1128, -1131, -1155, - - -1195, -1204, -1240, -1252, -1288, -1299, -1320, -1339, -1348, -1380, -1428, - - -1443, -1528, -1540, -1635, -1651, -1659, -1672, -1731, -1752, -1768, -1771, - - -1780, -1795, -1803, -1828, -1848, -1864, -1912, -1939, -1947, -1992, -1995, - - -2020, -2035, -2059, -2067, -2139, -2163, -2212, -2248, -2307, -2308, -2323, - - -2392, -2395, -2419, -2451, -2587, -2611, -2632, -2667, -2715, -2755, -2788, - - -2827, -2947, -2968, -2995, -3003, -3172, -3243, -3315, -3355, -3403, -3448, - - -3507, -3595, -3787, -3883, -3963, -4123, -4195, -4267, -4323, -4387, -4747, - - -4843, -4867, -5083, -5467, -5587, -5707, -5947, -6307, -199, -367, -419, - - -491, -563, -823, -1087, -1187, -1291, -1423, -1579, -2003, -2803, -3163, - - -3259, -3307, -3547, -3643, -4027, -4243, -4363, -4483, -4723, -4987, -5443, - - -6043, -6427, -6763, -6883, -7723, -8563, -8803, -9067, -10627, -119, -143, - - -159, -296, -303, -319, -344, -415, -488, -611, -635, -664, -699, -724, -779, - - -788, -803, -851, -872, -916, -923, -1115, -1268, -1384, -1492, -1576, -1643, - - -1684, -1688, -1707, -1779, -1819, -1835, -1891, -1923, -2152, -2164, -2363, - - -2452, -2643, -2776, -2836, -2899, -3028, -3091, -3139, -3147, -3291, -3412, - - -3508, -3635, -3667, -3683, -3811, -3859, -3928, -4083, -4227, -4372, -4435, - - -4579, -4627, -4852, -4915, -5131, -5163, -5272, -5515, -5611, -5667, -5803, - - -6115, -6259, -6403, -6667, -7123, -7363, -7387, -7435, -7483, -7627, -8227, - - -8947, -9307, -10147, -10483, -13843, -167, -271, -659, -967, -1283, -1303, - - -1307, -1459, -1531, -1699, -2027, -2267, -2539, -2731, -2851, -2971, -3203, - - -3347, -3499, -3739, -3931, -4051, -5179, -5683, -6163, -6547, -7027, -7507, - - -7603, -7867, -8443, -9283, -9403, -9643, -9787, -10987, -13003, -13267, - - -14107, -14683, -15667, -231, -255, -327, -356, -440, -516, -543, -655, -680, - - -687, -696, -728, -731, -744, -755, -804, -888, -932, -948, -964, -984, -996, - - -1011, -1067, -1096, -1144, -1208, -1235, -1236, -1255, -1272, -1336, -1355, - - -1371, -1419, -1464, -1480, -1491, -1515, -1547, -1572, -1668, -1720, -1732, - - -1763, -1807, -1812, -1892, -1955, -1972, -2068, -2091, -2104, -2132, -2148, - - -2155, -2235, -2260, -2355, -2387, -2388, -2424, -2440, -2468, -2472, -2488, - - -2491, -2555, -2595, -2627, -2635, -2676, -2680, -2692, -2723, -2728, -2740, - - -2795, -2867, -2872, -2920, -2955, -3012, -3027, -3043, -3048, -3115, -3208, - - -3252, -3256, -3268, -3304, -3387, -3451, -3459, -3592, -3619, -3652, -3723, - - -3747, -3768, -3796, -3835, -3880, -3892, -3955, -3972, -4035, -4120, -4132, - - -4147, -4152, -4155, -4168, -4291, -4360, -4411, -4467, -4531, -4552, -4555, - - -4587, -4648, -4699, -4708, -4755, -4771, -4792, -4795, -4827, -4888, -4907, - - -4947, -4963, -5032, -5035, -5128, -5140, -5155, -5188, -5259, -5299, -5307, - - -5371, -5395, -5523, -5595, -5755, -5763, -5811, -5835, -6187, -6232, -6235, - - -6267, -6283, -6472, -6483, -6603, -6643, -6715, -6787, -6843, -6931, -6955, - - -6963, -6987, -7107, -7291, -7492, -7555, -7683, -7891, -7912, -8068, -8131, - - -8155, -8248, -8323, -8347, -8395, -8787, -8827, -9003, -9139, -9355, -9523, - - -9667, -9843, -10003, -10603, -10707, -10747, -10795, -10915, -11155, -11347, - - -11707, -11803, -12307, -12643, -14443, -15163, -15283, -16003, -17803, -191, - - -263, -607, -631, -727, -1019, -1451, -1499, -1667, -1907, -2131, -2143, - - -2371, -2659, -2963, -3083, -3691, -4003, -4507, -4643, -5347, -5419, -5779, - - -6619, -7243, -7963, -9547, -9739, -11467, -11587, -11827, -11923, -12043, - - -14347, -15787, -16963, -215, -287, -391, -404, -447, -511, -535, -536, -596, - - -692, -703, -807, -899, -1112, -1211, -1396, -1403, -1527, -1816, -1851, - - -1883, -2008, -2123, -2147, -2171, -2335, -2427, -2507, -2536, -2571, -2612, - - -2779, -2931, -2932, -3112, -3227, -3352, -3579, -3707, -3715, -3867, -3988, - - -4187, -4315, -4443, -4468, -4659, -4803, -4948, -5027, -5091, -5251, -5267, - - -5608, -5723, -5812, -5971, -6388, -6499, -6523, -6568, -6979, -7067, -7099, - - -7147, -7915, -8035, -8187, -8611, -8899, -9115, -9172, -9235, -9427, -10123, - - -10315, -10363, -10411, -11227, -12147, -12667, -12787, -13027, -13435, - - -13483, -13603, -14203, -16867, -18187, -18547, -18643, -239, -439, -751, - - -971, -1259, -1327, -1427, -1567, -1619, -2243, -2647, -2699, -2843, -3331, - - -3571, -3803, -4099, -4219, -5003, -5227, -5323, -5563, -5827, -5987, -6067, - - -6091, -6211, -6571, -7219, -7459, -7547, -8467, -8707, -8779, -9043, -9907, - - -10243, -10267, -10459, -10651, -10723, -11083, -11971, -12163, -12763, - - -13147, -13963, -14323, -14827, -14851, -15187, -15643, -15907, -16603, - - -16843, -17467, -17923, -18043, -18523, -19387, -19867, -399, -407, -471, - - -559, -584, -644, -663, -740, -799, -884, -895, -903, -943, -1015, -1016, - - -1023, -1028, -1047, -1139, -1140, -1159, -1220, -1379, -1412, -1416, -1508, - - -1560, -1595, -1608, -1624, -1636, -1640, -1716, -1860, -1876, -1924, -1983, - - -2004, -2019, -2040, -2056, -2072, -2095, -2195, -2211, -2244, -2280, -2292, - - -2296, -2328, -2356, -2379, -2436, -2568, -2580, -2584, -2739, -2760, -2811, - - -2868, -2884, -2980, -3063, -3108, -3140, -3144, -3160, -3171, -3192, -3220, - - -3336, -3363, -3379, -3432, -3435, -3443, -3460, -3480, -3531, -3556, -3588, - - -3603, -3640, -3732, -3752, -3784, -3795, -3819, -3828, -3832, -3939, -3976, - - -4008, -4020, -4043, -4171, -4179, -4180, -4216, -4228, -4251, -4260, -4324, - - -4379, -4420, -4427, -4440, -4452, -4488, -4515, -4516, -4596, -4612, -4683, - - -4687, -4712, -4740, -4804, -4899, -4939, -4971, -4984, -5115, -5160, -5187, - - -5195, -5208, -5363, -5380, -5403, -5412, -5428, -5460, -5572, -5668, -5752, - - -5848, -5860, -5883, -5896, -5907, -5908, -5992, -5995, -6040, -6052, -6099, - - -6123, -6148, -6195, -6312, -6315, -6328, -6355, -6395, -6420, -6532, -6580, - - -6595, -6612, -6628, -6708, -6747, -6771, -6792, -6820, -6868, -6923, -6952, - - -7003, -7035, -7051, -7195, -7288, -7315, -7347, -7368, -7395, -7480, -7491, - - -7540, -7579, -7588, -7672, -7707, -7747, -7755, -7780, -7795, -7819, -7828, - - -7843, -7923, -7995, -8008, -8043, -8052, -8083, -8283, -8299, -8308, -8452, - - -8515, -8547, -8548, -8635, -8643, -8680, -8683, -8715, -8835, -8859, -8932, - - -8968, -9208, -9219, -9412, -9483, -9507, -9508, -9595, -9640, -9763, -9835, - - -9867, -9955, -10132, -10168, -10195, -10203, -10227, -10312, -10387, -10420, - - -10563, -10587, -10635, -10803, -10843, -10948, -10963, -11067, -11092, - - -11107, -11179, -11203, -11512, -11523, -11563, -11572, -11635, -11715, - - -11848, -11995, -12027, -12259, -12387, -12523, -12595, -12747, -12772, - - -12835, -12859, -12868, -13123, -13192, -13195, -13288, -13323, -13363, - - -13507, -13795, -13819, -13827, -14008, -14155, -14371, -14403, -14547, - - -14707, -14763, -14995, -15067, -15387, -15403, -15547, -15715, -16027, - - -16195, -16347, -16531, -16555, -16723, -17227, -17323, -17347, -17427, - - -17515, -18403, -18715, -18883, -18907, -19147, -19195, -19947, -19987, -383, - - -991, -1091, -1571, -1663, -1783, -2531, -3323, -3947, -4339, -4447, -4547, - - -4651, -5483, -6203, -6379, -6451, -6827, -6907, -7883, -8539, -8731, -9883, - - -11251, -11443, -12907, -13627, -14083, -14779, -14947, -16699, -17827, - - -18307, -19963, -335, -519, -527, -679, -1135, -1172, -1207, -1383, -1448, - - -1687, -1691, -1927, -2047, -2051, -2167, -2228, -2291, -2315, -2344, -2644, - - -2747, -2859, -3035, -3107, -3543, -3544, -3651, -3688, -4072, -4299, -4307, - - -4568, -4819, -4883, -5224, -5315, -5464, -5492, -5539, -5899, -6196, -6227, - - -6331, -6387, -6484, -6739, -6835, -7323, -7339, -7528, -7571, -7715, -7732, - - -7771, -7827, -8152, -8203, -8212, -8331, -8403, -8488, -8507, -8587, -8884, - - -9123, -9211, -9563, -9627, -9683, -9748, -9832, -10228, -10264, -10347, - - -10523, -11188, -11419, -11608, -11643, -11683, -11851, -11992, -12067, - - -12148, -12187, -12235, -12283, -12651, -12723, -12811, -12952, -13227, - - -13315, -13387, -13747, -13947, -13987, -14163, -14227, -14515, -14667, - - -14932, -15115, -15243, -16123, -16171, -16387, -16627, -17035, -17131, - - -17403, -17635, -18283, -18712, -19027, -19123, -19651, -311, -359, -919, - - -1063, -1543, -1831, -2099, -2339, -2459, -3343, -3463, -3467, -3607, -4019, - - -4139, -4327, -5059, -5147, -5527, -5659, -6803, -8419, -8923, -8971, -9619, - - -10891, -11299, -15091, -15331, -16363, -16747, -17011, -17299, -17539, - - -17683, -19507, -455, -615, -776, -824, -836, -920, -1064, -1124, -1160, - - -1263, -1284, -1460, -1495, -1524, -1544, -1592, -1604, -1652, -1695, -1739, - - -1748, -1796, -1880, -1887, -1896, -1928, -1940, -1956, -2136, -2247, -2360, - - -2404, -2407, -2483, -2487, -2532, -2552, -2596, -2603, -2712, -2724, -2743, - - -2948, -2983, -2987, -3007, -3016, -3076, -3099, -3103, -3124, -3131, -3155, - - -3219, -3288, -3320, -3367, -3395, -3496, -3512, -3515, -3567, -3655, -3668, - - -3684, -3748, -3755, -3908, -3979, -4011, -4015, -4024, -4036, -4148, -4264, - - -4355, -4371, -4395, -4403, -4408, -4539, -4548, -4660, -4728, -4731, -4756, - - -4763, -4855, -4891, -5019, -5028, -5044, -5080, -5092, -5268, -5331, -5332, - - -5352, -5368, -5512, -5560, -5592, -5731, -5944, -5955, -5956, -5988, -6051, - - -6088, -6136, -6139, -6168, -6280, -6339, -6467, -6504, -6648, -6712, -6755, - - -6808, -6856, -7012, -7032, -7044, -7060, -7096, -7131, -7144, -7163, -7171, - - -7192, -7240, -7428, -7432, -7467, -7572, -7611, -7624, -7635, -7651, -7667, - - -7720, -7851, -7876, -7924, -7939, -8067, -8251, -8292, -8296, -8355, -8404, - - -8472, -8491, -8632, -8692, -8755, -8808, -8920, -8995, -9051, -9124, -9147, - - -9160, -9195, -9331, -9339, -9363, -9443, -9571, -9592, -9688, -9691, -9732, - - -9755, -9795, -9892, -9976, -9979, -10027, -10083, -10155, -10171, -10291, - - -10299, -10308, -10507, -10515, -10552, -10564, -10819, -10888, -11272, - - -11320, -11355, -11379, -11395, -11427, -11428, -11539, -11659, -11755, - - -11860, -11883, -11947, -11955, -12019, -12139, -12280, -12315, -12328, - - -12331, -12355, -12363, -12467, -12468, -12472, -12499, -12532, -12587, - - -12603, -12712, -12883, -12931, -12955, -12963, -13155, -13243, -13528, - - -13555, -13588, -13651, -13803, -13960, -14307, -14331, -14467, -14491, - - -14659, -14755, -14788, -15235, -15268, -15355, -15603, -15688, -15691, - - -15763, -15883, -15892, -15955, -16147, -16228, -16395, -16408, -16435, - - -16483, -16507, -16612, -16648, -16683, -16707, -16915, -16923, -17067, - - -17187, -17368, -17563, -17643, -17763, -17907, -18067, -18163, -18195, - - -18232, -18355, -18363, -19083, -19443, -19492, -19555, -19923}; diff --git a/OSX/include/security_cryptkit/CurveParamDocs/ellproj.c b/OSX/include/security_cryptkit/CurveParamDocs/ellproj.c deleted file mode 100644 index b98b2573..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/ellproj.c +++ /dev/null @@ -1,448 +0,0 @@ -/************************************************************** - * - * ellproj.c - * - Fast algorithms for fundamental elliptic curve arithmetic, - projective format. Such algorithms apply in domains such as: - -- factoring - -- primality studies (e.g. rigorous primality proofs) - -- elliptic curve cryptography (ECC) - - PROJECTIVE FORMAT - - Functions are supplied herein for projective format - of points. Alternative formats differ in their - range of applicability, efficiency, and so on. - Primary advantages of the projective format herein are: - -- No explicit inversions (until perhaps one such at the end of - an elliptic multiply operation) - -- Fairly low operation count (~11 muls for point doubling, - ~16 muls for point addition) - - The elliptic curve is over F_p, with p > 3 prime, and Weierstrass - parameterization: - - y^2 = x^3 + a x + b - - The projective-format coordinates are actually stored in - the form {X, Y, Z}, with true x,y - coordinates on the curve given by {x,y} = {X/Z^2, Y/Z^3}. - The function normalize_proj() performs the - transformation from projective->true. - (The other direction is trivial, i.e. {x,y} -> {x,y,1} will do.) - The basic point multiplication function is - - ell_mul_proj() - - which obtains the result k * P for given point P and integer - multiplier k. If true {x,y} are required for a multiple, one - passes a point P = {X, Y, 1} to ell_mul_proj(), then afterwards - calls normalize_proj(), - - Projective format is an answer to the typical sluggishness of - standard elliptic arithmetic, whose explicit inversion in the - field is, depending of course on the machinery and programmer, - costly. Projective format is thus especially interesting for - cryptography. - - REFERENCES - - Crandall R and Pomerance C 1998, "Prime numbers: a computational - perspective," Springer-Verlag, manuscript - - Solinas J 1998, IEEE P1363 Annex A (draft standard) - - LEGAL AND PATENT NOTICE - - This and related PSI library source code is intended solely for - educational and research applications, and should not be used - for commercial purposes without explicit permission from PSI - (not to mention proper clearance of legal restrictions beyond - the purview of PSI). - The code herein will not perform cryptography per se, - although the number-theoretical algorithms herein -- all of which - are in the public domain -- can be used in principle to effect - what is known as elliptic curve cryptography (ECC). Note that - there are strict constraints on how cryptography may be used, - especially in regard to exportability. - Therefore one should avoid any casual distribution of actual - cryptographic software. Along similar lines, because of various - patents, proprietary to Apple Computer, Inc., and perhaps to other - organizations, one should not tacitly assume that an ECC scheme is - unconstrained. For example,the commercial use of certain fields - F_p^k (i.e., fixation of certain primes p) is covered in Apple - patents. - - * Updates: - * 3 Apr 98 REC Creation - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -/* include files */ - -#include -#include -#include -#include -#ifdef _WIN32 - -#include - -#endif - -#include -#include "giants.h" -#include "ellproj.h" -#include "tools.h" - -/* global variables */ - -static giant t0 = NULL, t1 = NULL, t2 = NULL, t3 = NULL, t4 = NULL, - t5 = NULL, t6 = NULL, t7 = NULL; - -/************************************************************** - * - * Maintenance functions - * - **************************************************************/ - -point_proj -new_point_proj(int shorts) -{ - point_proj pt; - - if(t0 == NULL) init_ell_proj(shorts); - pt = (point_proj) malloc(sizeof(point_struct_proj)); - pt->x = newgiant(shorts); - pt->y = newgiant(shorts); - pt->z = newgiant(shorts); - return(pt); -} - -void -free_point_proj(point_proj pt) -{ - free(pt->x); free(pt->y); free(pt->z); - free(pt); -} - -void -ptop_proj(point_proj pt1, point_proj pt2) -{ - gtog(pt1->x, pt2->x); - gtog(pt1->y, pt2->y); - gtog(pt1->z, pt2->z); -} - -void -init_ell_proj(int shorts) -/* Called by new_point_proj(), to set up giant registers. */ -{ - t0 = newgiant(shorts); - t1 = newgiant(shorts); - t2 = newgiant(shorts); - t3 = newgiant(shorts); - t4 = newgiant(shorts); - t5 = newgiant(shorts); - t6 = newgiant(shorts); - t7 = newgiant(shorts); -} - - -/************************************************************** - * - * Elliptic curve operations - * - **************************************************************/ - -/* Begin projective-format functions for - - y^2 = x^3 + a x + b. - - These are useful in elliptic curve cryptography (ECC). - A point is kept as a triple {X,Y,Z}, with the true (x,y) - coordinates given by - - {x,y} = {X/Z^2, Y/Z^3} - - The function normalize_proj() performs the inverse conversion to get - the true (x,y) pair. - */ - -void -ell_double_proj(point_proj pt, giant a, giant p) -/* pt := 2 pt on the curve. */ -{ - giant x = pt->x, y = pt->y, z = pt->z; - - if(isZero(y) || isZero(z)) { - itog(1,x); itog(1,y); itog(0,z); - return; - } - gtog(z,t1); squareg(t1); modg(p, t1); - squareg(t1); modg(p, t1); - mulg(a, t1); modg(p, t1); /* t1 := a z^4. */ - gtog(x, t2); squareg(t2); smulg(3, t2); modg(p, t2); /* t2 := 3x^2. */ - addg(t2, t1); modg(p, t1); /* t1 := slope m. */ - mulg(y, z); addg(z,z); modg(p, z); /* z := 2 y z. */ - gtog(y, t2); squareg(t2); modg(p, t2); /* t2 := y^2. */ - gtog(t2, t3); squareg(t3); modg(p, t3); /* t3 := y^4. */ - gshiftleft(3, t3); /* t3 := 8 y^4. */ - mulg(x, t2); gshiftleft(2, t2); modg(p, t2); /* t2 := 4xy^2. */ - gtog(t1, x); squareg(x); modg(p, x); - subg(t2, x); subg(t2, x); modg(p, x); /* x done. */ - gtog(t1, y); subg(x, t2); mulg(t2, y); subg(t3, y); - modg(p, y); -} -/* -elldouble[pt_] := Block[{x,y,z,m,y2,s}, - x = pt[[1]]; y = pt[[2]]; z = pt[[3]]; - If[(y==0) || (z==0), Return[{1,1,0}]]; - m = Mod[3 x^2 + a Mod[Mod[z^2,p]^2,p],p]; - z = Mod[2 y z, p]; - y2 = Mod[y^2,p]; - s = Mod[4 x y2,p]; - x = Mod[m^2 - 2s,p]; - y = Mod[m(s - x) - 8 y2^2,p]; - Return[{x,y,z}]; -]; -*/ - -void -ell_add_proj(point_proj pt0, point_proj pt1, giant a, giant p) -/* pt0 := pt0 + pt1 on the curve. */ -{ - giant x0 = pt0->x, y0 = pt0->y, z0 = pt0->z, - x1 = pt1->x, y1 = pt1->y, z1 = pt1->z; - - if(isZero(z0)) { - gtog(x1,x0); gtog(y1,y0); gtog(z1,z0); - return; - } - if(isZero(z1)) return; - gtog(x0, t1); gtog(y0,t2); gtog(z0, t3); - gtog(x1, t4); gtog(y1, t5); - if(!isone(z1)) { - gtog(z1, t6); - gtog(t6, t7); squareg(t7); modg(p, t7); - mulg(t7, t1); modg(p, t1); - mulg(t6, t7); modg(p, t7); - mulg(t7, t2); modg(p, t2); - } - gtog(t3, t7); squareg(t7); modg(p, t7); - mulg(t7, t4); modg(p, t4); - mulg(t3, t7); modg(p, t7); - mulg(t7, t5); modg(p, t5); - negg(t4); addg(t1, t4); modg(p, t4); - negg(t5); addg(t2, t5); modg(p, t5); - if(isZero(t4)) { - if(isZero(t5)) { - ell_double_proj(pt0, a, p); - } else { - itog(1, x0); itog(1, y0); itog(0, z0); - } - return; - } - addg(t1, t1); subg(t4, t1); modg(p, t1); - addg(t2, t2); subg(t5, t2); modg(p, t2); - if(!isone(z1)) { - mulg(t6, t3); modg(p, t3); - } - mulg(t4, t3); modg(p, t3); - gtog(t4, t7); squareg(t7); modg(p, t7); - mulg(t7, t4); modg(p, t4); - mulg(t1, t7); modg(p, t7); - gtog(t5, t1); squareg(t1); modg(p, t1); - subg(t7, t1); modg(p, t1); - subg(t1, t7); subg(t1, t7); modg(p, t7); - mulg(t7, t5); modg(p, t5); - mulg(t2, t4); modg(p, t4); - gtog(t5, t2); subg(t4,t2); modg(p, t2); - if(t2->n[0] & 1) { /* Test if t2 is odd. */ - addg(p, t2); - } - gshiftright(1, t2); - gtog(t1, x0); gtog(t2, y0); gtog(t3, z0); -} - -/* -elladd[pt0_, pt1_] := Block[ - {x0,y0,z0,x1,y1,z1, - t1,t2,t3,t4,t5,t6,t7}, - x0 = pt0[[1]]; y0 = pt0[[2]]; z0 = pt0[[3]]; - x1 = pt1[[1]]; y1 = pt1[[2]]; z1 = pt1[[3]]; - If[z0 == 0, Return[pt1]]; - If[z1 == 0, Return[pt0]]; - - t1 = x0; - t2 = y0; - t3 = z0; - t4 = x1; - t5 = y1; - If[(z1 != 1), - t6 = z1; - t7 = Mod[t6^2, p]; - t1 = Mod[t1 t7, p]; - t7 = Mod[t6 t7, p]; - t2 = Mod[t2 t7, p]; - ]; - t7 = Mod[t3^2, p]; - t4 = Mod[t4 t7, p]; - t7 = Mod[t3 t7, p]; - t5 = Mod[t5 t7, p]; - t4 = Mod[t1-t4, p]; - t5 = Mod[t2 - t5, p]; - If[t4 == 0, If[t5 == 0, - Return[elldouble[pt0]], - Return[{1,1,0}] - ] - ]; - t1 = Mod[2t1 - t4,p]; - t2 = Mod[2t2 - t5, p]; - If[z1 != 1, t3 = Mod[t3 t6, p]]; - t3 = Mod[t3 t4, p]; - t7 = Mod[t4^2, p]; - t4 = Mod[t4 t7, p]; - t7 = Mod[t1 t7, p]; - t1 = Mod[t5^2, p]; - t1 = Mod[t1-t7, p]; - t7 = Mod[t7 - 2t1, p]; - t5 = Mod[t5 t7, p]; - t4 = Mod[t2 t4, p]; - t2 = Mod[t5-t4, p]; - If[EvenQ[t2], t2 = t2/2, t2 = (p+t2)/2]; - Return[{t1, t2, t3}]; -]; -*/ - -void -ell_neg_proj(point_proj pt, giant p) -/* pt := -pt on the curve. */ -{ - negg(pt->y); modg(p, pt->y); -} - -void -ell_sub_proj(point_proj pt0, point_proj pt1, giant a, giant p) -/* pt0 := pt0 - pt1 on the curve. */ -{ - ell_neg_proj(pt1, p); - ell_add_proj(pt0, pt1,a,p); - ell_neg_proj(pt1,p); -} - -void -ell_mul_proj(point_proj pt0, point_proj pt1, giant k, giant a, giant p) -/* General elliptic multiplication; - pt1 := k*pt0 on the curve, - with k an arbitrary integer. - */ -{ - giant x = pt0->x, y = pt0->y, z = pt0->z, - xx = pt1->x, yy = pt1->y, zz = pt1->z; - int ksign, hlen, klen, b, hb, kb; - - if(isZero(k)) { - itog(1, xx); - itog(1, yy); - itog(0, zz); - return; - } - ksign = k->sign; - if(ksign < 0) negg(k); - gtog(x,xx); gtog(y,yy); gtog(z,zz); - gtog(k, t0); addg(t0, t0); addg(k, t0); /* t0 := 3k. */ - hlen = bitlen(t0); - klen = bitlen(k); - for(b = hlen-2; b > 0; b--) { - ell_double_proj(pt1,a,p); - hb = bitval(t0, b); - if(b < klen) kb = bitval(k, b); else kb = 0; - if((hb != 0) && (kb == 0)) - ell_add_proj(pt1, pt0, a, p); - else if((hb == 0) && (kb !=0)) - ell_sub_proj(pt1, pt0, a, p); - } - if(ksign < 0) { - ell_neg_proj(pt1, p); - k->sign = -k->sign; - } -} - -/* -elliptic[pt_, k_] := Block[{pt2, hh, kk, hb, kb, lenh, lenk}, - If[k==0, Return[{1,1,0}]]; - hh = Reverse[bitList[3k]]; - kk = Reverse[bitList[k]]; - pt2 = pt; - lenh = Length[hh]; - lenk = Length[kk]; - Do[ - pt2 = elldouble[pt2]; - hb = hh[[b]]; - If[b <= lenk, kb = kk[[b]], kb = 0]; - If[{hb,kb} == {1,0}, - pt2 = elladd[pt2, pt], - If[{hb, kb} == {0,1}, - pt2 = ellsub[pt2, pt]] - ] - ,{b, lenh-1, 2,-1} - ]; - Return[pt2]; -]; -*/ - -void -normalize_proj(point_proj pt, giant p) -/* Obtain actual x,y coords via normalization: - {x,y,z} := {x/z^2, y/z^3, 1}. - */ - -{ giant x = pt->x, y = pt->y, z = pt->z; - - if(isZero(z)) { - itog(1,x); itog(1,y); - return; - } - binvaux(p, z); gtog(z, t1); - squareg(z); modg(p, z); - mulg(z, x); modg(p, x); - mulg(t1, z); mulg(z, y); modg(p, y); - itog(1, z); -} - -/* -normalize[pt_] := Block[{z,z2,z3}, - If[pt[[3]] == 0, Return[pt]]; - z = ellinv[pt[[3]]]; - z2 = Mod[z^2,p]; - z3 = Mod[z z2,p]; - Return[{Mod[pt[[1]] z2, p], Mod[pt[[2]] z3, p], 1}]; - ]; -*/ - - -void -find_point_proj(point_proj pt, giant seed, giant a, giant b, giant p) -/* Starting with seed, finds a random (projective) point {x,y,1} on curve. - */ -{ giant x = pt->x, y = pt->y, z = pt->z; - - modg(p, seed); - while(1) { - gtog(seed, x); - squareg(x); modg(p, x); - addg(a, x); - mulg(seed,x); addg(b, x); - modg(p, x); /* x := seed^3 + a seed + b. */ - if(sqrtmod(p, x)) break; /* Test if cubic form has root. */ - iaddg(1, seed); - } - gtog(x, y); - gtog(seed,x); - itog(1, z); -} diff --git a/OSX/include/security_cryptkit/CurveParamDocs/ellproj.h b/OSX/include/security_cryptkit/CurveParamDocs/ellproj.h deleted file mode 100644 index 8f134144..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/ellproj.h +++ /dev/null @@ -1,59 +0,0 @@ -/************************************************************** - * - * ellproj.h - * - * Header file for ellproj.c - * - * Updates: - * 3 Apr 98 REC - Creation - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -/* definitions */ - -typedef struct /* This is how to define a projective point. */ -{ - giant x; - giant y; - giant z; -} point_struct_proj; - -typedef point_struct_proj *point_proj; - -point_proj /* Allocates a new projective point. */ -new_point_proj(int shorts); - -void /* Frees point. */ -free_point_proj(point_proj pt); - -void /* Copies point to point. */ -ptop_proj(point_proj pt1, point_proj pt2); - -void /* Initialization. */ -init_ell_proj(int shorts); - -void /* Point doubling. */ -ell_double_proj(point_proj pt, giant a, giant p); - -void /* Point addition. */ -ell_add_proj(point_proj pt0, point_proj pt1, giant a, giant p); - -void /* Point negation. */ -ell_neg_proj(point_proj pt, giant p); - -void /* Point subtraction. */ -ell_sub_proj(point_proj pt0, point_proj pt1, giant a, giant p); - -void /* General elliptic mul. */ -ell_mul_proj(point_proj pt0, point_proj pt1, giant k, giant a, giant p); - -void /* Generate normalized point (X, Y, 1) from given (x,y,z). */ -normalize_proj(point_proj pt, giant p); - -void /* Find a point (x, y, 1) on the curve. */ -find_point_proj(point_proj pt, giant seed, giant a, giant b, giant p); - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/factor.c b/OSX/include/security_cryptkit/CurveParamDocs/factor.c deleted file mode 100644 index a0d0186f..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/factor.c +++ /dev/null @@ -1,844 +0,0 @@ -/************************************************************** - * - * factor.c - * - * General purpose factoring program - * - * Updates: - * 18 May 97 REC - invoked new, fast divide functions - * 26 Apr 97 RDW - fixed tabs and unix EOL - * 20 Apr 97 RDW - conversion to TC4.5 - * - * c. 1997 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -/* include files */ - -#include -#include -#include -#include -#ifdef _WIN32 - -#include - -#endif - -#include -#include "giants.h" - - -/* definitions */ - -#define D 100 -#define NUM_PRIMES 6542 /* PrimePi[2^16]. */ - - -/* compiler options */ - -#ifdef _WIN32 -#pragma warning( disable : 4127 4706 ) /* disable conditional is constant warning */ -#endif - - -/* global variables */ - -extern giant scratch2; -int pr[NUM_PRIMES]; -giant xr = NULL, xs = NULL, zs = NULL, zr = NULL, xorg = NULL, - zorg = NULL, t1 = NULL, t2 = NULL, t3 = NULL, N = NULL, - gg = NULL, An = NULL, Ad = NULL; -giant xb[D+2], zb[D+2], xzb[D+2]; -int modmode = 0, Q, modcount = 0; - - -/* function prototypes */ - -void ell_even(giant x1, giant z1, giant x2, giant z2, giant An, - giant Ad, giant N); -void ell_odd(giant x1, giant z1, giant x2, giant z2, giant xor, - giant zor, giant N); -void ell_mul(giant xx, giant zz, int n, giant An, giant Ad, giant N); -int least_2(int n); -void dot(void); -int psi_rand(); - - -/************************************************************** - * - * Functions - * - **************************************************************/ - - -int -psi_rand( - void -) -{ - unsigned short hi; - unsigned short low; - time_t tp; - int result; - - time(&tp); - low = (unsigned short)rand(); - hi = (unsigned short)rand(); - result = ((hi << 16) | low) ^ ((int)tp); - - return (result & 0x7fffffff); -} - - -void -set_random_seed( - void -) -{ - /* Start the random number generator at a new position. */ - time_t tp; - - time(&tp); - srand((int)tp + (int)getpid()); -} - - -int -isprime( - int odd -) -{ - int j; - int p; - - for (j=1; ; j++) - { - p = pr[j]; - if (p*p > odd) - return(1); - if (odd % p == 0) - return(0); - } -} - - -int -primeq( - int p -) -{ - register int j=3; - - if ((p&1)==0) - return ((p==2)?1:0); - if (j>=p) - return (1); - while ((p%j)!=0) - { - j+=2; - if (j*j>p) - return(1); - } - return(0); -} - - -void -s_modg( - giant N, - giant t -) -{ - ++modcount; - switch (modmode) - { - case 0: - modg(N, t); - break; - case -1: - mersennemod(Q, t); - break; - case 1: - fermatmod(Q, t); - break; - } -} - - -void -reset_mod( - giant x, - giant N -) -/* Perform a divide (by the discovered factor) and switch back - to non-Fermat-non-Mersenne (i.e. normal) mod mode. */ -{ - divg(x, N); - modmode = 0; -} - -void -ell_even( - giant x1, - giant z1, - giant x2, - giant z2, - giant An, - giant Ad, - giant N -) -{ - gtog(x1, t1); - addg(z1, t1); - squareg(t1); - s_modg(N, t1); - gtog(x1, t2); - subg(z1, t2); - squareg(t2); - s_modg(N, t2); - gtog(t1, t3); - subg(t2, t3); - gtog(t2, x2); - mulg(t1, x2); - gshiftleft(2, x2); - s_modg(N, x2); - mulg(Ad, x2); - s_modg(N, x2); - mulg(Ad, t2); - gshiftleft(2, t2); - s_modg(N, t2); - gtog(t3, t1); - mulg(An, t1); - s_modg(N, t1); - addg(t1, t2); - mulg(t3, t2); - s_modg(N, t2); - gtog(t2,z2); -} - - -void -ell_odd( - giant x1, - giant z1, - giant x2, - giant z2, - giant xor, - giant zor, - giant N -) -{ - gtog(x1, t1); - subg(z1, t1); - gtog(x2, t2); - addg(z2, t2); - mulg(t1, t2); - s_modg(N, t2); - gtog(x1, t1); - addg(z1, t1); - gtog(x2, t3); - subg(z2, t3); - mulg(t3, t1); - s_modg(N, t1); - gtog(t2, x2); - addg(t1, x2); - squareg(x2); - s_modg(N, x2); - gtog(t2, z2); - subg(t1, z2); - squareg(z2); - s_modg(N, z2); - mulg(zor, x2); - s_modg(N, x2); - mulg(xor, z2); - s_modg(N, z2); -} - - -void -ell_mul( - giant xx, - giant zz, - int n, - giant An, - giant Ad, - giant N -) -{ - unsigned int c = (unsigned int)0x80000000; - - if (n==1) - return; - if (n==2) - { - ell_even(xx, zz, xx, zz, An, Ad, N); - return; - } - gtog(xx, xorg); - gtog(zz, zorg); - ell_even(xx, zz, xs, zs, An, Ad, N); - - while((c&n) == 0) - { - c >>= 1; - } - - c>>=1; - do - { - if (c&n) - { - ell_odd(xs, zs, xx, zz, xorg, zorg, N); - ell_even(xs, zs, xs, zs, An, Ad, N); - } - else - { - ell_odd(xx, zz, xs, zs, xorg, zorg, N); - ell_even(xx, zz, xx, zz, An, Ad, N); - } - c >>= 1; - } while(c); -} - - - -/* From R. P. Brent, priv. comm. 1996: -Let s > 5 be a pseudo-random seed (called $\sigma$ in the Tech. Report), - - u/v = (s^2 - 5)/(4s) - -Then starting point is (x_1, y_1) where - - x_1 = (u/v)^3 -and - a = (v-u)^3(3u+v)/(4u^3 v) - 2 -*/ - -void -choose12( - giant x, - giant z, - int k, - giant An, - giant Ad, - giant N -) -{ - itog(k, zs); - gtog(zs, xs); - squareg(xs); - itog(5, t2); - subg(t2, xs); - s_modg(N, xs); - addg(zs, zs); - addg(zs, zs); - s_modg(N, zs); - gtog(xs, x); - squareg(x); - s_modg(N, x); - mulg(xs, x); - s_modg(N, x); - gtog(zs, z); - squareg(z); - s_modg(N, z); - mulg(zs, z); - s_modg(N, z); - - /* Now for A. */ - gtog(zs, t2); - subg(xs, t2); - gtog(t2, t3); - squareg(t2); - s_modg(N, t2); - mulg(t3, t2); - s_modg(N, t2); /* (v-u)^3. */ - gtog(xs, t3); - addg(t3, t3); - addg(xs, t3); - addg(zs, t3); - s_modg(N, t3); - mulg(t3, t2); - s_modg(N, t2); /* (v-u)^3 (3u+v). */ - gtog(zs, t3); - mulg(xs, t3); - s_modg(N, t3); - squareg(xs); - s_modg(N, xs); - mulg(xs, t3); - s_modg(N, t3); - addg(t3, t3); - addg(t3, t3); - s_modg(N, t3); - gtog(t3, Ad); - gtog(t2, An); /* An/Ad is now A + 2. */ -} - - -void -ensure( - int q -) -{ - int nsh, j; - - N = newgiant(INFINITY); - if(!q) - { - gread(N,stdin); - q = bitlen(N) + 1; - } - nsh = q/4; /* Allowing (easily) enough space per giant, - since N is about 2^q, which is q bits, or - q/16 shorts. But squaring, etc. is allowed, - so we need at least q/8, and we choose q/4 - to be conservative. */ - if (!xr) - xr = newgiant(nsh); - if (!zr) - zr = newgiant(nsh); - if (!xs) - xs = newgiant(nsh); - if (!zs) - zs = newgiant(nsh); - if (!xorg) - xorg = newgiant(nsh); - if (!zorg) - zorg = newgiant(nsh); - if (!t1) - t1 = newgiant(nsh); - if (!t2) - t2 = newgiant(nsh); - if (!t3) - t3 = newgiant(nsh); - if (!gg) - gg = newgiant(nsh); - if (!An) - An = newgiant(nsh); - if (!Ad) - Ad = newgiant(nsh); - for (j=0;j 4) - /* This segment only takes effect in random mode. */ - limitbits = atoi(argv[argc-2]); - } - else - { - randmode = 0; - } - - modmode = 0; - if (argc > 2) - { - modmode = atoi(argv[1]); - Q = atoi(argv[2]); - } - if (modmode==0) - Q = 0; - ensure(Q); - if (modmode) - { - itog(1, N); - gshiftleft(Q, N); - itog(modmode, t1); - addg(t1, N); - } - pr[0] = 2; - for (k=0, npr=1;; k++) - { - if (primeq(3+2*k)) - { - pr[npr++] = 3+2*k; - if (npr >= NUM_PRIMES) - break; - } - } - - if (randmode == 0) - { - printf("Sieving...\n"); - fflush(stdout); - for (j=0; j < NUM_PRIMES; j++) - { - gtog(N, t1); - rem = idivg(pr[j], t1); - if (rem == 0) - { - printf("%d ", pr[j]); - gtog(t1, N); - if (isone(N)) - { - printf("\n"); - exit(0); - } - else - { - printf("* "); - fflush(stdout); - } - --j; - } - } - - if (bigprimeq(N)) - { - gout(N); - exit(0); - } - - printf("\n"); - printf("Commencing Pollard rho...\n"); - fflush(stdout); - itog(1, gg); - itog(3, t1); itog(3, t2); - - for (j=0; j < 15000; j++) - { - if((j%100) == 0) - { - dot(); - gcdg(N, gg); - if (!isone(gg)) - break; - } - squareg(t1); - iaddg(2, t1); - s_modg(N, t1); - squareg(t2); - iaddg(2, t2); - s_modg(N, t2); - squareg(t2); - iaddg(2, t2); - s_modg(N, t2); - gtog(t2, t3); - subg(t1, t3); - t3->sign = abs(t3->sign); - mulg(t3, gg); - s_modg(N, gg); - } - gcdg(N, gg); - - if ((gcompg(N,gg) != 0) && (!isone(gg))) - { - fprintf(stdout,"\n"); - gout(gg); - reset_mod(gg, N); - if (isone(N)) - { - printf("\n"); - exit(0); - } - else - { - printf("* "); - fflush(stdout); - } - if (bigprimeq(N)) - { - gout(N); - exit(0); - } - } - - printf("\n"); - printf("Commencing Pollard (p-1)...\n"); - fflush(stdout); - itog(1, gg); - itog(3, t1); - for (j=0; j< NUM_PRIMES; j++) - { - cnt = (int)(8*log(2.0)/log(1.0*pr[j])); - if (cnt < 2) - cnt = 1; - for (k=0; k< cnt; k++) - { - powermod(t1, pr[j], N); - } - itog(1, t2); - subg(t1, t2); - mulg(t2, gg); - s_modg(N, gg); - - if (j % 100 == 0) - { - dot(); - gcdg(N, gg); - if (!isone(gg)) - break; - } - } - gcdg(N, gg); - if ((gcompg(N,gg) != 0) && (!isone(gg))) - { - fprintf(stdout,"\n"); - gout(gg); - reset_mod(gg, N); - if (isone(N)) - { - printf("\n"); - exit(0); - } - else - { - printf("* "); - fflush(stdout); - } - if (bigprimeq(N)) - { - gout(N); - exit(0); - } - } - } /* This is the end of (randmode == 0) */ - - printf("\n"); - printf("Commencing ECM...\n"); - fflush(stdout); - - if (randmode) - set_random_seed(); - pass = 0; - while (++pass) - { - if (randmode == 0) - { - if (pass <= 3) - { - B = 1000; - } - else if (pass <= 10) - { - B = 10000; - } - else if (pass <= 100) - { - B = 100000L; - } else - { - B = 1000000L; - } - } - else - { - B = 2000000L; - } - C = 50*((int)B); - - /* Next, choose curve with order divisible by 16 and choose - * a point (xr/zr) on said curve. - */ - - /* Order-div-12 case. - * cnt = 8020345; Brent's parameter for stage one discovery - * of 27-digit factor of F_13. - */ - - cnt = psi_rand(); /* cnt = 8020345; */ - choose12(xr, zr, cnt, An, Ad, N); - printf("Choosing curve %d, with s = %d, B = %d, C = %d:\n", pass,cnt, B, C); fflush(stdout); - cnt = 0; - nshorts = 1; - count = 0; - for (j=0;jlimitbits)) - { - fprintf(stdout,"\n"); - gwriteln(gg, stdout); - fflush(stdout); - reset_mod(gg, N); - if (isone(N)) - { - printf("\n"); - exit(0); - } - else - { - printf("* "); - fflush(stdout); - } - if (bigprimeq(N)) - { - gout(N); - exit(0); - } - continue; - } - else - { - printf("\n"); - fflush(stdout); - } - - /* Continue; Invoke, to test Stage 1 only. */ - k = ((int)B)/D; - gtog(xr, xb[0]); - gtog(zr, zb[0]); - ell_mul(xb[0], zb[0], k*D+1 , An, Ad, N); - gtog(xr, xb[D+1]); - gtog(zr, zb[D+1]); - ell_mul(xb[D+1], zb[D+1], (k+2)*D+1 , An, Ad, N); - - for (j=1; j <= D; j++) - { - gtog(xr, xb[j]); - gtog(zr, zb[j]); - ell_mul(xb[j], zb[j], 2*j , An, Ad, N); - gtog(zb[j], xzb[j]); - mulg(xb[j], xzb[j]); - s_modg(N, xzb[j]); - } - modcount = 0; - printf("\nCommencing second stage, curve %d...\n",pass); fflush(stdout); - count = 0; - itog(1, gg); - - while (1) - { - gtog(zb[0], xzb[0]); - mulg(xb[0], xzb[0]); - s_modg(N, xzb[0]); - mulg(zb[0], gg); - s_modg(N,gg); /* Accumulate. */ - for (j = 1; j < D; j++) - { - if (!isprime(k*D+1+ 2*j)) - continue; - - /* Next, accumulate (xa - xb)(za + zb) - xa za + xb zb. */ - gtog(xb[0], t1); - subg(xb[j], t1); - gtog(zb[0], t2); - addg(zb[j], t2); - mulg(t1, t2); - s_modg(N, t1); - subg(xzb[0], t2); - addg(xzb[j], t2); - s_modg(N, t2); - --modcount; - mulg(t2, gg); - s_modg(N, gg); - if((++count)%1000==0) - dot(); - } - - k += 2; - if(k*D > C) - break; - gtog(xb[D+1], xs); - gtog(zb[D+1], zs); - ell_odd(xb[D], zb[D], xb[D+1], zb[D+1], xb[0], zb[0], N); - gtog(xs, xb[0]); - gtog(zs, zb[0]); - } - - gcdg(N, gg); - if((!isone(gg))&&(bitlen(gg)>limitbits)) - { - fprintf(stdout,"\n"); - gwriteln(gg, stdout); - fflush(stdout); - reset_mod(gg, N); - if (isone(N)) - { - printf("\n"); - exit(0); - } - else - { - printf("* "); - fflush(stdout); - } - if (bigprimeq(N)) - { - gout(N); - exit(0); - } - continue; - } - - printf("\n"); - fflush(stdout); - } - - return 0; -} - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/fmodule.c b/OSX/include/security_cryptkit/CurveParamDocs/fmodule.c deleted file mode 100644 index 492b33b3..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/fmodule.c +++ /dev/null @@ -1,410 +0,0 @@ -/************************************************************** - * - * fmodule.c - * - * Factoring utilities. - * - * Updates: - * 13 Apr 98 REC - creation - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -/* include files */ - -#include -#include -#include -#include -#ifdef _WIN32 - -#include - -#endif - -#include -#include "giants.h" -#include "fmodule.h" -#include "ellmont.h" - -#define NUM_PRIMES 6542 /* PrimePi[2^16]. */ -#define GENERAL_MOD 0 -#define FERMAT_MOD 1 -#define MERSENNE_MOD (-1) -#define D 100 /* A decimation parameter for stage-2 ECM factoring. */ - -/* compiler options */ - -#ifdef _WIN32 -#pragma warning( disable : 4127 4706 ) /* disable conditional is constant warning */ -#endif - - -/* global variables */ - -extern int pr[NUM_PRIMES]; /* Primes array from tools.c. */ - -unsigned short factors[NUM_PRIMES], exponents[NUM_PRIMES]; -int modmode = GENERAL_MOD; -int curshorts = 0; -static giant t1 = NULL, t2 = NULL, t3 = NULL, t4 = NULL; -static giant An = NULL, Ad = NULL; -static point_mont pt1, pt2; -point_mont pb[D+2]; -giant xzb[D+2]; - -static int verbosity = 0; - -/************************************************************** - * - * Functions - * - **************************************************************/ - -int -init_fmodule(int shorts) { - curshorts = shorts; - pb[0] = NULL; /* To guarantee proper ECM initialization. */ - t1 = newgiant(shorts); - t2 = newgiant(shorts); - t3 = newgiant(shorts); - t4 = newgiant(shorts); - An = newgiant(shorts); - Ad = newgiant(shorts); - pt1 = new_point_mont(shorts); - pt2 = new_point_mont(shorts); -} - -void -verbose(int state) -/* Call verbose(1) for output during factoring processes, - call verbose(0) to silence all that. - */ -{ - verbosity = state; -} - -void -dot(void) -{ - printf("."); - fflush(stdout); -} - -void -set_mod_mode(int mode) -/* Call this with mode := 1, 0, -1, for Fermat-mod, general mod, and Mersenne mod, - respectively; the point being that the special cases of - Fermat- and Mersenne-mod are much faster than - general mod. If all mods will be with respect to a number-to-be-factored, - of the form N = 2^m + 1, use Fermat mod; while if N = 2^m-1, use Mersenne mod. - */ -{ - modmode = mode; -} - -void -special_modg( - giant N, - giant t -) -{ - switch (modmode) - { - case MERSENNE_MOD: - mersennemod(bitlen(N), t); - break; - case FERMAT_MOD: - fermatmod(bitlen(N)-1, t); - break; - default: - modg(N, t); - break; - } -} - -unsigned short * -prime_list() { - return(&factors[0]); -} - -unsigned short * -exponent_list() { - return(&exponents[0]); -} - -int -sieve(giant N, int sievelim) -/* Returns number of N's prime factors < min(sievelim, 2^16), - with N reduced accordingly by said factors. - The n-th entry of factors[] becomes the n-th prime - factor of N, with corresponding exponent - becoming the n-th element of exponents[]. - */ -{ int j, pcount, rem; - unsigned short pri; - - pcount = 0; - exponents[0] = 0; - for (j=0; j < NUM_PRIMES; j++) - { - pri = pr[j]; - if(pri > sievelim) break; - do { - gtog(N, t1); - rem = idivg(pri, t1); - if(rem == 0) { - ++exponents[pcount]; - gtog(t1, N); - } - } while(rem == 0); - if(exponents[pcount] > 0) { - factors[pcount] = pr[j]; - ++pcount; - exponents[pcount] = 0; - } - } - return(pcount); -} - -int -pollard_rho(giant N, giant fact, int steps, int abort) -/* Perform Pollard-rho x:= 3; loop(x:= x^2 + 2), a total of steps times. - Parameter fact will be a nontrivial factor found, in which case - N is also modified as: N := N/fact. - The function returns 0 if no nontrivial factor found, else returns 1. - The abort parameter, when set, causes the factorer to exit on the - first nontrivial factor found (the requisite GCD is checked - every 1000 steps). If abort := 0, the full number - of steps are always performed, then one solitary GCD is taken, - before exit. - */ -{ - int j, found = 0; - - itog(3, t1); - gtog(t1, t2); - itog(1, fact); - for(j=0; j < steps; j++) { - squareg(t1); iaddg(2, t1); special_modg(N, t1); - squareg(t2); iaddg(2, t2); special_modg(N, t2); - squareg(t2); iaddg(2, t2); special_modg(N, t2); - gtog(t2, t3); subg(t1,t3); mulg(t3, fact); special_modg(N, fact); - if(((j % 1000 == 999) && abort) || (j == steps-1)) { - if(verbosity) dot(); - gcdg(N, fact); - if(!isone(fact)) { - found = (gcompg(N, fact) == 0) ? 0 : 1; - break; - } - } - } - if(verbosity) { printf("\n"); fflush(stdout); } - if(found) { - divg(fact, N); - return(1); - } - itog(1, fact); - return(0); -} - -int -pollard_pminus1(giant N, giant fact, int lim, int abort) -/* Perform Pollard-(p-1); where we test - - GCD[N, 3^P - 1], - - where P is an accumulation of primes <= min(lim, 2^16), - to appropriate powers. - Parameter fact will be a nontrivial factor found, in which case - N is also modified as: N := N/fact. - The function returns 0 if no nontrivial factor found, else returns 1. - The abort parameter, when set, causes the factorer to exit on the - first nontrivial factor found (the requisite GCD is checked - every 100 steps). If abort := 0, the full number - of steps are always performed, then one solitary GCD is taken, - before exit. - */ -{ int cnt, j, k, pri, found = 0; - - itog(3, fact); - for (j=0; j< NUM_PRIMES; j++) - { - pri = pr[j]; - if((pri > lim) || (j == NUM_PRIMES-1) || (abort && (j % 100 == 99))) { - if(verbosity) dot(); - gtog(fact, t1); - itog(1, t2); - subg(t2, t1); - special_modg(N, t1); - gcdg(N, t1); - if(!isone(t1)) { - found = (gcompg(N, t1) == 0) ? 0 : 1; - break; - } - if(pri > lim) break; - } - if(pri < 19) { cnt = 20-pri; /* Smaller primes get higher powers. */ - } else if(pri < 100) { - cnt = 2; - } else cnt = 1; - for (k=0; k< cnt; k++) - { - powermod(fact, pri, N); - } - } - if(verbosity) { printf("\n"); fflush(stdout); } - if(found) { - gtog(t1, fact); - divg(fact, N); - return(1); - } - itog(1, fact); - return(0); -} - -int -ecm(giant N, giant fact, int S, unsigned int B, unsigned int C) -/* Perform elliptic curve method (ECM), with: - Brent seed parameter = S - Stage-one limit = B - Stage-two limit = C - This function: - returns 1 if nontrivial factor is found in stage 1 of ECM; - returns 2 if nontrivial factor is found in stage 2 of ECM; - returns 0 otherwise. - In the positive return, parameter fact is the factor and N := N/fact. - */ -{ unsigned int pri, q; - int j, cnt, count, k; - - if(verbosity) { - printf("Finding curve and point, B = %u, C = %u, seed = %d...", B, C, S); - fflush(stdout); - } - find_curve_point_brent(pt1, S, An, Ad, N); - if(verbosity) { - printf("\n"); - printf("Commencing stage 1 of ECM...\n"); - fflush(stdout); - } - - q = pr[NUM_PRIMES-1]; - count = 0; - for(j=0; ; j++) { - if(j < NUM_PRIMES) { - pri = pr[j]; - } else { - q += 2; - if(primeq(q)) pri = q; - else continue; - } - if(verbosity) if((++count) % 100 == 0) dot(); - if(pri > B) break; - if(pri < 19) { cnt = 20-pri; - } else if(pri < 100) { - cnt = 2; - } else cnt = 1; - for(k = 0; k < cnt; k++) - ell_mul_int_brent(pt1, pri, An, Ad, N); - } - k = 19; - while (kz, fact); - gcdg(N, fact); - if((!isone(fact)) && (gcompg(N, fact) != 0)) { - divg(fact, N); - return(1); - } - if(B >= C) { /* No stage 2 planned. */ - itog(1, fact); - return(0); - } - -/* Commence second stage of ECM. */ - if(verbosity) { - printf("\n"); - printf("Commencing stage 2 of ECM...\n"); - fflush(stdout); - } - if(pb[0] == NULL) { - for(k=0; k < D+2; k++) { - pb[k] = new_point_mont(curshorts); - xzb[k] = newgiant(curshorts); - - } - } - k = ((int)B)/D; - ptop_mont(pt1, pb[0]); - ell_mul_int_brent(pb[0], k*D+1 , An, Ad, N); - ptop_mont(pt1, pb[D+1]); - ell_mul_int_brent(pb[D+1], (k+2)*D+1 , An, Ad, N); - - for (j=1; j <= D; j++) - { - ptop_mont(pt1, pb[j]); - ell_mul_int_brent(pb[j], 2*j , An, Ad, N); - gtog(pb[j]->z, xzb[j]); - mulg(pb[j]->x, xzb[j]); - special_modg(N, xzb[j]); - } - itog(1, fact); - count = 0; - while (1) { - if(verbosity) if((++count) % 10 == 0) dot(); - gtog(pb[0]->z, xzb[0]); - mulg(pb[0]->x, xzb[0]); - special_modg(N, xzb[0]); - mulg(pb[0]->z, fact); - special_modg(N, fact); /* Accumulate. */ - for (j = 1; j < D; j++) { - if (!primeq(k*D+1+2*j)) continue; -/* Next, accumulate (xa - xb)(za + zb) - xa za + xb zb. */ - gtog(pb[0]->x, t1); - subg(pb[j]->x, t1); - gtog(pb[0]->z, t2); - addg(pb[j]->z, t2); - mulg(t1, t2); - special_modg(N, t1); - subg(xzb[0], t2); - addg(xzb[j], t2); - special_modg(N, t2); - mulg(t2, fact); - special_modg(N, fact); - } - k += 2; - if(k*D > C) - break; - ptop_mont(pb[D+1], pt2); - ell_odd_brent(pb[D], pb[D+1], pb[0], N); - ptop_mont(pt2, pb[0]); - } - if(verbosity) { printf("\n"); fflush(stdout); } - - gcdg(N, fact); - if((!isone(fact)) && (gcompg(N, fact) != 0)) { - divg(fact, N); - return(2); /* Return value of 2 for stage-2 success! */ - } - itog(1, fact); - return(0); -} - - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/fmodule.h b/OSX/include/security_cryptkit/CurveParamDocs/fmodule.h deleted file mode 100644 index 36070812..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/fmodule.h +++ /dev/null @@ -1,36 +0,0 @@ -/************************************************************** - * - * fmodule.h - * - * Header file for fmodule.c. - * - * Updates: - * 13 Apr 98 REC - creation - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -#define GENERAL_MOD 0 -#define FERMAT_MOD 1 -#define MERSENNE_MOD (-1) - -int -init_fmodule(int shorts); - -void -s_modg( - giant N, - giant t -); - -unsigned short * -prime_list(); - -unsigned short * -exponent_list(); - -int -sieve(giant N, int sievelim); diff --git a/OSX/include/security_cryptkit/CurveParamDocs/giants.c b/OSX/include/security_cryptkit/CurveParamDocs/giants.c deleted file mode 100644 index abf62d26..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/giants.c +++ /dev/null @@ -1,3517 +0,0 @@ -/************************************************************** - * - * giants.c - * - * Library for large-integer arithmetic. - * - * The large-gcd implementation is due to J. P. Buhler. - * Special mod routines use ideas of R. McIntosh. - * Contributions from G. Woltman, A. Powell acknowledged. - * - * Updates: - * 18 Jul 99 REC Added routine fer_mod(), for use when Fermat - giant itself is available. - * 17 Jul 99 REC Fixed sign bug in fermatmod() - * 17 Apr 99 REC Fixed various comment/line wraps - * 25 Mar 99 REC G. Woltman/A. Powell fixes Karat. routines - * 05 Mar 99 REC Moved invaux, binvaux giants to stack - * 05 Mar 99 REC Moved gread/gwrite giants to stack - * 05 Mar 99 REC No static on cur_den, cur_recip (A. Powell) - * 28 Feb 99 REC Error detection added atop newgiant(). - * 27 Feb 99 REC Reduced wasted work in addsignal(). - * 27 Feb 99 REC Reduced wasted work in FFTmulg(). - * 19 Feb 99 REC Generalized iaddg() per R. Mcintosh. - * 2 Feb 99 REC Fixed comments. - * 6 Dec 98 REC Fixed yet another Karatsuba glitch. - * 1 Dec 98 REC Fixed errant case of addg(). - * 28 Nov 98 REC Installed A. Powell's (correct) variant of - Karatsuba multiply. - * 15 May 98 REC Modified gwrite() to handle huge integers. - * 13 May 98 REC Changed to static stack declarations - * 11 May 98 REC Installed Karatsuba multiply, to handle - * medregion 'twixt grammar- and FFT-multiply. - * 1 May 98 JF gshifts now handle bits < 0 correctly. - * 30 Apr 98 JF 68k assembler code removed, - * stack giant size now invariant and based - * on first call of newgiant(), - * stack memory leaks fixed. - * 29 Apr 98 JF function prototyes cleaned up, - * GCD no longer uses personal stack, - * optimized shifts for bits%16 == 0. - * 27 Apr 98 JF scratch giants now replaced with stack - * 20 Apr 98 JF grammarsquareg fixed for asize == 0. - * scratch giants now static. - * 29 Jan 98 JF Corrected out-of-range errors in - * mersennemod and fermatmod. - * 23 Dec 97 REC Sped up divide routines via split-shift. - * 18 Nov 97 JF Improved mersennemod, fermatmod. - * 9 Nov 97 JF Sped up grammarsquareg. - * 20 May 97 RDW Fixed Win32 compiler warnings. - * 18 May 97 REC Installed new, fast divide. - * 17 May 97 REC Reduced memory for FFT multiply. - * 26 Apr 97 REC Creation. - * - * c. 1997,1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - **************************************************************/ - - -/* Include Files. */ - -#include -#include -#include -#include -#include "giants.h" - - -/* Compiler options. */ - -#ifdef _WIN32 -#pragma warning( disable : 4127 4706 ) /* disable conditional is constant warning */ -#endif - - -/* Global variables. */ - -int error = 0; -int mulmode = AUTO_MUL; -int cur_prec = 0; -int cur_shift = 0; -static int cur_stack_size = 0; -static int cur_stack_elem = 0; -static int stack_glen = 0; -static giant *stack; -giant cur_den = NULL, - cur_recip = NULL; -int current_max_size = 0, - cur_run = 0; -double * sinCos=NULL; -int checkFFTerror = 0; -double maxFFTerror; -static giant u0=NULL, u1=NULL, v0=NULL, v1=NULL; -static double *z = NULL, - *z2 = NULL; - -/* stack handling functions. */ -static giant popg(void); -static void pushg(int); - - -/* Private function prototypes. */ - -int gerr(void); -double gfloor(double); -int radixdiv(int, int, giant); -void columnwrite(FILE *, short *, char *, short, int); - -void normal_addg(giant, giant); -void normal_subg(giant, giant); -void reverse_subg(giant, giant); -int binvaux(giant, giant); -int invaux(giant, giant); -int allzeros(int, int, giant); -void auxmulg(giant a, giant b); -void karatmulg(giant a, giant b); -void karatsquareg(giant b); -void grammarmulg(giant a, giant b); -void grammarsquareg(giant b); - -int lpt(int, int *); -void addsignal(giant, double *, int); -void FFTsquareg(giant x); -void FFTmulg(giant y, giant x); -void scramble_real(); -void fft_real_to_hermitian(double *z, int n); -void fftinv_hermitian_to_real(double *z, int n); -void mul_hermitian(double *a, double *b, int n); -void square_hermitian(double *b, int n); -void giant_to_double(giant x, int sizex, double *z, int L); -void gswap(giant *, giant *); -void onestep(giant, giant, gmatrix); -void mulvM(gmatrix, giant, giant); -void mulmM(gmatrix, gmatrix); -void writeM(gmatrix); -static void punch(giant, gmatrix); -static void dotproduct(giant, giant, giant, giant); -void fix(giant *, giant *); -void hgcd(int, giant, giant, gmatrix); -void shgcd(int, int, gmatrix); - - - -/************************************************************** - * - * Functions - * - **************************************************************/ - - -/************************************************************** - * - * Initialization and utility functions - * - **************************************************************/ - -double -gfloor( - double f -) -{ - return floor(f); -} - - -void -init_sinCos( - int n -) -{ - int j; - double e = TWOPI/n; - - if (n<=cur_run) - return; - cur_run = n; - if (sinCos) - free(sinCos); - sinCos = (double *)malloc(sizeof(double)*(1+(n>>2))); - for (j=0;j<=(n>>2);j++) - { - sinCos[j] = sin(e*j); - } -} - - -double -s_sin( - int n -) -{ - int seg = n/(cur_run>>2); - - switch (seg) - { - case 0: return(sinCos[n]); - case 1: return(sinCos[(cur_run>>1)-n]); - case 2: return(-sinCos[n-(cur_run>>1)]); - case 3: return(-sinCos[cur_run-n]); - } - return 0; -} - - -double -s_cos( - int n -) -{ - int quart = (cur_run>>2); - - if (n < quart) - return(s_sin(n+quart)); - return(-s_sin(n-quart)); -} - - -int -gerr(void) -{ - return(error); -} - - -giant -popg ( - void -) -{ - int i; - - if (current_max_size <= 0) current_max_size = MAX_SHORTS; - - if (cur_stack_size == 0) { -/* Initialize the stack if we're just starting out. - * Note that all stack giants will be whatever current_max_size is - * when newgiant() is first called. */ - cur_stack_size = STACK_GROW; - stack = (giant *) malloc (cur_stack_size * sizeof(giant)); - for(i = 0; i < STACK_GROW; i++) - stack[i] = NULL; - if (stack_glen == 0) stack_glen = current_max_size; - } else if (cur_stack_elem >= cur_stack_size) { -/* Expand the stack if we need to. */ - i = cur_stack_size; - cur_stack_size += STACK_GROW; - stack = (giant *) realloc (stack,cur_stack_size * sizeof(giant)); - for (; i < cur_stack_size; i++) - stack[i] = NULL; - } else if (cur_stack_elem < cur_stack_size - 2*STACK_GROW) { -/* Prune the stack if it's too big. Disabled, so the stack can only expand */ - /* cur_stack_size -= STACK_GROW; - for (i = cur_stack_size - STACK_GROW; i < cur_stack_size; i++) - free(stack[i]); - stack = (giant *) realloc (stack,cur_stack_size * sizeof(giant)); */ - } - -/* Malloc our giant. */ - if (stack[cur_stack_elem] == NULL) - stack[cur_stack_elem] = malloc(stack_glen*sizeof(short)+sizeof(int)); - stack[cur_stack_elem]->sign = 0; - - return(stack[cur_stack_elem++]); -} - - -void -pushg ( - int a -) -{ - if (a < 0) return; - cur_stack_elem -= a; - if (cur_stack_elem < 0) cur_stack_elem = 0; -} - - -giant -newgiant( - int numshorts -) -{ - int size; - giant thegiant; - - if (numshorts > MAX_SHORTS) { - fprintf(stderr, "Requested giant too big.\n"); - fflush(stderr); - } - if (numshorts<=0) - numshorts = MAX_SHORTS; - size = numshorts*sizeof(short)+sizeof(int); - thegiant = (giant)malloc(size); - thegiant->sign = 0; - - if (newmin(2*numshorts,MAX_SHORTS) > current_max_size) - current_max_size = newmin(2*numshorts,MAX_SHORTS); - -/* If newgiant() is being called for the first time, set the - * size of the stack giants. */ - if (stack_glen == 0) stack_glen = current_max_size; - - return(thegiant); -} - - -gmatrix -newgmatrix( - void -) -/* Allocates space for a gmatrix struct, but does not - * allocate space for the giants. */ -{ - return((gmatrix) malloc (4*sizeof(giant))); -} - -int -bitlen( - giant n -) -{ - int b = 16, c = 1<<15, w; - - if (isZero(n)) - return(0); - w = n->n[abs(n->sign) - 1]; - while ((w&c) == 0) - { - b--; - c >>= 1; - } - return (16*(abs(n->sign)-1) + b); -} - - -int -bitval( - giant n, - int pos -) -{ - int i = abs(pos)>>4, c = 1 << (pos&15); - - return ((n->n[i]) & c); -} - - -int -isone( - giant g -) -{ - return((g->sign==1)&&(g->n[0]==1)); -} - - -int isZero( - giant thegiant -) -/* Returns TR if thegiant == 0. */ -{ - register int count; - int length = abs(thegiant->sign); - register unsigned short * numpointer = thegiant->n; - - if (length) - { - for(count = 0; countsign)*sizeof(short); - - memcpy((char *)destgiant,(char *)srcgiant,numbytes); -} - - -void -itog( - int i, - giant g -) -/* The giant g becomes set to the integer value i. */ -{ - unsigned int j = abs(i); - - if (i==0) - { - g->sign = 0; - g->n[0] = 0; - return; - } - g->n[0] = (unsigned short)(j & 0xFFFF); - j >>= 16; - if (j) - { - g->n[1] = (unsigned short)j; - g->sign = 2; - } - else - { - g->sign = 1; - } - if (i<0) - g->sign = -(g->sign); -} - - -signed int -gtoi( - giant x -) -/* Calculate the value of an int-sized giant NOT exceeding 31 bits. */ -{ - register int size = abs(x->sign); - register int sign = (x->sign < 0) ? -1 : 1; - - switch(size) - { - case 0: - break; - case 1: - return sign * x->n[0]; - case 2: - return sign * (x->n[0]+((x->n[1])<<16)); - default: - fprintf(stderr,"Giant too large for gtoi\n"); - break; - } - return 0; -} - - -int -gsign( - giant g -) -/* Returns the sign of g. */ -{ - if (isZero(g)) - return(0); - if (g->sign >0) - return(1); - return(-1); -} - - -#if 0 -int gcompg(a,b) -/* Returns -1,0,1 if ab, respectively. */ - giant a,b; -{ - int size = abs(a->sign); - - if(isZero(a)) size = 0; - if (size == 0) { - if (isZero(b)) return(0); else return(-gsign(b)); - } - - if (b->sign == 0) return(gsign(a)); - if (gsign(a)!=gsign(b)) return(gsign(a)); - if (size>abs(b->sign)) return(gsign(a)); - if (sizesign)) return(-gsign(a)); - - do { - --size; - if (a->n[size] > b->n[size]) return(gsign(a)); - if (a->n[size] < b->n[size]) return(-gsign(a)); - } while(size>0); - - return(0); -} -#else - -int -gcompg( - giant a, - giant b -) -/* Returns -1,0,1 if ab, respectively. */ -{ - int sa = a->sign, j, sb = b->sign, va, vb, sgn; - - if(sa > sb) - return(1); - if(sa < sb) - return(-1); - if(sa < 0) - { - sa = -sa; /* Take absolute value of sa. */ - sgn = -1; - } - else - { - sgn = 1; - } - for(j = sa-1; j >= 0; j--) - { - va = a->n[j]; - vb = b->n[j]; - if (va > vb) - return(sgn); - if (va < vb) - return(-sgn); - } - return(0); -} -#endif - - -void -setmulmode( - int mode -) -{ - mulmode = mode; -} - - -/************************************************************** - * - * Private I/O Functions - * - **************************************************************/ - - -int -radixdiv( - int base, - int divisor, - giant thegiant -) -/* Divides giant of arbitrary base by divisor. - * Returns remainder. Used by idivg and gread. */ -{ - int first = TR; - int finalsize = abs(thegiant->sign); - int j = finalsize-1; - unsigned short *digitpointer=&thegiant->n[j]; - unsigned int num,rem=0; - - if (divisor == 0) - { - error = DIVIDEBYZERO; - exit(error); - } - - while (j>=0) - { - num=rem*base + *digitpointer; - *digitpointer = (unsigned short)(num/divisor); - if (first) - { - if (*digitpointer == 0) - --finalsize; - else - first = FA; - } - rem = num % divisor; - --digitpointer; - --j; - } - - if ((divisor<0) ^ (thegiant->sign<0)) - finalsize=-finalsize; - thegiant->sign=finalsize; - return(rem); -} - - -void -columnwrite( - FILE *filepointer, - short *column, - char *format, - short arg, - int newlines -) -/* Used by gwriteln. */ -{ - char outstring[10]; - short i; - - sprintf(outstring,format,arg); - for (i=0; outstring[i]!=0; ++i) - { - if (newlines) - { - if (*column >= COLUMNWIDTH) - { - fputs("\\\n",filepointer); - *column = 0; - } - } - fputc(outstring[i],filepointer); - ++*column; - } -} - - -void -gwrite( - giant thegiant, - FILE *filepointer, - int newlines -) -/* Outputs thegiant to filepointer. Output is terminated by a newline. */ -{ - short column; - unsigned int i; - unsigned short *numpointer; - giant garbagegiant, basetengrand; - - basetengrand = popg(); - garbagegiant = popg(); - - if (isZero(thegiant)) - { - fputs("0",filepointer); - } - else - { - numpointer = basetengrand->n; - gtog(thegiant,garbagegiant); - - basetengrand->sign = 0; - do - { - *numpointer = (unsigned short)idivg(10000,garbagegiant); - ++numpointer; - if (++basetengrand->sign >= current_max_size) - { - error = OVFLOW; - exit(error); - } - } while (!isZero(garbagegiant)); - - if (!error) - { - i = basetengrand->sign-1; - column = 0; - if (thegiant->sign<0 && basetengrand->n[i]!=0) - columnwrite(filepointer,&column,"-",0, newlines); - columnwrite(filepointer,&column,"%d",basetengrand->n[i],newlines); - for( ; i>0; ) - { - --i; - columnwrite(filepointer,&column,"%04d",basetengrand->n[i],newlines); - } - } - } - pushg(2); -} - - -void -gwriteln( - giant theg, - FILE *filepointer -) -{ - gwrite(theg, filepointer, 1); - fputc('\n',filepointer); -} - - -void -gread( - giant theg, - FILE *filepointer -) -{ - char currentchar; - int isneg,size,backslash=FA,numdigits=0; - unsigned short *numpointer; - giant basetenthousand; - static char *inbuf = NULL; - - basetenthousand = popg(); - if (inbuf == NULL) - inbuf = (char*)malloc(MAX_DIGITS); - - currentchar = (char)fgetc(filepointer); - if (currentchar=='-') - { - isneg=TR; - } - else - { - isneg=FA; - if (currentchar!='+') - ungetc(currentchar,filepointer); - } - - do - { - currentchar = (char)fgetc(filepointer); - if ((currentchar>='0') && (currentchar<='9')) - { - inbuf[numdigits]=currentchar; - if(++numdigits==MAX_DIGITS) - break; - backslash=FA; - } - else - { - if (currentchar=='\\') - backslash=TR; - } - } while(((currentchar!=' ') && (currentchar!='\n') && - (currentchar!='\t')) || (backslash) ); - if (numdigits) - { - size = 0; - do - { - inbuf[numdigits] = 0; - numdigits-=4; - if (numdigits<0) - numdigits=0; - basetenthousand->n[size] = (unsigned short)strtol(&inbuf[numdigits],NULL,10); - ++size; - } while (numdigits>0); - - basetenthousand->sign = size; - theg->sign = 0; - numpointer = theg->n; - do - { - *numpointer = (unsigned short) - radixdiv(10000,1<<(8*sizeof(short)),basetenthousand); - ++numpointer; - if (++theg->sign >= current_max_size) - { - error = OVFLOW; - exit(error); - } - } while (!isZero(basetenthousand)); - - if (isneg) - theg->sign = -theg->sign; - } - pushg(1); -} - - - -/************************************************************** - * - * Private Math Functions - * - **************************************************************/ - - -void -negg( - giant g -) -/* g becomes -g. */ -{ - g->sign = -g->sign; -} - - -void -absg( - giant g -) -{ - /* g becomes the absolute value of g. */ - if (g->sign <0) - g->sign=-g->sign; -} - - -void -iaddg( - int i, - giant g -) -/* Giant g becomes g + (int)i. */ -{ - int w,j=0,carry = 0, size = abs(g->sign); - giant tmp; - - if (isZero(g)) - { - itog(i,g); - } - else if(g->sign < 0) { - tmp = popg(); - itog(i, tmp); - addg(tmp, g); - pushg(1); - return; - } - else - { - w = g->n[0]+i; - do - { - g->n[j] = (unsigned short) (w & 65535L); - carry = w >> 16; - w = g->n[++j]+carry; - } while ((carry!=0) && (jsign; - g->n[size] = (unsigned short)carry; - } -} - - -/* New subtract routines. - The basic subtract "subg()" uses the following logic table: - - a b if(b > a) if(a > b) - - + + b := b - a b := -(a - b) - - + b := b + (-a) N.A. - + - N.A. b := -((-b) + a) - - - b := (-a) - (-b) b := -((-b) - (-a)) - - The basic addition routine "addg()" uses: - - a b if(b > -a) if(-a > b) - - + + b := b + a N.A. - - + b := b - (-a) b := -((-a) - b) - + - b := a - (-b) b := -((-b) - a) - - - N.A. b := -((-b) + (-a)) - - In this way, internal routines "normal_addg," "normal_subg," - and "reverse_subg;" each of which assumes non-negative - operands and a non-negative result, are now used for greater - efficiency. - */ - -void -normal_addg( - giant a, - giant b -) -/* b := a + b, both a,b assumed non-negative. */ -{ - int carry = 0; - int asize = a->sign, bsize = b->sign; - long k; - int j=0; - unsigned short *aptr = a->n, *bptr = b->n; - - if (asize < bsize) - { - for (j=0; j= 65536L) - { - k -= 65536L; - ++carry; - } - *bptr++ = (unsigned short)k; - } - for (j=asize; j= 65536L) - { - k -= 65536L; - ++carry; - } - *bptr++ = (unsigned short)k; - } - } - else - { - for (j=0; j= 65536L) - { - k -= 65536L; - ++carry; - } - *bptr++ = (unsigned short)k; - } - for (j=bsize; j= 65536L) - { - k -= 65536L; - ++carry; - } - *bptr++ = (unsigned short)k; - } - } - if (carry) - { - *bptr = 1; ++j; - } - b->sign = j; -} - - -void -normal_subg( - giant a, - giant b -) -/* b := b - a; requires b, a non-negative and b >= a. */ -{ - int j, size = b->sign; - unsigned int k; - - if (a->sign == 0) - return; - - k = 0; - for (j=0; jsign; ++j) - { - k += 0xffff - a->n[j] + b->n[j]; - b->n[j] = (unsigned short)(k & 0xffff); - k >>= 16; - } - for (j=a->sign; jn[j]; - b->n[j] = (unsigned short)(k & 0xffff); - k >>= 16; - } - - if (b->n[0] == 0xffff) - iaddg(1,b); - else - ++b->n[0]; - - while ((size-- > 0) && (b->n[size]==0)); - - b->sign = (b->n[size]==0) ? 0 : size+1; -} - - -void -reverse_subg( - giant a, - giant b -) -/* b := a - b; requires b, a non-negative and a >= b. */ -{ - int j, size = a->sign; - unsigned int k; - - k = 0; - for (j=0; jsign; ++j) - { - k += 0xffff - b->n[j] + a->n[j]; - b->n[j] = (unsigned short)(k & 0xffff); - k >>= 16; - } - for (j=b->sign; jn[j]; - b->n[j] = (unsigned short)(k & 0xffff); - k >>= 16; - } - - b->sign = size; /* REC, 21 Apr 1996. */ - if (b->n[0] == 0xffff) - iaddg(1,b); - else - ++b->n[0]; - - while (!b->n[--size]); - - b->sign = size+1; -} - -void -addg( - giant a, - giant b -) -/* b := b + a, any signs any result. */ -{ - int asgn = a->sign, bsgn = b->sign; - - if (asgn == 0) - return; - if (bsgn == 0) - { - gtog(a,b); - return; - } - if ((asgn < 0) == (bsgn < 0)) - { - if (bsgn > 0) - { - normal_addg(a,b); - return; - } - absg(b); - if(a != b) absg(a); - normal_addg(a,b); - negg(b); - if(a != b) negg(a); - return; - } - if(bsgn > 0) - { - negg(a); - if (gcompg(b,a) >= 0) - { - normal_subg(a,b); - negg(a); - return; - } - reverse_subg(a,b); - negg(a); - negg(b); - return; - } - negg(b); - if(gcompg(b,a) < 0) - { - reverse_subg(a,b); - return; - } - normal_subg(a,b); - negg(b); - return; -} - -void -subg( - giant a, - giant b -) -/* b := b - a, any signs, any result. */ -{ - int asgn = a->sign, bsgn = b->sign; - - if (asgn == 0) - return; - if (bsgn == 0) - { - gtog(a,b); - negg(b); - return; - } - if ((asgn < 0) != (bsgn < 0)) - { - if (bsgn > 0) - { - negg(a); - normal_addg(a,b); - negg(a); - return; - } - negg(b); - normal_addg(a,b); - negg(b); - return; - } - if (bsgn > 0) - { - if (gcompg(b,a) >= 0) - { - normal_subg(a,b); - return; - } - reverse_subg(a,b); - negg(b); - return; - } - negg(a); - negg(b); - if (gcompg(b,a) >= 0) - { - normal_subg(a,b); - negg(a); - negg(b); - return; - } - reverse_subg(a,b); - negg(a); - return; -} - - -int -numtrailzeros( - giant g -) -/* Returns the number of trailing zero bits in g. */ -{ - register int numshorts = abs(g->sign), j, bcount=0; - register unsigned short gshort, c; - - for (j=0;jn[j]; - c = 1; - for (bcount=0;bcount<16; bcount++) - { - if (c & gshort) - break; - c <<= 1; - } - if (bcount<16) - break; - } - return(bcount + 16*j); -} - - -void -bdivg( - giant v, - giant u -) -/* u becomes greatest power of two not exceeding u/v. */ -{ - int diff = bitlen(u) - bitlen(v); - giant scratch7; - - if (diff<0) - { - itog(0,u); - return; - } - scratch7 = popg(); - gtog(v, scratch7); - gshiftleft(diff,scratch7); - if (gcompg(u,scratch7) < 0) - diff--; - if (diff<0) - { - itog(0,u); - pushg(1); - return; - } - itog(1,u); - gshiftleft(diff,u); - - pushg(1); -} - - -int -binvaux( - giant p, - giant x -) -/* Binary inverse method. Returns zero if no inverse exists, - * in which case x becomes GCD(x,p). */ -{ - - giant scratch7, u0, u1, v0, v1; - - if (isone(x)) - return(1); - u0 = popg(); - u1 = popg(); - v0 = popg(); - v1 = popg(); - itog(1, v0); - gtog(x, v1); - itog(0,x); - gtog(p, u1); - - scratch7 = popg(); - while(!isZero(v1)) - { - gtog(u1, u0); - bdivg(v1, u0); - gtog(x, scratch7); - gtog(v0, x); - mulg(u0, v0); - subg(v0,scratch7); - gtog(scratch7, v0); - - gtog(u1, scratch7); - gtog(v1, u1); - mulg(u0, v1); - subg(v1,scratch7); - gtog(scratch7, v1); - } - - pushg(1); - - if (!isone(u1)) - { - gtog(u1,x); - if(x->sign<0) addg(p, x); - pushg(4); - return(0); - } - if(x->sign<0) - addg(p, x); - pushg(4); - return(1); -} - - -int -binvg( - giant p, - giant x -) -{ - modg(p, x); - return(binvaux(p,x)); -} - - -int -invg( - giant p, - giant x -) -{ - modg(p, x); - return(invaux(p,x)); -} - -int -invaux( - giant p, - giant x -) -/* Returns zero if no inverse exists, in which case x becomes - * GCD(x,p). */ -{ - - giant scratch7, u0, u1, v0, v1; - - if ((x->sign==1)&&(x->n[0]==1)) - return(1); - - u0 = popg(); - u1 = popg(); - v0 = popg(); - v1 = popg(); - - itog(1,u1); - gtog(p, v0); - gtog(x, v1); - itog(0,x); - - scratch7 = popg(); - while (!isZero(v1)) - { - gtog(v0, u0); - divg(v1, u0); - gtog(u0, scratch7); - mulg(v1, scratch7); - subg(v0, scratch7); - negg(scratch7); - gtog(v1, v0); - gtog(scratch7, v1); - gtog(u1, scratch7); - mulg(u0, scratch7); - subg(x, scratch7); - negg(scratch7); - gtog(u1,x); - gtog(scratch7, u1); - } - pushg(1); - - if ((v0->sign!=1)||(v0->n[0]!=1)) - { - gtog(v0,x); - pushg(4); - return(0); - } - if(x->sign<0) - addg(p, x); - pushg(4); - return(1); -} - - -int -mersenneinvg( - int q, - giant x -) -{ - int k; - giant u0, u1, v1; - - u0 = popg(); - u1 = popg(); - v1 = popg(); - - itog(1, u0); - itog(0, u1); - itog(1, v1); - gshiftleft(q, v1); - subg(u0, v1); - mersennemod(q, x); - while (1) - { - k = -1; - if (isZero(x)) - { - gtog(v1, x); - pushg(3); - return(0); - } - while (bitval(x, ++k) == 0); - - gshiftright(k, x); - if (k) - { - gshiftleft(q-k, u0); - mersennemod(q, u0); - } - if (isone(x)) - break; - addg(u1, u0); - mersennemod(q, u0); - negg(u1); - addg(u0, u1); - mersennemod(q, u1); - if (!gcompg(v1,x)) { - pushg(3); - return(0); - } - addg(v1, x); - negg(v1); - addg(x, v1); - mersennemod(q, v1); - } - gtog(u0, x); - mersennemod(q,x); - pushg(3); - return(1); -} - - -void -cgcdg( - giant a, - giant v -) -/* Classical Euclid GCD. v becomes gcd(a, v). */ -{ - giant u, r; - - v->sign = abs(v->sign); - if (isZero(a)) - return; - - u = popg(); - r = popg(); - gtog(a, u); - u->sign = abs(u->sign); - while (!isZero(v)) - { - gtog(u, r); - modg(v, r); - gtog(v, u); - gtog(r, v); - } - gtog(u,v); - pushg(2); -} - - -void -gcdg( - giant x, - giant y -) -{ - if (bitlen(y)<= GCDLIMIT) - bgcdg(x,y); - else - ggcd(x,y); -} - -void -bgcdg( - giant a, - giant b -) -/* Binary form of the gcd. b becomes the gcd of a,b. */ -{ - int k = isZero(b), m = isZero(a); - giant u, v, t; - - if (k || m) - { - if (m) - { - if (k) - itog(1,b); - return; - } - if (k) - { - if (m) - itog(1,b); - else - gtog(a,b); - return; - } - } - - u = popg(); - v = popg(); - t = popg(); - - /* Now neither a nor b is zero. */ - gtog(a, u); - u->sign = abs(a->sign); - gtog(b, v); - v->sign = abs(b->sign); - k = numtrailzeros(u); - m = numtrailzeros(v); - if (k>m) - k = m; - gshiftright(k,u); - gshiftright(k,v); - if (u->n[0] & 1) - { - gtog(v, t); - negg(t); - } - else - { - gtog(u,t); - } - - while (!isZero(t)) - { - m = numtrailzeros(t); - gshiftright(m, t); - if (t->sign > 0) - { - gtog(t, u); - subg(v,t); - } - else - { - gtog(t, v); - negg(v); - addg(u,t); - } - } - gtog(u,b); - gshiftleft(k, b); - pushg(3); -} - - -void -powerg( - int m, - int n, - giant g -) -/* g becomes m^n, NO mod performed. */ -{ - giant scratch2 = popg(); - - itog(1, g); - itog(m, scratch2); - while (n) - { - if (n & 1) - mulg(scratch2, g); - n >>= 1; - if (n) - squareg(scratch2); - } - pushg(1); -} - -#if 0 -void -jtest( - giant n -) -{ - if (n->sign) - { - if (n->n[n->sign-1] == 0) - { - fprintf(stderr,"%d %d tilt",n->sign, (int)(n->n[n->sign-1])); - exit(7); - } - } -} -#endif - - -void -make_recip( - giant d, - giant r -) -/* r becomes the steady-state reciprocal - * 2^(2b)/d, where b = bit-length of d-1. */ -{ - int b; - giant tmp, tmp2; - - if (isZero(d) || (d->sign < 0)) - { - exit(SIGN); - } - tmp = popg(); - tmp2 = popg(); - itog(1, r); - subg(r, d); - b = bitlen(d); - addg(r, d); - gshiftleft(b, r); - gtog(r, tmp2); - while (1) - { - gtog(r, tmp); - squareg(tmp); - gshiftright(b, tmp); - mulg(d, tmp); - gshiftright(b, tmp); - addg(r, r); - subg(tmp, r); - if (gcompg(r, tmp2) <= 0) - break; - gtog(r, tmp2); - } - itog(1, tmp); - gshiftleft(2*b, tmp); - gtog(r, tmp2); - mulg(d, tmp2); - subg(tmp2, tmp); - itog(1, tmp2); - while (tmp->sign < 0) - { - subg(tmp2, r); - addg(d, tmp); - } - pushg(2); -} - -void -divg_via_recip( - giant d, - giant r, - giant n -) -/* n := n/d, where r is the precalculated - * steady-state reciprocal of d. */ -{ - int s = 2*(bitlen(r)-1), sign = gsign(n); - giant tmp, tmp2; - - if (isZero(d) || (d->sign < 0)) - { - exit(SIGN); - } - - tmp = popg(); - tmp2 = popg(); - - n->sign = abs(n->sign); - itog(0, tmp2); - while (1) - { - gtog(n, tmp); - mulg(r, tmp); - gshiftright(s, tmp); - addg(tmp, tmp2); - mulg(d, tmp); - subg(tmp, n); - if (gcompg(n,d) >= 0) - { - subg(d,n); - iaddg(1, tmp2); - } - if (gcompg(n,d) < 0) - break; - } - gtog(tmp2, n); - n->sign *= sign; - pushg(2); -} - -#if 1 -void -modg_via_recip( - giant d, - giant r, - giant n -) -/* This is the fastest mod of the present collection. - * n := n % d, where r is the precalculated - * steady-state reciprocal of d. */ - -{ - int s = (bitlen(r)-1), sign = n->sign; - giant tmp, tmp2; - - if (isZero(d) || (d->sign < 0)) - { - exit(SIGN); - } - - tmp = popg(); - tmp2 = popg(); - - n->sign = abs(n->sign); - while (1) - { - gtog(n, tmp); gshiftright(s-1, tmp); - mulg(r, tmp); - gshiftright(s+1, tmp); - mulg(d, tmp); - subg(tmp, n); - if (gcompg(n,d) >= 0) - subg(d,n); - if (gcompg(n,d) < 0) - break; - } - if (sign >= 0) - goto done; - if (isZero(n)) - goto done; - negg(n); - addg(d,n); -done: - pushg(2); - return; -} - -#else -void -modg_via_recip( - giant d, - giant r, - giant n -) -{ - int s = 2*(bitlen(r)-1), sign = n->sign; - giant tmp, tmp2; - - if (isZero(d) || (d->sign < 0)) - { - exit(SIGN); - } - - tmp = popg(); - tmp2 = popg() - - n->sign = abs(n->sign); - while (1) - { - gtog(n, tmp); - mulg(r, tmp); - gshiftright(s, tmp); - mulg(d, tmp); - subg(tmp, n); - if (gcompg(n,d) >= 0) - subg(d,n); - if (gcompg(n,d) < 0) - break; - } - if (sign >= 0) - goto done; - if (isZero(n)) - goto done; - negg(n); - addg(d,n); -done: - pushg(2); - return; -} -#endif - -void -modg( - giant d, - giant n -) -/* n becomes n%d. n is arbitrary, but the denominator d must be positive! */ -{ - if (cur_recip == NULL) { - cur_recip = newgiant(current_max_size); - cur_den = newgiant(current_max_size); - gtog(d, cur_den); - make_recip(d, cur_recip); - } else if (gcompg(d, cur_den)) { - gtog(d, cur_den); - make_recip(d, cur_recip); - } - modg_via_recip(d, cur_recip, n); -} - - -#if 0 -int -feemulmod ( - giant a, - giant b, - int q, - int k -) -/* a becomes (a*b) (mod 2^q-k) where q % 16 == 0 and k is "small" (0 < k < 65535). - * Returns 0 if unsuccessful, otherwise 1. */ -{ - giant carry, kk, scratch; - int i, j; - int asize = abs(a->sign), bsize = abs(b->sign); - unsigned short *aptr,*bptr,*destptr; - unsigned int words; - int kpower, curk; - - if ((q % 16) || (k <= 0) || (k >= 65535)) { - return (0); - } - - carry = popg(); - kk = popg(); - scratch = popg(); - - for (i=0; in[i]=0; - - words = q >> 4; - - bptr = b->n; - for (i = 0; i < bsize; i++) { - mult = *bptr++; - if (mult) { - kpower = i/words; - - if (kpower >= 1) itog (kpower,kk); - for (j = 1; j < kpower; k++) smulg(kpower,kk); - - itog(0,carry); - - aptr = a->n; - for (j = 0; j < bsize; b++) { - gtog(kk,scratch); - smulg(*aptr++,scratch); - smulg(mult,scratch); - iaddg(*destptr,scratch); - addg(carry,scratch); - *destptr++ = scratch->n[0]; - gshiftright(scratch,16); - gtog(scratch,carry); - if (destptr - scratch->n >= words) { - smulg(k, carry); - smulg(k, kk); - destptr -= words; - } - } - } - } - - int i,j,m; - unsigned int prod,carry=0; - int asize = abs(a->sign), bsize = abs(b->sign); - unsigned short *aptr,*bptr,*destptr; - unsigned short mult; - int words, excess; - int temp; - giant scratch = popg(), scratch2 = popg(), scratch3 = popg(); - short *carryptr = scratch->n; - int kpower,kpowerlimit, curk; - - if ((q % 16) || (k <= 0) || (k >= 65535)) { - return (0); - } - - scratch - - for (i=0; in[i]=0; - - words = q >> 4; - - bptr = b->n; - for (i=0; in; - destptr = scratch->n + i; - - if (kpower == 0) { - carry = 0; - } else if (kpower <= kpowerlimit) { - carry = 0; - curk = k; - for (j = 1; j < kpower; j++) curk *= k; - } else { - itog (k,scratch); - for (j = 1; j < kpower; j++) smulg(k,scratch); - itog(0,scratch2); - } - - for (j = 0; j < asize; j++) { - if(kpower == 0) { - prod = *aptr++ * mult + *destptr + carry; - *destptr++ = (unsigned short)(prod & 0xFFFF); - carry = prod >> 16; - } else if (kpower < kpowerlimit) { - prod = kcur * *aptr++; - temp = prod >> 16; - prod &= 0xFFFF; - temp *= mult; - prod *= mult; - temp += prod >> 16; - prod &= 0xFFFF; - prod += *destptr + carry; - carry = prod >> 16 + temp; - *destptr++ = (unsigned short)(prod & 0xFFFF); - } else { - gtog(scratch,scratch3); - smulg(*aptr++,scratch3); - smulg(mult,scratch3); - iaddg(*destptr,scratch3); - addg(scratch3,scratch2); - *destptr++ = scratch2->n[0]; - memmove(scratch2->n,scratch2->n+1,2*(scratch2->size-1)); - scratch2->sign--; - } - if (destptr - scratch->n > words) { - if (kpower == 0) { - curk = k; - carry *= k; - } else if (kpower < kpowerlimit) { - curk *= k; - carry *= curk; - } else if (kpower == kpowerlimit) { - itog (k,scratch); - for (j = 1; j < kpower; j++) smulg(k,scratch); - itog(carry,scratch2); - smulg(k,scratch2); - } else { - smulg(k,scratch); - smulg(k,scratch2); - } - kpower++; - destptr -= words; - } - } - - /* Next, deal with the carry term. Needs to be improved to - handle overflow carry cases. */ - if (kpower <= kpowerlimit) { - iaddg(carry,scratch); - } else { - addg(scratch2,scratch); - } - while(scratch->sign > q) - gtog(scratch,scratch2) - } - } - scratch->sign = destptr - scratch->n; - if (!carry) - --(scratch->sign); - scratch->sign *= gsign(a)*gsign(b); - gtog(scratch,a); - pushg(3); - return (1); -} -#endif - -int -idivg( - int divisor, - giant theg -) -{ - /* theg becomes theg/divisor. Returns remainder. */ - int n; - int base = 1<<(8*sizeof(short)); - - n = radixdiv(base,divisor,theg); - return(n); -} - - -void -divg( - giant d, - giant n -) -/* n becomes n/d. n is arbitrary, but the denominator d must be positive! */ -{ - if (cur_recip == NULL) { - cur_recip = newgiant(current_max_size); - cur_den = newgiant(current_max_size); - gtog(d, cur_den); - make_recip(d, cur_recip); - } else if (gcompg(d, cur_den)) { - gtog(d, cur_den); - make_recip(d, cur_recip); - } - divg_via_recip(d, cur_recip, n); -} - - -void -powermod( - giant x, - int n, - giant g -) -/* x becomes x^n (mod g). */ -{ - giant scratch2 = popg(); - gtog(x, scratch2); - itog(1, x); - while (n) - { - if (n & 1) - { - mulg(scratch2, x); - modg(g, x); - } - n >>= 1; - if (n) - { - squareg(scratch2); - modg(g, scratch2); - } - } - pushg(1); -} - - -void -powermodg( - giant x, - giant n, - giant g -) -/* x becomes x^n (mod g). */ -{ - int len, pos; - giant scratch2 = popg(); - - gtog(x, scratch2); - itog(1, x); - len = bitlen(n); - pos = 0; - while (1) - { - if (bitval(n, pos++)) - { - mulg(scratch2, x); - modg(g, x); - } - if (pos>=len) - break; - squareg(scratch2); - modg(g, scratch2); - } - pushg(1); -} - - -void -fermatpowermod( - giant x, - int n, - int q -) -/* x becomes x^n (mod 2^q+1). */ -{ - giant scratch2 = popg(); - - gtog(x, scratch2); - itog(1, x); - while (n) - { - if (n & 1) - { - mulg(scratch2, x); - fermatmod(q, x); - } - n >>= 1; - if (n) - { - squareg(scratch2); - fermatmod(q, scratch2); - } - } - pushg(1); -} - - -void -fermatpowermodg( - giant x, - giant n, - int q -) -/* x becomes x^n (mod 2^q+1). */ -{ - int len, pos; - giant scratch2 = popg(); - - gtog(x, scratch2); - itog(1, x); - len = bitlen(n); - pos = 0; - while (1) - { - if (bitval(n, pos++)) - { - mulg(scratch2, x); - fermatmod(q, x); - } - if (pos>=len) - break; - squareg(scratch2); - fermatmod(q, scratch2); - } - pushg(1); -} - - -void -mersennepowermod( - giant x, - int n, - int q -) -/* x becomes x^n (mod 2^q-1). */ -{ - giant scratch2 = popg(); - - gtog(x, scratch2); - itog(1, x); - while (n) - { - if (n & 1) - { - mulg(scratch2, x); - mersennemod(q, x); - } - n >>= 1; - if (n) - { - squareg(scratch2); - mersennemod(q, scratch2); - } - } - pushg(1); -} - - -void -mersennepowermodg( - giant x, - giant n, - int q -) -/* x becomes x^n (mod 2^q-1). */ -{ - int len, pos; - giant scratch2 = popg(); - - gtog(x, scratch2); - itog(1, x); - len = bitlen(n); - pos = 0; - while (1) - { - if (bitval(n, pos++)) - { - mulg(scratch2, x); - mersennemod(q, x); - } - if (pos>=len) - break; - squareg(scratch2); - mersennemod(q, scratch2); - } - pushg(1); -} - - -void -gshiftleft( - int bits, - giant g -) -/* shift g left bits bits. Equivalent to g = g*2^bits. */ -{ - int rem = bits&15, crem = 16-rem, words = bits>>4; - int size = abs(g->sign), j, k, sign = gsign(g); - unsigned short carry, dat; - - if (!bits) - return; - if (!size) - return; - if (bits < 0) { - gshiftright(-bits,g); - return; - } - if (size+words+1 > current_max_size) { - error = OVFLOW; - exit(error); - } - if (rem == 0) { - memmove(g->n + words, g->n, size * sizeof(short)); - for (j = 0; j < words; j++) g->n[j] = 0; - g->sign += (g->sign < 0)?(-words):(words); - } else { - k = size+words; - carry = 0; - for (j=size-1; j>=0; j--) { - dat = g->n[j]; - g->n[k--] = (unsigned short)((dat >> crem) | carry); - carry = (unsigned short)(dat << rem); - } - do { - g->n[k--] = carry; - carry = 0; - } while(k>=0); - - k = size+words; - if (g->n[k] == 0) - --k; - g->sign = sign*(k+1); - } -} - - -void -gshiftright( - int bits, - giant g -) -/* shift g right bits bits. Equivalent to g = g/2^bits. */ -{ - register int j,size=abs(g->sign); - register unsigned int carry; - int words = bits >> 4; - int remain = bits & 15, cremain = (16-remain); - - if (bits==0) - return; - if (isZero(g)) - return; - if (bits < 0) { - gshiftleft(-bits,g); - return; - } - if (words >= size) { - g->sign = 0; - return; - } - if (remain == 0) { - memmove(g->n,g->n + words,(size - words) * sizeof(short)); - g->sign += (g->sign < 0)?(words):(-words); - } else { - size -= words; - - if (size) - { - for(j=0;jn[j+words+1] << cremain; - g->n[j] = (unsigned short)((g->n[j+words] >> remain ) | carry); - } - g->n[size-1] = (unsigned short)(g->n[size-1+words] >> remain); - } - - if (g->n[size-1] == 0) - --size; - - if (g->sign > 0) - g->sign = size; - else - g->sign = -size; - } -} - - -void -extractbits( - int n, - giant src, - giant dest -) -/* dest becomes lowermost n bits of src. Equivalent to dest = src % 2^n. */ -{ - register int words = n >> 4, numbytes = words*sizeof(short); - register int bits = n & 15; - - if (n<=0) - return; - if (words >= abs(src->sign)) - gtog(src,dest); - else - { - memcpy((char *)(dest->n), (char *)(src->n), numbytes); - if (bits) - { - dest->n[words] = (unsigned short)(src->n[words] & ((1<n[words-1] == 0) && (words > 0)) - { - --words; - } - if (src->sign<0) - dest->sign = -words; - else - dest->sign = words; - } -} - - -int -allzeros( - int shorts, - int bits, - giant g -) -{ - int i=shorts; - - while (i>0) - { - if (g->n[--i]) - return(0); - } - return((int)(!(g->n[shorts] & ((1<>4, - bits = n & 15, - i = shorts, - mask = 1<g->sign-1; --temp) - { - g->n[temp] = 0; - } - if (g->n[shorts] & mask) - { /* if high bit is set, -g = 1. */ - g->sign = 1; - g->n[0] = 1; - return; - } - if (allzeros(shorts,bits,g)) - return; /* if g=0, -g = 0. */ - - while (i>0) - { --i; - g->n[i] = (unsigned short)(~(g->n[i+1])); - } - g->n[shorts] ^= mask-1; - - carry = 2; - i = 0; - while (carry) - { - temp = g->n[i]+carry; - g->n[i++] = (unsigned short)(temp & 0xffff); - carry = temp>>16; - } - while(!g->n[shorts]) - { - --shorts; - } - g->sign = shorts+1; -} - - -void -mersennemod ( - int n, - giant g -) -/* g := g (mod 2^n - 1) */ -{ - int the_sign, s; - giant scratch3 = popg(), scratch4 = popg(); - - if ((the_sign = gsign(g)) < 0) absg(g); - while (bitlen(g) > n) { - gtog(g,scratch3); - gshiftright(n,scratch3); - addg(scratch3,g); - gshiftleft(n,scratch3); - subg(scratch3,g); - } - if(!isZero(g)) { - if ((s = gsign(g)) < 0) absg(g); - itog(1,scratch3); - gshiftleft(n,scratch3); - itog(1,scratch4); - subg(scratch4,scratch3); - if(gcompg(g,scratch3) >= 0) subg(scratch3,g); - if (s < 0) { - g->sign = -g->sign; - addg(scratch3,g); - } - if (the_sign < 0) { - g->sign = -g->sign; - addg(scratch3,g); - } - } - pushg(2); -} - -void -fermatmod ( - int n, - giant g -) -/* g := g (mod 2^n + 1), */ -{ - int the_sign, s; - giant scratch3 = popg(); - - if ((the_sign = gsign(g)) < 0) absg(g); - while (bitlen(g) > n) { - gtog(g,scratch3); - gshiftright(n,scratch3); - subg(scratch3,g); - gshiftleft(n,scratch3); - subg(scratch3,g); - } - if((bitlen(g) < n) && (the_sign * (g->sign) >= 0)) goto leave; - if(!isZero(g)) { - if ((s = gsign(g)) < 0) absg(g); - itog(1,scratch3); - gshiftleft(n,scratch3); - iaddg(1,scratch3); - if(gcompg(g,scratch3) >= 0) subg(scratch3,g); - if (s * the_sign < 0) { - g->sign = -g->sign; - addg(scratch3,g); - } - } -leave: - pushg(1); - -} - -void -fer_mod ( - int n, - giant g, - giant modulus -) -/* Same as fermatmod(), except modulus = 2^n should be passed -if available (i.e. if already allocated and set). */ -{ - int the_sign, s; - giant scratch3 = popg(); - - if ((the_sign = gsign(g)) < 0) absg(g); - while (bitlen(g) > n) { - gtog(g,scratch3); - gshiftright(n,scratch3); - subg(scratch3,g); - gshiftleft(n,scratch3); - subg(scratch3,g); - } - if((bitlen(g) < n) && (the_sign * (g->sign) >= 0)) goto leave; - if(!isZero(g)) { - if ((s = gsign(g)) < 0) absg(g); - if(gcompg(g,modulus) >= 0) subg(modulus,g); - if (s * the_sign < 0) { - g->sign = -g->sign; - addg(modulus,g); - } - } -leave: - pushg(1); -} - - -void -smulg( - unsigned short i, - giant g -) -/* g becomes g * i. */ -{ - unsigned short carry = 0; - int size = abs(g->sign); - register int j,k,mul = abs(i); - unsigned short *digit = g->n; - - for (j=0; j>16); - *digit = (unsigned short)(k & 0xffff); - ++digit; - } - if (carry) - { - if (++j >= current_max_size) - { - error = OVFLOW; - exit(error); - } - *digit = carry; - } - - if ((g->sign>0) ^ (i>0)) - g->sign = -j; - else - g->sign = j; -} - - -void -squareg( - giant b -) -/* b becomes b^2. */ -{ - auxmulg(b,b); -} - - -void -mulg( - giant a, - giant b -) -/* b becomes a*b. */ -{ - auxmulg(a,b); -} - - -void -auxmulg( - giant a, - giant b -) -/* Optimized general multiply, b becomes a*b. Modes are: - * AUTO_MUL: switch according to empirical speed criteria. - * GRAMMAR_MUL: force grammar-school algorithm. - * KARAT_MUL: force Karatsuba divide-conquer method. - * FFT_MUL: force floating point FFT method. */ -{ - float grammartime; - int square = (a==b); - int sizea, sizeb; - - switch (mulmode) - { - case GRAMMAR_MUL: - if (square) grammarsquareg(b); - else grammarmulg(a,b); - break; - case FFT_MUL: - if (square) - FFTsquareg(b); - else - FFTmulg(a,b); - break; - case KARAT_MUL: - if (square) karatsquareg(b); - else karatmulg(a,b); - break; - case AUTO_MUL: - sizea = abs(a->sign); - sizeb = abs(b->sign); - if((sizea > KARAT_BREAK) && (sizea <= FFT_BREAK) && - (sizeb > KARAT_BREAK) && (sizeb <= FFT_BREAK)){ - if(square) karatsquareg(b); - else karatmulg(a,b); - - } else { - grammartime = (float)sizea; - grammartime *= (float)sizeb; - if (grammartime < FFT_BREAK * FFT_BREAK) - { - if (square) grammarsquareg(b); - else grammarmulg(a,b); - } - else - { - if (square) FFTsquareg(b); - else FFTmulg(a,b); - } - } - break; - } -} - -void -justg(giant x) { - int s = x->sign, sg = 1; - - if(s<0) { - sg = -1; - s = -s; - } - --s; - while(x->n[s] == 0) { - --s; - if(s < 0) break; - } - x->sign = sg*(s+1); -} - -/* Next, improved Karatsuba routines from A. Powell, - improvements by G. Woltman. */ - -void -karatmulg(giant x, giant y) -/* y becomes x*y. */ -{ - int s = abs(x->sign), t = abs(y->sign), w, bits, - sg = gsign(x)*gsign(y); - giant a, b, c, d, e, f; - - if((s <= KARAT_BREAK) || (t <= KARAT_BREAK)) { - grammarmulg(x,y); - return; - } - w = (s + t + 2)/4; bits = 16*w; - a = popg(); b = popg(); c = popg(); - d = popg(); e = popg(); f = popg(); - gtog(x,a); absg(a); if (w <= s) {a->sign = w; justg(a);} - gtog(x,b); absg(b); - gshiftright(bits, b); - gtog(y,c); absg(c); if (w <= t) {c->sign = w; justg(c);} - gtog(y,d); absg(d); - gshiftright(bits,d); - gtog(a,e); normal_addg(b,e); /* e := (a + b) */ - gtog(c,f); normal_addg(d,f); /* f := (c + d) */ - karatmulg(e,f); /* f := (a + b)(c + d) */ - karatmulg(c,a); /* a := a c */ - karatmulg(d,b); /* b := b d */ - normal_subg(a,f); - /* f := (a + b)(c + d) - a c */ - normal_subg(b,f); - /* f := (a + b)(c + d) - a c - b d */ - gshiftleft(bits, b); - normal_addg(f, b); - gshiftleft(bits, b); - normal_addg(a, b); - gtog(b, y); y->sign *= sg; - pushg(6); - - return; -} - -void -karatsquareg(giant x) -/* x becomes x^2. */ -{ - int s = abs(x->sign), w, bits; - giant a, b, c; - - if(s <= KARAT_BREAK) { - grammarsquareg(x); - return; - } - w = (s+1)/2; bits = 16*w; - a = popg(); b = popg(); c = popg(); - gtog(x, a); a->sign = w; justg(a); - gtog(x, b); absg(b); - gshiftright(bits, b); - gtog(a,c); normal_addg(b,c); - karatsquareg(c); - karatsquareg(a); - karatsquareg(b); - normal_subg(b, c); - normal_subg(a, c); - gshiftleft(bits, b); - normal_addg(c,b); - gshiftleft(bits, b); - normal_addg(a, b); - gtog(b, x); - pushg(3); - - return; -} - -void -grammarmulg( - giant a, - giant b -) -/* b becomes a*b. */ -{ - int i,j; - unsigned int prod,carry=0; - int asize = abs(a->sign), bsize = abs(b->sign); - unsigned short *aptr,*bptr,*destptr; - unsigned short mult; - giant scratch = popg(); - - for (i=0; in[i]=0; - } - - bptr = &(b->n[0]); - for (i=0; in[0]); - destptr = &(scratch->n[i]); - for (j=0; j> 16; - } - *destptr = (unsigned short)carry; - } - } - bsize+=asize; - if (!carry) - --bsize; - scratch->sign = gsign(a)*gsign(b)*bsize; - gtog(scratch,b); - pushg(1); -} - - -void -grammarsquareg ( - giant a -) -/* a := a^2. */ -{ - unsigned int cur_term; - unsigned int prod, carry=0, temp; - int asize = abs(a->sign), max = asize * 2 - 1; - unsigned short *ptr = a->n, *ptr1, *ptr2; - giant scratch; - - if(asize == 0) { - itog(0,a); - return; - } - - scratch = popg(); - - asize--; - - temp = *ptr; - temp *= temp; - scratch->n[0] = temp; - carry = temp >> 16; - - for (cur_term = 1; cur_term < max; cur_term++) { - ptr1 = ptr2 = ptr; - if (cur_term <= asize) { - ptr2 += cur_term; - } else { - ptr1 += cur_term - asize; - ptr2 += asize; - } - prod = carry & 0xFFFF; - carry >>= 16; - while(ptr1 < ptr2) { - temp = *ptr1++ * *ptr2--; - prod += (temp << 1) & 0xFFFF; - carry += (temp >> 15); - } - if (ptr1 == ptr2) { - temp = *ptr1; - temp *= temp; - prod += temp & 0xFFFF; - carry += (temp >> 16); - } - carry += prod >> 16; - scratch->n[cur_term] = (unsigned short) (prod); - } - if (carry) { - scratch->n[cur_term] = carry; - scratch->sign = cur_term+1; - } else scratch->sign = cur_term; - - gtog(scratch,a); - pushg(1); -} - - -/************************************************************** - * - * FFT multiply Functions - * - **************************************************************/ - -int initL = 0; - -int -lpt( - int n, - int *lambda -) -/* Returns least power of two greater than n. */ -{ - register int i = 1; - - *lambda = 0; - while (i maxFFTerror) - maxFFTerror = err; - } - z[j] =0; - k = 0; - do - { - g = gfloor(f*TWOM16); - z[j+k] += f-g*TWO16; - ++k; - f=g; - } while(f != 0.0); - } - car = 0; - for(j=0;j < last + 1;j++) - { - m = (int)(z[j]+car); - x->n[j] = (unsigned short)(m & 0xffff); - car = (m>>16); - } - if (car) - x->n[j] = (unsigned short)car; - else - --j; - - while(!(x->n[j])) --j; - - x->sign = j+1; -} - - -void -FFTsquareg( - giant x -) -{ - int j,size = abs(x->sign); - register int L; - - if (size<4) - { - grammarmulg(x,x); - return; - } - L = lpt(size+size, &j); - if(!z) z = (double *)malloc(MAX_SHORTS * sizeof(double)); - giant_to_double(x, size, z, L); - fft_real_to_hermitian(z, L); - square_hermitian(z, L); - fftinv_hermitian_to_real(z, L); - addsignal(x,z,L); - x->sign = abs(x->sign); -} - - -void -FFTmulg( - giant y, - giant x -) -{ - /* x becomes y*x. */ - int lambda, sizex = abs(x->sign), sizey = abs(y->sign); - int finalsign = gsign(x)*gsign(y); - register int L; - - if ((sizex<=4)||(sizey<=4)) - { - grammarmulg(y,x); - return; - } - L = lpt(sizex+sizey, &lambda); - if(!z) z = (double *)malloc(MAX_SHORTS * sizeof(double)); - if(!z2) z2 = (double *)malloc(MAX_SHORTS * sizeof(double)); - - giant_to_double(x, sizex, z, L); - giant_to_double(y, sizey, z2, L); - fft_real_to_hermitian(z, L); - fft_real_to_hermitian(z2, L); - mul_hermitian(z2, z, L); - fftinv_hermitian_to_real(z, L); - addsignal(x,z,L); - x->sign = finalsign*abs(x->sign); -} - - -void -scramble_real( - double *x, - int n -) -{ - register int i,j,k; - register double tmp; - - for (i=0,j=0;i>=1; - } - j += k; - } -} - - -void -fft_real_to_hermitian( - double *z, - int n -) -/* Output is {Re(z^[0]),...,Re(z^[n/2),Im(z^[n/2-1]),...,Im(z^[1]). - * This is a decimation-in-time, split-radix algorithm. - */ -{ - register double cc1, ss1, cc3, ss3; - register int is, id, i0, i1, i2, i3, i4, i5, i6, i7, i8, - a, a3, b, b3, nminus = n-1, dil, expand; - register double *x, e; - int nn = n>>1; - double t1, t2, t3, t4, t5, t6; - register int n2, n4, n8, i, j; - - init_sinCos(n); - expand = cur_run/n; - scramble_real(z, n); - x = z-1; /* FORTRAN compatibility. */ - is = 1; - id = 4; - do - { - for (i0=is;i0<=n;i0+=id) - { - i1 = i0+1; - e = x[i0]; - x[i0] = e + x[i1]; - x[i1] = e - x[i1]; - } - is = (id<<1)-1; - id <<= 2; - } while(is>=1) - { - n2 <<= 1; - n4 = n2>>2; - n8 = n2>>3; - is = 0; - id = n2<<1; - do - { - for (i=is;i>1; - double t1, t2, t3, t4, t5; - int n2, n4, n8, i, j; - - init_sinCos(n); - expand = cur_run/n; - x = z-1; - n2 = n<<1; - while(nn >>= 1) - { - is = 0; - id = n2; - n2 >>= 1; - n4 = n2>>2; - n8 = n4>>1; - do - { - for(i=is;i>1; - register double aa, bb, am, bm; - - b[0] *= a[0]; - b[half] *= a[half]; - for (k=1;k>1; - register double c, d; - - b[0] *= b[0]; - b[half] *= b[half]; - for (k=1;kn[j]; - } -} - - -void -gswap( - giant *p, - giant *q -) -{ - giant t; - - t = *p; - *p = *q; - *q = t; -} - - -void -onestep( - giant x, - giant y, - gmatrix A -) -/* Do one step of the euclidean algorithm and modify - * the matrix A accordingly. */ -{ - giant s4 = popg(); - - gtog(x,s4); - gtog(y,x); - gtog(s4,y); - divg(x,s4); - punch(s4,A); - mulg(x,s4); - subg(s4,y); - - pushg(1); -} - - -void -mulvM( - gmatrix A, - giant x, - giant y -) -/* Multiply vector by Matrix; changes x,y. */ -{ - giant s0 = popg(), s1 = popg(); - - gtog(A->ur,s0); - gtog( A->lr,s1); - dotproduct(x,y,A->ul,s0); - dotproduct(x,y,A->ll,s1); - gtog(s0,x); - gtog(s1,y); - - pushg(2); -} - - -void -mulmM( - gmatrix A, - gmatrix B -) -/* Multiply matrix by Matrix; changes second matrix. */ -{ - giant s0 = popg(); - giant s1 = popg(); - giant s2 = popg(); - giant s3 = popg(); - - gtog(B->ul,s0); - gtog(B->ur,s1); - gtog(B->ll,s2); - gtog(B->lr,s3); - dotproduct(A->ur,A->ul,B->ll,s0); - dotproduct(A->ur,A->ul,B->lr,s1); - dotproduct(A->ll,A->lr,B->ul,s2); - dotproduct(A->ll,A->lr,B->ur,s3); - gtog(s0,B->ul); - gtog(s1,B->ur); - gtog(s2,B->ll); - gtog(s3,B->lr); - - pushg(4); -} - - -void -writeM( - gmatrix A -) -{ - printf(" ul:"); - gout(A->ul); - printf(" ur:"); - gout(A->ur); - printf(" ll:"); - gout(A->ll); - printf(" lr:"); - gout(A->lr); -} - - -void -punch( - giant q, - gmatrix A -) -/* Multiply the matrix A on the left by [0,1,1,-q]. */ -{ - giant s0 = popg(); - - gtog(A->ll,s0); - mulg(q,A->ll); - gswap(&A->ul,&A->ll); - subg(A->ul,A->ll); - gtog(s0,A->ul); - gtog(A->lr,s0); - mulg(q,A->lr); - gswap(&A->ur,&A->lr); - subg(A->ur,A->lr); - gtog(s0,A->ur); - - pushg(1); -} - - -static void -dotproduct( - giant a, - giant b, - giant c, - giant d -) -/* Replace last argument with the dot product of two 2-vectors. */ -{ - giant s4 = popg(); - - gtog(c,s4); - mulg(a, s4); - mulg(b,d); - addg(s4,d); - - pushg(1); -} - - -void -ggcd( - giant xx, - giant yy -) -/* A giant gcd. Modifies its arguments. */ -{ - giant x = popg(), y = popg(); - gmatrix A = newgmatrix(); - - gtog(xx,x); gtog(yy,y); - for(;;) - { - fix(&x,&y); - if (bitlen(y) <= GCDLIMIT ) - break; - A->ul = popg(); - A->ur = popg(); - A->ll = popg(); - A->lr = popg(); - itog(1,A->ul); - itog(0,A->ur); - itog(0,A->ll); - itog(1,A->lr); - hgcd(0,x,y,A); - mulvM(A,x,y); - pushg(4); - fix(&x,&y); - if (bitlen(y) <= GCDLIMIT ) - break; - modg(y,x); - gswap(&x,&y); - } - bgcdg(x,y); - gtog(y,yy); - pushg(2); - free(A); -} - - -void -fix( - giant *p, - giant *q -) -/* Insure that x > y >= 0. */ -{ - if( gsign(*p) < 0 ) - negg(*p); - if( gsign(*q) < 0 ) - negg(*q); - if( gcompg(*p,*q) < 0 ) - gswap(p,q); -} - - -void -hgcd( - int n, - giant xx, - giant yy, - gmatrix A -) -/* hgcd(n,x,y,A) chops n bits off x and y and computes th - * 2 by 2 matrix A such that A[x y] is the pair of terms - * in the remainder sequence starting with x,y that is - * half the size of x. Note that the argument A is modified - * but that the arguments xx and yy are left unchanged. - */ -{ - giant x, y; - - if (isZero(yy)) - return; - - x = popg(); - y = popg(); - gtog(xx,x); - gtog(yy,y); - gshiftright(n,x); - gshiftright(n,y); - if (bitlen(x) <= INTLIMIT ) - { - shgcd(gtoi(x),gtoi(y),A); - } - else - { - gmatrix B = newgmatrix(); - int m = bitlen(x)/2; - - hgcd(m,x,y,A); - mulvM(A,x,y); - if (gsign(x) < 0) - { - negg(x); negg(A->ul); negg(A->ur); - } - if (gsign(y) < 0) - { - negg(y); negg(A->ll); negg(A->lr); - } - if (gcompg(x,y) < 0) - { - gswap(&x,&y); - gswap(&A->ul,&A->ll); - gswap(&A->ur,&A->lr); - } - if (!isZero(y)) - { - onestep(x,y,A); - m /= 2; - B->ul = popg(); - B->ur = popg(); - B->ll = popg(); - B->lr = popg(); - itog(1,B->ul); - itog(0,B->ur); - itog(0,B->ll); - itog(1,B->lr); - hgcd(m,x,y,B); - mulmM(B,A); - pushg(4); - } - free(B); - } - pushg(2); -} - - -void -shgcd( - register int x, - register int y, - gmatrix A -) -/* - * Do a half gcd on the integers a and b, putting the result in A - * It is fairly easy to use the 2 by 2 matrix description of the - * extended Euclidean algorithm to prove that the quantity q*t - * never overflows. - */ -{ - register int q, t, start = x; - int Aul = 1, Aur = 0, All = 0, Alr = 1; - - while (y != 0 && y > start/y) - { - q = x/y; - t = y; - y = x%y; - x = t; - t = All; - All = Aul-q*t; - Aul = t; - t = Alr; - Alr = Aur-q*t; - Aur = t; - } - itog(Aul,A->ul); - itog(Aur,A->ur); - itog(All,A->ll); - itog(Alr,A->lr); -} diff --git a/OSX/include/security_cryptkit/CurveParamDocs/giants.h b/OSX/include/security_cryptkit/CurveParamDocs/giants.h deleted file mode 100644 index d25ffffb..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/giants.h +++ /dev/null @@ -1,314 +0,0 @@ -/************************************************************** - * - * giants.h - * - * Header file for large-integer arithmetic library giants.c. - * - * Updates: - * 18 Jul 99 REC Added fer_mod(). - * 30 Apr 98 JF USE_ASSEMBLER_MUL removed - * 29 Apr 98 JF Function prototypes cleaned up - * 20 Apr 97 RDW - * - * c. 1997 Perfectly Scientific, Inc. - * All Rights Reserved. - * - **************************************************************/ - - -/************************************************************** - * - * Error Codes - * - **************************************************************/ - -#define DIVIDEBYZERO 1 -#define OVFLOW 2 -#define SIGN 3 -#define OVERRANGE 4 -#define AUTO_MUL 0 -#define GRAMMAR_MUL 1 -#define FFT_MUL 2 -#define KARAT_MUL 3 - -/************************************************************** - * - * Preprocessor definitions - * - **************************************************************/ - -/* 2^(16*MAX_SHORTS)-1 will fit into a giant, but take care: - * one usually has squares, etc. of giants involved, and - * every intermediate giant in a calculation must fit into - * this many shorts. Thus, if you want systematically to effect - * arithmetic on B-bit operands, you need MAX_SHORTS > B/8, - * perferably a tad larger than this; e.g. MAX_SHORTS > B/7. - */ -#define MAX_SHORTS (1<<19) - -#define INFINITY (-1) -#define FA 0 -#define TR 1 -#define COLUMNWIDTH 64 - -#define TWOPI (double)(2*3.1415926535897932384626433) -#define SQRT2 (double)(1.414213562373095048801688724209) -#define SQRTHALF (double)(0.707106781186547524400844362104) -#define TWO16 (double)(65536.0) -#define TWOM16 (double)(0.0000152587890625) - -/* Decimal digit ceiling in digit-input routines. */ -#define MAX_DIGITS 10000 - -/* Next, mumber of shorts per operand - at which Karatsuba breaks over. */ -#define KARAT_BREAK 40 - -/* Next, mumber of shorts per operand - at which FFT breaks over. */ -#define FFT_BREAK 200 - -#define newmin(a,b) ((a)<(b)? (a) : (b)) -#define newmax(a,b) ((a)>(b)? (a) : (b)) - -/* Maximum number of recursive steps needed to calculate - * gcds of integers. */ -#define STEPS 32 - -/* The limit below which hgcd is too ponderous */ -#define GCDLIMIT 5000 - -/* The limit below which ordinary ints will be used */ -#define INTLIMIT 31 - -/* Size by which to increment the stack used in pushg() and popg(). */ -#define STACK_GROW 16 - -#define gin(x) gread(x,stdin) -#define gout(x) gwriteln(x,stdout) - - -/************************************************************** - * - * Structure definitions - * - **************************************************************/ - -typedef struct -{ - int sign; - unsigned short n[1]; /* number of shorts = abs(sign) */ -} giantstruct; - -typedef giantstruct *giant; - -typedef struct _matrix -{ - giant ul; /* upper left */ - giant ur; /* upper right */ - giant ll; /* lower left */ - giant lr; /* lower right */ -} *gmatrix; - -typedef struct -{ - double re; - double im; -} complex; - - -/************************************************************** - * - * Function Prototypes - * - **************************************************************/ - -/************************************************************** - * - * Initialization and utility functions - * - **************************************************************/ - -/* trig lookups. */ -void init_sinCos(int); -double s_sin(int); -double s_cos(int); - - -/* Creates a new giant, numshorts = INFINITY invokes the - * maximum MAX_SHORTS. */ -giant newgiant(int numshorts); - -/* Creates a new giant matrix, but does not malloc - * the component giants. */ -gmatrix newgmatrix(void); - -/* Returns the bit-length n; e.g. n=7 returns 3. */ -int bitlen(giant n); - -/* Returns the value of the pos bit of n. */ -int bitval(giant n, int pos); - -/* Returns whether g is one. */ -int isone(giant g); - -/* Returns whether g is zero. */ -int isZero(giant g); - -/* Copies one giant to another. */ -void gtog(giant src, giant dest); - -/* Integer <-> giant. */ -void itog(int n, giant g); -signed int gtoi (giant); - -/* Returns the sign of g: -1, 0, 1. */ -int gsign(giant g); - -/* Returns 1, 0, -1 as a>b, a=b, a -#include -#include -#include -#include "giants.h" -#include "tools.h" -#include "ellproj.h" - -#define P_BREAK 32 - -#ifdef _WIN32 -#include -#define bzero(D, n) memset(D, 0x00, n) -#define bcopy(S, D, n) memcpy(D, S, n) -#endif - -#define Q_MAX 256 /* Bits in largest primes handled. */ -#define L_CEIL 100 /* Bound on Schoof L values (not all needed in general). */ - - -typedef struct - { - int deg; - giant *coe; - } polystruct; -typedef polystruct *poly; - -extern int *pr; - -static int Q, L_MAX; -static int MAX_DIGS, MAX_COEFFS; - -static giant *mcand, coe, tmp, err, aux, aux2, globx, globy, t1, t2, - t3, t4, t5; -static poly qscratch, rscratch, sscratch, tscratch, pbuff, - pbuff2, precip, cubic, powx, powy, kxn, kyn, kxd, kyd, - txn, txd, tyn, tyd, txn1, txd1, tyn1, tyd1, - nx, dx, ny, dy, mn, md, tmp1, tmp2, tmp3, tmp4; -static poly s[L_CEIL+2], smonic; -static giant p, a, b; -static int L; - -void quickmodg(giant g, giant x) -{ int sgn = x->sign; - - if(sgn == 0) return; - if(sgn > 0) { - if(gcompg(x, g) >= 0) subg(g, x); - return; - } - addg(g,x); - return; -} - -int -log_2(int n) { - int c = 1, d = -1; - while(c <= n) { - c <<= 1; - ++d; - } - return(d); -} - -void -justifyp(poly x) { - int j; - for(j = x->deg; j >= 0; j--) { - if(!is0(x->coe[j])) break; - } - x->deg = (j>0)? j : 0; -} - -void -polyrem(poly x) { - int j; - for(j=0; j <= x->deg; j++) { - modg(p, x->coe[j]); - } - justifyp(x); -} - - -giant * -newa(int n) { - giant *p = (giant *)malloc(n*sizeof(giant)); - int j; - for(j=0; jcoe = (giant *)newa(coeffs); - return(pol); -} - -void -init_all() { - int j; - - j = (2*Q + log_2(MAX_COEFFS) + 32 + 15)/16; - j = j * MAX_COEFFS; - globx = newgiant(j); - globy = newgiant(j); - s[0] = newpoly(MAX_COEFFS); - - for(j=1; j<=L_MAX+1; j++) { - s[j] = newpoly(j*(j+1)); - } - smonic = newpoly(MAX_COEFFS); - powx = newpoly(MAX_COEFFS); - powy = newpoly(MAX_COEFFS); - kxn = newpoly(MAX_COEFFS); - kxd = newpoly(MAX_COEFFS); - kyn = newpoly(MAX_COEFFS); - kyd = newpoly(MAX_COEFFS); - txn = newpoly(MAX_COEFFS); - txd = newpoly(MAX_COEFFS); - tyn = newpoly(MAX_COEFFS); - tyd = newpoly(MAX_COEFFS); - txn1 = newpoly(MAX_COEFFS); - txd1 = newpoly(MAX_COEFFS); - tyn1 = newpoly(MAX_COEFFS); - tyd1 = newpoly(MAX_COEFFS); - nx = newpoly(MAX_COEFFS); - ny = newpoly(MAX_COEFFS); - dx = newpoly(MAX_COEFFS); - dy = newpoly(MAX_COEFFS); - mn = newpoly(MAX_COEFFS); - md = newpoly(MAX_COEFFS); - tmp1 = newpoly(MAX_COEFFS); - tmp2 = newpoly(MAX_COEFFS); - tmp3 = newpoly(MAX_COEFFS); - tmp4 = newpoly(MAX_COEFFS); - mcand = (giant *)newa(MAX_COEFFS); -/* The next three need extra space for remaindering routines. */ - qscratch = newpoly(2*MAX_COEFFS); - rscratch = newpoly(2*MAX_COEFFS); - pbuff = newpoly(2*MAX_COEFFS); - pbuff2 = newpoly(MAX_COEFFS); - sscratch = newpoly(MAX_COEFFS); - tscratch = newpoly(MAX_COEFFS); - tmp = newgiant(MAX_DIGS); - err = newgiant(MAX_DIGS); - coe = newgiant(MAX_DIGS); - aux = newgiant(MAX_DIGS); - aux2 = newgiant(MAX_DIGS); - t3 = newgiant(MAX_DIGS); - t4 = newgiant(MAX_DIGS); - t5 = newgiant(MAX_DIGS); - cubic = newpoly(4); - precip = newpoly(MAX_COEFFS); -} - -void -atoa(giant *a, giant *b, int n) { - int j; - for(j=0; jdeg = x->deg; - atoa(x->coe, y->coe, y->deg+1); -} - -void -negp(poly y) -/* y := -y. */ -{ int j; - for(j=0; j <= y->deg; j++) { - negg(y->coe[j]); - quickmodg(p, y->coe[j]); - } -} - -int -iszer(giant a) { - - if(a->sign == 0) return(1); - return(0); - -} - -int -iszerop(poly x) { - if(x->deg == 0 && iszer(x->coe[0])) return 1; - return 0; -} - -int -is0(giant a) { - return(iszer(a)); -} - -int -is1(giant a) { - return(isone(a)); -} - - -void -addp(poly x, poly y) -/* y += x. */ -{ - int d = x->deg, j; - - if(y->deg > d) d = y->deg; - for(j = 0; j <= d; j++) { - if((j <= x->deg) && (j <= y->deg)) { - addg(x->coe[j], y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - if((j <= x->deg) && (j > y->deg)) { - gtog(x->coe[j], y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - } - y->deg = d; - justifyp(y); -} - -void -subp(poly x, poly y) -/* y -= x. */ -{ - int d = x->deg, j; - - if(y->deg > d) d = y->deg; - for(j = 0; j <= d; j++) { - if((j <= x->deg) && (j <= y->deg)) { - subg(x->coe[j], y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - if((j <= x->deg) && (j > y->deg)) { - gtog(x->coe[j], y->coe[j]); - negg(y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - } - y->deg = d; - justifyp(y); -} - - -void -grammarmulp(poly a, poly b) -/* b *= a. */ -{ - int dega = a->deg, degb = b->deg, deg = dega + degb; - register int d, kk, first, diffa; - - for(d=deg; d>=0; d--) { - diffa = d-dega; - itog(0, coe); - for(kk=0; kk<=d; kk++) { - if((kk>degb)||(kkcoe[kk], tmp); - mulg(a->coe[d-kk], tmp); - modg(p, tmp); - addg(tmp, coe); - quickmodg(p, coe); - } - gtog(coe, mcand[d]); - } - atoa(mcand, b->coe, deg+1); - b->deg = deg; - justifyp(b); -} - -void -atop(giant *a, poly x, int deg) -/* Copy array to poly, with monic option. */ -{ - int adeg = abs(deg); - x->deg = adeg; - atoa(a, x->coe, adeg); - if(deg < 0) { - itog(1, x->coe[adeg]); - } else { - gtog(a[adeg], x->coe[adeg]); - } -} - -void -just(giant g) { - while((g->n[g->sign-1] == 0) && (g->sign > 0)) --g->sign; -} - -void -unstuff_partial(giant g, poly y, int words){ - int j; - for(j=0; j < y->deg; j++) { - bcopy((g->n) + j*words, y->coe[j]->n, words*sizeof(short)); - y->coe[j]->sign = words; - just(y->coe[j]); - } -} - -void -stuff(poly x, giant g, int words) { - int deg = x->deg, j, coedigs; - - g->sign = words*(1 + deg); - for(j=0; j <= deg; j++) { - coedigs = (x->coe[j])->sign; - bcopy(x->coe[j]->n, (g->n) + j*words, coedigs*sizeof(short)); - bzero((g->n) + (j*words+coedigs), - sizeof(short)*(words-coedigs)); - } - just(g); -} - -int maxwords = 0; -void - -binarysegmul(poly x, poly y) { - int bits = bitlen(p), xwords, ywords, words; - - xwords = (2*bits + log_2(x->deg+1) + 32 + 15)/16; - ywords = (2*bits + log_2(y->deg+1) + 32 + 15)/16; - if(xwords > ywords) words = xwords; else words = ywords; - stuff(x, globx, words); - stuff(y, globy, words); - mulg(globx, globy); - gtog(y->coe[y->deg], globx); /* Save high coeff. */ - y->deg += x->deg; - gtog(globx, y->coe[y->deg]); /* Move high coeff. */ - unstuff_partial(globy, y, words); - mulg(x->coe[x->deg], y->coe[y->deg]); /* resolve high coeff. */ - justifyp(y); -} - -binarysegsquare(poly y) { - int bits = bitlen(p), words; - words = (2*bits + log_2(y->deg+1) + 32 + 15)/16; - stuff(y, globy, words); - squareg(globy); - gtog(y->coe[y->deg], globx); /* Save high coeff. */ - y->deg += y->deg; - gtog(globx, y->coe[y->deg]); /* Move high coeff. */ - unstuff_partial(globy, y, words); - mulg(y->coe[y->deg], y->coe[y->deg]); /* resolve high coeff. */ - justifyp(y); -} - -void -assess(poly x, poly y){ - int max = 0, j; - for(j=0; j <= x->deg; j++) { - if(bitlen(x->coe[j]) > max) max = bitlen(x->coe[j]); - } - max = 0; - for(j=0; j <= y->deg; j++) { - if(bitlen(y->coe[j]) > max) max = bitlen(y->coe[j]); - } -} - -int -pcompp(poly x, poly y) { - int j; - if(x->deg != y->deg) return 1; - for(j=0; j <= x->deg; j++) { - if(gcompg(x->coe[j], y->coe[j])) return 1; - } - return 0; -} - -/* -int max_deg = 0; -*/ - -void -mulp(poly x, poly y) -/* y *= x. */ -{ - int n, degx = x->deg, degy = y->deg; - -/* -if(degx > max_deg) { - max_deg = degx; printf("xdeg: %d\n", degx); -} - -if(degy > max_deg) { - max_deg = degy; printf("ydeg: %d\n", degy); -} -*/ - if((degx < P_BREAK) || (degy < P_BREAK)) { - grammarmulp(x,y); - justifyp(y); - return; - } - if(x==y) binarysegsquare(y); - else binarysegmul(x, y); -} - -void -revp(poly x) -/* Reverse the coefficients of x. */ -{ int j, deg = x->deg; - - for(j=0; j <= deg/2; j++) { - gtog(x->coe[deg-j], tmp); - gtog(x->coe[j], x->coe[deg-j]); - gtog(tmp, x->coe[j]); - } - justifyp(x); -} - -void -recipp(poly f, int deg) -/* f := 1/f, via newton method. */ -{ - int lim = deg + 1, prec = 1; - - sscratch->deg = 0; itog(1, sscratch->coe[0]); - itog(1, aux); - while(prec < lim) { - prec <<= 1; - if(prec > lim) prec = lim; - f->deg = prec-1; - ptop(sscratch, tscratch); - mulp(f, tscratch); - tscratch->deg = prec-1; - polyrem(tscratch); - subg(aux, tscratch->coe[0]); - quickmodg(p, tscratch->coe[0]); - mulp(sscratch, tscratch); - tscratch->deg = prec-1; - polyrem(tscratch); - subp(tscratch, sscratch); - sscratch->deg = prec-1; - polyrem(sscratch); - } - justifyp(sscratch); - ptop(sscratch, f); -} - -int -left_justifyp(poly x, int start) -/* Left-justify the polynomial, checking from position "start." */ -{ - int j, shift = 0; - - for(j = start; j <= x->deg; j++) { - if(!is0(x->coe[j])) { - shift = start; - break; - } - } - x->deg -= shift; - for(j=0; j<= x->deg; j++) { - gtog(x->coe[j+shift], x->coe[j]); - } - return(shift); -} - -void -remp(poly x, poly y, int mode) -/* y := x (mod y). - mode = 0 is normal operation, - = 1 jams a fixed reciprocal, - = 2 uses the fixed reciprocal. - */ -{ - int degx = x->deg, degy = y->deg, d, shift; - - if(degy == 0) { - y->deg = 0; - itog(0, y->coe[0]); - return; - } - d = degx - degy; - if(d < 0) { - ptop(x, y); - return; - } - revp(x); revp(y); - ptop(y, rscratch); - switch(mode) { - case 0: recipp(rscratch, d); - break; - case 1: recipp(rscratch, degy); /* degy -1. */ - ptop(rscratch, precip); - rscratch->deg = d; justifyp(rscratch); - break; - case 2: ptop(precip, rscratch); - rscratch->deg = d; justifyp(rscratch); - break; - } -/* Next, a limited-precision multiply. */ - if(d < degx) { x->deg = d; justifyp(x);} - mulp(x, rscratch); - rscratch->deg = d; - polyrem(rscratch); - justifyp(rscratch); - x->deg = degx; justifyp(x); - mulp(rscratch, y); - subp(x, y); - negp(y); polyrem(y); - shift = left_justifyp(y, d+1); - for(d = y->deg+1; d <= degx-shift; d++) itog(0, y->coe[d]); - y->deg = degx - shift; - revp(y); - revp(x); -} - -fullmod(poly x) { - polyrem(x); - ptop(smonic, s[0]); - remp(x, s[0], 2); - ptop(s[0], x); - polyrem(x); -} - -scalarmul(giant s, poly x) { - int j; - for(j=0; j <= x->deg; j++) { - mulg(s, x->coe[j]); - modg(p, x->coe[j]); - } -} - - -schain(int el) { - int j; - - s[0]->deg = 0; - itog(0, s[0]->coe[0]); - - s[1]->deg = 0; - itog(1, s[1]->coe[0]); - s[2]->deg = 0; - itog(2, s[2]->coe[0]); - - s[3]->deg = 4; - gtog(a, aux); mulg(a, aux); negg(aux); - gtog(aux, s[3]->coe[0]); - gtog(b, aux); smulg(12, aux); - gtog(aux, s[3]->coe[1]); - gtog(a, aux); smulg(6, aux); - gtog(aux, s[3]->coe[2]); - itog(0, s[3]->coe[3]); - itog(3, s[3]->coe[4]); - - s[4]->deg = 6; - gtog(a, aux); mulg(a, aux); mulg(a, aux); - gtog(b, tmp); mulg(b, tmp); smulg(8, tmp); addg(tmp, aux); - negg(aux); - gtog(aux, s[4]->coe[0]); - gtog(b, aux); mulg(a, aux); smulg(4, aux); negg(aux); - gtog(aux, s[4]->coe[1]); - gtog(a, aux); mulg(a, aux); smulg(5, aux); negg(aux); - gtog(aux, s[4]->coe[2]); - gtog(b, aux); smulg(20, aux); - gtog(aux, s[4]->coe[3]); - gtog(a, aux); smulg(5, aux); - gtog(aux, s[4]->coe[4]); - itog(0, s[4]->coe[5]); - itog(1, s[4]->coe[6]); - itog(4, aux); - scalarmul(aux, s[4]); - cubic->deg = 3; - itog(1, cubic->coe[3]); - itog(0, cubic->coe[2]); - gtog(a, cubic->coe[1]); - gtog(b, cubic->coe[0]); - for(j=5; j <= el; j++) { - if(j % 2 == 0) { - ptop(s[j/2 + 2], s[j]); mulp(s[j/2-1], s[j]); - polyrem(s[j]); mulp(s[j/2-1], s[j]); polyrem(s[j]); - ptop(s[j/2-2], s[0]); mulp(s[j/2+1], s[0]); polyrem(s[0]); - mulp(s[j/2+1], s[0]); polyrem(s[0]); - subp(s[0], s[j]); mulp(s[j/2], s[j]); polyrem(s[j]); - gtog(p, aux); iaddg(1, aux); gshiftright(1, aux); - scalarmul(aux, s[j]); - } else { - ptop(s[(j-1)/2+2], s[j]); - mulp(s[(j-1)/2], s[j]); -polyrem(s[j]); - mulp(s[(j-1)/2], s[j]); -polyrem(s[j]); - mulp(s[(j-1)/2], s[j]); -polyrem(s[j]); - ptop(s[(j-1)/2-1], s[0]); - mulp(s[(j-1)/2 + 1], s[0]); polyrem(s[0]); - mulp(s[(j-1)/2 + 1], s[0]); polyrem(s[0]); - mulp(s[(j-1)/2 + 1], s[0]); polyrem(s[0]); - if(((j-1)/2) % 2 == 1) { - mulp(cubic, s[0]); polyrem(s[0]); - mulp(cubic, s[0]); polyrem(s[0]); - } else { - mulp(cubic, s[j]); polyrem(s[j]); - mulp(cubic, s[j]); polyrem(s[j]); - } -// polyout(s[1]); polyout(s[3]); polyout(s[0]); polyout(s[j]); - subp(s[0], s[j]); - polyrem(s[j]); - } - } -} - -init_recip(int el) { - int j; - ptop(s[el], smonic); - if(el == 2) { - mulp(cubic, smonic); polyrem(smonic); - } - gtog(smonic->coe[smonic->deg], aux); /* High coeff. */ - binvg(p, aux); - scalarmul(aux, smonic); /* s is now monic. */ - s[0]->deg = smonic->deg + 1; - for(j=0; j <= s[0]->deg; j++) itog(1, s[0]->coe[j]); - ptop(smonic, pbuff); - remp(s[0], pbuff, 1); /* Initialize reciprocal of s as precip. */ -} - -/* void powerpoly(poly x, giant n) -{ int len, pos; - ptop(x, pbuff); - x->deg = 0; itog(1, x->coe[0]); - len = bitlen(n); - pos = 0; - while(1) { - if(bitval(n, pos++)) { - mulp(pbuff, x); - fullmod(x); - } - if(pos>=len) break; - mulp(pbuff, pbuff); - fullmod(pbuff); - } -} -*/ - -void powerpoly(poly x, giant n) -/* Base-4 window. */ -{ int pos, code; - ptop(x, pbuff); /* x. */ - ptop(pbuff, pbuff2); - mulmod(pbuff2, pbuff2); mulmod(pbuff, pbuff2); /* x^3. */ - pos = bitlen(n)-2; - while(pos >= 0) { - mulmod(x, x); - if(pos==0) { - if(bitval(n, pos) != 0) { - mulmod(pbuff, x); - } - break; - } - code = (bitval(n, pos) != 0) * 2 + (bitval(n, pos-1) != 0); - switch(code) { - case 0: mulmod(x,x); break; - case 1: mulmod(x,x); - mulmod(pbuff, x); - break; - case 2: mulmod(pbuff, x); - mulmod(x,x); break; - case 3: mulmod(x,x); mulmod(pbuff2, x); break; - } - pos -= 2; - } -} - -mulmod(poly x, poly y) { - mulp(x, y); fullmod(y); -} - -elldoublep(poly n1, poly d1, poly m1, poly c1, poly n0, poly d0, - poly m0, poly c0) { - - ptop(n1, mn); mulmod(n1, mn); - ptop(mn, pbuff); addp(mn, mn); addp(pbuff, mn); - fullmod(mn); - ptop(d1, pbuff); mulmod(d1, pbuff); - scalarmul(a, pbuff); addp(pbuff, mn); - fullmod(mn); - mulmod(c1, mn); - ptop(m1, md); addp(md, md); - mulmod(d1, md); mulmod(d1, md); mulmod(cubic, md); - - ptop(d1, n0); mulmod(mn, n0); mulmod(mn, n0); - mulmod(cubic, n0); - ptop(n1, pbuff); addp(pbuff, pbuff); fullmod(pbuff); - mulmod(md, pbuff); mulmod(md, pbuff); - subp(pbuff, n0); fullmod(n0); - ptop(md, d0); mulmod(md, d0); mulmod(d1, d0); - - ptop(mn, m0); mulmod(c1, m0); - ptop(d0, pbuff); mulmod(n1, pbuff); - ptop(n0, c0); mulmod(d1, c0); subp(c0, pbuff); - fullmod(pbuff); - mulmod(pbuff, m0); - ptop(m1, pbuff); mulmod(md, pbuff); - mulmod(d1, pbuff); mulmod(d0, pbuff); - subp(pbuff, m0); fullmod(m0); - - ptop(c1, c0); mulmod(md, c0); mulmod(d1, c0); mulmod(d0, c0); -} - -elladdp(poly n1, poly d1, poly m1, poly c1, poly n2, poly d2, poly m2, poly c2, poly n0, poly d0, poly m0, poly c0) { - ptop(m2, mn); mulmod(c1, mn); - ptop(m1, pbuff); mulmod(c2, pbuff); - subp(pbuff, mn); fullmod(mn); - mulmod(d1, mn); mulmod(d2, mn); - - ptop(n2, md); mulmod(d1, md); - ptop(n1, pbuff); mulmod(d2, pbuff); - subp(pbuff, md); fullmod(md); - mulmod(c1, md); mulmod(c2, md); - - ptop(cubic, n0); mulmod(mn, n0); mulmod(mn, n0); - mulmod(d1, n0); mulmod(d2, n0); - ptop(n1, pbuff); mulmod(d2, pbuff); - ptop(n2, d0); mulmod(d1, d0); - addp(d0, pbuff); mulmod(md, pbuff); mulmod(md, pbuff); - subp(pbuff, n0); fullmod(n0); - - ptop(md, d0); mulmod(md, d0); mulmod(d1, d0); mulmod(d2, d0); - - ptop(mn, m0); mulmod(c1, m0); - ptop(d0, pbuff); mulmod(n1, pbuff); - ptop(d1, c0); mulmod(n0, c0); - subp(c0, pbuff); fullmod(pbuff); - mulmod(pbuff, m0); - ptop(m1, pbuff); mulmod(md, pbuff); - mulmod(d0, pbuff); mulmod(d1, pbuff); - subp(pbuff, m0); fullmod(m0); - - ptop(md, c0); mulmod(c1, c0); mulmod(d0, c0); mulmod(d1, c0); - -} - -polyout(poly x) { - int j; - for(j=0; j <= x->deg; j++) {printf("%d: ",j); gout(x->coe[j]);} -} - -main(int argc, char **argv) { - int j, ct = 0, el, xmatch, ymatch; - int k, t; - int T[L_CEIL], P[L_CEIL], LL[L_CEIL]; - giant ss[L_CEIL]; - unsigned int ord, ordminus; - point_proj pt, pt2; - - p = newgiant(INFINITY); /* Also sets up internal giants' stacks. */ - j = ((Q_MAX+15)/16); - init_tools(2*j); - a = newgiant(j); - b = newgiant(j); - -entry: - printf("Give p > 3, a, b on separate lines:\n"); fflush(stdout); - gin(p); /* Field prime. */ - if((Q = bitlen(p)) > Q_MAX) { - fprintf(stderr, "p too large, larger than %d bits.\n", Q); - goto entry; - } - if(!prime_probable(p)) { - fprintf(stderr, "p is not but must be prime.\n", Q); - goto entry; - } - gin(a); gin(b); /* Curve parameters. */ - - t1 = newgiant(2*j); - t2 = newgiant(2*j); -/* Next, discriminant test for legitimacy of curve. */ - gtog(a, t1); squareg(t1); modg(p, t1); mulg(a, t1); modg(p, t1); - gshiftleft(2, t1); /* 4 a^3 mod p. */ - gtog(b, t2); squareg(t2); modg(p, t2); smulg(27, t2); - addg(t2, t1); modg(p, t1); - if(isZero(t1)) { - fprintf(stderr, "Discriminant FAILED\n"); - goto entry; - } - printf("Discriminant PASSED\n"); fflush(stdout); - -/* Next, find an efficient prime power array such that - Prod[powers] >= 16 p. */ - - /* Create minimal prime power array such that Prod[powers]^2 > 16p. */ - - gtog(p, t2); gshiftleft(4, t2); /* t2 := 16p. */ - - L_MAX = 3; - while(L_MAX <= L_CEIL-1) { - for(j=0; j <= L_MAX; j++) LL[j] = 0; - for(j=2; j <= L_MAX; j++) { - if(primeq(j)) { - LL[j] = 1; - k = j; - while(1) { - k *= j; - if(k <= L_MAX) { - LL[k] = 1; - LL[k/j] = 0; - } - else break; - } - } - } - itog(1, t1); - for(j=2; j <= L_MAX; j++) { - if(LL[j]) { smulg(j, t1); smulg(j, t1); } /* Building up t1^2. */ - } - if(gcompg(t1, t2) > 0) break; - ++L_MAX; - } - - printf("Initializing for prime powers:\n"); - for(j=2; j <= L_MAX; j++) { - if(LL[j]) printf("%d ", j); - } - printf("\n"); - fflush(stdout); - - - MAX_DIGS = (2 + (Q+15)/8); /* Size of (squared) coefficients. */ - MAX_COEFFS = ((L_MAX+1)*(L_MAX+2)); - - init_all(); - schain(L_MAX+1); - -for(L = 2; L <= L_MAX; L++) { - if(!LL[L]) continue; -printf("Resolving Schoof L = %d...\n", L); - P[ct] = L; /* Stuff another prime power. */ - init_recip(L); -// printf("s: "); polyout(s[L]); - gtog(p, aux2); - k = idivg(L, aux2); /* p (mod L). */ - -printf("power...\n"); - txd->deg = 0; itog(1, txd->coe[0]); - tyd->deg = 0; itog(1, tyd->coe[0]); - txn->deg = 1; itog(0, txn->coe[0]); itog(1, txn->coe[1]); - ptop(txn, kxn); - - gtog(p, aux2); - powerpoly(txn, aux2); /* x^p. */ -printf("x^p done...\n"); - ptop(txn, powx); - powerpoly(powx, aux2); -printf("x^p^2 done...\n"); - ptop(cubic, tyn); - gtog(p, aux2); itog(1, aux); subg(aux, aux2); - gshiftright(1, aux2); /* aux2 := (p-1)/2. */ - powerpoly(tyn, aux2); /* y^p. */ -printf("y^p done...\n"); - ptop(tyn, powy); mulp(tyn, powy); fullmod(powy); - mulp(cubic, powy); fullmod(powy); - powerpoly(powy, aux2); - mulp(tyn, powy); fullmod(powy); -printf("Powers done...\n"); - -// printf("pow" ); polyout(powx); polyout(powy); - ptop(txn, txn1); ptop(txd, txd1); /* Save t = 1 case. */ - ptop(tyn, tyn1); ptop(tyd, tyd1); -/* We now shall test - (powx, y powy) + k(kxn/kxd, y kyn/kyd) = t(txn/txd, y tyn/tyd) - */ - - if(k==1) { ptop(txd, kxd); ptop(txd, kyd); - ptop(txd, kyn); - } else { - ptop(s[k], kxd); mulp(s[k], kxd); fullmod(kxd); - if(k%2==0) { mulp(cubic, kxd); fullmod(kxd); } - mulp(kxd, kxn); fullmod(kxn); - ptop(s[k-1], pbuff); mulp(s[k+1], pbuff); fullmod(pbuff); - if(k%2==1) {mulp(cubic, pbuff); fullmod(pbuff); } - subp(pbuff, kxn); fullmod(kxn); - - ptop(s[k+2], kyn); mulp(s[k-1], kyn); fullmod(kyn); - mulp(s[k-1], kyn); fullmod(kyn); - if(k > 2) { - ptop(s[k-2], pbuff); mulp(s[k+1], pbuff); fullmod(pbuff); - mulp(s[k+1], pbuff); fullmod(pbuff); - subp(pbuff, kyn); fullmod(kyn); - } - ptop(s[k], kyd); mulp(s[k], kyd); fullmod(kyd); - mulp(s[k], kyd); fullmod(kyd); - if(k%2==0) { mulp(cubic, kyd); fullmod(kyd); - mulp(cubic, kyd); fullmod(kyd);} - itog(4, aux2); scalarmul(aux2, kyd); - } -//printf("kP: "); polyout(kxn); polyout(kxd); polyout(kyn); polyout(kyd); -/* Commence t = 0 check. */ -printf("Checking t = %d ...\n", 0); -fflush(stdout); - - ptop(powx, pbuff); mulp(kxd, pbuff); - subp(kxn, pbuff); - fullmod(pbuff); - - xmatch = ymatch = 0; - if(iszerop(pbuff)) { - xmatch = 1; - /* Now check y coords. */ - if(L == 2) goto resolve; - ptop(powy, pbuff); mulp(kyd, pbuff); - addp(kyn, pbuff); - fullmod(pbuff); - if(iszerop(pbuff)) { - resolve: - printf("%d %d\n", L, 0); - T[ct++] = 0; - continue; - } else ymatch = 1; - } -/* Combine pt1 and pt2. */ - if((xmatch == 1) && (ymatch == 1)) - elldoublep(powx, txd, powy, txd, nx, dx, ny, dy); - else - elladdp(powx, txd, powy, txd, kxn, kxd, kyn, kyd, nx, dx, ny, dy); -/* Now {nx/dx, ny/dy} is (fixed) LHS. */ -// printf("add12: "); polyout(nx); polyout(dx); polyout(ny); polyout(dy); -/* Commence t > 0 check. */ - for(t=1; t <= L/2; t++) { -printf("Checking t = %d ...\n", t); - if(t > 1) { /* Add (tx1, ty1) to (txn, tyn). */ - ptop(txn1, pbuff); mulmod(txd, pbuff); - ptop(txn, powx); mulmod(txd1, powx); - subp(powx, pbuff); fullmod(pbuff); - if(!iszerop(pbuff)) - elladdp(txn1, txd1, tyn1, tyd1, txn, txd, tyn, tyd, - tmp1, tmp2, tmp3, tmp4); - else elldoublep(txn, txd, tyn, tyd, - tmp1, tmp2, tmp3, tmp4); - ptop(tmp1, txn); ptop(tmp2, txd); - ptop(tmp3, tyn); ptop(tmp4, tyd); - } -// printf("tQ: "); polyout(txn); polyout(txd); polyout(tyn); polyout(tyd); - /* Next, check {nx/dx, ny/dy} =? {txn/txd, tyn/tyd}. */ - ptop(nx, pbuff); mulmod(txd, pbuff); - ptop(dx, powx); mulmod(txn, powx); - subp(powx, pbuff); fullmod(pbuff); - if(!iszerop(pbuff)) continue; - /* Next, check y. */ - // printf("y check!\n"); - ptop(ny, pbuff); mulmod(tyd, pbuff); - ptop(dy, powx); mulmod(tyn, powx); - subp(powx, pbuff); fullmod(pbuff); - if(iszerop(pbuff)) { - printf("%d %d\n", L, t); - T[ct++] = t; - } else { - printf("%d %d\n", L, L-t); - T[ct++] = L-t; - } - fflush(stdout); - break; - } -} - -/* Now, prime powers P[] and CRT residues T[] are intact. */ - printf("Prime powers L:\n"); - printf("{"); - for(j=0; j < ct-1; j++) { - printf("%d, ", P[j]); - } - printf("%d }\n", P[ct-1]); - - printf("Residues t (mod L):\n"); - printf("{"); - for(j=0; j < ct-1; j++) { - printf("%d, ", T[j]); - } - printf("%d }\n", T[ct-1]); - -/* Mathematica algorithm for order: -plis = {2^5, 3^3, 5^2, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}; -tlis = {1, 26, 4, 2, 4, 11, 6, 5, 19, 22, 10, 16, 7, 22, 11}; -prod = Apply[Times, plis]; -prlis = prod/plis; -invlis = Table[PowerMod[prlis[[q]], -1, plis[[q]]],{q,1,Length[plis]}]; -p = 2^127 - 1; -t = Mod[tlis . (prlis * invlis), prod]; -ord = p + 1 - If[t^2 > 4p, t - prod, t] -*/ - - itog(1, t1); - for(j=0; j < ct; j++) { - free(s[j]); /* Just to clear memory. */ - smulg(P[j], t1); - } - - for(j=0; j < 2*ct; j++) { - ss[j] = newgiant(MAX_DIGS); - } - - for(j=0; j < ct; j++) { - gtog(t1, ss[j]); - itog(P[j], t2); - divg(t2, ss[j]); - } - - for(j=0; j < ct; j++) { - gtog(ss[j], ss[j+ct]); - itog(P[j], t2); - invg(t2, ss[j+ct]); - } - - itog(0, t4); - for(j=0; j < ct; j++) { - itog(T[j], t5); - mulg(ss[j], t5); - mulg(ss[j+ct], t5); - addg(t5, t4); - } - modg(t1, t4); - gtog(p, t5); - iaddg(1, t5); - gtog(t4, t2); - squareg(t4); - gtog(p, t3); gshiftleft(2, t3); - if(gcompg(t4, t3) > 0) subg(t1, t2); - subg(t2, t5); - printf("Parameters:\n"); - printf("p = "); gout(p); - printf("a = "); gout(a); - printf("b = "); gout(b); - printf("Curve order:\n"); - printf("o = "); gout(t5); gtog(t5, t3); /* Save order as t3. */ - printf("Twist order:\n"); - printf("o' = "); - addg(t2, t5); - addg(t2, t5); - gout(t5); -/* Next, verify the order. */ - printf("Verifying order o:...\n"); - init_ell_proj(MAX_DIGS); - pt = new_point_proj(MAX_DIGS); - pt2 = new_point_proj(MAX_DIGS); - itog(1,t2); - find_point_proj(pt, t2, a, b, p); - printf("A point on the curve y^2 = x^3 + a x + b (mod p) is:\n"); - printf("(x,y,z) = {\n"); gout(pt->x); printf(","); - gout(pt->y); printf(","); gout(pt->z); - printf("}\n"); - ell_mul_proj(pt, pt2, t3, a, p); - printf("A multiple is:\n"); - printf("o * (x,y,z) = {\n"); - gout(pt2->x); printf(",");gout(pt2->y); printf(",");gout(pt2->z); - printf("}\n"); - if(!isZero(pt2->z)) { - printf("TILT: multiple should be point-at-infinity.\n"); - exit(1); - } - printf("VERIFIED: multiple is indeed point-at-infinity.\n"); -} diff --git a/OSX/include/security_cryptkit/CurveParamDocs/schoofs.c b/OSX/include/security_cryptkit/CurveParamDocs/schoofs.c deleted file mode 100644 index bf70b3ab..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/schoofs.c +++ /dev/null @@ -1,1044 +0,0 @@ -/* schoofs.c - - Elliptic curve order calculator, for - - y^2 = x^3 + a x + b (mod p) - - (NOTE: - This version has order sieving, triggering on the - initial b parameter and incrementing same. - Parameter details are described in schoof.c) - - Compile with: - - % cc -O schoofs.c giants.c tools.c -lm -o schoofs - - and run, entering the a,b parameters. - - * Change history: - - 20 Mar 01 (REC) Added binarysegsquare() and base-4 ladder - 20 Mar 01 (REC) Bumped MAX_DIGS as in schoof.c - 4 Feb 99 (REC) Sieving invoked. - 2 Feb 99 (REC) Added explicit CRT result - 12 Jan 99 (REC) Removed (hopefully) last of memory crashes - 20 Jan 98 (REC) Creation - - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -#include -#include -#include -#include"giants.h" -#include "tools.h" - -#define P_BREAK 32 - - -#define Q 256 /* See schoof.c for explanation. */ -#define L_MAX 100 -#define MAX_DIGS (2 + (Q+15)/8) /* Size of (squared) coefficients. */ -#define MAX_COEFFS ((L_MAX+1)*(L_MAX+2)) - -typedef struct - { - int deg; - giant *coe; - } polystruct; -typedef polystruct *poly; - - -static giant *mcand, coe, tmp, err, aux, aux2, globx, globy, t1, t2, - t3, t4, t5; -static poly qscratch, rscratch, sscratch, tscratch, pbuff, pbuff2, - precip, cubic, powx, powy, kxn, kyn, kxd, kyd, - txn, txd, tyn, tyd, txn1, txd1, tyn1, tyd1, - nx, dx, ny, dy, mn, md, tmp1, tmp2, tmp3, tmp4; -static poly s[L_MAX+2], smonic; -static giant p, a, b, magcheck; -int L; - -void quickmodg(giant g, giant x) -{ int sgn = x->sign; - - if(sgn == 0) return; - if(sgn > 0) { - if(gcompg(x, g) >= 0) subg(g, x); - return; - } - addg(g,x); - return; -} - -int -log_2(int n) { - int c = 1, d = -1; - while(c <= n) { - c <<= 1; - ++d; - } - return(d); -} - -void -justifyp(poly x) { - int j; - for(j = x->deg; j >= 0; j--) { - if(!is0(x->coe[j])) break; - } - x->deg = (j>0)? j : 0; -} - -void -polyrem(poly x) { - int j; - for(j=0; j <= x->deg; j++) { - modg(p, x->coe[j]); - } - justifyp(x); -} - - -giant * -newa(int n) { - giant *p = (giant *)malloc(n*sizeof(giant)); - int j; - for(j=0; jcoe = (giant *)newa(coeffs); - return(pol); -} - -void -init_all() { - int j; - - j = (2*Q + log_2(MAX_COEFFS) + 32 + 15)/16; - globx = newgiant(MAX_COEFFS * j); - globy = newgiant(MAX_COEFFS * j); - - init_tools(MAX_DIGS); - powx = newpoly(MAX_COEFFS); - powy = newpoly(MAX_COEFFS); - kxn = newpoly(MAX_COEFFS); - kxd = newpoly(MAX_COEFFS); - kyn = newpoly(MAX_COEFFS); - kyd = newpoly(MAX_COEFFS); - txn = newpoly(MAX_COEFFS); - txd = newpoly(MAX_COEFFS); - tyn = newpoly(MAX_COEFFS); - tyd = newpoly(MAX_COEFFS); - txn1 = newpoly(MAX_COEFFS); - txd1 = newpoly(MAX_COEFFS); - tyn1 = newpoly(MAX_COEFFS); - tyd1 = newpoly(MAX_COEFFS); - nx = newpoly(MAX_COEFFS); - ny = newpoly(MAX_COEFFS); - dx = newpoly(MAX_COEFFS); - dy = newpoly(MAX_COEFFS); - mn = newpoly(MAX_COEFFS); - md = newpoly(MAX_COEFFS); - tmp1 = newpoly(MAX_COEFFS); - tmp2 = newpoly(MAX_COEFFS); - tmp3 = newpoly(MAX_COEFFS); - tmp4 = newpoly(MAX_COEFFS); - mcand = (giant *)newa(MAX_COEFFS); - - s[0] = newpoly(MAX_COEFFS); - - for(j=1; j<=L_MAX+1; j++) { - s[j] = newpoly(j*(j+1)); - } - smonic = newpoly(MAX_COEFFS); -/* The next three need extra space for remaindering routine. */ - qscratch = newpoly(2*MAX_COEFFS); - rscratch = newpoly(2*MAX_COEFFS); - pbuff = newpoly(2*MAX_COEFFS); - pbuff2 = newpoly(MAX_COEFFS); - sscratch = newpoly(MAX_COEFFS); - tscratch = newpoly(MAX_COEFFS); - tmp = newgiant(MAX_DIGS); - err = newgiant(MAX_DIGS); - coe = newgiant(MAX_DIGS); - aux = newgiant(MAX_DIGS); - aux2 = newgiant(MAX_DIGS); - t1 = newgiant(MAX_DIGS); - t2 = newgiant(MAX_DIGS); - t3 = newgiant(MAX_DIGS); - t4 = newgiant(MAX_DIGS); - t5 = newgiant(MAX_DIGS); - cubic = newpoly(4); - p = newgiant(MAX_DIGS); - a = newgiant(MAX_DIGS); - b = newgiant(MAX_DIGS); - magcheck = newgiant(MAX_DIGS); - precip = newpoly(MAX_COEFFS); -} - -void -atoa(giant *a, giant *b, int n) { - int j; - for(j=0; jdeg = x->deg; - atoa(x->coe, y->coe, y->deg+1); -} - -void -negp(poly y) -/* y := -y. */ -{ int j; - for(j=0; j <= y->deg; j++) { - negg(y->coe[j]); - quickmodg(p, y->coe[j]); - } -} - -int -iszer(giant a) { - - if(a->sign == 0) return(1); - return(0); - -} - -int -iszerop(poly x) { - if(x->deg == 0 && iszer(x->coe[0])) return 1; - return 0; -} - -int -is0(giant a) { - return(iszer(a)); -} - -int -is1(giant a) { - return(isone(a)); -} - - -void -addp(poly x, poly y) -/* y += x. */ -{ - int d = x->deg, j; - - if(y->deg > d) d = y->deg; - for(j = 0; j <= d; j++) { - if((j <= x->deg) && (j <= y->deg)) { - addg(x->coe[j], y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - if((j <= x->deg) && (j > y->deg)) { - gtog(x->coe[j], y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - } - y->deg = d; - justifyp(y); -} - -void -subp(poly x, poly y) -/* y -= x. */ -{ - int d = x->deg, j; - - if(y->deg > d) d = y->deg; - for(j = 0; j <= d; j++) { - if((j <= x->deg) && (j <= y->deg)) { - subg(x->coe[j], y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - if((j <= x->deg) && (j > y->deg)) { - gtog(x->coe[j], y->coe[j]); - negg(y->coe[j]); - quickmodg(p, y->coe[j]); - continue; - } - } - y->deg = d; - justifyp(y); -} - - -void -grammarmulp(poly a, poly b) -/* b *= a. */ -{ - int dega = a->deg, degb = b->deg, deg = dega + degb; - register int d, kk, first, diffa; - - for(d=deg; d>=0; d--) { - diffa = d-dega; - itog(0, coe); - for(kk=0; kk<=d; kk++) { - if((kk>degb)||(kkcoe[kk], tmp); - mulg(a->coe[d-kk], tmp); - modg(p, tmp); - addg(tmp, coe); - quickmodg(p, coe); - } - gtog(coe, mcand[d]); - } - atoa(mcand, b->coe, deg+1); - b->deg = deg; - justifyp(b); -} - -void -atop(giant *a, poly x, int deg) -/* Copy array to poly, with monic option. */ -{ - int adeg = abs(deg); - x->deg = adeg; - atoa(a, x->coe, adeg); - if(deg < 0) { - itog(1, x->coe[adeg]); - } else { - gtog(a[adeg], x->coe[adeg]); - } -} - -void -just(giant g) { - while((g->n[g->sign-1] == 0) && (g->sign > 0)) --g->sign; -} - -void -unstuff_partial(giant g, poly y, int words){ - int j; - for(j=0; j < y->deg; j++) { - bcopy((g->n) + j*words, y->coe[j]->n, words*sizeof(short)); - y->coe[j]->sign = words; - just(y->coe[j]); - } -} - -void -stuff(poly x, giant g, int words) { - int deg = x->deg, j, coedigs; - - g->sign = words*(1 + deg); - for(j=0; j <= deg; j++) { - coedigs = (x->coe[j])->sign; - bcopy(x->coe[j]->n, (g->n) + j*words, coedigs*sizeof(short)); - bzero((g->n) + (j*words+coedigs), - sizeof(short)*(words-coedigs)); - } - just(g); -} - -int maxwords = 0; -void - -binarysegmul(poly x, poly y) { - int bits = bitlen(p), xwords, ywords, words; - - xwords = (2*bits + log_2(x->deg+1) + 32 + 15)/16; - ywords = (2*bits + log_2(y->deg+1) + 32 + 15)/16; - if(xwords > ywords) words = xwords; else words = ywords; -if(words > maxwords) { - maxwords = words; -// printf("m: %d\n", words); - fflush(stdout); -} - stuff(x, globx, words); - stuff(y, globy, words); - mulg(globx, globy); - gtog(y->coe[y->deg], globx); /* Save high coeff. */ - y->deg += x->deg; - gtog(globx, y->coe[y->deg]); /* Move high coeff. */ - unstuff_partial(globy, y, words); - mulg(x->coe[x->deg], y->coe[y->deg]); /* resolve high coeff. */ - justifyp(y); -} - -binarysegsquare(poly y) { - int bits = bitlen(p), words; - words = (2*bits + log_2(y->deg+1) + 32 + 15)/16; - stuff(y, globy, words); - squareg(globy); - gtog(y->coe[y->deg], globx); /* Save high coeff. */ - y->deg += y->deg; - gtog(globx, y->coe[y->deg]); /* Move high coeff. */ - unstuff_partial(globy, y, words); - mulg(y->coe[y->deg], y->coe[y->deg]); /* resolve high coeff. */ - justifyp(y); -} - - -void -assess(poly x, poly y){ - int max = 0, j; - for(j=0; j <= x->deg; j++) { - if(bitlen(x->coe[j]) > max) max = bitlen(x->coe[j]); - } -// printf("max: %d ", max); - max = 0; - for(j=0; j <= y->deg; j++) { - if(bitlen(y->coe[j]) > max) max = bitlen(y->coe[j]); - } -// printf("%d\n", max); - - -} - -int -pcompp(poly x, poly y) { - int j; - if(x->deg != y->deg) return 1; - for(j=0; j <= x->deg; j++) { - if(gcompg(x->coe[j], y->coe[j])) return 1; - } - return 0; -} - -int maxdeg = 0; - -void -mulp(poly x, poly y) -/* y *= x. */ -{ - int n, degx = x->deg, degy = y->deg; - -/* -if(degx > max_deg) { - max_deg = degx; printf("xdeg: %d\n", degx); -} - -if(degy > max_deg) { - max_deg = degy; printf("ydeg: %d\n", degy); -} -*/ - if((degx < P_BREAK) || (degy < P_BREAK)) { - grammarmulp(x,y); - justifyp(y); - return; - } - if(x==y) binarysegsquare(y); - else binarysegmul(x, y); -} - -void -revp(poly x) -/* Reverse the coefficients of x. */ -{ int j, deg = x->deg; - - for(j=0; j <= deg/2; j++) { - gtog(x->coe[deg-j], tmp); - gtog(x->coe[j], x->coe[deg-j]); - gtog(tmp, x->coe[j]); - } - justifyp(x); -} - -void -recipp(poly f, int deg) -/* f := 1/f, via newton method. */ -{ - int lim = deg + 1, prec = 1; - - sscratch->deg = 0; itog(1, sscratch->coe[0]); - itog(1, aux); - while(prec < lim) { - prec <<= 1; - if(prec > lim) prec = lim; - f->deg = prec-1; - ptop(sscratch, tscratch); - mulp(f, tscratch); - tscratch->deg = prec-1; - polyrem(tscratch); - subg(aux, tscratch->coe[0]); - quickmodg(p, tscratch->coe[0]); - mulp(sscratch, tscratch); - tscratch->deg = prec-1; - polyrem(tscratch); - subp(tscratch, sscratch); - sscratch->deg = prec-1; - polyrem(sscratch); - } - justifyp(sscratch); - ptop(sscratch, f); -} - -int -left_justifyp(poly x, int start) -/* Left-justify the polynomial, checking from position "start." */ -{ - int j, shift = 0; - - for(j = start; j <= x->deg; j++) { - if(!is0(x->coe[j])) { - shift = start; - break; - } - } - x->deg -= shift; - for(j=0; j<= x->deg; j++) { - gtog(x->coe[j+shift], x->coe[j]); - } - return(shift); -} - -void -remp(poly x, poly y, int mode) -/* y := x (mod y). - mode = 0 is normal operation, - = 1 jams a fixed reciprocal, - = 2 uses the fixed reciprocal. - */ -{ - int degx = x->deg, degy = y->deg, d, shift; - - if(degy == 0) { - y->deg = 0; - itog(0, y->coe[0]); - return; - } - d = degx - degy; - if(d < 0) { - ptop(x, y); - return; - } - revp(x); revp(y); - ptop(y, rscratch); - switch(mode) { - case 0: recipp(rscratch, d); - break; - case 1: recipp(rscratch, degy); /* degy -1. */ - ptop(rscratch, precip); - rscratch->deg = d; justifyp(rscratch); - break; - case 2: ptop(precip, rscratch); - rscratch->deg = d; justifyp(rscratch); - break; - } -/* Next, a limited-precision multiply. */ - if(d < degx) { x->deg = d; justifyp(x);} - mulp(x, rscratch); - rscratch->deg = d; - polyrem(rscratch); - justifyp(rscratch); - x->deg = degx; justifyp(x); - mulp(rscratch, y); - subp(x, y); - negp(y); polyrem(y); - shift = left_justifyp(y, d+1); - for(d = y->deg+1; d <= degx-shift; d++) itog(0, y->coe[d]); - y->deg = degx - shift; - revp(y); - revp(x); -} - -fullmod(poly x) { - polyrem(x); - ptop(smonic, s[0]); - remp(x, s[0], 2); - ptop(s[0], x); - polyrem(x); -} - -scalarmul(giant s, poly x) { - int j; - for(j=0; j <= x->deg; j++) { - mulg(s, x->coe[j]); - modg(p, x->coe[j]); - } -} - - -schain(int el) { - int j; - - s[0]->deg = 0; - itog(0, s[0]->coe[0]); - - s[1]->deg = 0; - itog(1, s[1]->coe[0]); - s[2]->deg = 0; - itog(2, s[2]->coe[0]); - - s[3]->deg = 4; - gtog(a, aux); mulg(a, aux); negg(aux); - gtog(aux, s[3]->coe[0]); - gtog(b, aux); smulg(12, aux); - gtog(aux, s[3]->coe[1]); - gtog(a, aux); smulg(6, aux); - gtog(aux, s[3]->coe[2]); - itog(0, s[3]->coe[3]); - itog(3, s[3]->coe[4]); - - s[4]->deg = 6; - gtog(a, aux); mulg(a, aux); mulg(a, aux); - gtog(b, tmp); mulg(b, tmp); smulg(8, tmp); addg(tmp, aux); - negg(aux); - gtog(aux, s[4]->coe[0]); - gtog(b, aux); mulg(a, aux); smulg(4, aux); negg(aux); - gtog(aux, s[4]->coe[1]); - gtog(a, aux); mulg(a, aux); smulg(5, aux); negg(aux); - gtog(aux, s[4]->coe[2]); - gtog(b, aux); smulg(20, aux); - gtog(aux, s[4]->coe[3]); - gtog(a, aux); smulg(5, aux); - gtog(aux, s[4]->coe[4]); - itog(0, s[4]->coe[5]); - itog(1, s[4]->coe[6]); - itog(4, aux); - scalarmul(aux, s[4]); - cubic->deg = 3; - itog(1, cubic->coe[3]); - itog(0, cubic->coe[2]); - gtog(a, cubic->coe[1]); - gtog(b, cubic->coe[0]); - for(j=5; j <= el; j++) { - if(j % 2 == 0) { - ptop(s[j/2 + 2], s[j]); mulp(s[j/2-1], s[j]); - polyrem(s[j]); mulp(s[j/2-1], s[j]); polyrem(s[j]); - ptop(s[j/2-2], s[0]); mulp(s[j/2+1], s[0]); polyrem(s[0]); - mulp(s[j/2+1], s[0]); polyrem(s[0]); - subp(s[0], s[j]); mulp(s[j/2], s[j]); polyrem(s[j]); - gtog(p, aux); iaddg(1, aux); gshiftright(1, aux); - scalarmul(aux, s[j]); - } else { - ptop(s[(j-1)/2+2], s[j]); - mulp(s[(j-1)/2], s[j]); polyrem(s[j]); - mulp(s[(j-1)/2], s[j]); polyrem(s[j]); - mulp(s[(j-1)/2], s[j]); polyrem(s[j]); - ptop(s[(j-1)/2-1], s[0]); - mulp(s[(j-1)/2 + 1], s[0]); polyrem(s[0]); - mulp(s[(j-1)/2 + 1], s[0]); polyrem(s[0]); - mulp(s[(j-1)/2 + 1], s[0]); polyrem(s[0]); - if(((j-1)/2) % 2 == 1) { - mulp(cubic, s[0]); polyrem(s[0]); - mulp(cubic, s[0]); polyrem(s[0]); - } else { - mulp(cubic, s[j]); polyrem(s[j]); - mulp(cubic, s[j]); polyrem(s[j]); - } -// polyout(s[1]); polyout(s[3]); polyout(s[0]); polyout(s[j]); - subp(s[0], s[j]); - polyrem(s[j]); - } - } -} - -init_recip(int el) { - int j; - ptop(s[el], smonic); - if(el == 2) { - mulp(cubic, smonic); polyrem(smonic); - } - gtog(smonic->coe[smonic->deg], aux); /* High coeff. */ - binvg(p, aux); - scalarmul(aux, smonic); /* s is now monic. */ - s[0]->deg = smonic->deg + 1; - for(j=0; j <= s[0]->deg; j++) itog(1, s[0]->coe[j]); - ptop(smonic, pbuff); - remp(s[0], pbuff, 1); /* Initialize reciprocal of s as precip. */ -} - -void powerpoly(poly x, giant n) -/* Base-4 window. */ -{ int pos, code; - ptop(x, pbuff); /* x. */ - ptop(pbuff, pbuff2); - mulmod(pbuff2, pbuff2); mulmod(pbuff, pbuff2); /* x^3. */ - pos = bitlen(n)-2; - while(pos >= 0) { - mulmod(x, x); - if(pos==0) { - if(bitval(n, pos) != 0) { - mulmod(pbuff, x); - } - break; - } - code = (bitval(n, pos) != 0) * 2 + (bitval(n, pos-1) != 0); - switch(code) { - case 0: mulmod(x,x); break; - case 1: mulmod(x,x); - mulmod(pbuff, x); - break; - case 2: mulmod(pbuff, x); - mulmod(x,x); break; - case 3: mulmod(x,x); mulmod(pbuff2, x); break; - } - pos -= 2; - } -} - -mulmod(poly x, poly y) { - mulp(x, y); fullmod(y); -} - -elldoublep(poly n1, poly d1, poly m1, poly c1, poly n0, poly d0, - poly m0, poly c0) { - - ptop(n1, mn); mulmod(n1, mn); - ptop(mn, pbuff); addp(mn, mn); addp(pbuff, mn); - fullmod(mn); - ptop(d1, pbuff); mulmod(d1, pbuff); - scalarmul(a, pbuff); addp(pbuff, mn); - fullmod(mn); - mulmod(c1, mn); - ptop(m1, md); addp(md, md); - mulmod(d1, md); mulmod(d1, md); mulmod(cubic, md); - - ptop(d1, n0); mulmod(mn, n0); mulmod(mn, n0); - mulmod(cubic, n0); - ptop(n1, pbuff); addp(pbuff, pbuff); fullmod(pbuff); - mulmod(md, pbuff); mulmod(md, pbuff); - subp(pbuff, n0); fullmod(n0); - ptop(md, d0); mulmod(md, d0); mulmod(d1, d0); - - ptop(mn, m0); mulmod(c1, m0); - ptop(d0, pbuff); mulmod(n1, pbuff); - ptop(n0, c0); mulmod(d1, c0); subp(c0, pbuff); - fullmod(pbuff); - mulmod(pbuff, m0); - ptop(m1, pbuff); mulmod(md, pbuff); - mulmod(d1, pbuff); mulmod(d0, pbuff); - subp(pbuff, m0); fullmod(m0); - - ptop(c1, c0); mulmod(md, c0); mulmod(d1, c0); mulmod(d0, c0); -} - -elladdp(poly n1, poly d1, poly m1, poly c1, poly n2, poly d2, poly m2, poly c2, poly n0, poly d0, poly m0, poly c0) { - ptop(m2, mn); mulmod(c1, mn); - ptop(m1, pbuff); mulmod(c2, pbuff); - subp(pbuff, mn); fullmod(mn); - mulmod(d1, mn); mulmod(d2, mn); - - ptop(n2, md); mulmod(d1, md); - ptop(n1, pbuff); mulmod(d2, pbuff); - subp(pbuff, md); fullmod(md); - mulmod(c1, md); mulmod(c2, md); - - ptop(cubic, n0); mulmod(mn, n0); mulmod(mn, n0); - mulmod(d1, n0); mulmod(d2, n0); - ptop(n1, pbuff); mulmod(d2, pbuff); - ptop(n2, d0); mulmod(d1, d0); - addp(d0, pbuff); mulmod(md, pbuff); mulmod(md, pbuff); - subp(pbuff, n0); fullmod(n0); - - ptop(md, d0); mulmod(md, d0); mulmod(d1, d0); mulmod(d2, d0); - - ptop(mn, m0); mulmod(c1, m0); - ptop(d0, pbuff); mulmod(n1, pbuff); - ptop(d1, c0); mulmod(n0, c0); - subp(c0, pbuff); fullmod(pbuff); - mulmod(pbuff, m0); - ptop(m1, pbuff); mulmod(md, pbuff); - mulmod(d0, pbuff); mulmod(d1, pbuff); - subp(pbuff, m0); fullmod(m0); - - ptop(md, c0); mulmod(c1, c0); mulmod(d0, c0); mulmod(d1, c0); - -} - -polyout(poly x) { - int j; - for(j=0; j <= x->deg; j++) {printf("%d: ",j); gout(x->coe[j]);} -} - -#define SIEVE_CUT 7 - -main(int argc, char **argv) { - int j, ct, el, xmatch, ymatch; - int k, k2, t, linit; - int T[L_MAX], P[L_MAX]; - giant ss[L_MAX]; - unsigned int ord, ordminus; - - printf("Initializing...\n"); fflush(stdout); - init_all(); - - for(j=0; j < L_MAX; j++) { /* Array to be used for CRT reconstruction. */ - ss[j] = NULL; - } - - printf("Give p, a, b on separate lines:\n"); fflush(stdout); - gin(p); /* Field prime. */ - if(bitlen(p) > Q) { - fprintf(stderr, "p too large, larger than %d bits.\n", Q); - exit(0); - } - - gin(a); gin(b); /* Curve parameters. */ - -newb: - printf("Checking discriminant for:\nb = "); - gout(b); - gtog(a, t1); squareg(t1); modg(p, t1); mulg(a, t1); modg(p, t1); - gshiftleft(2, t1); /* 4 a^3. */ - gtog(b, t2); squareg(t2); modg(p, t2); smulg(27, t2); - addg(t2, t1); modg(p, t1); - if(isZero(t1)) { - printf("Discriminant FAILED\n"); - iaddg(1, b); - goto newb; - } - printf("Discriminant PASSED\n"); - printf("Starting sieve process:\n"); - - - schain(SIEVE_CUT + 1); /* Do first piece of chain, for small-sieving. */ - linit = 0; - ct = 0; - itog(1, magcheck); -for(el = 2; el <= L_MAX; el += 1 + (el%2)) { - if(!primeq(el)) continue; - L = el; while(L*el <= 4) L *= el; -printf("Resolving Schoof L = %d...\n", L); - P[ct] = L; /* Stuff another prime power. */ - smulg(L, magcheck); - gtog(magcheck, tmp); squareg(tmp); gshiftright(2, tmp); - if(gcompg(tmp, p) > 0) break; /* Done...go to CRT phase. */ -if((L > SIEVE_CUT) && (linit == 0)) { - schain(L_MAX+1); - linit = 1; - } - init_recip(L); -// printf("s: "); polyout(s[L]); - gtog(p, aux2); - k = idivg(L, aux2); /* p (mod L). */ - gtog(p, aux2); - k2 = idivg(el, aux2); -// printf("power...\n"); - txd->deg = 0; itog(1, txd->coe[0]); - tyd->deg = 0; itog(1, tyd->coe[0]); - txn->deg = 1; itog(0, txn->coe[0]); itog(1, txn->coe[1]); - ptop(txn, kxn); - - gtog(p, aux2); - powerpoly(txn, aux2); /* x^p. */ -// printf("x^p done...\n"); - ptop(txn, powx); - powerpoly(powx, aux2); -// printf("x^p^2 done...\n"); - ptop(cubic, tyn); - gtog(p, aux2); itog(1, aux); subg(aux, aux2); - gshiftright(1, aux2); /* aux2 := (p-1)/2. */ - powerpoly(tyn, aux2); /* y^p. */ -// printf("y^p done...\n"); - ptop(tyn, powy); mulp(tyn, powy); fullmod(powy); - mulp(cubic, powy); fullmod(powy); - powerpoly(powy, aux2); - mulp(tyn, powy); fullmod(powy); -// printf("Powers done...\n"); - -// printf("pow" ); polyout(powx); polyout(powy); - ptop(txn, txn1); ptop(txd, txd1); /* Save t = 1 case. */ - ptop(tyn, tyn1); ptop(tyd, tyd1); -/* We now shall test - (powx, y powy) + k(kxn/kxd, y kyn/kyd) = t(txn/txd, y tyn/tyd) - */ - - if(k==1) { ptop(txd, kxd); ptop(txd, kyd); - ptop(txd, kyn); - } else { - ptop(s[k], kxd); mulp(s[k], kxd); fullmod(kxd); - if(k%2==0) { mulp(cubic, kxd); fullmod(kxd); } - mulp(kxd, kxn); fullmod(kxn); - ptop(s[k-1], pbuff); mulp(s[k+1], pbuff); fullmod(pbuff); - if(k%2==1) {mulp(cubic, pbuff); fullmod(pbuff); } - subp(pbuff, kxn); fullmod(kxn); - - ptop(s[k+2], kyn); mulp(s[k-1], kyn); fullmod(kyn); - mulp(s[k-1], kyn); fullmod(kyn); - if(k > 2) { - ptop(s[k-2], pbuff); mulp(s[k+1], pbuff); fullmod(pbuff); - mulp(s[k+1], pbuff); fullmod(pbuff); - subp(pbuff, kyn); fullmod(kyn); - } - ptop(s[k], kyd); mulp(s[k], kyd); fullmod(kyd); - mulp(s[k], kyd); fullmod(kyd); - if(k%2==0) { mulp(cubic, kyd); fullmod(kyd); - mulp(cubic, kyd); fullmod(kyd);} - itog(4, aux2); scalarmul(aux2, kyd); - } -//printf("kP: "); polyout(kxn); polyout(kxd); polyout(kyn); polyout(kyd); -/* Commence t = 0 check. */ -// printf("Checking t = %d ...\n", 0); -fflush(stdout); - - ptop(powx, pbuff); mulp(kxd, pbuff); - subp(kxn, pbuff); - fullmod(pbuff); - - xmatch = ymatch = 0; - if(iszerop(pbuff)) { - xmatch = 1; - /* Now check y coords. */ - if(L == 2) goto resolve; - ptop(powy, pbuff); mulp(kyd, pbuff); - addp(kyn, pbuff); - fullmod(pbuff); - if(iszerop(pbuff)) { - resolve: - printf("%d %d\n", L, 0); - T[ct++] = 0; - if((k2 + 1 - T[ct-1]) % el == 0) { - printf("TILT: %d\n", el); - el = 2; - iaddg(1, b); - goto newb; - } - continue; - } else ymatch = 1; - } -/* Combine pt1 and pt2. */ - if((xmatch == 1) && (ymatch == 1)) - elldoublep(powx, txd, powy, txd, nx, dx, ny, dy); - else - elladdp(powx, txd, powy, txd, kxn, kxd, kyn, kyd, nx, dx, ny, dy); - -/* Now {nx/dx, ny/dy} is (fixed) LHS. */ -// printf("add12: "); polyout(nx); polyout(dx); polyout(ny); polyout(dy); -/* Commence t > 0 check. */ - for(t=1; t <= L/2; t++) { -// printf("Checking t = %d ...\n", t); - if(t > 1) { /* Add (tx1, ty1) to (txn, tyn). */ - ptop(txn1, pbuff); mulmod(txd, pbuff); - ptop(txn, powx); mulmod(txd1, powx); - subp(powx, pbuff); fullmod(pbuff); - if(!iszerop(pbuff)) - elladdp(txn1, txd1, tyn1, tyd1, txn, txd, tyn, tyd, - tmp1, tmp2, tmp3, tmp4); - else elldoublep(txn, txd, tyn, tyd, - tmp1, tmp2, tmp3, tmp4); - ptop(tmp1, txn); ptop(tmp2, txd); - ptop(tmp3, tyn); ptop(tmp4, tyd); - } -// printf("tQ: "); polyout(txn); polyout(txd); polyout(tyn); polyout(tyd); - /* Next, check {nx/dx, ny/dy} =? {txn/txd, tyn/tyd}. */ - ptop(nx, pbuff); mulmod(txd, pbuff); - ptop(dx, powx); mulmod(txn, powx); - subp(powx, pbuff); fullmod(pbuff); - if(!iszerop(pbuff)) continue; - /* Next, check y. */ - // printf("y check!\n"); - ptop(ny, pbuff); mulmod(tyd, pbuff); - ptop(dy, powx); mulmod(tyn, powx); - subp(powx, pbuff); fullmod(pbuff); - if(iszerop(pbuff)) { - printf("%d %d\n", L, t); - T[ct++] = t; - } else { - printf("%d %d\n", L, L-t); - T[ct++] = L-t; - } - if((k2 + 1 - T[ct-1]) % el == 0) { - printf("TILT: %d\n", el); - el = 2; - iaddg(1, b); - goto newb; - } - - fflush(stdout); - break; - } -} - -/* Now, prime powers P[] and CRT residues T[] are intact. */ - printf("Prime powers L:\n"); - printf("{"); - for(j=0; j < ct-1; j++) { - printf("%d, ", P[j]); - } - printf("%d }\n", P[ct-1]); - - printf("Residues t (mod L):\n"); - printf("{"); - for(j=0; j < ct-1; j++) { - printf("%d, ", T[j]); - } - printf("%d }\n", T[ct-1]); - -/* Mathematica algorithm for order: -plis = {2^5, 3^3, 5^2, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}; -tlis = {1, 26, 4, 2, 4, 11, 6, 5, 19, 22, 10, 16, 7, 22, 11}; -prod = Apply[Times, plis]; -prlis = prod/plis; -invlis = Table[PowerMod[prlis[[q]], -1, plis[[q]]],{q,1,Length[plis]}]; -p = 2^127 - 1; -t = Mod[tlis . (prlis * invlis), prod]; -ord = p + 1 - If[t^2 > 4p, t - prod, t] -*/ - - itog(1, t1); - for(j=0; j < ct; j++) { - smulg(P[j], t1); - } - - for(j=0; j < 2*ct; j++) { - if(!ss[j]) ss[j] = newgiant(MAX_DIGS); - } - - for(j=0; j < ct; j++) { - gtog(t1, ss[j]); - itog(P[j], t2); - divg(t2, ss[j]); - } - - for(j=0; j < ct; j++) { - gtog(ss[j], ss[j+ct]); - itog(P[j], t2); - invg(t2, ss[j+ct]); - } - - itog(0, t4); - for(j=0; j < ct; j++) { - itog(T[j], t5); - mulg(ss[j], t5); - mulg(ss[j+ct], t5); - addg(t5, t4); - } - modg(t1, t4); - gtog(p, t5); - iaddg(1, t5); - gtog(t4, t2); - squareg(t4); - gtog(p, t3); gshiftleft(2, t3); - if(gcompg(t4, t3) > 0) subg(t1, t2); - subg(t2, t5); - printf("Parameters:\n"); - printf("p = "); gout(p); - printf("a = "); gout(a); - printf("b = "); gout(b); - printf("Curve order:\n"); - printf("o = "); gout(t5); - printf("pprob: %d\n", prime_probable(t5)); - printf("Twist order:\n"); - printf("o' = "); - addg(t2, t5); - addg(t2, t5); - gout(t5); - printf("pprob: %d\n", prime_probable(t5)); - - iaddg(1,b); - goto newb; -} diff --git a/OSX/include/security_cryptkit/CurveParamDocs/tools.c b/OSX/include/security_cryptkit/CurveParamDocs/tools.c deleted file mode 100644 index 9586537b..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/tools.c +++ /dev/null @@ -1,445 +0,0 @@ -/************************************************************** - * - * tools.c - * - * Number-theoretical algorithm implementations - * - * Updates: - * 30 Apr 99 REC Modified init_tools type to void. - * 3 Apr 98 REC Creation - * - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -/* include files */ - -#include -#include -#include -#include -#ifdef _WIN32 - -#include - -#endif - -#include -#include "giants.h" -#include "tools.h" - -/* definitions */ - -#define STACK_COUNT 20 - -/* global variables */ - -int pr[NUM_PRIMES]; /* External use allowed. */ -static giant tmp[STACK_COUNT]; -static int stack = 0; -static giant popg(); -static void pushg(); - -/************************************************************** - * - * Maintenance functions - * - **************************************************************/ - - -void -init_tools(int shorts) -{ - int j; - - for(j = 0; j < STACK_COUNT; j++) { - tmp[j] = newgiant(shorts); - } - make_primes(); /* Create table of all primes < 2^16, - to be used by other programs as array - pr[0..NUM_PRIMES]. */ -} - -static giant -popg() { - return(tmp[stack++]); -} - -static void -pushg(int n) { - stack -= n; -} - -/************************************************************** - * - * Number-theoretical functions - * - **************************************************************/ - -int -prime_literal( - unsigned int p -) -/* Primality test via small, literal sieve. - After init, one should use primeq() instead. - */ -{ - unsigned int j=3; - - if ((p & 1)==0) - return ((p == 2)?1:0); - if (j >= p) - return (1); - while ((p%j)!=0) - { - j += 2; - if (j*j > p) - return(1); - } - return(0); -} - -int -primeq( - unsigned int odd -) -/* Faster primality test, using preset array pr[] of primes. - This test is valid for all unsigned, 32-bit integers odd. - */ -{ - unsigned int p; - unsigned int j; - - if(odd < 2) return (0); - if ((odd & 1)==0) - return ((odd == 2)?1:0); - for (j=1; ;j++) - { - p = pr[j]; - if (p*p > odd) - return(1); - if (odd % p == 0) - return(0); - } -} - -void -make_primes() -{ int k, npr; - pr[0] = 2; - for (k=0, npr=1;; k++) - { - if (prime_literal(3+2*k)) - { - pr[npr++] = 3+2*k; - if (npr >= NUM_PRIMES) - break; - } - } -} - -int -prime_probable(giant p) -/* Invoke Miller-Rabin test of given security depth. - For MILLER_RABIN_DEPTH == 8, this is an ironclad primality - test for suspected primes p < 3.4 x 10^{14}. -*/ -{ - giant t1 = popg(), t2 = popg(), t3 = popg(); - int j, ct, s; - - if((p->n[0] & 1) == 0) { /* Evenness test. */ - pushg(3); return(0); - } - if(bitlen(p) < 32) { /* Single-word case. */ - pushg(3); - return(primeq((unsigned int)gtoi(p))); - } - itog(-1, t1); - addg(p, t1); /* t1 := p-1. */ - gtog(t1, t2); - s = 1; - gshiftright(1, t2); - while(t2->n[0] & 1 == 0) { - gshiftright(1, t2); - ++s; - } - /* Now, p-1 = 2^s * t2. */ - for(j = 0; j < MILLER_RABIN_DEPTH; j++) { - itog(pr[j+1], t3); - powermodg(t3, t2, p); - ct = 1; - if(isone(t3)) continue; - if(gcompg(t3, t1) == 0) continue; - while((ct < s) && (gcompg(t1, t3) != 0)) { - squareg(t3); modg(p, t3); - if(isone(t3)) { - goto composite; - } - ++ct; - } - if(gcompg(t1, t3) != 0) goto composite; - } - goto prime; - -composite: - pushg(3); return(0); -prime: pushg(3); return(1); -} - -int -jacobi_symbol(giant a, giant n) -/* Standard Jacobi symbol (a/n). Parameter n must be odd, positive. */ -{ int t = 1, u; - giant t5 = popg(), t6 = popg(), t7 = popg(); - - gtog(a, t5); modg(n, t5); - gtog(n, t6); - while(!isZero(t5)) { - u = (t6->n[0]) & 7; - while((t5->n[0] & 1) == 0) { - gshiftright(1, t5); - if((u==3) || (u==5)) t = -t; - } - gtog(t5, t7); gtog(t6, t5); gtog(t7, t6); - u = (t6->n[0]) & 3; - if(((t5->n[0] & 3) == 3) && ((u & 3) == 3)) t = -t; - modg(t6, t5); - } - if(isone(t6)) { - pushg(3); - return(t); - } - pushg(3); - return(0); -} - -int -pseudoq(giant a, giant p) -/* Query whether a^(p-1) = 1 (mod p). */ -{ - int x; - giant t1 = popg(), t2 = popg(); - - gtog(p, t1); itog(1, t2); subg(t2, t1); - gtog(a, t2); - powermodg(t2, t1, p); - x = isone(t2); - pushg(2); - return(x); -} - -int -pseudointq(int a, giant p) -/* Query whether a^(p-1) = 1 (mod p). */ -{ - int x; - giant t4 = popg(); - - itog(a, t4); - x = pseudoq(t4, p); - pushg(1); - return(x); -} - - -void -powFp2(giant a, giant b, giant w2, giant n, giant p) -/* Perform powering in the field F_p^2: - a + b w := (a + b w)^n (mod p), where parameter w2 is a quadratic - nonresidue (formally equal to w^2). - */ -{ int j; - giant t6 = popg(), t7 = popg(), t8 = popg(), t9 = popg(); - - if(isZero(n)) { - itog(1,a); - itog(0,b); - pushg(4); - return; - } - gtog(a, t8); gtog(b, t9); - for(j = bitlen(n)-2; j >= 0; j--) { - gtog(b, t6); - mulg(a, b); addg(b,b); modg(p, b); /* b := 2 a b. */ - squareg(t6); modg(p, t6); - mulg(w2, t6); modg(p, t6); - squareg(a); addg(t6, a); modg(p, a); /* a := a^2 + b^2 w2. */ - if(bitval(n, j)) { - gtog(b, t6); mulg(t8, b); modg(p, b); - gtog(a, t7); mulg(t9, a); addg(a, b); modg(p, b); - mulg(t9, t6); modg(p, t6); mulg(w2, t6); modg(p, t6); - mulg(t8, a); addg(t6, a); modg(p, a); - } - } - pushg(4); - return; -} - -int -sqrtmod(giant p, giant x) -/* If Sqrt[x] (mod p) exists, function returns 1, else 0. - In either case x is modified, but if 1 is returned, - x:= Sqrt[x] (mod p). - */ -{ giant t0 = popg(), t1 = popg(), t2 = popg(), t3 = popg(), - t4 = popg(); - - modg(p, x); /* Justify the argument. */ - gtog(x, t0); /* Store x for eventual validity check on square root. */ - if((p->n[0] & 3) == 3) { /* The case p = 3 (mod 4). */ - gtog(p, t1); - iaddg(1, t1); gshiftright(2, t1); - powermodg(x, t1, p); - goto resolve; - } -/* Next, handle case p = 5 (mod 8). */ - if((p->n[0] & 7) == 5) { - gtog(p, t1); itog(1, t2); - subg(t2, t1); gshiftright(2, t1); - gtog(x, t2); - powermodg(t2, t1, p); /* t2 := x^((p-1)/4) % p. */ - iaddg(1, t1); - gshiftright(1, t1); /* t1 := (p+3)/8. */ - if(isone(t2)) { - powermodg(x, t1, p); /* x^((p+3)/8) is root. */ - goto resolve; - } else { - itog(1, t2); subg(t2, t1); /* t1 := (p-5)/8. */ - gshiftleft(2,x); - powermodg(x, t1, p); - mulg(t0, x); addg(x, x); modg(p, x); /* 2x (4x)^((p-5)/8. */ - goto resolve; - } - } - -/* Next, handle tougher case: p = 1 (mod 8). */ - itog(2, t1); - while(1) { /* Find appropriate nonresidue. */ - gtog(t1, t2); - squareg(t2); subg(x, t2); modg(p, t2); - if(jacobi_symbol(t2, p) == -1) break; - iaddg(1, t1); - } /* t2 is now w^2 in F_p^2. */ - itog(1, t3); - gtog(p, t4); iaddg(1, t4); gshiftright(1, t4); - powFp2(t1, t3, t2, t4, p); - gtog(t1, x); - -resolve: - gtog(x,t1); squareg(t1); modg(p, t1); - if(gcompg(t0, t1) == 0) { - pushg(5); - return(1); /* Success. */ - } - pushg(5); - return(0); /* No square root. */ -} - -void -sqrtg(giant n) -/* n:= Floor[Sqrt[n]]. */ -{ giant t5 = popg(), t6 = popg(); - - itog(1, t5); gshiftleft(1 + bitlen(n)/2, t5); - while(1) { - gtog(n, t6); - divg(t5, t6); - addg(t5, t6); gshiftright(1, t6); - if(gcompg(t6, t5) >= 0) break; - gtog(t6, t5); - } - gtog(t5, n); - pushg(2); -} - -int -cornacchia4(giant n, int d, giant u, giant v) -/* Seek representation 4n = u^2 + |d| v^2, - for (negative) discriminant d and n > |D|/4. - Parameter u := 0 and 0 is returned, if no representation is found; - else 1 is returned and u, v properly set. - */ -{ int r = n->n[0] & 7, sym; - giant t1 = popg(), t2 = popg(), t3 = popg(), t4 = popg(); - - itog(d, t1); - if((n->n[0]) & 7 == 1) { /* n = 1 (mod 8). */ - sym = jacobi_symbol(t1,n); - if(sym != 1) { - itog(0,u); - pushg(4); - return(0); - } - gtog(t1, t2); - sqrtmod(n, t2); /* t2 := Sqrt[d] (mod n). */ - } else { /* Avoid separate Jacobi/Legendre test. */ - gtog(t1, t2); - if(sqrtmod(n, t2) == 0) { - itog(0, u); - pushg(4); - return(0); - } - } -/* t2 is now a valid square root of d (mod n). */ - gtog(t2, t3); - subg(t1, t3); /* t3 := t2 - d. */ - if((t3->n[0] & 1) == 1) { - negg(t2); - addg(n, t2); - } - gtog(n, t3); addg(t3, t3); /* t3 := 2n. */ - gtog(n, t4); gshiftleft(2, t4); sqrtg(t4); /* t4 = [Sqrt[4 p]]. */ - while(gcompg(t2, t4) > 0) { - gtog(t3, t1); - gtog(t2, t3); - gtog(t1, t2); - modg(t3, t2); - } - gtog(n, t4); gshiftleft(2, t4); - gtog(t2, t3); squareg(t3); - subg(t3, t4); /* t4 := 4n - t2^2. */ - gtog(t4, t3); - itog(d, t1); absg(t1); - modg(t1, t3); - if(!isZero(t3)) { - itog(0,u); - pushg(4); - return(0); - } - divg(t1, t4); - gtog(t4, t1); - sqrtg(t4); /* t4 := [Sqrt[t4/Abs[d]]]. */ - gtog(t4, t3); - squareg(t3); - if(gcompg(t3, t1) != 0) { - itog(0, u); - pushg(4); - return(0); - } - gtog(t2, u); - gtog(t4, v); - pushg(4); - return(1); -} - -/* -rep[p_, d_] := Module[{t, x0, a, b, c}, - If[JacobiSymbol[d,p] != 1, Return[{0,0}]]; - x0 = sqrt[d, p]; - If[Mod[x0-d,2] == 1, x0 = p-x0]; - a = 2p; b = x0; c = sqrtint[4 p]; - While[b > c, {a,b} = {b, Mod[a,b]}]; - t = 4p - b^2; - If[Mod[t,Abs[d]] !=0, Return[{0,0}]]; - v = t/Abs[d]; - u = sqrtint[v]; - If[u^2 != v, Return[{0,0}]]; - Return[{b, u}] - ]; -*/ - - diff --git a/OSX/include/security_cryptkit/CurveParamDocs/tools.h b/OSX/include/security_cryptkit/CurveParamDocs/tools.h deleted file mode 100644 index 34981eee..00000000 --- a/OSX/include/security_cryptkit/CurveParamDocs/tools.h +++ /dev/null @@ -1,65 +0,0 @@ -/************************************************************** - * - * tools.h - * - * Header file for tools.c. - * - * Updates: - * 30 Apr 99 REC Modified init_tools type to void. - * 3 Apr 98 REC Creation - * - * - * c. 1998 Perfectly Scientific, Inc. - * All Rights Reserved. - * - * - *************************************************************/ - -#define NUM_PRIMES 6542 /* PrimePi[2^16]. */ -#define MILLER_RABIN_DEPTH (8) - -void -init_tools(int shorts); - -void -make_primes(); - -int -prime_literal( - unsigned int p -); - -int -primeq( - unsigned int odd -); - -void -make_primes(); - -int -prime_probable(giant p); - -int -jacobi_symbol(giant a, giant n); - -int -pseudoq(giant a, giant p); - -int -pseudointq(int a, giant p); - - -void -powFp2(giant a, giant b, giant w2, giant n, giant p); - -int -sqrtmod(giant p, giant x); - -void -sqrtg(giant n); - -int -cornacchia4(giant n, int d, giant u, giant v); - - diff --git a/OSX/include/security_cryptkit/ECDSA_Profile.h b/OSX/include/security_cryptkit/ECDSA_Profile.h deleted file mode 100644 index eb7a7cc9..00000000 --- a/OSX/include/security_cryptkit/ECDSA_Profile.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - File: ECDSA_Profile.h - - Contains: ECDSA Profiling support. - - - Copyright: Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - - Change History (most recent first): - - <7> 10/06/98 ap Changed to compile with C++. - - To Do: -*/ - -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - */ - -#ifndef _CK_ECDSA_PROFILE_H_ -#define _CK_ECDSA_PROFILE_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_ECDSA_ENABLE - -#include "feeDebug.h" - -#ifdef FEE_DEBUG -#define ECDSA_PROFILE 0 -#else /* FEE_DEBUG */ -#define ECDSA_PROFILE 0 /* always off */ -#endif /* FEE_DEBUG */ - -#if ECDSA_PROFILE - -#include - -/* - * Unlike the profiling macros in feeDebug.h, these are intended to - * be used for fragments of code, not entire functions. - */ -#define SIGPROF_START \ -{ \ - struct tsval _profStartTime; \ - struct tsval _profEndTime; \ - kern_timestamp(&_profStartTime); - -/* - * This one goes at the end of the routine, just before the (only) return. - * There must be a static accumulator (an unsigned int) on a per-routine basis. - */ -#define SIGPROF_END(accum) \ - kern_timestamp(&_profEndTime); \ - accum += (_profEndTime.low_val - _profStartTime.low_val); \ -} - - -/* - * Accumulators. - */ -extern unsigned signStep1; -extern unsigned signStep2; -extern unsigned signStep34; -extern unsigned signStep5; -extern unsigned signStep67; -extern unsigned signStep8; -extern unsigned vfyStep1; -extern unsigned vfyStep3; -extern unsigned vfyStep4; -extern unsigned vfyStep5; -extern unsigned vfyStep6; -extern unsigned vfyStep7; - -#else /* ECDSA_PROFILE */ - -#define SIGPROF_START -#define SIGPROF_END(accum) - -#endif /* ECDSA_PROFILE */ - -#endif /* CRYPTKIT_ECDSA_ENABLE */ -#endif /* _CK_ECDSA_PROFILE_H_ */ diff --git a/OSX/include/security_cryptkit/ECDSA_Verify_Prefix.h b/OSX/include/security_cryptkit/ECDSA_Verify_Prefix.h deleted file mode 100644 index 3c52bde5..00000000 --- a/OSX/include/security_cryptkit/ECDSA_Verify_Prefix.h +++ /dev/null @@ -1,6 +0,0 @@ -/* - * Prefix file for ECDSA Verify build. - * - * This symbol disables features not needed for ECDSA verify. - */ -#define ECDSA_VERIFY_ONLY 1 diff --git a/OSX/include/security_cryptkit/HmacSha1Legacy.c b/OSX/include/security_cryptkit/HmacSha1Legacy.c deleted file mode 100644 index 83e77619..00000000 --- a/OSX/include/security_cryptkit/HmacSha1Legacy.c +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -/* - File: HmacSha1Legacy.c - Contains: HMAC/SHA1, bug-for-bug compatible with BSAFE 4.0. - Copyright (c) 2001,2011-2014 Apple Inc. All Rights Reserved. -*/ - -#include "ckconfig.h" - -#if CRYPTKIT_HMAC_LEGACY - -#include "HmacSha1Legacy.h" -#include "ckSHA1.h" -#include -#include -#include -#define kHMACSHA1DigestSize 20 - -/* XXX These should really be in ckSHA1.h */ -#define kSHA1DigestSize 20 -#define kSHA1BlockSize 64 - -/* - * bug-for-bug compatible with BSAFE 4.0. See - * BSafe/bsource/algs/ahchhmac.c. - * - * This implementation, and the BSAFE implementation it emulates, work fine - * when calculating a MAC in a single update (init, update, final). They - * generate nonconforming MACs when performing multiple updates because - * the entire algorithm - both inner and outer digests - are performed - * in the update() step. As a result, if one e.g. calculates a MAC of - * a block of text with one update, and then calculates the MAC over the - * same block of text via two updates, different results will obtain.ÊThe - * incorrect result from the multiple-update scenario is repeatable if and - * only if the same boundaries (same update sizes) are observed on each operation. - * - * Because all of the data to be MAC'd is in fact protected by both levels of - * SHA1, and all of the key bits are used, this nonconforming implementation is - * believed to be as strong, cryptographically, as a conforming SHA1HMAC - * implementation. - */ -struct hmacLegacyContext { - sha1Obj sha1Context; - UInt8 k_ipad[kSHA1BlockSize]; - UInt8 k_opad[kSHA1BlockSize]; -}; - -hmacLegacyContextRef hmacLegacyAlloc(void) -{ - hmacLegacyContextRef hmac = - (hmacLegacyContextRef)malloc(sizeof(struct hmacLegacyContext)); - memset(hmac, 0, sizeof(struct hmacLegacyContext)); - return hmac; -} - -void hmacLegacyFree( - hmacLegacyContextRef hmac) -{ - if(hmac != NULL) { - if(hmac->sha1Context != NULL) { - sha1Free (hmac->sha1Context); - } - memset(hmac, 0, sizeof(struct hmacLegacyContext)); - free(hmac); - } -} - -/* reusable init */ -OSStatus hmacLegacyInit( - hmacLegacyContextRef hmac, - const void *keyPtr, - UInt32 keyLen) -{ - UInt8 *key; - UInt32 byte; - - if(hmac->sha1Context == NULL) { - hmac->sha1Context = sha1Alloc(); - if(hmac->sha1Context == NULL) { - return errSecAllocate; - } - } - else { - sha1Reinit(hmac->sha1Context); - } - /* this implementation requires a 20-byte key */ - if (keyLen != kSHA1DigestSize) { - /* FIXME */ - return errSecParam; - } - key = (UInt8*)keyPtr; - - /* The HMAC_SHA_1 transform looks like: - SHA1 (K XOR opad || SHA1 (K XOR ipad || text)) - Where K is a n byte key - ipad is the byte 0x36 repeated 64 times. - opad is the byte 0x5c repeated 64 times. - text is the data being protected. - */ - /* Copy the key into k_ipad and k_opad while doing the XOR. */ - for (byte = 0; byte < keyLen; byte++) - { - hmac->k_ipad[byte] = key[byte] ^ 0x36; - hmac->k_opad[byte] = key[byte] ^ 0x5c; - } - - /* Fill the remainder of k_ipad and k_opad with 0 XORed with - * appropriate value. */ - memset (hmac->k_ipad + keyLen, 0x36, kSHA1BlockSize - keyLen); - memset (hmac->k_opad + keyLen, 0x5c, kSHA1BlockSize - keyLen); - - /* remainder happens in update */ - return errSecSuccess; -} - -OSStatus hmacLegacyUpdate( - hmacLegacyContextRef hmac, - const void *textPtr, - UInt32 textLen) -{ - UInt8 innerDigest[kSHA1DigestSize]; - - /* compute SHA1(k_ipad || data) ==> innerDigest */ - sha1AddData (hmac->sha1Context, hmac->k_ipad, kSHA1BlockSize); - sha1AddData (hmac->sha1Context, (UInt8*)textPtr, textLen); - memcpy (innerDigest, sha1Digest(hmac->sha1Context), kSHA1DigestSize); - - /* reset context (BSAFE does this implicitly in a final() call) */ - sha1Reinit(hmac->sha1Context); - - /* compute SHA1(k_opad || innerDigest) */ - sha1AddData (hmac->sha1Context, hmac->k_opad, kSHA1BlockSize); - sha1AddData (hmac->sha1Context, innerDigest, kSHA1DigestSize); - - /* if there is another update coming, it gets added in to existing - * context; if the next step is a final, the current digest state is used. */ - return errSecSuccess; -} - -OSStatus hmacLegacyFinal( - hmacLegacyContextRef hmac, - void *resultPtr) // caller mallocs, must be HMACSHA1_OUT_SIZE bytes -{ - memcpy (resultPtr, sha1Digest (hmac->sha1Context), kSHA1DigestSize); - return errSecSuccess; -} - -#endif /* CRYPTKIT_HMAC_LEGACY */ diff --git a/OSX/include/security_cryptkit/HmacSha1Legacy.h b/OSX/include/security_cryptkit/HmacSha1Legacy.h deleted file mode 100644 index 691ca5bb..00000000 --- a/OSX/include/security_cryptkit/HmacSha1Legacy.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -/* - File: HmacSha1Legacy.h - Contains: HMAC/SHA1, bug-for-bug compatible a legacy implementation. - Copyright (c) 2001,2011-2014 Apple Inc. All Rights Reserved. -*/ -#ifndef __HMAC_SHA1_LEGACY__ -#define __HMAC_SHA1_LEGACY__ - -#if !defined(__MACH__) -#include -#else -#include -#endif - -#if CRYPTKIT_HMAC_LEGACY - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * This version is bug-for-bug compatible with the HMACSHA1 implementation in - * an old crypto library. - */ -struct hmacLegacyContext; -typedef struct hmacLegacyContext *hmacLegacyContextRef; - -hmacLegacyContextRef hmacLegacyAlloc(void); -void hmacLegacyFree( - hmacLegacyContextRef hmac); -OSStatus hmacLegacyInit( - hmacLegacyContextRef hmac, - const void *keyPtr, - UInt32 keyLen); -OSStatus hmacLegacyUpdate( - hmacLegacyContextRef hmac, - const void *textPtr, - UInt32 textLen); -OSStatus hmacLegacyFinal( - hmacLegacyContextRef hmac, - void *resultPtr); // caller mallocs, must be kSHA1DigestSize bytes - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_HMAC_LEGACY */ - -#endif /* __HMAC_SHA1_LEGACY__ */ diff --git a/OSX/include/security_cryptkit/Mathematica.FEE b/OSX/include/security_cryptkit/Mathematica.FEE deleted file mode 100644 index 7f129d52..00000000 --- a/OSX/include/security_cryptkit/Mathematica.FEE +++ /dev/null @@ -1,57 +0,0 @@ -(* Elliptic algebra functions: FEE format. - - y^2 = x^3 + c x^2 + a x + b. - - Montgomery: b = 0, a = 1; - Weierstrass: c = 0; - Atkin3: c = a = 0; - Atkin4: c = b = 0; - - Parameters c, a, b, p must be global. - *) - -elleven[pt_] := Block[{x1 = pt[[1]], z1 = pt[[2]], e, f }, - e = Mod[(x1^2 - a z1^2)^2 - 4 b (2 x1 + c z1) z1^3, p]; - f = Mod[4 z1 (x1^3 + c x1^2 z1 + a x1 z1^2 + b z1^3), p]; - Return[{e,f}] -]; - -ellodd[pt_, pu_, pv_] := Block[ - {x1 = pt[[1]], z1 = pt[[2]], - x2 = pu[[1]], z2 = pu[[2]], - xx = pv[[1]], zz = pv[[2]], i, j}, - i = Mod[zz ((x1 x2 - a z1 z2)^2 - - 4 b(x1 z2 + x2 z1 + c z1 z2) z1 z2), p]; - j = Mod[xx (x1 z2 - x2 z1)^2, p]; - Return[{i,j}] -]; - -bitList[k_] := Block[{li = {}, j = k}, - While[j > 0, - li = Append[li, Mod[j,2]]; - j = Floor[j/2]; - ]; - Return[Reverse[li]]; - ]; - -elliptic[pt_, k_] := Block[{porg, ps, pp, q}, - - If[k ==1, Return[pt]]; - If[k ==2, Return[elleven[pt]]]; - porg = pt; - ps = elleven[pt]; - pp = pt; - bitlist = bitList[k]; - Do[ - If[bitlist[[q]] == 1, - pp = ellodd[ps, pp, porg]; - ps = elleven[ps], - ps = ellodd[pp, ps, porg]; - pp = elleven[pp] - ], - {q,2,Length[bitlist]} - ]; - Return[Mod[pp,p]] -]; -ellinv[n_] := PowerMod[n,-1,p]; -ex[pt_] := Mod[pt[[1]] * ellinv[pt[[2]]], p]; diff --git a/OSX/include/security_cryptkit/NSCipherFile.h b/OSX/include/security_cryptkit/NSCipherFile.h deleted file mode 100644 index 13f103c5..00000000 --- a/OSX/include/security_cryptkit/NSCipherFile.h +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSCipherFile.h - ObjC wrapper for feeCipherFile - * - * Revision History - * ---------------- - * 28 Oct 96 at NeXT - * Created. - */ - -#import -#import - -@interface NSCipherFile : NSObject -{ - void *_priv; -} - -/* - * Alloc and return an autoreleased NSCipherFile object associated with - * the specified data. - */ -+ newFromCipherText : (NSData *)cipherText - encrType : (cipherFileEncrType)encrType - sendPubKeyData : (NSData *)sendPubKeyData - otherKeyData : (NSData *)otherKeyData - sigData : (NSData *)sigData // optional; nil means no signature - userData : (unsigned)userData; // for caller's convenience - -/* - * Obtain the contents of a feeCipherFile as NSData. - */ -- (NSData *)dataRepresentation; - -/* - * Alloc and return an autoreleased NSCipherFile object given a data - * representation. - */ -+ newFromDataRepresentation : (NSData *)dataRep; - -/* - * Given an NSCipherFile object, obtain its constituent parts. - */ -- (cipherFileEncrType)encryptionType; -- (NSData *)cipherText; -- (NSData *)sendPubKeyData; -- (NSData *)otherKeyData; -- (NSData *)sigData; -- (unsigned)userData; - -/* - * High-level cipherFile support. - */ - -/* - * Obtain the data representation of a NSCipherFile given the specified - * plainText and cipherFileEncrType. - * Receiver's public key is required for all encrTypes; sender's private - * key is required for signature generation and also for encrType - * CFE_PublicDES and CFE_FEED. - */ -+(feeReturn)createCipherFileForPrivKey : (NSFEEPublicKey *)sendPrivKey - recvPubKey : (NSFEEPublicKey *)recvPubKey - encrType : (cipherFileEncrType)encrType - plainText : (NSData *)plainText - genSig : (BOOL)genSig - doEnc64 : (BOOL)doEnc64 // YES ==> perform enc64 - userData : (unsigned)userData // for caller's convenience - cipherFileData : (NSData **)cipherFileData; // RETURNED - -/* - * Parse and decrypt a data representation of an NSCipherFile object. - * - * recvPrivKey is required in all cases. If sendPubKey is present, - * sendPubKey - rather than the embedded sender's public key - will be - * used for signature validation. - */ -+ (feeReturn)parseCipherFileData : (NSFEEPublicKey *)recvPrivKey - sendPubKey : (NSFEEPublicKey *)sendPubKey - cipherFileData : (NSData *)cipherFileData - doDec64 : (BOOL)doDec64 - encrType : (cipherFileEncrType *)encrType // RETURNED - plainText : (NSData **)plainText // RETURNED - sigStatus : (feeSigStatus *)sigStatus // RETURNED - sigSigner : (NSString **)sigSigner // RETURNED - userData : (unsigned *)userData; // RETURNED - -/* - * Parse and decrypt an NSCipherFile object obtained via - * +newFromDataRepresentation. - * - * recvPrivKey is required in all cases. If sendPubKey is present, - * sendPubKey - rather than the embedded sender's public key - will be - * used for signature validation. - */ -- (feeReturn)decryptCipherFileData : (NSFEEPublicKey *)recvPrivKey - sendPubKey : (NSFEEPublicKey *)sendPubKey - plainText : (NSData **)plainText // RETURNED - sigStatus : (feeSigStatus *)sigStatus // RETURNED - sigSigner : (NSString **)sigSigner; // RETURNED - - -@end diff --git a/OSX/include/security_cryptkit/NSCipherFile.m b/OSX/include/security_cryptkit/NSCipherFile.m deleted file mode 100644 index 93598d72..00000000 --- a/OSX/include/security_cryptkit/NSCipherFile.m +++ /dev/null @@ -1,360 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSCipherFile.m - ObjC wrapper for feeCipherFile - * - * Revision History - * ---------------- - * 28 Oct 96 at NeXT - * Created. - */ - -#import "NSCipherFile.h" -#import "feeCipherFile.h" -#import "falloc.h" -#import "NSFEEPublicKeyPrivate.h" /* for -feePubKey */ - -/* - * Private instance data. - */ -typedef struct { - feeCipherFile cfile; -} _cfPriv; - -@implementation NSCipherFile - -- (void)dealloc -{ - if(_priv) { - _cfPriv *cfPriv = _priv; - if(cfPriv->cfile) { - feeCFileFree(cfPriv->cfile); - } - } - [super dealloc]; -} - -/* - * Alloc and return an autoreleased NSCipherFile object associated with - * the specified data. - */ -+ newFromCipherText : (NSData *)cipherText - encrType : (cipherFileEncrType)encrType - sendPubKeyData : (NSData *)sendPubKeyData - otherKeyData : (NSData *)otherKeyData - sigData : (NSData *)sigData // optional; nil means no signature - userData : (unsigned)userData // for caller's convenience -{ - NSCipherFile *result; - _cfPriv *cfPriv; - - result = [[self alloc] autorelease]; - result->_priv = cfPriv = fmalloc(sizeof(_cfPriv)); - cfPriv->cfile = feeCFileNewFromCipherText(encrType, - [cipherText bytes], - [cipherText length], - [sendPubKeyData bytes], - [sendPubKeyData length], - [otherKeyData bytes], - [otherKeyData length], - [sigData bytes], - [sigData length], - userData); - if(cfPriv->cfile) { - return result; - } - else { - return nil; - } -} - -/* - * Obtain the contents of a feeCipherFile as NSData. - */ -- (NSData *)dataRepresentation -{ - _cfPriv *cfPriv = _priv; - NSData *result; - const unsigned char *rep; - unsigned repLen; - feeReturn frtn; - - if(cfPriv == NULL) { - return nil; - } - frtn = feeCFileDataRepresentation(cfPriv->cfile, - &rep, - &repLen); - if(frtn) { - return nil; - } - result = [NSData dataWithBytesNoCopy:(unsigned char *)rep - length:repLen]; - return result; -} - -/* - * Alloc and return an autoreleased NSCipherFile object given a data - * representation. - */ -+ newFromDataRepresentation : (NSData *)dataRep -{ - NSCipherFile *result; - _cfPriv *cfPriv; - feeReturn frtn; - - result = [[self alloc] autorelease]; - result->_priv = cfPriv = fmalloc(sizeof(_cfPriv)); - frtn = feeCFileNewFromDataRep([dataRep bytes], - [dataRep length], - &cfPriv->cfile); - if(frtn) { - return nil; - } - else { - return result; - } -} - -/* - * Given an NSCipherFile object, obtain its constituent parts. - */ -- (cipherFileEncrType)encryptionType -{ - _cfPriv *cfPriv = _priv; - - if(cfPriv == NULL) { - return CFE_Other; - } - return feeCFileEncrType(cfPriv->cfile); -} - -- (NSData *)cipherText -{ - _cfPriv *cfPriv = _priv; - const unsigned char *ctext; - unsigned ctextLen; - - if(cfPriv == NULL) { - return nil; - } - ctext = feeCFileCipherText(cfPriv->cfile, &ctextLen); - return [NSData dataWithBytesNoCopy:(unsigned char *)ctext - length:ctextLen]; -} - -- (NSData *)sendPubKeyData -{ - _cfPriv *cfPriv = _priv; - const unsigned char *key; - unsigned keyLen; - - if(cfPriv == NULL) { - return nil; - } - key = feeCFileSendPubKeyData(cfPriv->cfile, &keyLen); - if(key) { - return [NSData dataWithBytesNoCopy:(unsigned char *)key - length:keyLen]; - } - else { - return nil; - } -} - -- (NSData *)otherKeyData -{ - _cfPriv *cfPriv = _priv; - const unsigned char *key; - unsigned keyLen; - - if(cfPriv == NULL) { - return nil; - } - key = feeCFileOtherKeyData(cfPriv->cfile, &keyLen); - if(key) { - return [NSData dataWithBytesNoCopy:(unsigned char *)key - length:keyLen]; - } - else { - return nil; - } -} - -- (NSData *)sigData -{ - _cfPriv *cfPriv = _priv; - const unsigned char *sig; - unsigned sigLen; - - if(cfPriv == NULL) { - return nil; - } - sig = feeCFileSigData(cfPriv->cfile, &sigLen); - if(sig) { - return [NSData dataWithBytesNoCopy:(unsigned char *)sig - length:sigLen]; - } - else { - return nil; - } -} - -- (unsigned)userData -{ - _cfPriv *cfPriv = _priv; - - if(cfPriv == NULL) { - return 0; - } - return feeCFileUserData(cfPriv->cfile); -} - -/* - * High-level cipherFile support. - */ - -/* - * Create a cipherfile of specified cipherFileEncrType for given plaintext. - */ -+(feeReturn)createCipherFileForPrivKey : (NSFEEPublicKey *)sendPrivKey - recvPubKey : (NSFEEPublicKey *)recvPubKey - encrType : (cipherFileEncrType)encrType - plainText : (NSData *)plainText - genSig : (BOOL)genSig - doEnc64 : (BOOL)doEnc64 // YES ==> perform enc64 - userData : (unsigned)userData // for caller's convenience - cipherFileData : (NSData **)cipherFileData // RETURNED -{ - feeReturn frtn; - unsigned char *cfileData; - unsigned cfileDataLen; - feePubKey privKey = NULL; - - if(sendPrivKey) { - privKey = [sendPrivKey feePubKey]; - } - frtn = createCipherFile(privKey, - [recvPubKey feePubKey], - encrType, - [plainText bytes], - [plainText length], - genSig, - doEnc64, - userData, - &cfileData, - &cfileDataLen); - if(frtn) { - return frtn; - } - *cipherFileData = - [NSData dataWithBytesNoCopy:(unsigned char *)cfileData - length:cfileDataLen]; - return frtn; -} - -/* - * Parse and decrypt a data representation of an NSCipherFile object. - */ -+ (feeReturn)parseCipherFileData : (NSFEEPublicKey *)recvPrivKey - sendPubKey : (NSFEEPublicKey *)sendPubKey - cipherFileData : (NSData *)cipherFileData - doDec64 : (BOOL)doDec64 - encrType : (cipherFileEncrType *)encrType // RETURNED - plainText : (NSData **)plainText // RETURNED - sigStatus : (feeSigStatus *)sigStatus // RETURNED - sigSigner : (NSString **)sigSigner // RETURNED - userData : (unsigned *)userData // RETURNED -{ - feeReturn frtn; - unsigned char *ptext; - unsigned ptextLen; - feeUnichar *signer; - unsigned signerLen; - feePubKey _pubKey = NULL; - - if(recvPrivKey == nil) { - return FR_IllegalArg; // always required - } - if(sendPubKey) { - _pubKey = [sendPubKey feePubKey]; - } - - frtn = parseCipherFile([recvPrivKey feePubKey], - _pubKey, - [cipherFileData bytes], - [cipherFileData length], - doDec64, - encrType, - &ptext, - &ptextLen, - sigStatus, - &signer, - &signerLen, - userData); - if(frtn) { - return frtn; - } - *plainText = [NSData dataWithBytesNoCopy:ptext length:ptextLen]; - *sigSigner = [NSString stringWithCharacters:signer length:signerLen]; - ffree(signer); - return frtn; -} - -/* - * Parse and decrypt an NSCipherFile object obtained via - * +newFromDataRepresentation. - * - * recvPrivKey is required in all cases. If sendPubKey is present, - * sendPubKey - rather than the embedded sender's public key - will be - * used for signature validation. - */ -- (feeReturn)decryptCipherFileData : (NSFEEPublicKey *)recvPrivKey - sendPubKey : (NSFEEPublicKey *)sendPubKey - plainText : (NSData **)plainText // RETURNED - sigStatus : (feeSigStatus *)sigStatus // RETURNED - sigSigner : (NSString **)sigSigner // RETURNED -{ - _cfPriv *cfPriv = _priv; - feeReturn frtn; - unsigned char *ptext; - unsigned ptextLen; - feeUnichar *signer; - unsigned signerLen; - feePubKey _pubKey = NULL; - - if(cfPriv == NULL) { - return FR_IllegalArg; - } - if(recvPrivKey == nil) { - return FR_IllegalArg; // always required - } - if(sendPubKey) { - _pubKey = [sendPubKey feePubKey]; - } - - frtn = decryptCipherFile(cfPriv->cfile, - [recvPrivKey feePubKey], - _pubKey, - &ptext, - &ptextLen, - sigStatus, - &signer, - &signerLen); - if(frtn) { - return frtn; - } - *plainText = [NSData dataWithBytesNoCopy:ptext length:ptextLen]; - *sigSigner = [NSString stringWithCharacters:signer length:signerLen]; - ffree(signer); - return frtn; - -} -@end diff --git a/OSX/include/security_cryptkit/NSCryptors.h b/OSX/include/security_cryptkit/NSCryptors.h deleted file mode 100644 index 33935a7d..00000000 --- a/OSX/include/security_cryptkit/NSCryptors.h +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSCryptors.h - common cryptographic protocols - * - * Revision History - * ---------------- - * ??? 1994 Blaine Garst at NeXT - * Created. - */ - - -#import -#import -#import - - -/************ Utilities ******************************************/ - -#ifdef NeXT - -NSString *NSPromptForPassPhrase(NSString *prompt); - // useful for command line (/dev/tty) programs - -#endif NeXT - -/************ Data Hashing Protocol *****************/ - -@protocol NSDataDigester -+ digester; // provides a concrete digester - -// primitives -- (void)digestData:(NSData *)data; // use for multi-bite messages -- (NSData *)messageDigest; // provide digest; re-init - -// conveniences that only use the above primitives -// all in one gulp (eats salt first, if present) -- (NSData *)digestData:(NSData *)data withSalt:(NSData *)salt; - -@end - - -/****** Encryption/Decryption Protocol ***********/ - -@protocol NSCryptor -- (NSData *)encryptData:(NSData *)input; -- (NSData *)decryptData:(NSData *)input; -- (unsigned)keyBitsize; -@end - - -/*************** Public Key Services *************/ - -@protocol NSPublicKey -- (NSString *)publicKeyString; -- (NSString *)algorithmName; // "Diffie-Hellman" "FEE" ... -- (NSString *)usageName; // "Blaine Garst - home" -- (NSData *)padWithPublicKey:(id )otherKey; -- (unsigned)keyBitsize; -@end - -/********* Key Ring ************************/ - -@protocol NSKeyRing -- keyForUsageName:(NSString *)user; -@end - -/********** Digital Signatures **************/ - -// protocol adapted by various signature schemes (FEE, DSA, RSA...) -@protocol NSDigitalSignature -- (NSData *)digitalSignatureForData:(NSData *)message; - // generate a signature for the data - -- (BOOL)isValidDigitalSignature:(NSData *)sig forData:(NSData *)data; -@end diff --git a/OSX/include/security_cryptkit/NSDESCryptor.h b/OSX/include/security_cryptkit/NSDESCryptor.h deleted file mode 100644 index 6f3ed08b..00000000 --- a/OSX/include/security_cryptkit/NSDESCryptor.h +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSDESCryptor.h created by blaine on Thu 22-Feb-1996 - */ - -#import "NSCryptors.h" - -/****** Digital Encryption Standard/Algorithm ********/ - -@interface NSDESCryptor : NSObject -{ - void *_priv; -} - -+ cryptorWithState:(NSData *)s; - -- initWithState:(NSData *)state; - // designated initializer - // 8 bytes with most sig bit ignored: 56 bits - -- (void)setCryptorState:(NSData *)state; // reset -- (void)setBlockMode:(BOOL)yorn; // default is chaining mode - -/* - * NSCryptor methods - */ -- (NSData *)encryptData:(NSData *)input; -- (NSData *)decryptData:(NSData *)input; -- (unsigned)keyBitsize; - -@end diff --git a/OSX/include/security_cryptkit/NSDESCryptor.m b/OSX/include/security_cryptkit/NSDESCryptor.m deleted file mode 100644 index 2e071b2e..00000000 --- a/OSX/include/security_cryptkit/NSDESCryptor.m +++ /dev/null @@ -1,130 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSDESCryptor.m - DES encrypt/decrypt class - * - * Revision History - * ---------------- - * 28 Mar 97 at Apple - * Rewrote using feeDES module. - * 22 Feb 96 at NeXT - * Created. - */ - -#import -#import "NSDESCryptor.h" -#import "feeDES.h" -#import "falloc.h" -#import "ckutilities.h" -#import "feeFunctions.h" - -/* - * Note: Our _priv ivar is actuall a feeDES pointer. - */ -@implementation NSDESCryptor - -+ cryptorWithState:(NSData *)s { - return [[[self alloc] initWithState:s] autorelease]; -} - -- (void)setCryptorState:(NSData *)state { - if(_priv == NULL) { - return; - } - feeDESSetState(_priv, [state bytes], [state length]); -} - -- initWithState:(NSData *)state { - feeReturn frtn; - - if(_priv == NULL) { - _priv = feeDESNewWithState([state bytes], [state length]); - } - else { - frtn = feeDESSetState(_priv, [state bytes], [state length]); - if(frtn) { - NSLog(@"NSDESCryptor: bad initial state\n"); - return nil; - } - } - return self; -} - -- (void)dealloc -{ - if(_priv) { - feeDESFree(_priv); - } - [super dealloc]; -} - -- (void)setBlockMode:(BOOL)yorn { - if(_priv == NULL) { - return; - } - if(yorn) { - feeDESSetBlockMode(_priv); - } - else { - feeDESSetChainMode(_priv); - } -} - -- (NSData *)encryptData:(NSData *)input { - NSData *result; - feeReturn frtn; - unsigned char *cipherText; - unsigned cipherTextLen; - - if(_priv == NULL) { - return nil; - } - frtn = feeDESEncrypt(_priv, - [input bytes], - [input length], - &cipherText, - &cipherTextLen); - if(frtn) { - NSLog(@"NSDESCryptor encrypt: %s", feeReturnString(frtn)); - return nil; - } - result = [NSData dataWithBytes:cipherText length:cipherTextLen]; - ffree(cipherText); - return result; -} - -- (NSData *)decryptData:(NSData *)input { - NSData *result; - feeReturn frtn; - unsigned char *plainText; - unsigned plainTextLen; - - if(_priv == NULL) { - return nil; - } - frtn = feeDESDecrypt(_priv, - [input bytes], - [input length], - &plainText, - &plainTextLen); - if(frtn) { - NSLog(@"NSDESCryptor decrypt: %s", feeReturnString(frtn)); - return nil; - } - result = [NSData dataWithBytes:plainText length:plainTextLen]; - ffree(plainText); - return result; -} - -- (unsigned)keyBitsize { - return feeDESKeySize(_priv); -} - -@end diff --git a/OSX/include/security_cryptkit/NSFEEPublicKey.h b/OSX/include/security_cryptkit/NSFEEPublicKey.h deleted file mode 100644 index 42377a28..00000000 --- a/OSX/include/security_cryptkit/NSFEEPublicKey.h +++ /dev/null @@ -1,74 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSFEEPublicKey.h - * - * Revision History - * ---------------- - * 27 Feb 1997 at Apple - * Broke out from NSCryptors.h. - */ - -#import - -@interface NSFEEPublicKey : NSObject - { -@private - void *_pubKey; -} - -+ keyWithPrivateData:(NSData *)private - depth:(unsigned)depth // depth is in range 0-23 - usageName:(NSString *)uname; - // able to encrypt/decrypt data - // able to create/verify digital signatures - -+ keyWithPublicKeyString:(NSString *)hexstr; - // able to encrypt data - // able to verify digital signatures - -/* - * Create new key with curve parameters matching existing oldKey. - */ -+ keyWithPrivateData:(NSData *)passwd - andKey:(NSFEEPublicKey *)oldKey - usageName:(NSString *)uname; - -/* - * Convenience methods. The first three use the default depth - * (FEE_DEPTH_DEFAULT). - */ -+ keyWithPrivateData:(NSData *)passwd - usageName:(NSString *)uname; -+ keyWithPrivateString:(NSString *)private - usageName:(NSString *)uname; -+ keyWithPrivateString:(NSString *)private - andKey:(NSFEEPublicKey *)oldKey - usageName:(NSString *)uname; - -+ keyWithPrivateString:(NSString *)private - depth:(unsigned)depth - usageName:(NSString *)uname; - -/* - * NSCryptor protocol - */ -- (NSData *)encryptData:(NSData *)data; // done with public knowledge -- (NSData *)decryptData:(NSData *)data; // done with private knowledge - -/* - * NSDigitalSignature protocol - */ -- (NSData *)digitalSignatureForData:(NSData *)data; - // data is hashed with MD5 and then signed with private knowledge -- (BOOL)isValidDigitalSignature:(NSData *)sig forData:(NSData *)data; - // data is hashed with MD5 and then verified with public knowledge - -@end diff --git a/OSX/include/security_cryptkit/NSFEEPublicKey.m b/OSX/include/security_cryptkit/NSFEEPublicKey.m deleted file mode 100644 index 034af79d..00000000 --- a/OSX/include/security_cryptkit/NSFEEPublicKey.m +++ /dev/null @@ -1,496 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSFEEPublicKey.m - NSFEEPublicKey class implementation - * - * Revision History - * ---------------- - * 17 Jul 97 at Apple - * Added ECDSA signature routines. - * 21 Aug 96 at NeXT - * Modified to use C-only FeePublicKey module. - * ???? 1994 Blaine Garst at NeXT - * Created. - */ - -#import -#import - -#import "NSCryptors.h" -#import "NSFEEPublicKeyPrivate.h" -#import "feePublicKey.h" -#import "feePublicKeyPrivate.h" -#import "ckutilities.h" -#import "mutils.h" -#import "feeTypes.h" -#import "curveParams.h" -#import "falloc.h" -#import "feeDigitalSignature.h" -#import "feeHash.h" -#import "feeFunctions.h" -#import "feeFEEDExp.h" - -/* - Elliptic curve algebra over finite fields F(p**k), where p = 2**q -1 is a - Mersenne prime. - q is bit-depth. - A private key (a) is a large integer that when multiplied by an initial - curve point P yields the public key aP. - Public keys can be used to generate one-time pads because multiplication - is commutative: - - a(bP) == b(aP) - */ - -@implementation NSFEEPublicKey - -/* - * Root method to create new public key from private "password" data. - */ -+ keyWithPrivateData:(NSData *)passwd - depth:(unsigned)depth - usageName:(NSString *)uname -{ - NSFEEPublicKey *result; - feeReturn frtn; - unichar *uc; - - result = [[self alloc] autorelease]; - result->_pubKey = feePubKeyAlloc(); - uc = fmalloc([uname length] * sizeof(unichar)); - [uname getCharacters:uc]; - frtn = feePubKeyInitFromPrivData(result->_pubKey, - [passwd bytes], [passwd length], - uc, [uname length], - depth); - ffree(uc); - if(frtn) { - NSLog(@"keyWithPrivateData: %s\n", feeReturnString(frtn)); - return nil; - } - return result; -} - -/* - * Create new key with curve parameters matching existing oldKey. - */ -+ keyWithPrivateData:(NSData *)passwd - andKey:(NSFEEPublicKey *)oldKey - usageName:(NSString *)uname -{ - NSFEEPublicKey *result; - feeReturn frtn; - unichar *uc; - - result = [[self alloc] autorelease]; - result->_pubKey = feePubKeyAlloc(); - uc = fmalloc([uname length] * sizeof(unichar)); - [uname getCharacters:uc]; - frtn = feePubKeyInitFromKey(result->_pubKey, - [passwd bytes], [passwd length], - uc, [uname length], - oldKey->_pubKey); - ffree(uc); - if(frtn) { - NSLog(@"keyWithPrivateData:andKey: %s\n", - feeReturnString(frtn)); - return nil; - } - return result; -} - -+ keyWithPrivateData:(NSData *)passwd - usageName:(NSString *)uname -{ - // 4 gives 127 bits of protection - // although the RSA challenge number of 127 bits has been - // broken, FEE is much stronger at the same length - return [self keyWithPrivateData:passwd - depth:FEE_DEPTH_DEFAULT - usageName:uname]; -} - -/* - * The standard way of creating a new key given a private "password" string. - */ -+ keyWithPrivateString:(NSString *)private - usageName:(NSString *)uname -{ - NSData *pdata; - id result; - - /* - * FIXME - handle other encodings? - */ - pdata = [private dataUsingEncoding:NSUTF8StringEncoding]; - result = [self keyWithPrivateData:pdata usageName:uname]; - return result; -} - -+ keyWithPrivateString:(NSString *)private - andKey:(NSFEEPublicKey *)oldKey - usageName:(NSString *)uname -{ - NSData *pdata; - id result; - - if (!uname) return nil; - - pdata = [private dataUsingEncoding:NSUTF8StringEncoding]; - result = [self keyWithPrivateData:pdata andKey:oldKey usageName:uname]; - return result; -} - -+ keyWithPrivateString:(NSString *)private - depth:(unsigned)depth - usageName:(NSString *)uname -{ - NSData *pdata; - id result; - - if (!uname) return nil; - - pdata = [private dataUsingEncoding:NSUTF8StringEncoding]; - result = [self keyWithPrivateData:pdata depth:depth usageName:uname]; - return result; -} - -/* - * The standard way of creating a new key given a public key string. - */ -+ keyWithPublicKeyString:(NSString *)hexstr -{ - NSFEEPublicKey *result; - feeReturn frtn; - NSStringEncoding defEndoding; - const char *s; - - /* - * Protect against gross errors in the key string formatting... - */ - defEndoding = [NSString defaultCStringEncoding]; - if([hexstr canBeConvertedToEncoding:defEndoding] == NO) { - NSLog(@"NSFEEPublicKey: Bad Public Key String Format (1)\n"); - return nil; - } - - /* - * FIXME - docs say this string is "autoreleased". How is a cString - * autoreleased? - */ - s = [hexstr cString]; - result = [[self alloc] autorelease]; - result->_pubKey = feePubKeyAlloc(); - - frtn = feePubKeyInitFromKeyString(result->_pubKey, - s, strlen(s)); - if(frtn) { - NSLog(@"keyWithPublicKeyString:andKey: %s\n", - feeReturnString(frtn)); - return nil; - } - return result; -} - -- (void)dealloc -{ - if(_pubKey) { - feePubKeyFree(_pubKey); - } - [super dealloc]; -} - -/* - * Create a public key in the form of a string. This string contains an - * encoded version of all of our ivars except for _private. - * - * See KeyStringFormat.doc for info on the format of the public key string; - * PLEASE UPDATE THIS DOCUMENT WHEN YOU MAKE CHANGES TO THE STRING FORMAT. - */ -- (NSString *)publicKeyString -{ - char *keyStr; - unsigned keyStrLen; - feeReturn frtn; - NSString *result; - - if(_pubKey == NULL) { - return nil; - } - frtn = feePubKeyCreateKeyString(_pubKey, &keyStr, &keyStrLen); - if(frtn) { - NSLog(@"publicKeyString: %s\n", - feeReturnString(frtn)); - return nil; - } - result = [NSString stringWithCString:keyStr]; - ffree((void *)keyStr); - return result; -} - -- (BOOL)isEqual:(NSFEEPublicKey *)other -{ - if((other == nil) || (other->_pubKey == NULL) || (_pubKey == NULL)) { - return NO; - } - if(feePubKeyIsEqual(_pubKey, other->_pubKey)) { - return YES; - } - else { - return NO; - } -} - -- (unsigned)keyBitsize -{ - if(_pubKey == NULL) { - return 0; - } - return feePubKeyBitsize(_pubKey); -} - -- (NSString *)algorithmName -{ - return [NSString stringWithCString:feePubKeyAlgorithmName()]; -} - -- (NSString *)usageName -{ - unsigned unameLen; - const feeUnichar *uname; - NSString *result; - - if(_pubKey == NULL) { - return nil; - } - uname = feePubKeyUsageName(_pubKey, &unameLen); - result = [NSString stringWithCharacters:uname length:unameLen]; - return result; -} - -- (NSString *)signer -{ - return [self usageName]; -} - -- (NSData *)padWithPublicKey:(id )otherKey -{ - NSFEEPublicKey *other; - NSMutableData *result; - feeReturn frtn; - unsigned char *padData; - unsigned padDataLen; - - if(_pubKey == NULL) { - return nil; - } - if (![otherKey isMemberOfClass:isa]) { - return nil; - } - other = otherKey; - if(other->_pubKey == NULL) { - return nil; - } - frtn = feePubKeyCreatePad(_pubKey, - other->_pubKey, - &padData, - &padDataLen); - if(frtn) { - NSLog(@"padWithPublicKey: %s\n", feeReturnString(frtn)); - return nil; - } - result = [NSData dataWithBytesNoCopy:padData length:padDataLen]; - return result; -} - -- (NSData *)encryptData:(NSData *)data -{ - feeFEEDExp feed; - NSData *result; - feeReturn frtn; - unsigned char *ctext; - unsigned ctextLen; - - if(_pubKey == NULL) { - return nil; - } - feed = feeFEEDExpNewWithPubKey(_pubKey); - frtn = feeFEEDExpEncrypt(feed, - [data bytes], - [data length], - &ctext, - &ctextLen); - if(frtn == FR_Success) { - result = [NSData dataWithBytesNoCopy:ctext length:ctextLen]; - } - else { - NSLog(@"feeFEEDEncrypt: %s\n", feeReturnString(frtn)); - result = nil; - } - feeFEEDExpFree(feed); - return result; -} - -- (NSData *)decryptData:(NSData *)data -{ - feeFEEDExp feed; - NSData *result; - feeReturn frtn; - unsigned char *ptext; - unsigned ptextLen; - - if(_pubKey == NULL) { - return nil; - } - feed = feeFEEDExpNewWithPubKey(_pubKey); - frtn = feeFEEDExpDecrypt(feed, - [data bytes], - [data length], - &ptext, - &ptextLen); - if(frtn == FR_Success) { - result = [NSData dataWithBytesNoCopy:ptext length:ptextLen]; - } - else { - NSLog(@"feeFEEDDecrypt: %s\n", feeReturnString(frtn)); - result = nil; - } - feeFEEDExpFree(feed); - return result; -} - -/* - * When 1, we use ECDSA unless we're using a depth which does not - * have curve orders. - * WARNING - enabling ECDSA by default breaks ICE and compatibility - * with Java signatures, at least until we have a Java ECDSA - * implementation. - */ -#define ECDSA_SIG_DEFAULT 0 - -- (NSData *)digitalSignatureForData:(NSData *)data -{ - NSData *result; - unsigned char *sig; - unsigned sigLen; - feeReturn frtn; - curveParams *cp; - - if(_pubKey == NULL) { - return nil; - } - cp = feePubKeyCurveParams(_pubKey); - if(!ECDSA_SIG_DEFAULT || isZero(cp->x1OrderPlus)) { - frtn = feePubKeyCreateSignature(_pubKey, - [data bytes], - [data length], - &sig, - &sigLen); - } - else { - frtn = feePubKeyCreateECDSASignature(_pubKey, - [data bytes], - [data length], - &sig, - &sigLen); - } - if(frtn) { - NSLog(@"digitalSignatureForData: %s\n", feeReturnString(frtn)); - return nil; - } - result = [NSData dataWithBytesNoCopy:sig length:sigLen]; - return result; -} - -- (BOOL)isValidDigitalSignature:(NSData *)signa - forData:(NSData *)data -{ - feeReturn frtn; - feeUnichar *sigSigner; - unsigned sigSignerLen; - curveParams *cp; - - if(_pubKey == NULL) { - return NO; - } - cp = feePubKeyCurveParams(_pubKey); - if(!ECDSA_SIG_DEFAULT || isZero(cp->x1OrderPlus)) { - frtn = feePubKeyVerifySignature(_pubKey, - [data bytes], - [data length], - [signa bytes], - [signa length], - &sigSigner, - &sigSignerLen); - } - else { - frtn = feePubKeyVerifyECDSASignature(_pubKey, - [data bytes], - [data length], - [signa bytes], - [signa length], - &sigSigner, - &sigSignerLen); - } - - /* - * FIXME - We just throw away the signer for now... - */ - if(sigSignerLen) { - ffree(sigSigner); - } - - switch(frtn) { - case FR_Success: - return YES; - case FR_InvalidSignature: - return NO; - default: - /* - * Something other than simple signature mismatch... - */ - NSLog(@"isValidDigitalSignature: %s\n", feeReturnString(frtn)); - return NO; - } -} - -@end - -@implementation NSFEEPublicKey(Private) - -- (key)minus -{ - if(_pubKey == NULL) { - return NULL; - } - return feePubKeyMinusCurve(_pubKey); -} - -- (key)plus -{ - if(_pubKey == NULL) { - return NULL; - } - return feePubKeyPlusCurve(_pubKey); -} - -- (feePubKey)feePubKey -{ - return _pubKey; -} - -#if FEE_DEBUG -- (void)dump -{ - printPubKey(_pubKey); -} -#endif FEE_DEBUG - -@end diff --git a/OSX/include/security_cryptkit/NSFEEPublicKeyPrivate.h b/OSX/include/security_cryptkit/NSFEEPublicKeyPrivate.h deleted file mode 100644 index 37576972..00000000 --- a/OSX/include/security_cryptkit/NSFEEPublicKeyPrivate.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSFEEPublicKeyPrivate.h - * - * Revision History - * ---------------- - * 21 Aug 96 at NeXT - * Created. - */ - -#import "NSFEEPublicKey.h" -#import "elliptic.h" -#import "feeDebug.h" -#import "feePublicKey.h" - -@interface NSFEEPublicKey(Private) - -- (key)minus; -- (key)plus; -#if 0 -- (NSData *)privData; -#endif 0 -- (feePubKey)feePubKey; - -#if FEE_DEBUG -- (void)dump; -#endif FEE_DEBUG -@end diff --git a/OSX/include/security_cryptkit/NSMD5Hash.h b/OSX/include/security_cryptkit/NSMD5Hash.h deleted file mode 100644 index 1553a496..00000000 --- a/OSX/include/security_cryptkit/NSMD5Hash.h +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSMD5Hash.h - * - * Revision History - * ---------------- - * 28 Mar 97 at Apple - * Created. - */ - -#import -#import - -@interface NSMD5Hash : NSObject - -{ - void *_priv; -} - -+ digester; // provides a concrete digester -- init; // reusable -- (void)digestData:(NSData *)data; -- (NSData *)messageDigest; // provide digest; re-init -- (NSData *)digestData:(NSData *)data withSalt:(NSData *)salt; - -@end diff --git a/OSX/include/security_cryptkit/NSMD5Hash.m b/OSX/include/security_cryptkit/NSMD5Hash.m deleted file mode 100644 index 8e372be7..00000000 --- a/OSX/include/security_cryptkit/NSMD5Hash.m +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSMD5Hash.h - * - * Revision History - * ---------------- - * 28 Mar 97 at Apple - * Created. - */ - -/* - * Note: our _priv ivar is actually a feeHash pointer. - */ -#import "NSCryptors.h" -#import "NSMD5Hash.h" -#import "feeHash.h" -#import "falloc.h" - -@implementation NSMD5Hash - -+ digester -{ - return [[self alloc] init]; -} - -- init -{ - if(_priv == NULL) { - _priv = feeHashAlloc(); - } - else { - feeHashReinit(_priv); - } - return self; -} - -- (void)digestData:(NSData *)data -{ - if(_priv == NULL) { - return; - } - feeHashAddData(_priv, [data bytes], [data length]); -} - -- (NSData *)messageDigest -{ - unsigned char *cp; - NSData *md; - - if(_priv == NULL) { - return nil; - } - cp = feeHashDigest(_priv); - md = [NSData dataWithBytes:cp length:feeHashDigestLen()]; - feeHashReinit(_priv); - return md; -} - -- (NSData *)digestData:(NSData *)data withSalt:(NSData *)salt -{ - if(_priv == NULL) { - return nil; - } - if(salt != nil) { - [self digestData:salt]; - } - [self digestData:data]; - return [self messageDigest]; -} - -@end diff --git a/OSX/include/security_cryptkit/NSRandomNumberGenerator.h b/OSX/include/security_cryptkit/NSRandomNumberGenerator.h deleted file mode 100644 index 1de469cd..00000000 --- a/OSX/include/security_cryptkit/NSRandomNumberGenerator.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSRandomNumberGenerator.h - * - * Revision History - * ---------------- - * 28 Mar 97 at Apple - * Simplified. - * ?? 96 Blaine Garst at NeXT - * Created. - */ - -#import - -@interface NSRandomNumberGenerator : NSObject -{ - void *_priv; -} - -- initWithSeed:(unsigned)seed; // designated initializer -- init; // we'll come up with the best seed - // we can - -- (unsigned)nextNumber; -- (unsigned)nextNumberInRange:(NSRange)range; -- (NSData *)randomDataWithLength:(unsigned)l; - -@end diff --git a/OSX/include/security_cryptkit/NSRandomNumberGenerator.m b/OSX/include/security_cryptkit/NSRandomNumberGenerator.m deleted file mode 100644 index 4d92fc55..00000000 --- a/OSX/include/security_cryptkit/NSRandomNumberGenerator.m +++ /dev/null @@ -1,83 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * NSRandomNumberGenerator.m - * - * Revision History - * ---------------- - * 28 Mar 97 at Apple - * Rewrote using feeRandom module. - * ?? 96 Blaine Garst at NeXT - * Created. - */ - -/* - * Note: out _priv ivar is actually a feeRand pointer. - */ - -#import -#import "NSRandomNumberGenerator.h" -#import "feeRandom.h" -#import "falloc.h" - -@implementation NSRandomNumberGenerator - -- init -{ - if(_priv == NULL) { - _priv = feeRandAlloc(); - } - /* - * else no need to re-init - */ - return self; -} - -- initWithSeed:(unsigned)seed -{ - if(_priv != NULL) { - /* - * Free & re-init to use new seed - */ - feeRandFree(_priv); - } - _priv = feeRandAllocWithSeed(seed); - return self; -} - -- (unsigned)nextNumber -{ - if(_priv == NULL) { - return 0; - } - return feeRandNextNum(_priv); -} - -- (unsigned)nextNumberInRange:(NSRange)range -{ - if(_priv == NULL) { - return 0; - } - return range.location + ([self nextNumber] % range.length); -} - -- (NSData *)randomDataWithLength:(unsigned)l -{ - unsigned char *cp; - - if(_priv == NULL) { - return nil; - } - cp = fmalloc(l); - feeRandBytes(_priv, cp, l); - return [NSData dataWithBytesNoCopy:cp length:l]; -} - -@end diff --git a/OSX/include/security_cryptkit/README b/OSX/include/security_cryptkit/README deleted file mode 100644 index e4b8f04a..00000000 --- a/OSX/include/security_cryptkit/README +++ /dev/null @@ -1,221 +0,0 @@ - Apple FEE Library Source, v. 1.0 - Last Update: 26 Sep 2001 - - - NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE COMPUTER, INC. AND THE - ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE COMPUTER, - INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - EXPOSE YOU TO LIABILITY. - - -This directory contains the source code for Apple's Fast Elliptic -Encryption (FEE) library. All code is written in ANSI C. A UNIX -Makefile is provided. - -Note that all source files in this directory are best viewed with an -editor configured for 8-space tabs, a fixed pitch font, and a window -of at least 80 characters in width. - - -Public Header Files -------------------- - -These files contain the public API used by clients of the FEE library. - - Crypt.h - ------- - A top-level header which includes all of the other public headers. - Typically a client application will only include this file. - - feeTypes.h - ---------- - Common #defines and typedefs used throughout the library. - - feePublicKey.h - -------------- - Functions for generating and manipulating FEE public and private keys, - performing key exchange, and high-level digital signature operations. - - feeDigitalSignature.h - --------------------- - Low-level primitives for performing ElGamal digital signature - operations. Not normally used by clients; high-level functions - for performing signature operations are provided in feePublicKey.h. - - feeECDSA.h - ---------- - Low-level primitives for performing ECDSA digital signature operations. - Not normally used by clients; high-level functions for performing - signature operations are provided in feePublicKey.h. - - feeDES.h - -------- - DES symmetric encryption and decryption functions. - - feeHash.h - --------- - MD5 Hash functions. - - ckSHA1.h - ------ - SHA-1 hash functions. - - feeRandom.h - ----------- - Pseudo-random number generator. - - feeFunctions.h - -------------- - General-purpose C functions. - - feeFEED.h - --------- - Asymmetric encryption functions using the FEE Direct Embedding, - or FEED, algorithm. - - feeFEEDExp.h - ------------ - Asymmetric encryption functions using the Expanding FEED algorithm. - - enc64.h - ------- - Functions for performing encoding and decoding via base-64 IA5 - format, per RFC 1421. - - feeCipherFile.h - CipherFileTypes.h - ------------------ - High-level CipherFile support. Provides encapsulation of ciphertext, - digital signature, and public key strings in a portable format. - - falloc.h - -------- - Memory alloc/free routines. All memory mallocd by CryptKit and - returned to called must be freed via ffree(), declared here. - - -'C' Files ---------- - -In addition to the '.c' files associated with the abovementioned public -headers (e.g., feePublicKey.c, feeCipherFile.c), the FEE library -contains the following source files: - - giantIntegers.[ch] - -------------------- - Large-precision integer arithmetic package. - - elliptic.[ch] - ------------- - Elliptic Curve algebra, Apple "FEE" style. - - ellipticProj.[ch] - ----------------- - Elliptic Curve Algebra using projective coordinates. - - curveParams.[ch], curveParamData.h - ---------------------------------- - Elliptic curve parameters. Declarations of known curves. - - byteRep.[ch] - ------------ - Platform-independent implement implementation of portable - representation of all aggregate data types used in FEE library. - - ckutilities.[ch] - -------------- - Miscellaneous C utilities. - - feeCipherFileAtom.c - CipherFileDES.c - CipherFileFEED.c - ---------------- - CipherFile support. - - ckDES.c - ckMD5.c - ckSHA1_priv.c - ----------- - Low-level primitives for DES, MD5, SHA-1 algorithms. - - -Porting to other platforms --------------------------- - -The FEE library has been built and tested on the Macintosh platform using Metrowerks CodeWarrior, on the OpenStep OS on both the 68k and Pentium platforms, and on Windows NT (on which it was built using the Gnu gcc compiler). - -There are at least 3 files which need to be edited in order to port the -FEE library to other platforms. One is platform.c. This file has two -platform-specific functions: - - void NSGiantRaise(const char *reason); - - This function is called interally in the library in the unlikely - event of a fatal runtime error. The current versions of this - function use printf() to log the reason and call exit(1). - - unsigned createRandomSeed(); - - This function obtains a 32-bit number with which FEE's - pseudo-random number generator is seeded. The implementation - of this function is highly platform-specific and also depends - on the amount of security required from the RNG in a - particular application. Common (and simple) implementations - involve obtaining a high-precision system clock, process - ID values. etc. - - Note that this function is called during a call to feeRandAlloc() - in feeRandom.c. Clients of the FEE library can also avoid this - mechanism by instantiating the RNG via feeRandAllocWithSeed(), - passing in an application-specific seed. - -The file platform.h contains a definition for the endianness of the -current platform. Either __BIG_ENDIAN__ or __LITTLE_ENDIAN__ must -be #defined at compile time. If your compiler does not implicitly -define one of these symbols, edit platform.h appropriately. - -Another file which may be modified during a port is falloc.c. All -memory allocation calls in the library are performed via fmalloc() and -ffree() in falloc.c. The current implementation of falloc.c merely -passes these calls on to the standard malloc() and free(). A port to -another platform may require the use of different memory allocators. - -The giantIntegers module, which implements large integer arithmetic, -allows for specification of platform-dependent digit size. In addition, -provisions are made for implementation of platform-dependent routines -to perform low-level digit arithmetic (single and double precision add, -subtract with carry, double precision multiply, multiply an array -of digits by another digit). The current library contains assembly -languange macros for the Intel and PPC platforms. The specification of -the size of a giant digit, type giantDigit, is found in giantIntegers.h. -The files which use low-level platform-dependent giant arithmentic -include giantPortCommon.h, which select one of several possible header -files. The header giantPortGeneric.h can be specified; this has -no assembly language, but implements the necessary functions using -the C "unsigned long long" type and static lines functions. The API for -the low-level digit functions is the same in all three of the following -files: - - giantPortGeneric.h - giantPort_i486.h - giantPort_PPC.h - -Currently, the implementation of the PPC-specific giant digit routines -is in giantPort_PPC.c; the implementation of the Intels-specific giant -routines is found in both giantPort_i486.h and giantPort_i486.s. - -Building the library --------------------- - -This directory contains a UNIX Makefile. Just type 'make' in the current -(writable) directory to build the library. The result is libFEE.a. - - - Copyright (c) 1998 Apple Inc. All rights reserved. - -Apple and Macintosh are trademarks of Apple Computer, Inc., registered -in the U.S.A. and other countries. OpenStep is a trademark of NeXT -Software, Inc. registered in the U.S.A. and other countries. All other -trademarks are the property of their respective owners. diff --git a/OSX/include/security_cryptkit/TOP_README b/OSX/include/security_cryptkit/TOP_README deleted file mode 100644 index b177be81..00000000 --- a/OSX/include/security_cryptkit/TOP_README +++ /dev/null @@ -1,30 +0,0 @@ - Apple FEE Library Source, v. 1.0 - Last Update: 28 Jan 1998 - - - NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE COMPUTER, INC. AND THE - ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE COMPUTER, - INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - EXPOSE YOU TO LIABILITY. - -This directory contains two subdirecories. One, CryptKit, contains the -source code for the Apple Fast Elliptic Encryption (FEE) library. The -other directory, Examples, contains a number of programs which illustrate -the use of the FEE library. All code is written in ANSI C; UNIX Makefiles -are provided for each directory. See the README files in the respective -directories for information on the contents of specific files, porting -issues, and so forth. - -Note that all source files in these directories are best viewed with an -editor configured for 8-space tabs, a fixed pitch font, and a window -of at least 80 characters in width. - - - Copyright (c) 1998 Apple Inc. All rights reserved. - -Apple and Macintosh are trademarks of Apple Computer, Inc., registered -in the U.S.A. and other countries. OpenStep is a trademark of NeXT -Software, Inc. registered in the U.S.A. and other countries. All other -trademarks are the property of their respective owners. diff --git a/OSX/include/security_cryptkit/buildSrcTree b/OSX/include/security_cryptkit/buildSrcTree deleted file mode 100644 index b4a1c999..00000000 --- a/OSX/include/security_cryptkit/buildSrcTree +++ /dev/null @@ -1,34 +0,0 @@ -#! /bin/csh -f -# -# Build "outside release" version of CryptKit source tree. Places -# source in $argv[1]/CryptKit. -# -if ( $#argv < 1 ) then - echo Usage: buildSrcTree target_dir - exit(1) -endif -# -set TARGDIR=CryptKit -# -set CFILES="CipherFileDES.c CipherFileFEED.c ckDES.c ckMD5.c elliptic.c giantIntegers.c ckSHA1.c ckSHA1_priv.c byteRep.c curveParams.c enc64.c falloc.c feeCipherFile.c feeCipherFileAtom.c feeDES.c feeDigitalSignature.c feeECDSA.c feeFEED.c feeFEEDExp.c feeHash.c feePublicKey.c feeRandom.c platform.c ckutilities.c giantPort_PPC.c ellipticProj.c" -# -set HFILES="CipherFileDES.h CipherFileFEED.h CipherFileTypes.h Crypt.h ckDES.h ECDSA_Profile.h ckMD5.h elliptic.h giantIntegers.h ckSHA1.h ckSHA1_priv.h byteRep.h ckconfig.h curveParams.h curveParamData.h ellipticMeasure.h enc64.h falloc.h feeCipherFile.h feeDES.h feeDebug.h feeDigitalSignature.h feeECDSA.h feeFEED.h feeFEEDExp.h feeFunctions.h feeHash.h feePublicKey.h feePublicKeyPrivate.h feeRandom.h feeTypes.h platform.h ckutilities.h giantPortCommon.h giantPort_Generic.h giantPort_PPC_Gnu.h giantPort_PPC.h giantPort_i486.h ellipticProj.h" -# -set SFILES="giantPort_i486.s giantPort_PPC_Gnu.s" -set OTHERFILES="README" -# -set MAKEFILE_SRC=unixMakefile -set MAKEFILE_DEST=Makefile -set TOP_README_SRC=TOP_README -set TOP_README_DST=README -# -set DSTROOT=$argv[1] -set DSTDIR=${DSTROOT}/${TARGDIR} -mkdir -p ${DSTDIR} || exit(1) -# -cp -p ${CFILES} ${HFILES} ${SFILES} ${OTHERFILES} ${DSTDIR} || exit(1) -# -# These files get renamed... -# -cp -p ${MAKEFILE_SRC} ${DSTDIR}/${MAKEFILE_DEST} || exit(1) -cp -p ${TOP_README_SRC} ${DSTROOT}/${TOP_README_DST} diff --git a/OSX/include/security_cryptkit/byteRep.c b/OSX/include/security_cryptkit/byteRep.c deleted file mode 100644 index f24f6d80..00000000 --- a/OSX/include/security_cryptkit/byteRep.c +++ /dev/null @@ -1,476 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * byteRep.c - FEE portable byte representation support - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 18 Apr 98 at Apple - * Mods for variable size giantDigit. - * 20 Jan 98 at Apple - * Added curve param fields for CURVE_PARAM_VERSION 2. - * 17 Jul 97 at Apple - * Added signature routines. - * 9 Jan 97 at NeXT - * Split off from utilities.c - */ - -#include "byteRep.h" -#include "feeTypes.h" -#include "curveParams.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "falloc.h" -#include "ckutilities.h" -#include "feeDebug.h" -#include - -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ - -/* - * Support for portable bytestream representation of keys and signatures. - * Platform and endianness independent; format shared with JavaFEE - * implementation. - */ - -/* - * Some handy macros. - */ -#define ENC_BYTE(n, b, bytes) \ - *b++ = n; \ - bytes++; - -#define ENC_INT(n, b, bytes, i) \ - i = intToByteRep(n, b); \ - bytes += i; \ - b += i; - -#define ENC_GIANT(g, b, bytes, i) \ - i = giantToByteRep(g, b); \ - bytes += i; \ - b += i; - -#define DEC_BYTE(n, b, blen, bytes) \ - n = *b++; \ - bytes++; \ - blen--; - -#define DEC_INT(n, b, blen, bytes) \ - n = byteRepToInt(b); \ - b += sizeof(int); \ - bytes += sizeof(int); \ - blen -= gLen; - -#define DEC_GIANT(g, b, blen, glen, bytes, out) \ - g = byteRepToGiant(b, blen, &glen); \ - if(g == NULL) { \ - goto out; \ - } \ - b += glen; \ - bytes += glen; \ - blen -= gLen; - - - - -/* - * The routines which convert various types to byte reps return the number - * of bytes written to the output stream. - */ -int intToByteRep(int i, unsigned char *buf) -{ - *buf++ = (unsigned char)((i >> 24) & 0xff); - *buf++ = (unsigned char)((i >> 16) & 0xff); - *buf++ = (unsigned char)((i >> 8) & 0xff); - *buf = (unsigned char)(i & 0xff); - return 4; -} - -int shortToByteRep(short s, unsigned char *buf) -{ - *buf++ = (unsigned char)((s >> 8) & 0xff); - *buf = (unsigned char)(s & 0xff); - return 2; -} - -/* - * 7 Apr 1998 : leading int is now the number of bytes in the giant's - * giantDigits array. This value is signed. - */ -int giantToByteRep(giant g, unsigned char *buf) -{ - int numBytes = g->sign * GIANT_BYTES_PER_DIGIT; - unsigned aNumBytes = abs(numBytes); - - CKASSERT(g != NULL); - intToByteRep(numBytes, buf); - buf += sizeof(int); - serializeGiant(g, buf, aNumBytes); - return (sizeof(int) + aNumBytes); -} - -int keyToByteRep(key k, unsigned char *buf) -{ - int numBytes = 0; - int i; - - CKASSERT(k != NULL); - ENC_GIANT(k->x, buf, numBytes, i); - - /* only write y for plus curve */ - if(k->twist == CURVE_PLUS) { - CKASSERT(k->y != NULL); - ENC_GIANT(k->y, buf, numBytes, i); - } - return numBytes; -} - -#define CURVE_PARAM_VERSION 3 -#define CURVE_PARAM_VERSION_MIN 3 - -int curveParamsToByteRep(curveParams *cp, unsigned char *buf) -{ - int numBytes = 0; - int i; - - CKASSERT(cp != NULL); - ENC_INT(CURVE_PARAM_VERSION, buf, numBytes, i); - ENC_INT(CURVE_PARAM_VERSION_MIN, buf, numBytes, i); - ENC_BYTE(cp->primeType, buf, numBytes); - ENC_BYTE(cp->curveType, buf, numBytes); - ENC_INT(cp->q, buf, numBytes, i); - ENC_INT(cp->k, buf, numBytes, i); - ENC_INT(cp->m, buf, numBytes, i); - ENC_INT(0, buf, numBytes, i); // spare - - ENC_GIANT(cp->a, buf, numBytes, i); - ENC_GIANT(cp->b, buf, numBytes, i); - ENC_GIANT(cp->c, buf, numBytes, i); - ENC_GIANT(cp->x1Plus, buf, numBytes, i); - ENC_GIANT(cp->x1Minus, buf, numBytes, i); - ENC_GIANT(cp->cOrderPlus, buf, numBytes, i); - ENC_GIANT(cp->cOrderMinus, buf, numBytes, i); - ENC_GIANT(cp->x1OrderPlus, buf, numBytes, i); - ENC_GIANT(cp->x1OrderMinus, buf, numBytes, i); - if(cp->primeType == FPT_General) { - ENC_GIANT(cp->basePrime, buf, numBytes, i); - } - return numBytes; -} - -int sigToByteRep(int magic, - int version, - int minVersion, - giant g0, - giant g1, - unsigned char *buf) -{ - int numBytes = 0; - int i; - - ENC_INT(magic, buf, numBytes, i); - ENC_INT(version, buf, numBytes, i); - ENC_INT(minVersion, buf, numBytes, i); - ENC_INT(0, buf, numBytes, i); // spare - ENC_GIANT(g0, buf, numBytes, i); - ENC_GIANT(g1, buf, numBytes, i); - - return numBytes; -} - - -/* - * return the size of various data types' byte representations. - */ -int lengthOfByteRepGiant(giant g) -{ - CKASSERT(g != NULL); - return sizeof(int) + (GIANT_BYTES_PER_DIGIT * abs(g->sign)); -} - -int lengthOfByteRepKey(key k) -{ - int len = lengthOfByteRepGiant(k->x); - - CKASSERT(k != NULL); - if(k->twist == CURVE_PLUS) { - CKASSERT(k->y != NULL); - len += lengthOfByteRepGiant(k->y); - } - return len; -} - -int lengthOfByteRepCurveParams(curveParams *cp) -{ - int length; - - CKASSERT(cp != NULL); - length = (6 * sizeof(int)) + // ver, minVers, q, k, m, spare - 2 + // primeType + curveType - lengthOfByteRepGiant(cp->a) + - lengthOfByteRepGiant(cp->b) + - lengthOfByteRepGiant(cp->c) + - lengthOfByteRepGiant(cp->x1Plus) + - lengthOfByteRepGiant(cp->x1Minus) + - lengthOfByteRepGiant(cp->cOrderPlus) + - lengthOfByteRepGiant(cp->cOrderMinus) + - lengthOfByteRepGiant(cp->x1OrderPlus) + - lengthOfByteRepGiant(cp->x1OrderMinus); - if(cp->primeType == FPT_General) { - length += lengthOfByteRepGiant(cp->basePrime); - } - return length; -} - -int lengthOfByteRepSig(giant g0, - giant g1) -{ - int length = (4 * sizeof(int)) + // magic, version, minVersion, - // spare - lengthOfByteRepGiant(g0) + - lengthOfByteRepGiant(g1); - return length; -} - -/* - * Routine to cons up various types from a byte rep stream. - */ -int byteRepToInt(const unsigned char *buf) { - int result; - - result = (((int)buf[0] << 24) & 0xff000000) | - (((int)buf[1] << 16) & 0x00ff0000) | - (((int)buf[2] << 8) & 0xff00) | - (((int)buf[3]) & 0xff); - return result; -} - -unsigned short byteRepToShort(const unsigned char *buf) { - unsigned short result; - - result = (((unsigned short)buf[0] << 8) & 0xff00) | - (((unsigned short)buf[1]) & 0xff); - return result; -} - -/* - * Probably need byteRepToShortArray... - */ - -/* - * byte rep stream to giant. Returns NULL on error; returns number of bytes - * of *buf snarfed in *giantLen if successful. - * - * 7 Apr 1998 : leading int is now the number of bytes in the giant's - * giantDigits array. This value is signed. - */ -giant byteRepToGiant(const unsigned char *buf, - unsigned bufLen, - unsigned *giantLen) -{ - giant g; - int numDigits; - int numBytes; // signed! - unsigned aNumBytes; - - if(bufLen < sizeof(int)) { - return (giant)NULL; - } - numBytes = byteRepToInt(buf); - aNumBytes = abs(numBytes); - numDigits = BYTES_TO_GIANT_DIGITS(aNumBytes); - buf += sizeof(int); - bufLen -= sizeof(int); - if(numDigits > MAX_DIGITS) { - return (giant)NULL; - } - - if(bufLen < aNumBytes) { - return (giant)NULL; - } - - /* 9 Apr 1998 - sign = 0 means no following n[] bytes in the - * byteRep. We do need to alloc one digit, in this case, though... - * Note that the giantstruct has one implicit digit in n[]. - */ - if(aNumBytes == 0) { - g = (giant)fmalloc(sizeof(giantstruct)); - g->capacity = 1; - } - else { - g = (giant)fmalloc(sizeof(giantstruct) + - aNumBytes - GIANT_BYTES_PER_DIGIT); - g->capacity = numDigits; - } - deserializeGiant(buf, g, aNumBytes); - - /* deserializeGiant always cooks up positive giant; sign is - * properly trimmed to handle trailing (M.S.) zeroes. */ - if(numBytes < 0) { - g->sign = -g->sign; - } - *giantLen = sizeof(int) + aNumBytes; - return g; - -} - -/* - * Convert a byte stream (and some other parameters) into a - * keystruct. - * Returns NULL on error; returns number of bytes of *buf snarfed in - * *keyLen if successful. - */ -key byteRepToKey(const unsigned char *buf, - unsigned bufLen, - int twist, - curveParams *cp, - unsigned *keyLen) // returned -{ - key k; - giant x; - giant y; - unsigned gLen; - unsigned totalLen; - - x = byteRepToGiant(buf, bufLen, &gLen); - if(x == NULL) { - return NULL; - } - bufLen -= gLen; - buf += gLen; - totalLen = gLen; - if(twist == CURVE_PLUS) { - /* this also contains y */ - y = byteRepToGiant(buf, bufLen, &gLen); - if(y == NULL) { - freeGiant(x); - return NULL; - } - totalLen += gLen; - } - else { - /* minus curve, y is not used */ - y = newGiant(1); - int_to_giant(0, y); - } - k = (key)fmalloc(sizeof(keystruct)); - k->twist = twist; - k->cp = cp; - k->x = x; - k->y = y; - *keyLen = totalLen; - return k; -} - -curveParams *byteRepToCurveParams(const unsigned char *buf, - unsigned bufLen, - unsigned *cpLen) -{ - curveParams *cp; - unsigned gLen = 0; - int version; - int minVersion; - int spare; - int bytes = 0; - - if(bufLen < (5 * sizeof(int))) { // ver, minVers, q, k, spare - return NULL; - } - cp = newCurveParams(); - - DEC_INT(version, buf, bufLen, bytes); - DEC_INT(minVersion, buf, bufLen, bytes); - if(minVersion > CURVE_PARAM_VERSION) { - /* - * Can't parse this; things have changed too much between - * this version of the code and the time this curveParams - * was written. - */ - goto abort; - } - - DEC_BYTE(cp->primeType, buf, bufLen, bytes); - DEC_BYTE(cp->curveType, buf, bufLen, bytes); - DEC_INT(cp->q, buf, bufLen, bytes); - DEC_INT(cp->k, buf, bufLen, bytes); - DEC_INT(cp->m, buf, bufLen, bytes); - DEC_INT(spare, buf, bufLen, bytes); - - DEC_GIANT(cp->a, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->b, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->c, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->x1Plus, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->x1Minus, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->cOrderPlus, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->cOrderMinus, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->x1OrderPlus, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(cp->x1OrderMinus, buf, bufLen, gLen, bytes, abort); - - /* - * basePrime only present in byte rep for PT_GENERAL - */ - if(cp->primeType == FPT_General) { - DEC_GIANT(cp->basePrime, buf, bufLen, gLen, bytes, abort); - } - - /* remaining fields inferred */ - curveParamsInferFields(cp); - allocRecipGiants(cp); - - *cpLen = bytes; - return cp; - -abort: - freeCurveParams(cp); - return NULL; -} - -/* - * Returns 0 if bad format, e.g., if minVersion of sig is > than codeVersion. - */ -int byteRepToSig(const unsigned char *buf, - unsigned bufLen, - int codeVersion, - int *sigMagic, // RETURNED - int *sigVersion, // RETURNED - int *sigMinVersion, // RETURNED - giant *g0, // alloc'd & RETURNED - giant *g1) // alloc'd & RETURNED -{ - unsigned gLen = 0; - int spare; - int bytes = 0; - - if(bufLen < (4 * sizeof(int))) { // magic, version, minVersion, - // spare - return 0; - } - DEC_INT(*sigMagic, buf, bufLen, bytes); - DEC_INT(*sigVersion, buf, bufLen, bytes); - DEC_INT(*sigMinVersion, buf, bufLen, bytes); - if(*sigMinVersion > codeVersion) { - return 0; - } - DEC_INT(spare, buf, bufLen, bytes); - // deleted 2/20/01 DEC_INT(*signerLen, buf, bufLen, bytes); - // deleted 2/20/01 *signer = byteRepToUnichars(buf, *signerLen); - // deleted 2/20/01 buf += (2 * *signerLen); - // deleted 2/20/01 bufLen -= (2 * *signerLen); - DEC_GIANT(*g0, buf, bufLen, gLen, bytes, abort); - DEC_GIANT(*g1, buf, bufLen, gLen, bytes, abort); - - return 1; -abort: - return 0; -} diff --git a/OSX/include/security_cryptkit/byteRep.h b/OSX/include/security_cryptkit/byteRep.h deleted file mode 100644 index 134f0482..00000000 --- a/OSX/include/security_cryptkit/byteRep.h +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * byteRep.h - FEE portable byte representation support - * - * Revision History - * ---------------- - * 17 Jul 97 at Apple - * Added signature routines. - * 9 Jan 97 at NeXT - * Split off from ckutilities.h - */ - -#ifndef _CK_BYTEREP_H_ -#define _CK_BYTEREP_H_ - -#include "feeTypes.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "curveParams.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Support for bytestream key and signature representation. - */ -int intToByteRep(int i, unsigned char *buf); -int shortToByteRep(short s, unsigned char *buf); -int giantToByteRep(giant g, unsigned char *buf); -int keyToByteRep(key k, unsigned char *buf); -int curveParamsToByteRep(curveParams *cp, unsigned char *buf); -int sigToByteRep(int magic, - int version, - int minVersion, - giant g0, - giant g1, - unsigned char *buf); - -int lengthOfByteRepGiant(giant g); -int lengthOfByteRepKey(key k); -int lengthOfByteRepCurveParams(curveParams *cp); -int lengthOfByteRepSig(giant g0, - giant g1); - -int byteRepToInt(const unsigned char *buf); -unsigned short byteRepToShort(const unsigned char *buf); -giant byteRepToGiant(const unsigned char *buf, - unsigned bufLen, - unsigned *giantLen); -key byteRepToKey(const unsigned char *buf, - unsigned bufLen, - int twist, - curveParams *cp, - unsigned *keyLen); // returned -curveParams *byteRepToCurveParams(const unsigned char *buf, - unsigned bufLen, - unsigned *cpLen); -int byteRepToSig(const unsigned char *buf, - unsigned bufLen, - int codeVersion, - int *sigMagic, // RETURNED - int *sigVersion, // RETURNED - int *sigMinVersion, // RETURNED - giant *g0, // alloc'd & RETURNED - giant *g1); // alloc'd & RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_BYTEREP_H_*/ diff --git a/OSX/include/security_cryptkit/changes b/OSX/include/security_cryptkit/changes deleted file mode 100644 index 6ca31b42..00000000 --- a/OSX/include/security_cryptkit/changes +++ /dev/null @@ -1,222 +0,0 @@ - CryptKit change log - -CryptKit-8 - -- Added prototypes for NSFEEPublicKey convenience methods to NSCryptors.h - -CryptKit-9 - * Alpha version to dreece and crandall 13 Aug 1996 - * FEE_KEY_VERSION 3, FEE_KEYSTRING_VERSION 1 - -CryptKit-10 - -- Added KeyStringFormat.doc - -- Deleted -publicKeyData, keyWithPublicKeyData (public keys now always - represented as strings) - -- Beefed up range and validity checking in: - -- hexstr_to_giant() - -- new_hexstr_from_key() - -- +keyWithPublicKeyString - -- Added check for valid_hexstr() and NULL hexstr_to_key() in - +digitalSignatureWithDataRepresentation - -- Added and enforced MAX_UNAME_LENGTH - -- added key_equal(_plus, other->_plus) to -[NSFEEPublicKey isEqual:] - -- last version with NSGiantIntegers.m, utilities.m, NSFastEllipticCurve.m - as ObjC files - -CryptKit-11 - * FEE_KEYSTRING_VERSION = 2 - FEE_KEYSTRING_VERSION_MIN = 1 - -- Major rewrite of all top-level classes; ported bulk of logic to - portable C code. ObjC API (in NSCryptors.h, NSDESCryptor.h) unchanged. - -CryptKit-12 - * Alpha version sent to REC 6 Sep 1996 and to dreece 12 Sep 96 - -- Added platform.[ch] - -- Fixed (bminBytes kludge from make_pad() - -- was iszero(); is isZero() - -- made bitlen() assertion conditional on FEE_DEBUG - -- Trimmed plainBlockSize by one byte if q mod 8 = 0 in feeFEED, - feeFEEEDExp. This is an incompatible change! But I don't think anyone - was using the last version.... - -CryptKit-22 - * Integrated into cryptdev master 31 Mar 1997 - -- New NSMD5Hash class - -- Rewrote NSDESCryptor using feeDES - -- NSDataDigester was interface, is protocol - -- Deleted digestObjectsWithKeys method from NSDataDigester - -- Deleted NSRequestConcreteImplementation from NSDESCryptor and - NSRandomNumberGenerator - -- Rewrote NSRandomNumberGenerator using feeRandom - -- Cleaned up misc. #ifdefs and stale code - -- Put DES per-instance variables in struct _desInst - -- Fixed memory leaks in feePubKeyCreateKeyString(), feeFEED.c - -- Removed ANSI C headers from Public Header; framework is now strictly - ObjC - -CryptKit-23 - * Integrated into cryptdev master 1 May 1997 - * Associated with ComDemo announcement 1 May 1997 - -- No functional changes, only debugging printfs - -CryptKit-24 - * Integrated into cryptdev master 11 June 1997 - -- Mods to build on Mac CodeWarrior - -- was #import, is #include - -- mods to platform.[ch] - -- lots of compiler warning fixes, mainly due to MW's inability to - implicitly cast unsigned char * to char * - -CryptKit-25 - * Integrated into cryptdev master 18 June 1997 - -- New divg_via_recip(), modg_via_recip(), make_recip() - -- new per-curveParams fields x1OrderPlusRecip and lesserX1OrderRecip - -- Added lesserX1OrderJustify(), x1OrderPlusJustify(), binvg_cp() - -- Added new multiple stack borrowGiant() mechanism - -- All calls to borrowGiant() and newGiant() explicitly pass needed size; - no more borrowGiant(0) - -- Deleted old (i.e., obsolete and/or debugging) code from - NSGiantIntegers.c and NSFastEllipticCurve.c - -- Added description of FEED and FEEDExp ciphertext to ByteRep.doc - -- Marked KeyStringFormat.doc as obsolete - -CryptKit-26 - -- Implemented ECDSA in feeECDSA.[ch] - -- Added binvg_orderPlus(), x1OrderPlusMod() - -- Added generic signature encode/decode to byteRep.[ch] diff --git a/OSX/include/security_cryptkit/ckDES.c b/OSX/include/security_cryptkit/ckDES.c deleted file mode 100644 index 983f59e1..00000000 --- a/OSX/include/security_cryptkit/ckDES.c +++ /dev/null @@ -1,545 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * DES.c - raw DES encryption engine - * - * Revision History - * ---------------- - * Added braces to static array definition of si[][]. - * 10/06/98 ap - * Changed to compile with C++. - * 28 May 98 at Apple - * Changed to use platform-dependent fmalloc(), ffree() - * 31 Mar 97 at Apple - * Put per-instance data in struct _desInst - * Changed setkey() to dessetkey() to avoid collision with libc version - * 21 Aug 96 at NeXT - * Broke out from NSDESCryptor.m - * 22 Feb 96 at NeXT - * Created. - */ - -#include "ckconfig.h" - -#if CRYPTKIT_SYMMETRIC_ENABLE - -#include "ckDES.h" -#include "falloc.h" -#include - -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ - -#define DES_DEBUG 0 /* enables some printfs */ - -/* Sofware DES functions - * written 12 Dec 1986 by Phil Karn, KA9Q; large sections adapted from - * the 1977 public-domain program by Jim Gillogly - */ - -#ifdef __LITTLE_ENDIAN__ -/* Byte swap a long */ -static unsigned int byteswap(unsigned int x) { - register char *cp,tmp; - - cp = (char *)&x; - tmp = cp[3]; - cp[3] = cp[0]; - cp[0] = tmp; - - tmp = cp[2]; - cp[2] = cp[1]; - cp[1] = tmp; - - return x; -} -#endif - -/* Tables defined in the Data Encryption Standard documents */ - -/* initial permutation IP */ -static const char ip[] = { - 58, 50, 42, 34, 26, 18, 10, 2, - 60, 52, 44, 36, 28, 20, 12, 4, - 62, 54, 46, 38, 30, 22, 14, 6, - 64, 56, 48, 40, 32, 24, 16, 8, - 57, 49, 41, 33, 25, 17, 9, 1, - 59, 51, 43, 35, 27, 19, 11, 3, - 61, 53, 45, 37, 29, 21, 13, 5, - 63, 55, 47, 39, 31, 23, 15, 7 -}; - -/* final permutation IP^-1 */ -static const char fp[] = { - 40, 8, 48, 16, 56, 24, 64, 32, - 39, 7, 47, 15, 55, 23, 63, 31, - 38, 6, 46, 14, 54, 22, 62, 30, - 37, 5, 45, 13, 53, 21, 61, 29, - 36, 4, 44, 12, 52, 20, 60, 28, - 35, 3, 43, 11, 51, 19, 59, 27, - 34, 2, 42, 10, 50, 18, 58, 26, - 33, 1, 41, 9, 49, 17, 57, 25 -}; - -/* expansion operation matrix - * This is for reference only; it is unused in the code - * as the f() function performs it implicitly for speed - */ -#ifdef notdef -static char ei[] = { - 32, 1, 2, 3, 4, 5, - 4, 5, 6, 7, 8, 9, - 8, 9, 10, 11, 12, 13, - 12, 13, 14, 15, 16, 17, - 16, 17, 18, 19, 20, 21, - 20, 21, 22, 23, 24, 25, - 24, 25, 26, 27, 28, 29, - 28, 29, 30, 31, 32, 1 -}; -#endif - -/* permuted choice table (key) */ -static const char pc1[] = { - 57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4 -}; - -/* number left rotations of pc1 */ -static const char totrot[] = { - 1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28 -}; - -/* permuted choice key (table) */ -static const char pc2[] = { - 14, 17, 11, 24, 1, 5, - 3, 28, 15, 6, 21, 10, - 23, 19, 12, 4, 26, 8, - 16, 7, 27, 20, 13, 2, - 41, 52, 31, 37, 47, 55, - 30, 40, 51, 45, 33, 48, - 44, 49, 39, 56, 34, 53, - 46, 42, 50, 36, 29, 32 -}; - -/* The (in)famous S-boxes */ -static const char si[8][64] = { - { - /* S1 */ - 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, - 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, - 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, - 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 - }, - { - /* S2 */ - 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, - 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, - 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, - 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 - }, - { - /* S3 */ - 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, - 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, - 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, - 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 - }, - { - /* S4 */ - 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, - 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, - 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, - 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 - }, - { - /* S5 */ - 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, - 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, - 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, - 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 - }, - { - /* S6 */ - 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, - 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, - 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, - 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 - }, - { - /* S7 */ - 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, - 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, - 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, - 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 - }, - { - /* S8 */ - 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, - 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, - 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, - 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 - } -}; - -/* 32-bit permutation function P used on the output of the S-boxes */ -static const char p32i[] = { - 16, 7, 20, 21, - 29, 12, 28, 17, - 1, 15, 23, 26, - 5, 18, 31, 10, - 2, 8, 24, 14, - 32, 27, 3, 9, - 19, 13, 30, 6, - 22, 11, 4, 25 -}; -/* End of DES-defined tables */ - -/* Lookup tables initialized once only at startup by desinit() */ -static long (*sp)[64]; /* Combined S and P boxes */ - -static char (*iperm)[16][8]; /* Initial and final permutations */ -static char (*fperm)[16][8]; - - -/* bit 0 is left-most in byte */ -static const int bytebit[] = { - 0200,0100,040,020,010,04,02,01 -}; - -static const int nibblebit[] = { - 010,04,02,01 -}; - -/* Allocate space and initialize DES lookup arrays - * mode == 0: standard Data Encryption Algorithm - * mode == 1: DEA without initial and final permutations for speed - * mode == 2: DEA without permutations and with 128-byte key (completely - * independent subkeys for each round) - */ -/* Initialize the lookup table for the combined S and P boxes */ -static void spinit() { - char pbox[32]; - int p,i,s,j,rowcol; - long val; - - /* Compute pbox, the inverse of p32i. - * This is easier to work with - */ - for(p=0;p<32;p++){ - for(i=0;i<32;i++){ - if(p32i[i]-1 == p){ - pbox[p] = i; - break; - } - } - } - for(s = 0; s < 8; s++){ /* For each S-box */ - for(i=0; i<64; i++){ /* For each possible input */ - val = 0; - /* The row number is formed from the first and last - * bits; the column number is from the middle 4 - */ - rowcol = (i & 32) | ((i & 1) ? 16 : 0) | ((i >> 1) & 0xf); - for(j=0;j<4;j++){ /* For each output bit */ - if(si[s][rowcol] & (8 >> j)){ - val |= 1L << (31 - pbox[4*s + j]); - } - } - sp[s][i] = val; - -#if DES_DEBUG - printf("sp[%d][%2d] = %08lx\n",s,i,sp[s][i]); -#endif - } - } -} - -/* initialize a perm array */ -static void perminit(char perm[16][16][8], const char p[64]) { - register int l, j, k; - int i,m; - - /* Clear the permutation array */ - for (i=0; i<16; i++) - for (j=0; j<16; j++) - for (k=0; k<8; k++) - perm[i][j][k]=0; - - for (i=0; i<16; i++) /* each input nibble position */ - for (j = 0; j < 16; j++)/* each possible input nibble */ - for (k = 0; k < 64; k++)/* each output bit position */ - { l = p[k] - 1; /* where does this bit come from*/ - if ((l >> 2) != i) /* does it come from input posn?*/ - continue; /* if not, bit k is 0 */ - if (!(j & nibblebit[l & 3])) - continue; /* any such bit in input? */ - m = k & 07; /* which bit is this in the byte*/ - perm[i][j][k>>3] |= bytebit[m]; - } -} - -int desinit(desInst dinst, int mode) { - dinst->desmode = mode; - - /* - * Remainder only has to be done once. - */ - if(sp != NULL){ - /* Already initialized */ - return 0; - } - if((sp = (long (*)[64])fmalloc(sizeof(long) * 8 * 64)) == NULL){ - return -1; - } - spinit(); - if(mode == 1 || mode == 2) /* No permutations */ - return 0; - - iperm = (char (*)[16][8])fmalloc(sizeof(char) * 16 * 16 * 8); - if(iperm == NULL){ - ffree((char *)sp); - return -1; - } - perminit(iperm,ip); - - fperm = (char (*)[16][8])fmalloc(sizeof(char) * 16 * 16 * 8); - if(fperm == NULL){ - ffree((char *)sp); - ffree((char *)iperm); - return -1; - } - perminit(fperm,fp); - - return 0; -} -/* Free up storage used by DES */ -void desdone(desInst dinst) { -#if 0 - /* - * no per-instance mallocd data - */ - if(sp == NULL) - return; /* Already done */ - - // free((char *)sp); // NO! just free instance data; leave statics - // since these are consts - ffree((char *)dinst->kn); - //if(iperm != NULL) - // free((char *)iperm); - //if(fperm != NULL) - // free((char *)fperm); - - //sp = NULL; - //iperm = NULL; - //fperm = NULL; - dinst->kn = NULL; -#endif /* 0 */ -} -/* Set key (initialize key schedule array) */ -void dessetkey(desInst dinst, char *key) { - char pc1m[56]; /* place to modify pc1 into */ - char pcr[56]; /* place to rotate pc1 into */ - register int i,j,l; - int m; - - /* In mode 2, the 128 bytes of subkey are set directly from the - * user's key, allowing him to use completely independent - * subkeys for each round. Note that the user MUST specify a - * full 128 bytes. - * - * I would like to think that this technique gives the NSA a real - * headache, but I'm not THAT naive. - */ - if(dinst->desmode == 2){ - for(i=0;i<16;i++) - for(j=0;j<8;j++) - dinst->kn[i][j] = *key++; - return; - } - /* Clear key schedule */ - for (i=0; i<16; i++) - for (j=0; j<8; j++) - dinst->kn[i][j]=0; - - for (j=0; j<56; j++) { /* convert pc1 to bits of key */ - l=pc1[j]-1; /* integer bit location */ - m = l & 07; /* find bit */ - pc1m[j]=(key[l>>3] & /* find which key byte l is in */ - bytebit[m]) /* and which bit of that byte */ - ? 1 : 0; /* and store 1-bit result */ - } - for (i=0; i<16; i++) { /* key chunk for each iteration */ - for (j=0; j<56; j++) /* rotate pc1 the right amount */ - pcr[j] = pc1m[(l=j+totrot[i])<(j<28? 28 : 56) ? l: l-28]; - /* rotate left and right halves independently */ - for (j=0; j<48; j++){ /* select bits individually */ - /* check bit that goes to dinst->kn[j] */ - if (pcr[pc2[j]-1]){ - /* mask it in if it's there */ - l= j % 6; - dinst->kn[i][j/6] |= bytebit[l] >> 2; - } - } - } -#if DES_DEBUG - for(i=0;i<16;i++) { - printf("dinst->kn[%d] = ", i); - for(j=0;j<8;j++) { - printf("%x ", dinst->kn[i][j]); - } - printf("\n"); - } - -#endif /* 1 */ -} - -/* The nonlinear function f(r,k), the heart of DES */ -static long int f(unsigned long r, unsigned char subkey[8]) { - /* 32 bits */ - /* 48-bit key for this round */ - register unsigned long rval,rt; -#if DES_DEBUG - printf("f(%08lx, %02x %02x %02x %02x %02x %02x %02x %02x) = ", - r, - subkey[0], subkey[1], subkey[2], - subkey[3], subkey[4], subkey[5], - subkey[6], subkey[7]); -#endif - /* Run E(R) ^ K through the combined S & P boxes - * This code takes advantage of a convenient regularity in - * E, namely that each group of 6 bits in E(R) feeding - * a single S-box is a contiguous segment of R. - */ - rt = (r >> 1) | ((r & 1) ? 0x80000000 : 0); - rval = 0; - rval |= sp[0][((rt >> 26) ^ *subkey++) & 0x3f]; - rval |= sp[1][((rt >> 22) ^ *subkey++) & 0x3f]; - rval |= sp[2][((rt >> 18) ^ *subkey++) & 0x3f]; - rval |= sp[3][((rt >> 14) ^ *subkey++) & 0x3f]; - rval |= sp[4][((rt >> 10) ^ *subkey++) & 0x3f]; - rval |= sp[5][((rt >> 6) ^ *subkey++) & 0x3f]; - rval |= sp[6][((rt >> 2) ^ *subkey++) & 0x3f]; - rt = (r << 1) | ((r & 0x80000000) ? 1 : 0); - rval |= sp[7][(rt ^ *subkey) & 0x3f]; -#if DES_DEBUG - printf(" %08lx\n",rval); -#endif - return rval; -} - -/* Do one DES cipher round */ -static void round(desInst dinst, int num, unsigned long int *block) { - /* i.e. the num-th one */ - - /* The rounds are numbered from 0 to 15. On even rounds - * the right half is fed to f() and the result exclusive-ORs - * the left half; on odd rounds the reverse is done. - */ - if(num & 1){ - block[1] ^= f(block[0],dinst->kn[num]); - } else { - block[0] ^= f(block[1],dinst->kn[num]); - } -} - -/* Permute inblock with perm */ -static void permute(char *inblock, char perm[16][16][8], char *outblock) { - /* result into outblock,64 bits */ - /* 2K bytes defining perm. */ - register int i,j; - register char *ib, *ob; /* ptr to input or output block */ - register char *p, *q; - - if(perm == NULL){ - /* No permutation, just copy */ - for(i=8; i!=0; i--) - *outblock++ = *inblock++; - return; - } - /* Clear output block */ - for (i=8, ob = outblock; i != 0; i--) - *ob++ = 0; - - ib = inblock; - for (j = 0; j < 16; j += 2, ib++) { /* for each input nibble */ - ob = outblock; - p = perm[j][(*ib >> 4) & 017]; - q = perm[j + 1][*ib & 017]; - for (i = 8; i != 0; i--){ /* and each output byte */ - *ob++ |= *p++ | *q++; /* OR the masks together*/ - } - } -} -/* In-place encryption of 64-bit block */ -void endes(desInst dinst, char *block) { - register int i; - unsigned long work[2]; /* Working data storage */ - long tmp; - - permute(block,iperm,(char *)work); /* Initial Permutation */ -#ifdef __LITTLE_ENDIAN__ - work[0] = byteswap(work[0]); - work[1] = byteswap(work[1]); -#endif - - /* Do the 16 rounds */ - for (i=0; i<16; i++) - round(dinst,i,work); - - /* Left/right half swap */ - tmp = work[0]; - work[0] = work[1]; - work[1] = tmp; - -#ifdef __LITTLE_ENDIAN__ - work[0] = byteswap(work[0]); - work[1] = byteswap(work[1]); -#endif - permute((char *)work,fperm,block); /* Inverse initial permutation */ -} -/* In-place decryption of 64-bit block */ -void dedes(desInst dinst, char *block) { - register int i; - unsigned long work[2]; /* Working data storage */ - long tmp; - - permute(block,iperm,(char *)work); /* Initial permutation */ - -#ifdef __LITTLE_ENDIAN__ - work[0] = byteswap(work[0]); - work[1] = byteswap(work[1]); -#endif - - /* Left/right half swap */ - tmp = work[0]; - work[0] = work[1]; - work[1] = tmp; - - /* Do the 16 rounds in reverse order */ - for (i=15; i >= 0; i--) - round(dinst,i,work); - -#ifdef __LITTLE_ENDIAN__ - work[0] = byteswap(work[0]); - work[1] = byteswap(work[1]); -#endif - - permute((char *)work,fperm,block); /* Inverse initial permutation */ -} - -#endif /* CRYPTKIT_SYMMETRIC_ENABLE */ diff --git a/OSX/include/security_cryptkit/ckDES.h b/OSX/include/security_cryptkit/ckDES.h deleted file mode 100644 index 8f1da0a2..00000000 --- a/OSX/include/security_cryptkit/ckDES.h +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * DES.h - raw DES encryption engine interface - * - * Revision History - * ---------------- - * 31 Mar 97 at Apple - * Put per-instance data in struct _desInst - * 21 Aug 96 at NeXT - * Broke out from NSDESCryptor.m - * 22 Feb 96 at NeXT - * Created. - */ - -#ifndef _CK_DES_H_ -#define _CK_DES_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_SYMMETRIC_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - -#define DES_BLOCK_SIZE_BYTES 8 /* in bytes */ -#define DES_KEY_SIZE_BITS 56 /* effective key size in bits */ -#define DES_KEY_SIZE_BITS_EXTERNAL 64 /* clients actually pass in this much */ -#define DES_KEY_SIZE_BYTES_EXTERNAL (DES_KEY_SIZE_BITS_EXTERNAL / 8) - -#define DES_MODE_STD 0 /* standard Data Encryption Algorithm */ -#define DES_MODE_FAST 1 /* DEA without initial and final */ - /* permutations for speed */ -#define DES_MODE_128 2 /* DEA without permutations and with */ - /* 128-byte key (completely independent */ - /* subkeys for each round) */ - -/* - * Per-instance data. - */ -struct _desInst { - /* 8 16-bit subkeys for each of 16 rounds, initialized by setkey() - */ - unsigned char kn[16][8]; - int desmode; -}; - -typedef struct _desInst *desInst; - -int desinit(desInst dinst, int mode); -void dessetkey(desInst dinst, char *key); -void endes(desInst dinst, char *block); -void dedes(desInst dinst, char *block); -void desdone(desInst dinst); - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_SYMMETRIC_ENABLE */ - -#endif /*_CK_DES_H_*/ diff --git a/OSX/include/security_cryptkit/ckMD5.c b/OSX/include/security_cryptkit/ckMD5.c deleted file mode 100644 index 76f61d19..00000000 --- a/OSX/include/security_cryptkit/ckMD5.c +++ /dev/null @@ -1,365 +0,0 @@ -/* - File: MD5.c - - Written by: Colin Plumb - - Copyright: Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - - Change History (most recent first): - - <7> 10/06/98 ap Changed to compile with C++. - - To Do: -*/ - -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * MD5.c - */ - -/* - * This code implements the MD5 message-digest algorithm. - * The algorithm is due to Ron Rivest. This code was - * written by Colin Plumb in 1993, no copyright is claimed. - * This code is in the public domain; do with it what you wish. - * - * Equivalent code is available from RSA Data Security, Inc. - * This code has been tested against that, and is equivalent, - * except that you don't need to include two pages of legalese - * with every copy. - * - * To compute the message digest of a chunk of bytes, declare an - * MD5Context structure, pass it to MD5Init, call MD5Update as - * needed on buffers full of bytes, and then call MD5Final, which - * will fill a supplied 16-byte array with the digest. - */ - -/* - * Revision History - * ---------------- - * 06 Feb 1997 at Apple - * Fixed endian-dependent cast in MD5Final() - * Made byteReverse() tolerant of platform-dependent alignment - * restrictions - */ - -#include "ckconfig.h" - -#if CRYPTKIT_MD5_ENABLE && !CRYPTKIT_LIBMD_DIGEST - -#include "ckMD5.h" -#include "platform.h" -#include "byteRep.h" -#include - - -#define MD5_DEBUG 0 - -#if MD5_DEBUG -static inline void dumpCtx(MD5Context *ctx, char *label) -{ - int i; - - printf("%s\n", label); - printf("buf = "); - for(i=0; i<4; i++) { - printf("%x:", ctx->buf[i]); - } - printf("\nbits: %d:%d\n", ctx->bits[0], ctx->bits[1]); - printf("in[]:\n "); - for(i=0; i<64; i++) { - printf("%02x:", ctx->in[i]); - if((i % 16) == 15) { - printf("\n "); - } - } - printf("\n"); -} -#else // MD5_DEBUG -#define dumpCtx(ctx, label) -#endif // MD5_DEBUG - -static void MD5Transform(UINT32 buf[4], UINT32 const in[16]); - -#if __LITTLE_ENDIAN__ -#define byteReverse(buf, len) /* Nothing */ -#else -static void byteReverse(unsigned char *buf, unsigned longs); - -#ifndef ASM_MD5 -/* - * Note: this code is harmless on little-endian machines. - */ -static void byteReverse(unsigned char *buf, unsigned longs) -{ -#if old_way - /* - * this code is NOT harmless on big-endian machine which require - * natural alignment. - */ - UINT32 t; - do { - t = (UINT32) ((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(UINT32 *) buf = t; - buf += 4; - } while (--longs); -#else // new_way - - unsigned char t; - do { - t = buf[0]; - buf[0] = buf[3]; - buf[3] = t; - t = buf[1]; - buf[1] = buf[2]; - buf[2] = t; - buf += 4; - } while (--longs); -#endif // old_way -} -#endif // ASM_MD5 -#endif // __LITTLE_ENDIAN__ - -/* - * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious - * initialization constants. - */ -void MD5Init(MD5Context *ctx) -{ - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; -} - -/* - * Update context to reflect the concatenation of another buffer full - * of bytes. - */ -void MD5Update(MD5Context *ctx, unsigned char const *buf, unsigned len) -{ - UINT32 t; - - dumpCtx(ctx, "MD5.c update top"); - /* Update bitcount */ - - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((UINT32) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ - ctx->bits[1] += len >> 29; - - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ - - /* Handle any leading odd-sized chunks */ - - if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) { - memcpy(p, buf, len); - return; - } - memcpy(p, buf, t); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (UINT32 *) ctx->in); - dumpCtx(ctx, "update - return from transform (1)"); - buf += t; - len -= t; - } - /* Process data in 64-byte chunks */ - - while (len >= 64) { - memcpy(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (UINT32 *) ctx->in); - dumpCtx(ctx, "update - return from transform (2)"); - buf += 64; - len -= 64; - } - - /* Handle any remaining bytes of data. */ - - memcpy(ctx->in, buf, len); -} - -/* - * Final wrapup - pad to 64-byte boundary with the bit pattern - * 1 0* (64-bit count of bits processed, MSB-first) - */ -void MD5Final(MD5Context *ctx, unsigned char *digest) -{ - unsigned count; - unsigned char *p; - - dumpCtx(ctx, "final top"); - - /* Compute number of bytes mod 64 */ - count = (ctx->bits[0] >> 3) & 0x3F; - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - p = ctx->in + count; - *p++ = 0x80; - #if MD5_DEBUG - printf("in[%d] = %x\n", count, ctx->in[count]); - #endif - /* Bytes of padding needed to make 64 bytes */ - count = 64 - 1 - count; - - /* Pad out to 56 mod 64 */ - dumpCtx(ctx, "final, before pad"); - if (count < 8) { - /* Two lots of padding: Pad the first block to 64 bytes */ - bzero(p, count); - byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (UINT32 *) ctx->in); - - /* Now fill the next block with 56 bytes */ - bzero(ctx->in, 56); - } else { - /* Pad block to 56 bytes */ - bzero(p, count - 8); - } - byteReverse(ctx->in, 14); - - /* Append length in bits and transform */ - #if old_way - /* - * On a little endian machine, this writes the l.s. byte of - * the bit count to ctx->in[56] and the m.s byte of the bit count to - * ctx->in[63]. - */ - ((UINT32 *) ctx->in)[14] = ctx->bits[0]; - ((UINT32 *) ctx->in)[15] = ctx->bits[1]; - #else // new_way - intToByteRep(ctx->bits[0], &ctx->in[56]); - intToByteRep(ctx->bits[1], &ctx->in[60]); - #endif // new_way - - dumpCtx(ctx, "last transform"); - MD5Transform(ctx->buf, (UINT32 *) ctx->in); - byteReverse((unsigned char *) ctx->buf, 4); - memcpy(digest, ctx->buf, MD5_DIGEST_SIZE); - dumpCtx(ctx, "final end"); - - bzero(ctx, sizeof(*ctx)); /* In case it's sensitive */ -} - -#ifndef ASM_MD5 - -/* The four core functions - F1 is optimized somewhat */ - -/* #define F1(x, y, z) (x & y | ~x & z) */ -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -/* This is the central step in the MD5 algorithm. */ -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) - -/* - * The core of the MD5 algorithm, this alters an existing MD5 hash to - * reflect the addition of 16 longwords of new data. MD5Update blocks - * the data and converts bytes into longwords for this routine. - */ -static void MD5Transform(UINT32 buf[4], UINT32 const in[16]) -{ - register UINT32 a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} - -#endif /* ASM_MD5 */ - -#endif /* CRYPTKIT_MD5_ENABLE && CRYPTKIT_LIBMD_DIGEST */ diff --git a/OSX/include/security_cryptkit/ckMD5.h b/OSX/include/security_cryptkit/ckMD5.h deleted file mode 100644 index a4833b37..00000000 --- a/OSX/include/security_cryptkit/ckMD5.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - File: MD5.h - - Written by: Colin Plumb - - Copyright: Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - - Change History (most recent first): - - <8> 10/06/98 ap Changed to compile with C++. - - To Do: -*/ - -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * MD5.h - * derived and used without need for permission from public domain source - */ - -#ifndef _CK_MD5_H_ -#define _CK_MD5_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_MD5_ENABLE -#if CRYPTKIT_LIBMD_DIGEST - -/* - * In this case we use the MD5 implementation in libSystem. - */ -#include - -typedef CC_MD5_CTX MD5Context; - -#define MD5Init(c) CC_MD5_Init(c) -#define MD5Update(c, d, l) CC_MD5_Update(c, d, l) -#define MD5Final(c, d) CC_MD5_Final(d, c) - -#define MD5_DIGEST_SIZE CC_MD5_DIGEST_LENGTH - -#else /* ! CRYPTKIT_LIBMD_DIGEST */ - -/* Our own private implementation */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __alpha -typedef unsigned int UINT32; -#elif defined (macintosh) || defined (__ppc__) -typedef unsigned int UINT32; -#else -typedef unsigned long UINT32; -#endif - -typedef struct { - UINT32 buf[4]; - UINT32 bits[2]; // bits[0] is low 32 bits of bit count - unsigned char in[64]; -} MD5Context; - -#define MD5_DIGEST_SIZE 16 /* in bytes */ - -void MD5Init(MD5Context *context); -void MD5Update(MD5Context *context, unsigned char const *buf, - unsigned len); -void MD5Final(MD5Context *context, unsigned char *digest); - -/* - * This is needed to make RSAREF happy on some MS-DOS compilers. - */ -typedef MD5Context MD5_CTX; - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_LIBMD_DIGEST */ -#endif /* CRYPTKIT_MD5_ENABLE */ -#endif /*_CK_MD5_H_*/ diff --git a/OSX/include/security_cryptkit/ckSHA1.c b/OSX/include/security_cryptkit/ckSHA1.c deleted file mode 100644 index 94a20a6a..00000000 --- a/OSX/include/security_cryptkit/ckSHA1.c +++ /dev/null @@ -1,227 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ckSHA1.c - generic, portable SHA-1 hash object - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 07 Jan 1998 at Apple - * Created. - */ - -#include "ckconfig.h" -#include "feeTypes.h" -#include "ckSHA1.h" - -#if CRYPTKIT_LIBMD_DIGEST -/* - * For linking with AppleCSP: use libSystem SHA1 implementation. - */ -#include -#else -#include "ckSHA1_priv.h" -#endif -#include "falloc.h" -#include "platform.h" - -#if CRYPTKIT_LIBMD_DIGEST -/* - * Trivial wrapper for SHA_CTX; a sha1Obj is a pointer to this. - */ -typedef struct { - CC_SHA1_CTX ctx; - unsigned char digest[CC_SHA1_DIGEST_LENGTH]; -} Sha1Obj; - -sha1Obj sha1Alloc(void) -{ - void *rtn = fmalloc(sizeof(Sha1Obj)); - memset(rtn, 0, sizeof(Sha1Obj)); - CC_SHA1_Init(&(((Sha1Obj *)rtn)->ctx)); - return (sha1Obj)rtn; -} - -void sha1Reinit(sha1Obj sha1) -{ - Sha1Obj *ctx = (Sha1Obj *)sha1; - CC_SHA1_Init(&ctx->ctx); -} - -void sha1Free(sha1Obj sha1) -{ - memset(sha1, 0, sizeof(Sha1Obj)); - ffree(sha1); -} - -void sha1AddData(sha1Obj sha1, - const unsigned char *data, - unsigned dataLen) -{ - Sha1Obj *ctx = (Sha1Obj *)sha1; - CC_SHA1_Update(&ctx->ctx, data, dataLen); -} - -unsigned char *sha1Digest(sha1Obj sha1) -{ - Sha1Obj *ctx = (Sha1Obj *)sha1; - CC_SHA1_Final(ctx->digest, &ctx->ctx); - return ctx->digest; -} - -unsigned sha1DigestLen(void) -{ - return CC_SHA1_DIGEST_LENGTH; -} - -#else /* standalone cryptkit implementation */ - -/* - * Private data for this object. A sha1Obj handle is cast to a pointer - * to one of these. - */ -typedef struct { - SHS_INFO context; - int isDone; - - /* - * For storing partial blocks - */ - BYTE dataBuf[SHS_BLOCKSIZE]; - unsigned bufBytes; // valid bytes in dataBuf[p] -} sha1Inst; - -/* - * Alloc and init an empty sha1 object. - */ -sha1Obj sha1Alloc(void) -{ - sha1Inst *sinst; - - sinst = (sha1Inst *)fmalloc(sizeof(sha1Inst)); - if(sinst == NULL) { - return NULL; - } - shsInit(&sinst->context); - sha1Reinit((sha1Obj)sinst); - return (sha1Obj)sinst; -} - -/* - * Reusable init function. - */ -void sha1Reinit(sha1Obj sha1) -{ - sha1Inst *sinst = (sha1Inst *) sha1; - - shsInit(&sinst->context); - sinst->isDone = 0; - sinst->bufBytes = 0; -} - -/* - * Free an sha1 object. - */ -void sha1Free(sha1Obj sha1) -{ - sha1Inst *sinst = (sha1Inst *) sha1; - - memset(sha1, 0, sizeof(sha1Inst)); - ffree(sinst); -} - -/* - * Add some data to the sha1 object. - */ -void sha1AddData(sha1Obj sha1, - const unsigned char *data, - unsigned dataLen) -{ - sha1Inst *sinst = (sha1Inst *) sha1; - unsigned toMove; - unsigned blocks; - - if(sinst->isDone) { - /* - * Log some kind of error here... - */ - return; - } - - /* - * First deal with partial buffered block - */ - if(sinst->bufBytes != 0) { - toMove = SHS_BLOCKSIZE - sinst->bufBytes; - if(toMove > dataLen) { - toMove = dataLen; - } - memmove(sinst->dataBuf+sinst->bufBytes, data, toMove); - data += toMove; - dataLen -= toMove; - sinst->bufBytes += toMove; - if(sinst->bufBytes == SHS_BLOCKSIZE) { - shsUpdate(&sinst->context, sinst->dataBuf, SHS_BLOCKSIZE); - sinst->bufBytes = 0; - } - } - - /* - * Now the bulk of the data, in a multiple of full blocks - */ - blocks = dataLen / SHS_BLOCKSIZE; - toMove = blocks * SHS_BLOCKSIZE; - if(toMove != 0) { - shsUpdate(&sinst->context, data, toMove); - data += toMove; - dataLen -= toMove; - } - - /* - * Store any remainder in dataBuf - */ - if(dataLen != 0) { - memmove(sinst->dataBuf, data, dataLen); - sinst->bufBytes = dataLen; - } -} - -/* - * Obtain a pointer to completed message digest, and the length of the digest. - */ -unsigned char *sha1Digest(sha1Obj sha1) -{ - sha1Inst *sinst = (sha1Inst *) sha1; - - if(!sinst->isDone) { - /* - * Deal with partial resid block - */ - if(sinst->bufBytes != 0) { - shsUpdate(&sinst->context, sinst->dataBuf, - sinst->bufBytes); - sinst->bufBytes = 0; - } - shsFinal(&sinst->context); - sinst->isDone = 1; - } - /* - * FIXME - should do explicit conversion to char array....? - */ - return (unsigned char *)sinst->context.digest; -} - -unsigned sha1DigestLen(void) -{ - return SHS_DIGESTSIZE; -} - -#endif /* CRYPTKIT_LIBMD_DIGEST */ diff --git a/OSX/include/security_cryptkit/ckSHA1.h b/OSX/include/security_cryptkit/ckSHA1.h deleted file mode 100644 index de101716..00000000 --- a/OSX/include/security_cryptkit/ckSHA1.h +++ /dev/null @@ -1,75 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ckSHA1.h - generic, portable SHA-1 hash object - * - * Revision History - * ---------------- - * 05 Jan 1998 at Apple - * Created. - */ - -#ifndef _CK_SHA1_H_ -#define _CK_SHA1_H_ - -#if !defined(__MACH__) -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Opaque sha1 object handle. - */ -typedef void *sha1Obj; - -/* - * Alloc and init an empty sha1 object. - */ -sha1Obj sha1Alloc(void); - -/* - * reinitialize an sha1 object for reuse. - */ -void sha1Reinit(sha1Obj sha1); - -/* - * Free an sha1 object. - */ -void sha1Free(sha1Obj sha1); - -/* - * Add some data to the sha1 object. - */ -void sha1AddData(sha1Obj sha1, - const unsigned char *data, - unsigned dataLen); - -/* - * Obtain a pointer to completed message digest. This disables further calls - * to sha1AddData(). This pointer is NOT malloc'd; the associated data - * persists only as long as this object does. - */ -unsigned char *sha1Digest(sha1Obj sha1); - -/* - * Obtain the length of the message digest. - */ -unsigned sha1DigestLen(void); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_SHA1_H_*/ diff --git a/OSX/include/security_cryptkit/ckSHA1_priv.c b/OSX/include/security_cryptkit/ckSHA1_priv.c deleted file mode 100644 index 4ea15ae0..00000000 --- a/OSX/include/security_cryptkit/ckSHA1_priv.c +++ /dev/null @@ -1,321 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ckSHA1_priv.c - low-level SHA-1 hash algorithm. - * - * Revision History - * ---------------- - * 05 Jan 1998 at Apple - * Created, based on source by Peter C. Gutmann. - * Mods: made reentrant, added NIST fix to expand(), eliminated - * unnecessary copy to local W[] array. - */ - - -/* NIST proposed Secure Hash Standard. - - Written 2 September 1992, Peter C. Gutmann. - This implementation placed in the public domain. - - Comments to pgut1@cs.aukuni.ac.nz */ - -#include "ckconfig.h" - -#if !CRYPTKIT_LIBMD_DIGEST - -#include "ckSHA1_priv.h" -#include "platform.h" -#include - -/* The SHS f()-functions */ - -#define f1(x,y,z) ( ( x & y ) | ( ~x & z ) ) /* Rounds 0-19 */ -#define f2(x,y,z) ( x ^ y ^ z ) /* Rounds 20-39 */ -#define f3(x,y,z) ( ( x & y ) | ( x & z ) | ( y & z ) ) /* Rounds 40-59 */ -#define f4(x,y,z) ( x ^ y ^ z ) /* Rounds 60-79 */ - -/* The SHS Mysterious Constants */ - -#define K1 0x5A827999L /* Rounds 0-19 */ -#define K2 0x6ED9EBA1L /* Rounds 20-39 */ -#define K3 0x8F1BBCDCL /* Rounds 40-59 */ -#define K4 0xCA62C1D6L /* Rounds 60-79 */ - -/* SHS initial values */ - -#define h0init 0x67452301L -#define h1init 0xEFCDAB89L -#define h2init 0x98BADCFEL -#define h3init 0x10325476L -#define h4init 0xC3D2E1F0L - -/* 32-bit rotate - kludged with shifts */ - -#define S(n,X) ( ( X << n ) | ( X >> ( 32 - n ) ) ) - -/* The initial expanding function */ - -/* - * 06 Jan 1998. Added left circular shift per NIST FIPS-180-1 (at - * http://www.nist.gov/itl/div897/pubs/fip180-1.htm). Also see - * B. Schneier, Applied Cryptography, Second Edition, section 18.7 - * for info on this addenda to the original NIST spec. - */ -#define expand(count) { \ - W[count] = W[count - 3] ^ W[count - 8] ^ W[count - 14] ^ W[count - 16]; \ - W[count] = S(1, W[count]); \ -} - -/* The four SHS sub-rounds */ - -#define subRound1(count) \ - { \ - temp = S( 5, A ) + f1( B, C, D ) + E + W[ count ] + K1; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ - } - -#define subRound2(count) \ - { \ - temp = S( 5, A ) + f2( B, C, D ) + E + W[ count ] + K2; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ - } - -#define subRound3(count) \ - { \ - temp = S( 5, A ) + f3( B, C, D ) + E + W[ count ] + K3; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ - } - -#define subRound4(count) \ - { \ - temp = S( 5, A ) + f4( B, C, D ) + E + W[ count ] + K4; \ - E = D; \ - D = C; \ - C = S( 30, B ); \ - B = A; \ - A = temp; \ - } - -/* Initialize the SHS values */ - -void shsInit( SHS_INFO *shsInfo ) - { - /* Set the h-vars to their initial values */ - shsInfo->digest[ 0 ] = h0init; - shsInfo->digest[ 1 ] = h1init; - shsInfo->digest[ 2 ] = h2init; - shsInfo->digest[ 3 ] = h3init; - shsInfo->digest[ 4 ] = h4init; - - /* Initialise bit count */ - shsInfo->countLo = shsInfo->countHi = 0L; - } - -/* Perform the SHS transformation. Note that this code, like MD5, seems to - break some optimizing compilers - it may be necessary to split it into - sections, eg based on the four subrounds */ - -static void shsTransform( SHS_INFO *shsInfo ) -{ - LONG *W, temp; - LONG A, B, C, D, E; - - /* Step A. Copy the data buffer into the local work buffer. */ - /* 07 Jan 1998, dmitch: skip this bogus move, and let the caller - * copy data directly into the W[] array. To minimize changes, - * we'll just increase the size of shsInfo->data[] and make W - * a pointer here. - */ - W = shsInfo->data; - - /* Step B. Expand the 16 words into 64 temporary data words */ - - /* - * Note: I tried optimizing this via a for loop, and for some reason, - * the "optimized" version ran slower on PPC than the original - * unrolled version. The optimized version does run faster on i486 than - * the unrolled version. - * - * Similarly, the set of subRounds, below, runs slower on i486 when - * optimized via 4 'for' loops. The "optimized" version of that is - * a wash on PPC. - * - * Conclusion: leave both of 'em unrolled. We could ifdef per machine, - * but this would get messy once we had more than two architectures. - * We may want to revisit this. --dpm - */ - expand( 16 ); expand( 17 ); expand( 18 ); expand( 19 ); expand( 20 ); - expand( 21 ); expand( 22 ); expand( 23 ); expand( 24 ); expand( 25 ); - expand( 26 ); expand( 27 ); expand( 28 ); expand( 29 ); expand( 30 ); - expand( 31 ); expand( 32 ); expand( 33 ); expand( 34 ); expand( 35 ); - expand( 36 ); expand( 37 ); expand( 38 ); expand( 39 ); expand( 40 ); - expand( 41 ); expand( 42 ); expand( 43 ); expand( 44 ); expand( 45 ); - expand( 46 ); expand( 47 ); expand( 48 ); expand( 49 ); expand( 50 ); - expand( 51 ); expand( 52 ); expand( 53 ); expand( 54 ); expand( 55 ); - expand( 56 ); expand( 57 ); expand( 58 ); expand( 59 ); expand( 60 ); - expand( 61 ); expand( 62 ); expand( 63 ); expand( 64 ); expand( 65 ); - expand( 66 ); expand( 67 ); expand( 68 ); expand( 69 ); expand( 70 ); - expand( 71 ); expand( 72 ); expand( 73 ); expand( 74 ); expand( 75 ); - expand( 76 ); expand( 77 ); expand( 78 ); expand( 79 ); - - /* Step C. Set up first buffer */ - A = shsInfo->digest[ 0 ]; - B = shsInfo->digest[ 1 ]; - C = shsInfo->digest[ 2 ]; - D = shsInfo->digest[ 3 ]; - E = shsInfo->digest[ 4 ]; - - /* Step D. Serious mangling, divided into four sub-rounds */ - subRound1( 0 ); subRound1( 1 ); subRound1( 2 ); subRound1( 3 ); - subRound1( 4 ); subRound1( 5 ); subRound1( 6 ); subRound1( 7 ); - subRound1( 8 ); subRound1( 9 ); subRound1( 10 ); subRound1( 11 ); - subRound1( 12 ); subRound1( 13 ); subRound1( 14 ); subRound1( 15 ); - subRound1( 16 ); subRound1( 17 ); subRound1( 18 ); subRound1( 19 ); - subRound2( 20 ); subRound2( 21 ); subRound2( 22 ); subRound2( 23 ); - subRound2( 24 ); subRound2( 25 ); subRound2( 26 ); subRound2( 27 ); - subRound2( 28 ); subRound2( 29 ); subRound2( 30 ); subRound2( 31 ); - subRound2( 32 ); subRound2( 33 ); subRound2( 34 ); subRound2( 35 ); - subRound2( 36 ); subRound2( 37 ); subRound2( 38 ); subRound2( 39 ); - subRound3( 40 ); subRound3( 41 ); subRound3( 42 ); subRound3( 43 ); - subRound3( 44 ); subRound3( 45 ); subRound3( 46 ); subRound3( 47 ); - subRound3( 48 ); subRound3( 49 ); subRound3( 50 ); subRound3( 51 ); - subRound3( 52 ); subRound3( 53 ); subRound3( 54 ); subRound3( 55 ); - subRound3( 56 ); subRound3( 57 ); subRound3( 58 ); subRound3( 59 ); - subRound4( 60 ); subRound4( 61 ); subRound4( 62 ); subRound4( 63 ); - subRound4( 64 ); subRound4( 65 ); subRound4( 66 ); subRound4( 67 ); - subRound4( 68 ); subRound4( 69 ); subRound4( 70 ); subRound4( 71 ); - subRound4( 72 ); subRound4( 73 ); subRound4( 74 ); subRound4( 75 ); - subRound4( 76 ); subRound4( 77 ); subRound4( 78 ); subRound4( 79 ); - - /* Step E. Build message digest */ - shsInfo->digest[ 0 ] += A; - shsInfo->digest[ 1 ] += B; - shsInfo->digest[ 2 ] += C; - shsInfo->digest[ 3 ] += D; - shsInfo->digest[ 4 ] += E; -} - -/* __LITTLE_ENDIAN__ is in fact #defined on OS X on PPC.... */ -//#ifdef __LITTLE_ENDIAN__ -#if 0 - -/* When run on a little-endian CPU we need to perform byte reversal on an - array of longwords. It is possible to make the code endianness- - independant by fiddling around with data at the byte level, but this - makes for very slow code, so we rely on the user to sort out endianness - at compile time */ - -static void byteReverse( buffer, byteCount ) - LONG *buffer; - int byteCount; - - { - LONG value; - int count; - - byteCount /= sizeof( LONG ); - for( count = 0; count < byteCount; count++ ) - { - value = ( buffer[ count ] << 16 ) | ( buffer[ count ] >> 16 ); - buffer[ count ] = ( ( value & 0xFF00FF00L ) >> 8 ) | ( ( value & 0x00FF00FFL ) << 8 ); - } - } - -#else /* __LITTLE_ENDIAN__ */ - -/* - * Nop for big-endian machines - */ -#define byteReverse( buffer, byteCount ) - -#endif /* __LITTLE_ENDIAN__ */ - - -/* Update SHS for a block of data. This code assumes that the buffer size - is a multiple of SHS_BLOCKSIZE bytes long, which makes the code a lot - more efficient since it does away with the need to handle partial blocks - between calls to shsUpdate() */ - -void shsUpdate( - SHS_INFO *shsInfo, - const BYTE *buffer, - int count) - - { - /* Update bitcount */ - if( ( shsInfo->countLo + ( ( LONG ) count << 3 ) ) < shsInfo->countLo ) - shsInfo->countHi++; /* Carry from low to high bitCount */ - shsInfo->countLo += ( ( LONG ) count << 3 ); - shsInfo->countHi += ( ( LONG ) count >> 29 ); - - /* Process data in SHS_BLOCKSIZE chunks */ - while( count >= SHS_BLOCKSIZE ) - { - memcpy( shsInfo->data, buffer, SHS_BLOCKSIZE ); - byteReverse( shsInfo->data, SHS_BLOCKSIZE ); - shsTransform( shsInfo ); - buffer += SHS_BLOCKSIZE; - count -= SHS_BLOCKSIZE; - } - - /* Handle any remaining bytes of data. This should only happen once - on the final lot of data */ - memcpy( shsInfo->data, buffer, count ); - } - -void shsFinal(SHS_INFO *shsInfo) - { - int count; - LONG lowBitcount = shsInfo->countLo, highBitcount = shsInfo->countHi; - - /* Compute number of bytes mod 64 */ - count = ( int ) ( ( shsInfo->countLo >> 3 ) & 0x3F ); - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - ( ( BYTE * ) shsInfo->data )[ count++ ] = 0x80; - - /* Pad out to 56 mod 64 */ - if( count > 56 ) - { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset( ( BYTE * ) &shsInfo->data + count, 0, 64 - count ); - byteReverse( shsInfo->data, SHS_BLOCKSIZE ); - shsTransform( shsInfo ); - - /* Now fill the next block with 56 bytes */ - memset( &shsInfo->data, 0, 56 ); - } - else - /* Pad block to 56 bytes */ - memset( ( BYTE * ) &shsInfo->data + count, 0, 56 - count ); - byteReverse( shsInfo->data, SHS_BLOCKSIZE ); - - /* Append length in bits and transform */ - shsInfo->data[ 14 ] = highBitcount; - shsInfo->data[ 15 ] = lowBitcount; - - shsTransform( shsInfo ); - byteReverse( shsInfo->data, SHS_DIGESTSIZE ); - } - -#endif /* CRYPTKIT_LIBMD_DIGEST */ diff --git a/OSX/include/security_cryptkit/ckSHA1_priv.h b/OSX/include/security_cryptkit/ckSHA1_priv.h deleted file mode 100644 index 05cb9cb6..00000000 --- a/OSX/include/security_cryptkit/ckSHA1_priv.h +++ /dev/null @@ -1,60 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ckSHA1_priv.h - private low-level API for SHA-1 hash algorithm - * - * Revision History - * ---------------- - * 22 Aug 96 at NeXT - * Created. - */ - -/* Useful defines/typedefs */ - -#ifndef _CK_SHA1_PRIV_H_ -#define _CK_SHA1_PRIV_H_ - -#include "ckconfig.h" - -#if !CRYPTKIT_LIBMD_DIGEST - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned char BYTE; -typedef unsigned long LONG; - -/* The SHS block size and message digest sizes, in bytes */ - -#define SHS_BLOCKSIZE 64 -#define SHS_DIGESTSIZE 20 - -/* The structure for storing SHS info */ - -typedef struct { - LONG digest[ 5 ]; /* Message digest */ - LONG countLo, countHi; /* 64-bit bit count */ - LONG data[ 80 ]; /* SHS data buffer */ - } SHS_INFO; - -extern void shsInit(SHS_INFO *shsInfo); -extern void shsUpdate(SHS_INFO *shsInfo, - const BYTE *buffer, - int count); -extern void shsFinal(SHS_INFO *shsInfo); - -#ifdef __cplusplus -} -#endif - -#endif /* !CRYPTKIT_LIBMD_DIGEST */ - -#endif /* _CK_SHA1_PRIV_H_ */ diff --git a/OSX/include/security_cryptkit/ckconfig.h b/OSX/include/security_cryptkit/ckconfig.h deleted file mode 100644 index c1737ea6..00000000 --- a/OSX/include/security_cryptkit/ckconfig.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - File: ckconfig.h - - Contains: Common config info. - - - Copyright: Copyright (c) 1998,2011,2014 Apple Inc. - All rights reserved. - - Change History (most recent first): - - <7> 10/06/98 ap Changed to compile with C++. - - To Do: -*/ - -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - */ - -#ifndef _CK_CONFIG_H_ -#define _CK_CONFIG_H_ - -/* - * Common build flags. - */ -#define DEBUG_ENGINE 0 - -#define ENGINE_127_BITS 0 /* hard-coded 127 elliptic() */ - -/* - * These flags are set en masse, one set per target in the XCode project file or - * Makefile. They determine what gets compiled into the library. Every flag - * has to be defined for every configureation - preprocessors directives use - * #if, not #ifdef. - */ - -#ifdef CK_SECURITY_BUILD -/* - * Standard Security.framework build - */ -#define CRYPTKIT_DER_ENABLE 1 /* DER encoding support */ -#define CRYPTKIT_LIBMD_DIGEST 1 /* use CommonCrypto digests */ -#define CRYPTKIT_ELL_PROJ_ENABLE 1 /* elliptic projection */ -#define CRYPTKIT_ECDSA_ENABLE 1 /* ECDSA (requires ELL_PROJ_ENABLE) */ -#define CRYPTKIT_CIPHERFILE_ENABLE 0 /* cipherfile w/symmetric encryption */ -#define CRYPTKIT_SYMMETRIC_ENABLE 0 /* symmetric encryption */ -#define CRYPTKIT_ASYMMETRIC_ENABLE 1 /* asymmetric encryption */ -#define CRYPTKIT_MD5_ENABLE 1 /* MD5 hash */ -#define CRYPTKIT_SHA1_ENABLE 1 /* SHA1 hash - needed for GHMAX_LEGACY */ -#define CRYPTKIT_HMAC_LEGACY 1 -#define CRYPTKIT_KEY_EXCHANGE 0 /* FEE key exchange */ -#define CRYPTKIT_HIGH_LEVEL_SIG 0 /* high level one-shot signature */ -#define CRYPTKIT_GIANT_STACK_ENABLE 0 /* cache of giants */ - -#elif defined(CK_STANDALONE_BUILD) -/* - * Standalone library build - */ -#define CRYPTKIT_DER_ENABLE 0 -#define CRYPTKIT_LIBMD_DIGEST 0 -#define CRYPTKIT_ELL_PROJ_ENABLE 1 -#define CRYPTKIT_ECDSA_ENABLE 1 -#define CRYPTKIT_CIPHERFILE_ENABLE 1 -#define CRYPTKIT_SYMMETRIC_ENABLE 1 -#define CRYPTKIT_ASYMMETRIC_ENABLE 1 -#define CRYPTKIT_MD5_ENABLE 1 -#define CRYPTKIT_SHA1_ENABLE 1 -#define CRYPTKIT_HMAC_LEGACY 0 -#define CRYPTKIT_KEY_EXCHANGE 1 -#define CRYPTKIT_HIGH_LEVEL_SIG 1 -#define CRYPTKIT_GIANT_STACK_ENABLE 1 - -#elif defined(CK_MINIMUM_SIG_BUILD) -/* - * Standalone, just ElGamal signature and key generation - */ -#define CRYPTKIT_DER_ENABLE 0 -#define CRYPTKIT_LIBMD_DIGEST 0 -#define CRYPTKIT_ELL_PROJ_ENABLE 0 -#define CRYPTKIT_ECDSA_ENABLE 0 -#define CRYPTKIT_CIPHERFILE_ENABLE 0 -#define CRYPTKIT_SYMMETRIC_ENABLE 0 -#define CRYPTKIT_ASYMMETRIC_ENABLE 0 -#define CRYPTKIT_MD5_ENABLE 1 -/* FIXME convert native ElGamal to use SHA1! */ -#define CRYPTKIT_SHA1_ENABLE 0 -#define CRYPTKIT_HMAC_LEGACY 0 -#define CRYPTKIT_KEY_EXCHANGE 0 -#define CRYPTKIT_HIGH_LEVEL_SIG 0 -#define CRYPTKIT_GIANT_STACK_ENABLE 1 - -#else - -#error You must supply a build configuration. -#endif - -#endif /* _CK_CONFIG_H_ */ diff --git a/OSX/include/security_cryptkit/ckutilities.c b/OSX/include/security_cryptkit/ckutilities.c deleted file mode 100644 index bbbe252b..00000000 --- a/OSX/include/security_cryptkit/ckutilities.c +++ /dev/null @@ -1,416 +0,0 @@ -/* Copyright (c) 1998,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ckutilities.c - general C routines - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 08 Apr 98 at Apple - * Mods for variable size giantDigit. - * Rewrote serializeGiant(), deserializeGiant() to conform to IEEE P1363. - * 23 Mar 98 at Apple - * Added FR_WrongSignatureType, FR_BadKeyBlob to frtnStrings. - * Added initCryptKit(). - * 19 Jan 98 at Apple - * Added cStringToUc() - * 09 Jan 98 at Apple - * Added non-FEE_DEBUG version of printGiantHex() - * 27 Jan 97 at NeXT - * Addd serializeGiant(), deserializeGiant; Deleted data_to_giant() - * 12 Dec 96 at NeXT - * Added byteRepTo{int,key,giant}(). - * 2 Aug 96 at NeXT - * Broke out from Blaine Garst's original NSCryptors.m - */ - -#include "ckutilities.h" -#include "falloc.h" -#include "feeTypes.h" -#include "feeDebug.h" -#include "feeFunctions.h" -#include "byteRep.h" -#include "platform.h" -#include "curveParams.h" -#include -#ifdef NeXT -#include -#include -#include -#include -#endif // NeXT - -/* - * feeReturn strings. - */ -typedef struct { - feeReturn frtn; - const char *frtnString; -} frtnItem; - -static const frtnItem frtnStrings[] = { -#ifndef NDEBUG - { FR_Success, "Success" }, - { FR_BadPubKey, "Bad Public Key" }, - { FR_BadPubKeyString, "Bad Public Key String" }, - { FR_IncompatibleKey, "Incompatible key format" }, - { FR_IllegalDepth, "Illegal Depth" }, - { FR_BadUsageName, "Bad Usage Name" }, - { FR_BadSignatureFormat, "Bad Signature Format" }, - { FR_InvalidSignature, "Invalid Signature" }, - { FR_IllegalArg, "Illegal Argument" }, - { FR_BadCipherText, "Bad Ciphertext Format" }, - { FR_Unimplemented, "Unimplemented Function" }, - { FR_BadCipherFile, "Bad CipherFile Format" }, - { FR_BadEnc64, "Bad enc64 Format" }, - { FR_WrongSignatureType, "Wrong Signature Type" }, - { FR_BadKeyBlob, "Bad Key Blob" }, - { FR_IllegalCurve, "Bad curve type" }, - { FR_Internal, "Internal Library Error" }, - { FR_Memory, "Out of Memory" }, - { FR_ShortPrivData, "Insufficient Seed Data" }, -#endif /* NDEBUG */ - { (feeReturn) 0, NULL }, -}; - -/* - * One-time only init of CryptKit library. - */ -void initCryptKit(void) -{ - #if GIANTS_VIA_STACK - curveParamsInitGiants(); - #endif -} - -/* - * Shutdown. - */ -void terminateCryptKit(void) -{ - #if GIANTS_VIA_STACK - freeGiantStacks(); - #endif -} - -/* - * Create a giant, initialized with specified char[] data. - */ -giant giant_with_data(const unsigned char *d, int len) { - int numDigits = BYTES_TO_GIANT_DIGITS(len); - giant result; - - result = newGiant(numDigits); - deserializeGiant(d, result, len); - return result; -} - -/* - * Obtain a malloc'd memory chunk init'd with specified giant's data. - * Resulting bytes are portable. Size of malloc'd memory is always zero - * mod GIANT_BYTES_PER_DIGIT. - * - * Calling this function for a giant obtained by giant_with_data() yields - * the original data, with extra byte(s) of leading zeros if the original - * was not zero mod GIANT_BYTES_PER_DIGIT. - */ -unsigned char *mem_from_giant(giant g, - unsigned *memLen) /* RETURNED size of malloc'd region */ -{ - unsigned char *cp; - unsigned numDigits = (g->sign < 0) ? -g->sign : g->sign; - - *memLen = numDigits * GIANT_BYTES_PER_DIGIT; - cp = (unsigned char*) fmalloc(*memLen); - serializeGiant(g, cp, *memLen); - return cp; -} - -extern const char *feeReturnString(feeReturn frtn) -{ - const frtnItem *fi = frtnStrings; - - while(fi->frtnString) { - if(fi->frtn == frtn) { - return fi->frtnString; - } - fi++; - } - return "Unknown Status"; -} - -#if FEE_DEBUG -void printGiant(const giant x) -{ - int i; - - printf("sign=%d cap=%d n[]=", x->sign, x->capacity); - for(i=0; isign); i++) { - printf("%u:", x->n[i]); - } - printf("\n"); -} - -void printGiantHex(const giant x) -{ - int i; - - printf("sign=%d cap=%d n[]=", x->sign, x->capacity); - for(i=0; isign); i++) { - printf("%x:", x->n[i]); - } - printf("\n"); -} - -/* - * Print in the form - * sign=8 cap=16 n[]=29787 + 3452 * w^1 + 55260 * w^2 + ... - */ -void printGiantExp(const giant x) -{ - int i; - int size = abs(x->sign); - - printf("sign=%d cap=%d n[]=", x->sign, x->capacity); - for(i=0; in[i]); - if(i > 0) { - printf("* w^%d ", i); - } - if(i<(size-1)) { - printf("+ "); - } - } - printf("\n"); -} - -void printKey(const key k) -{ - printf(" twist %d\n", k->twist); - printf(" x: "); - printGiant(k->x); -} - -void printCurveParams(const curveParams *p) -{ - const char *pt; - const char *ct; - - switch(p->primeType) { - case FPT_Mersenne: - pt = "FPT_Mersenne"; - break; - case FPT_FEE: - pt = "FPT_FEE"; - break; - case FPT_General: - pt = "FPT_General"; - break; - default: - pt = "UNKNOWN!"; - break; - } - switch(p->curveType) { - case FCT_Montgomery: - ct = "FCT_Montgomery"; - break; - case FCT_Weierstrass: - ct = "FCT_Weierstrass"; - break; - case FCT_General: - ct = "FCT_General"; - break; - default: - ct = "UNKNOWN!"; - break; - } - printf(" q %d k %d primeType %s curveType %s\n", - p->q, p->k, pt, ct); - printf(" minBytes %d maxDigits %d\n", p->minBytes, p->maxDigits); - printf(" a : "); - printGiant(p->a); - printf(" b : "); - printGiant(p->b); - printf(" c : "); - printGiant(p->c); - printf(" basePrime : "); - printGiant(p->basePrime); - printf(" x1Plus : "); - printGiant(p->x1Plus); - printf(" x1Minus : "); - printGiant(p->x1Minus); - printf(" cOrderPlus : "); - printGiant(p->cOrderPlus); - printf(" cOrderMinus : "); - printGiant(p->cOrderMinus); - printf(" x1OrderPlus : "); - printGiant(p->x1OrderPlus); - printf(" x1OrderMinus: "); - printGiant(p->x1OrderMinus); -} -#else -void printGiant(const giant x) {} -void printGiantHex(const giant x) {} -void printGiantExp(const giant x) {} -void printKey(const key k) {} -void printCurveParams(const curveParams *p) {} - -#endif /* FEE_DEBUG */ - -#if defined(NeXT) && !defined(WIN32) - -void getpassword(const char *prompt, char *pbuf) -{ - struct sgttyb ttyb; - int flags; - register char *p; - register int c; - FILE *fi; - void (*sig)(int); - - if ((fi = fdopen(open("/dev/tty", 2, 0), "r")) == NULL) - fi = stdin; - else - setbuf(fi, (char *)NULL); - sig = signal(SIGINT, SIG_IGN); - ioctl(fileno(fi), TIOCGETP, &ttyb); - flags = ttyb.sg_flags; - ttyb.sg_flags &= ~ECHO; - ioctl(fileno(fi), TIOCSETP, &ttyb); - fprintf(stderr, "%s", prompt); fflush(stderr); - for (p=pbuf; (c = getc(fi))!='\n' && c!=EOF;) { - if (p < &pbuf[PHRASELEN-1]) - *p++ = c; - } - *p = '\0'; - fprintf(stderr, "\n"); fflush(stderr); - ttyb.sg_flags = flags; - ioctl(fileno(fi), TIOCSETP, &ttyb); - (void)signal(SIGINT, sig); - if (fi != stdin) - fclose(fi); -} -#endif // NeXT - -/* - * serialize, deserialize giants's n[] to/from byte stream. - * First byte of byte stream is the MS byte of the resulting giant, - * regardless of the size of giantDigit. - * - * No assumption is made about the alignment of cp. - * - * As of 7 Apr 1998, these routines are in compliance with IEEE P1363, - * section 5.5.1, for the representation of a large integer as a byte - * stream. - */ -void serializeGiant(giant g, - unsigned char *cp, - unsigned numBytes) -{ - unsigned digitDex; - unsigned numDigits = BYTES_TO_GIANT_DIGITS(numBytes); - giantDigit digit; - unsigned char *ptr; - unsigned digitByte; - int size = abs(g->sign); - - if(numBytes == 0) { - return; - } - if(numBytes > (g->capacity * GIANT_BYTES_PER_DIGIT)) { - CKRaise("serializeGiant: CAPACITY EXCEEDED!\n"); - } - - /* - * note we might be asked to write more than the valid number - * if bytes in the giant in the case if truncated sign due to - * zero M.S. digit(s).... - */ - - /* - * zero out unused digits so we can infer sign during deserialize - */ - for(digitDex=size; digitDexn[digitDex] = 0; - } - - /* - * Emit bytes starting from l.s. byte. L.s. byte of the outgoing - * data stream is *last*. L.s. digit of giant's digits is *first*. - */ - digitDex = 0; - ptr = &cp[numBytes - 1]; - do { - /* one loop per giant digit */ - digit = g->n[digitDex++]; - for(digitByte=0; digitByte>= 8; - } - } while(numBytes != 0); - -} - -/* - * Resulting sign here is always positive; leading zeroes are reflected - * in an altered g->sign. - */ -void deserializeGiant(const unsigned char *cp, - giant g, - unsigned numBytes) -{ - unsigned numDigits; - giantDigit digit; - int digitDex; - unsigned digitByte; - const unsigned char *ptr; - - if(numBytes == 0) { - g->sign = 0; - return; - } - numDigits = (numBytes + GIANT_BYTES_PER_DIGIT - 1) / - GIANT_BYTES_PER_DIGIT; - if(numBytes > (g->capacity * GIANT_BYTES_PER_DIGIT)) { - CKRaise("deserializeGiant: CAPACITY EXCEEDED!\n"); - } - - /* - * Start at l.s. byte. That's the end of the cp[] array and - * the beginning of the giantDigit array. - */ - digitDex = 0; - ptr = &cp[numBytes - 1]; - do { - /* one loop per digit */ - digit = 0; - for(digitByte=0; digitByten before this break? */ - if(--numBytes == 0) { - break; - } - } - g->n[digitDex++] = digit; - } while (numBytes != 0); - - /* - * Infer sign from non-zero n[] elements - */ - g->sign = numDigits; - gtrimSign(g); -} - diff --git a/OSX/include/security_cryptkit/ckutilities.h b/OSX/include/security_cryptkit/ckutilities.h deleted file mode 100644 index 8bf8a228..00000000 --- a/OSX/include/security_cryptkit/ckutilities.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ckutilities.h - general private C routine declarations - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 2 Aug 96 at NeXT - * Broke out from Blaine Garst's original NSCryptors.m - */ - -#ifndef _CK_UTILITIES_H_ -#define _CK_UTILITIES_H_ - -#include "giantIntegers.h" -#include "elliptic.h" -#include "feeTypes.h" - -#ifdef __cplusplus -extern "C" { -#endif - -unsigned char *mem_from_giant(giant x, unsigned *memLen); -giant giant_with_data(const unsigned char *d, int len); - -void serializeGiant(giant g, - unsigned char *cp, - unsigned numBytes); - -void deserializeGiant(const unsigned char *cp, - giant g, - unsigned numBytes); - -#ifdef __cplusplus -} -#endif - -#endif /* _CK_UTILITIES_H_ */ diff --git a/OSX/include/security_cryptkit/curveParamData.h b/OSX/include/security_cryptkit/curveParamData.h deleted file mode 100644 index 24b5e6fc..00000000 --- a/OSX/include/security_cryptkit/curveParamData.h +++ /dev/null @@ -1,540 +0,0 @@ -/* New ECC curves, - - 14 Apr 2001 (REC) ensured x1Minus arithmetic & prime point orders - 5 Apr 2001 (REC) factored minusorder for NIST-P-192 - 3 Apr 2001 (REC) first draft - - c. 2001 Apple Computer, Inc. - All Rights Reserved. - - Currently there are 7 (seven) curves, at varying - bit-depth and varying parameter types: - - FEE curves (use Montgomery arithmetic and feemod base-prime): - 31 bits - 127 bits - IEEE curves (use projective arithmetic): - 31 bits (feemod base-prime) - 128 bits (feemod base-prime) - 161 bits (feemod base-prime) (default preference) - 161 bits (general prime) - 192 bits (general. prime) (NIST-recommended) - - Each curve is given key comments atop the parameters. - For performance considerations, - - primeType->Mersenne is faster than primeType->feemod is - faster than primeType->general - - curveType->Montgomery is faster than curveType->Weierstrass, - - Some choices are not obvious except to cryptographers; - e.g., the two curves given for 161 bits exist because - of cryptographic controversies; probably the curve with - both orders prime is more secure, so it is perhaps - the curve of choice at 161 bits. - - The parameters/points have standard meaning, except for our - special entities as listed below. It is important to note the - principle thgat, without exception, every CryptKit base prime - p is = 3 (mod 4). This allows simple square-rooting in the field - F_p. Because of this universal constraint, (-1) is always a - quadratic nonresidue and so twist curves as below can assume - g = -1. - - (...)plusOrder := The usual elliptic-curve order; - (...)x1Plus := x-coordinate on y^2 = x^3 + c x^2 + a x + b; - (...)x1OrderPlus := Order of x1Plus, always divides plusOrder - (...)minusOrder := Order of the twist curve = 2p+2-plusOrder - (...)x1Minus := x-coordinate chosen on the twist curve - g y^2 = x^3 + c x^2 + a x + b - where g = -1 is the nonresidue, and such that - the special, x-coordinates-only, twofold-ambiguous "add" of - FEED works on the minus curve, using the same curve - parameters a,b,c as for the plus curve. Note that - x1Minus is to be chosen so that the correct "add" arithmetic - occurs, and also so that the desired point order accrues. - (...)x1OrderMinus := Order of x1Plus, always divides minusOrder. - - In each of the curves specified below, the plusOrder (at least) - is prime, while each of the point orders x1OrderPlus/Minus - is always prime. - - Note that the older labels Atkin3, Atkin4 have been abolished. - - */ - - /* FEE CURVE: USE FOR FEE SIG. & FEED ONLY. - * primeType->Mersenne - * curveType->Montgomery - * q = 31; k = 1; p = 2^q - k; - * a = 1; b = 0; c = 666; - * Both orders composite. - */ -static const arrayDigit ga_31m_x1Plus[] = - {2, 61780, 6237}; - /* 408809812 */ -static const arrayDigit ga_31m_x1Minus[] = - {2,12973,30585}; - /* 2004431533 */ -static const arrayDigit ga_31m_plusOrder[] = - {2, 25928, 32768 }; - /* 2147509576 = 2^3 * 268438697. */ -static const arrayDigit ga_31m_minusOrder[] = - {2, 39608, 32767 }; - /* 2147457720 = 2^3 * 3 * 5 * 17895481. */ -static const arrayDigit ga_31m_x1OrderPlus[] = - {2, 3241, 4096}; - /* 268438697 */ -static const arrayDigit ga_31m_x1OrderMinus[] = - {2, 4153, 273}; - /* 17895481 */ -static const arrayDigit ga_31m_x1OrderPlusRecip[] = - {2, 52572, 16383}; -static const arrayDigit ga_31m_lesserX1OrderRecip[] = - {2, 759, 960}; - - /* IEEE P1363 COMPATIBLE. - * primeType->Mersenne - * curveType->Weierstrass - * q = 31; k = 1; p = 2^q-k; - * a = 5824692 b = 2067311435 c = 0 - * Both orders prime. - */ -static const arrayDigit ga_31w_x1Plus[] = - {1, 6 }; -static const arrayDigit ga_31w_x1Minus[] = - {1, 7 }; -static const arrayDigit ga_31w_plusOrder[] = - {2,59003,32766 }; - /* 2147411579 */ -static const arrayDigit ga_31w_minusOrder[] = - {2,6533,32769 }; - /* 2147555717 */ -static const arrayDigit ga_31w_x1OrderPlus[] = - {2,59003,32766}; - /* 2147411579 */ -static const arrayDigit ga_31w_x1OrderMinus[] = - {2,6533,32769}; - /* 2147555717 */ -static const arrayDigit ga_31w_x1OrderPlusRecip[] = - {2, 6535, 32769}; - -static const arrayDigit ga_31w_a[] = - {2,57524,88}; - /* 5824692 */ -static const arrayDigit ga_31w_b[] = - {2,43851,31544}; - /* 2067311435 */ - - /* FEE CURVE: USE FOR FEE SIG. & FEED ONLY. - * primeType->Mersenne - * curveType->Montgomery - * q = 127; k = 1; p = 2^q - k; - * a = 1; b = 0; c = 666; - * Both orders composite. - */ -static const arrayDigit ga_127m_x1Plus[] = - {8, 24044, 39922, 11050, - 24692, 34049, 9793, 1228, 31562}; - /* 163879370753099435779911346846180728300 */ -static const arrayDigit ga_127m_x1Minus[] = - {8,49015,6682,26772,63672,45560,46133,24769,8366}; - /* 43440717976631899041527862406676135799 */ -static const arrayDigit ga_127m_plusOrder[] = - { 8, 14612, 61088, 34331, - 32354, 65535, 65535, 65535, - 32767}; - /* 170141183460469231722347548493196835092 = -2^2 * 3^4 * 71 * 775627 * 9535713005180210505588285449. */ -static const arrayDigit ga_127m_minusOrder[] = - { 8, 50924, 4447, 31204, - 33181, 0, 0, 0, - 32768 }; - /* 170141183460469231741027058938571376364 = -2^2 * 17 * 743 * 1593440383 * 2113371777483973234080067. */ -static const arrayDigit ga_127m_x1OrderPlus[] = - {6, 8201, 61942, 37082, - 53787, 49605, 7887 }; - /* 9535713005180210505588285449 */ -static const arrayDigit ga_127m_x1OrderMinus[] = - {6, 14659, 1977,16924, - 7446, 49030, 1}; - /* 2113371777483973234080067 */ -static const arrayDigit ga_127m_x1OrderPlusRecip[] = - {6, 21911, 8615, 0, 40960, 64107, 8507}; -static const arrayDigit ga_127m_lesserX1OrderRecip[] = - {6, 44759, 65533, 17695, 61560, 18883, 2}; - - /* IEEE P1363 COMPATIBLE. - * primeType->feemod - * curveType->Weierstrass - * q = 127; k = -57675; p = 2^q - k; - * a = 170141183460469025572049133804586627403; - * b = 170105154311605172483148226534443139403; c = 0; - * Both orders prime.: - */ -static const arrayDigit ga_128w_x1Plus[] = - {1,6}; - /* 6 */ -static const arrayDigit ga_128w_x1Minus[] = - {1,3}; - /* 3 */ -static const arrayDigit ga_128w_plusOrder[] = - {8,40455,13788,48100,24190,1,0,0,32768}; - /* 170141183460469231756943134065055014407. */ -static const arrayDigit ga_128w_minusOrder[] = - {8,9361,51749,17435,41345,65534,65535,65535,32767}; - /* 170141183460469231706431473366713312401. */ -static const arrayDigit ga_128w_x1OrderPlus[] = - {8,40455,13788,48100,24190,1,0,0,32768}; - /* 170141183460469231756943134065055014407. */ -static const arrayDigit ga_128w_x1OrderMinus[] = - {8,9361,51749,17435,41345,65534,65535,65535,32767}; - /* 170141183460469231706431473366713312401. */ -static const arrayDigit ga_128w_x1OrderPlusRecip[] = - {9,34802,10381,4207,34309,65530,65535,65535,65535,1}; -static const arrayDigit ga_128w_lesserX1OrderRecip[] = - {8,56178,13786,48100,24190,1,0,0,32768}; - -static const arrayDigit ga_128w_a[] = - {8,29003,44777,29962,4169,54360,65535,65535,32767}; - /* 170141183460469025572049133804586627403; */ -static const arrayDigit ga_128w_b[] = - {8,16715,42481,16221,60523,56573,13644,4000,32761}; - /* 170105154311605172483148226534443139403. */ - - /* IEEE P1363 COMPATIBLE. - * primeType->feemod - * curveType->Weierstrass - * q = 160; k = -5875; p = 2^q - k; - * a = 1461501637330902918203684832716283019448563798259; - * b = 36382017816364032; c = 0; - * Both orders prime.: - */ -static const arrayDigit ga_161w_x1Plus[] = - {1,7}; - /* 7 */ -static const arrayDigit ga_161w_x1Minus[] = - {1,4}; - /* 4 */ -static const arrayDigit ga_161w_plusOrder[] = - {11,50651,30352,49719,403,64085,1,0,0,0,0,1}; - /* 1461501637330902918203687223801810245920805144027. */ -static const arrayDigit ga_161w_minusOrder[] = - {10,26637,35183,15816,65132,1450,65534,65535,65535,65535,65535}; - /* 1461501637330902918203682441630755793391059953677. */ -static const arrayDigit ga_161w_x1OrderPlus[] = - {11,50651,30352,49719,403,64085,1,0,0,0,0,1}; - /* 1461501637330902918203687223801810245920805144027. */ -static const arrayDigit ga_161w_x1OrderMinus[] = - {10,26637,35183,15816,65132,1450,65534,65535,65535,65535,65535}; - /* 1461501637330902918203682441630755793391059953677. */ -static const arrayDigit ga_161w_x1OrderPlusRecip[] = - {11,59555,9660,63266,63920,5803,65528,65535,65535,65535,65535,3}; -/* added by dmitch */ -static const arrayDigit ga_161w_lesserX1OrderRecip[] = - {12,38902,30352,49719,403,64085,1,0,0,0,0,1,0}; -/* end addenda */ - -static const arrayDigit ga_161w_a[] = {10,4339,47068,65487,65535,65535,65535,65535,65535,65535,65535}; -/* 1461501637330902918203684832716283019448563798259; */ -static const arrayDigit ga_161w_b[] = {4,1024,41000,16704,129}; -/* 36382017816364032. */ - - /* IEEE P1363 COMPATIBLE. - * primeType->General - * curveType->Weierstrass - * p is a 161-bit random prime (below, ga_161_gen_bp[]); - * a = -152; b = 722; c = 0; - * Both orders composite.: - */ -static const arrayDigit ga_161_gen_bp[] = - {11,41419,58349,36408,14563,25486,9098,29127,50972,7281,8647,1}; - /* baseprime = 1654338658923174831024422729553880293604080853451 */ -static const arrayDigit ga_161_gen_x1Plus[] = - {10,59390,38748,49144,50217,32781,46057,53816,62856,18968,55868}; - /* 1245904487553815885170631576005220733978383542270 */ -static const arrayDigit ga_161_gen_x1Minus[] = - {10,12140,40021,9852,49578,18446,39468,28773,10952,26720,52624}; - /* 1173563507729187954550227059395955904200719019884 */ -static const arrayDigit ga_161_gen_plusOrder[] = - {11,41420,58349,36408,14563,25486,9100,29127,50972,7281,8647,1}; - /* 1654338658923174831024425147405519522862430265804 = - 2^2 * 23 * 359 * 479 * 102107 * 1024120625531724089187207582052247831. */ -static const arrayDigit ga_161_gen_minusOrder[] = - {11,41420,58349,36408,14563,25486,9096,29127,50972,7281,8647,1}; - /* 1654338658923174831024420311702241064345731441100 = -2^2 * 5^2 * 17^2 * 57243552211874561627142571339177891499852299. */ -static const arrayDigit ga_161_gen_x1OrderPlus[] = - {8,59671,64703,58305,55887,34170,37971,15627,197}; - /* 1024120625531724089187207582052247831 */ -static const arrayDigit ga_161_gen_x1OrderMinus[] = - {10,49675,56911,64364,6281,5543,59511,52057,44604,37151,2}; - /* 57243552211874561627142571339177891499852299 */ -static const arrayDigit ga_161_gen_x1OrderPlusRecip[] = - {8, 7566, 37898, 14581, 2404, 52670, 23839, 17554, 332}; - -static const arrayDigit ga_161_gen_a[] = {-1, 152}; /* a = -152 */ -static const arrayDigit ga_161_gen_b[] = { 1, 722}; /* b = 722 */ - - - /* IEEE P1363 COMPATIBLE. - * (NIST-P-192 RECOMMENDED PRIME) - * primeType->General - * curveType->Weierstrass - * p is a 192-bit prime (with efficient bit structure) (below, ga_192_gen_bp[]); - * a = -3; b = 2455155546008943817740293915197451784769108058161191238065; c = 0; - * Plus-order is prime, minus-order is composite. - */ -static const arrayDigit ga_192_gen_bp[] = - {12,65535,65535,65535,65535,65534,65535,65535,65535,65535,65535,65535,65535}; - /* baseprime = -6277101735386680763835789423207666416083908700390324961279 */ -static const arrayDigit ga_192_gen_x1Plus[] = - {1,3}; - /* 3 */ -static const arrayDigit ga_192_gen_x1Minus[] = - {12,25754,63413,46363,42413,24848,21836,55473,50853,40413,10264,8715,59556}; - /* 5704344264203732742656350325931731344592841761552300598426 */ -static const arrayDigit ga_192_gen_plusOrder[] = - {12,10289,46290,51633,5227,63542,39390,65535,65535,65535,65535,65535,65535}; - /* 6277101735386680763835789423176059013767194773182842284081 */ -static const arrayDigit ga_192_gen_minusOrder[] = - {13,55247,19245,13902,60308,1991,26145,0,0,0,0,0,0,1}; - /* 6277101735386680763835789423239273818400622627597807638479 = - 23 * 10864375060560251605900677743 * - 25120401793443689936479125511 */ -static const arrayDigit ga_192_gen_x1OrderPlus[] = - {12,10289,46290,51633,5227,63542,39390,65535,65535,65535,65535,65535,65535}; - /* 6277101735386680763835789423176059013767194773182842284081 */ -static const arrayDigit ga_192_gen_x1OrderMinus[] = - {12,16649,40728,9152,53911,59923,9684,22795,17096,45590,34192,25644,2849}; - /* 272917466755942641905903887966924948626114027286861201673 = -10864375060560251605900677743 * 25120401793443689936479125511 -*/ -static const arrayDigit ga_192_gen_x1OrderPlusRecip[] = - {13,55247,19245,13902,60308,1993,26145,0,0,0,0,0,0,1}; -static const arrayDigit ga_192_gen_lesserX1OrderRecip[] = -{12,57756,63294,44830,2517,2125,63187,65535,65535,65535,65535,65535,5887}; - -static const arrayDigit ga_192_gen_a[] = {-1, 3}; /* a = -3. */ -static const arrayDigit ga_192_gen_b[] = -{12,47537,49478,57068,65208,12361,29220,59819,4007,32999,58780,1305,25633}; -/* b = 2455155546008943817740293915197451784769108058161191238065. */ - -/*** - *** ANSI X9.62/Certicom curves - ***/ - -/* - * secp192r1 - * - * p = FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF - * = 6277101735386680763835789423207666416083908700390324961279 (d) - * a = FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC - * = 6277101735386680763835789423207666416083908700390324961276 - * b = 64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1 - * = 2455155546008943817740293915197451784769108058161191238065 - * x = 188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012 - * = 602046282375688656758213480587526111916698976636884684818 - * y = 07192B95FFC8DA78631011ED6B24CDD573F977A11E794811 - * = 174050332293622031404857552280219410364023488927386650641 - * order = FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 - * = 6277101735386680763835789423176059013767194773182842284081 - * x1OrderRecip = 1000000000000000000000000662107c9eb94364e4b2dd7cf - */ -static const arrayDigit ga_192_secp_bp[] = - {12, 0xffff, 0xffff, 0xffff, 0xffff, 0xfffe, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_192_secp_x1Plus[] = - {12, 0x1012, 0x82ff, 0xafd, 0xf4ff, 0x8800, 0x43a1, 0x20eb, 0x7cbf, 0x90f6, 0xb030, 0xa80e, 0x188d}; -static const arrayDigit ga_192_secp_y1Plus[] = - {12, 0x4811, 0x1e79, 0x77a1, 0x73f9, 0xcdd5, 0x6b24, 0x11ed, 0x6310, 0xda78, 0xffc8, 0x2b95, 0x719}; -static const arrayDigit ga_192_secp_plusOrder[] = - {12, 0x2831, 0xb4d2, 0xc9b1, 0x146b, 0xf836, 0x99de, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -/* the curve order is prime, so x1Order = curveOrder */ -static const arrayDigit ga_192_secp_x1OrderPlus[] = - {12, 0x2831, 0xb4d2, 0xc9b1, 0x146b, 0xf836, 0x99de, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_192_secp_x1OrderPlusRecip[] = - {13, 0xd7cf, 0x4b2d, 0x364e, 0xeb94, 0x7c9, 0x6621, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}; -static const arrayDigit ga_192_secp_a[] = - {12, 0xfffc, 0xffff, 0xffff, 0xffff, 0xfffe, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_192_secp_b[] = - {12, 0xb9b1, 0xc146, 0xdeec, 0xfeb8, 0x3049, 0x7224, 0xe9ab, 0xfa7, 0x80e7, 0xe59c, 0x519, 0x6421}; - - -/* - * secp256r1 - * - * p = FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF - * = 115792089210356248762697446949407573530086143415290314195533631308867097853951 - * a = FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC - * = 115792089210356248762697446949407573530086143415290314195533631308867097853948 - * b = 5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B - * = 41058363725152142129326129780047268409114441015993725554835256314039467401291 - * x = 6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 - * = 48439561293906451759052585252797914202762949526041747995844080717082404635286 - * y = 4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5 - * = 36134250956749795798585127919587881956611106672985015071877198253568414405109 - * order = FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 - * = 115792089210356248762697446949407573529996955224135760342422259061068512044369 - * FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 - * x1OrderRecip = 100000000fffffffffffffffeffffffff43190552df1a6c21012ffd85eedf9bfe - */ -static const arrayDigit ga_256_secp_bp[] = - {16, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x1, 0x0, 0xffff, 0xffff}; -static const arrayDigit ga_256_secp_x1Plus[] = - {16, 0xc296, 0xd898, 0x3945, 0xf4a1, 0x33a0, 0x2deb, 0x7d81, 0x7703, 0x40f2, - 0x63a4, 0xe6e5, 0xf8bc, 0x4247, 0xe12c, 0xd1f2, 0x6b17}; -static const arrayDigit ga_256_secp_y1Plus[] = - {16, 0x51f5, 0x37bf, 0x4068, 0xcbb6, 0x5ece, 0x6b31, 0x3357, 0x2bce, 0x9e16, - 0x7c0f, 0xeb4a, 0x8ee7, 0x7f9b, 0xfe1a, 0x42e2, 0x4fe3}; -static const arrayDigit ga_256_secp_plusOrder[] = - {16, 0x2551, 0xfc63, 0xcac2, 0xf3b9, 0x9e84, 0xa717, 0xfaad, 0xbce6, 0xffff, - 0xffff, 0xffff, 0xffff, 0x0, 0x0, 0xffff, 0xffff}; -static const arrayDigit ga_256_secp_x1OrderPlus[] = - {16, 0x2551, 0xfc63, 0xcac2, 0xf3b9, 0x9e84, 0xa717, 0xfaad, 0xbce6, 0xffff, - 0xffff, 0xffff, 0xffff, 0x0, 0x0, 0xffff, 0xffff}; -static const arrayDigit ga_256_secp_x1OrderPlusRecip[] = - {17, 0x9bfe, 0xeedf, 0xfd85, 0x12f, 0x6c21, 0xdf1a, 0x552, 0x4319, 0xffff, - 0xffff, 0xfffe, 0xffff, 0xffff, 0xffff, 0x0, 0x0, 0x1}; -static const arrayDigit ga_256_secp_a[] = - {16, 0xfffc, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0, 0x0, 0x0, 0x0, 0x0, - 0x0, 0x1, 0x0, 0xffff, 0xffff}; -static const arrayDigit ga_256_secp_b[] = - {16, 0x604b, 0x27d2, 0x3c3e, 0x3bce, 0xb0f6, 0xcc53, 0x6b0, 0x651d, 0x86bc, - 0x7698, 0xbd55, 0xb3eb, 0x93e7, 0xaa3a, 0x35d8, 0x5ac6}; - -/* - * secp384r1 - * - * p = FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF\ - * 0000000000000000FFFFFFFF - * = 394020061963944792122790401001436138050797392704654466679482934042457217\ - * 71496870329047266088258938001861606973112319 - * a = FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF\ - * 0000000000000000FFFFFFFC - * = 394020061963944792122790401001436138050797392704654466679482934042457217\ - * 71496870329047266088258938001861606973112316 - * b = B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D\ - * 8A2ED19D2A85C8EDD3EC2AEF - * = 275801935599597058778490118403890480930569058563615685214287073019886892\ - * 41309860865136260764883745107765439761230575 - * x = AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25D\ - * BF55296C3A545E3872760AB7 - * = 262470350957996892686231567445669818918529234911092133878156159009255188\ - * 54738050089022388053975719786650872476732087 - * y = 3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE\ - * 1D7E819D7A431D7C90EA0E5F - * = 832571096148902998554675128952010817928785304886131559470920590248050319\ - * 9884419224438643760392947333078086511627871 - * order = FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB2\ - * 48B0A77AECEC196ACCC52973 - * = 394020061963944792122790401001436138050797392704654466679469052796276593\ - * 99113263569398956308152294913554433653942643 - */ -static const arrayDigit ga_384_secp_bp[] = - {24, 0xffff, 0xffff, 0x0, 0x0, 0x0, 0x0, 0xffff, 0xffff, 0xfffe, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_384_secp_x1Plus[] = - {24, 0xab7, 0x7276, 0x5e38, 0x3a54, 0x296c, 0xbf55, 0xf25d, 0x5502, 0x2a38, - 0x8254, 0x41e0, 0x59f7, 0x9b98, 0x8ba7, 0x3b62, 0x6e1d, 0xad74, 0xf320, - 0xc71e, 0x8eb1, 0x537, 0xbe8b, 0xca22, 0xaa87}; -static const arrayDigit ga_384_secp_y1Plus[] = - {24, 0xe5f, 0x90ea, 0x1d7c, 0x7a43, 0x819d, 0x1d7e, 0xb1ce, 0xa60, 0xb8c0, - 0xb5f0, 0x3113, 0xe9da, 0x147c, 0x289a, 0x1dbd, 0xf8f4, 0xdc29, 0x9292, - 0x98bf, 0x5d9e, 0x2c6f, 0x9626, 0xde4a, 0x3617}; -static const arrayDigit ga_384_secp_plusOrder[] = - {24, 0x2973, 0xccc5, 0x196a, 0xecec, 0xa77a, 0x48b0, 0xdb2, 0x581a, 0x2ddf, - 0xf437, 0x4d81, 0xc763, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_384_secp_x1OrderPlus[] = - {24, 0x2973, 0xccc5, 0x196a, 0xecec, 0xa77a, 0x48b0, 0xdb2, 0x581a, 0x2ddf, - 0xf437, 0x4d81, 0xc763, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_384_secp_x1OrderPlusRecip[] = - {25, 0xd68d, 0x333a, 0xe695, 0x1313, 0x5885, 0xb74f, 0xf24d, 0xa7e5, 0xd220, 0xbc8, - 0xb27e, 0x389c, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}; -static const arrayDigit ga_384_secp_a[] = - {24, 0xfffc, 0xffff, 0x0, 0x0, 0x0, 0x0, 0xffff, 0xffff, 0xfffe, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff}; -static const arrayDigit ga_384_secp_b[] = - {24, 0x2aef, 0xd3ec, 0xc8ed, 0x2a85, 0xd19d, 0x8a2e, 0x398d, 0xc656, 0x875a, - 0x5013, 0x88f, 0x314, 0x4112, 0xfe81, 0x9c6e, 0x181d, 0x2d19, 0xe3f8, 0x56b, - 0x988e, 0xe7e4, 0xe23e, 0x2fa7, 0xb331}; - -/* - * secp521r1 - * p = 01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\ - * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - * = 686479766013060971498190079908139321726943530014330540939446345918554318\ - * 339765605212255964066145455497729631139148085803712198799971664381257402\ - * 8291115057151 - * a = 01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\ - * FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC - * = 686479766013060971498190079908139321726943530014330540939446345918554318\ - * 339765605212255964066145455497729631139148085803712198799971664381257402\ - * 8291115057148 - * b = 0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E15619\ - * 3951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00 - * = 109384903807373427451111239076680556993620759895168374899458639449595311\ - * 615073501601370873757375962324859213229670631330943845253159101291214232\ - * 7488478985984 - * x = 00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B\ - * 5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66 - * = 266174080205021706322876871672336096072985916875697314770667136841880294\ - * 499642780849154508062777190235209424122506555866215711354557091681416163\ - * 7315895999846 - * y = 011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE\ - * 72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650 - * = 375718002577002046354550722449118360359445513476976248669456777961554447\ - * 744055631669123440501294553956214444453728942852258566672919658081012434\ - * 4277578376784 - * order = 01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA5186\ - * 8783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409 - * = 686479766013060971498190079908139321726943530014330540939446345918554318\ - * 339765539424505774633321719753296399637136332111386476861244038034037280\ - * 8892707005449 - * orderRecip = 200 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000005 \ - * ae79787c 40d06994 8033feb7 08f65a2f c44a3647 7663b851 449048e1 6ec79bf7 - * orderRecip = 2000000000000000000000000000000000000000000000000000000000000000005ae79787c40d069948033feb708f65a2fc44a36477663b851449048e16ec79bf7 - */ -static const arrayDigit ga_521_secp_bp[] = - {33, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0x1ff}; -static const arrayDigit ga_521_secp_x1Plus[] = - {33, 0xbd66, 0xc2e5, 0x7e31, 0xf97e, 0x429b, 0x856a, 0xb3c1, 0x3348, 0xa8de, 0xa2ff, - 0xc127, 0xfe1d, 0x5928, 0xefe7, 0x5e77, 0xa14b, 0x3dba, 0x6b4d, 0xaf60, 0xf828, 0xb521, - 0x53f, 0x8139, 0x9c64, 0xb442, 0x2395, 0xcb66, 0x9e3e, 0xe9cd, 0x404, 0x6b7, 0x858e, 0xc6}; -static const arrayDigit ga_521_secp_y1Plus[] = - {33, 0x6650, 0x9fd1, 0x9476, 0x88be, 0xc240, 0xa272, 0x7086, 0x353c, 0x761, 0x3fad, - 0xb901, 0xc550, 0x2640, 0x5ef4, 0x7299, 0x97ee, 0x662c, 0x273e, 0xbd17, 0x17af, 0x4468, - 0x579b, 0x4449, 0x98f5, 0x1bd9, 0x2c7d, 0x5fb4, 0x5c8a, 0xc004, 0x9a3b, 0x6a78, 0x3929, - 0x118}; -static const arrayDigit ga_521_secp_plusOrder[] = - {33, 0x6409, 0x9138, 0xb71e, 0xbb6f, 0x47ae, 0x899c, 0xc9b8, 0x3bb5, 0xa5d0, 0xf709, - 0x148, 0x7fcc, 0x966b, 0xbf2f, 0x8783, 0x5186, 0xfffa, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0x1ff}; -static const arrayDigit ga_521_secp_x1OrderPlus[] = - {33, 0x6409, 0x9138, 0xb71e, 0xbb6f, 0x47ae, 0x899c, 0xc9b8, 0x3bb5, 0xa5d0, 0xf709, - 0x148, 0x7fcc, 0x966b, 0xbf2f, 0x8783, 0x5186, 0xfffa, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0x1ff}; -static const arrayDigit ga_521_secp_x1OrderPlusRecip[] = -{33, 0x9bf7, 0x6ec7, 0x48e1, 0x4490, 0xb851, 0x7663, 0x3647, 0xc44a, 0x5a2f, 0x8f6, 0xfeb7, 0x8033, 0x6994, 0x40d0, 0x787c, 0xae79, 0x5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x200}; -static const arrayDigit ga_521_secp_a[] = - {33, 0xfffc, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, - 0xffff, 0xffff, 0xffff, 0x1ff}; -static const arrayDigit ga_521_secp_b[] = - {33, 0x3f00, 0x6b50, 0x1fd4, 0xef45, 0x34f1, 0x3d2c, 0xdf88, 0x3573, 0xbf07, - 0x3bb1, 0xc0bd, 0x1652, 0x937b, 0xec7e, 0x3951, 0x5619, 0x9e1, 0x8ef1, 0x8991, - 0xb8b4, 0x15f3, 0x99b3, 0x725b, 0xa2da, 0x40ee, 0xb685, 0x21a0, 0x929a, 0x9a1f, - 0x8e1c, 0xb961, 0x953e, 0x51}; diff --git a/OSX/include/security_cryptkit/curveParamDataOld.h b/OSX/include/security_cryptkit/curveParamDataOld.h deleted file mode 100644 index 2b0c6fbf..00000000 --- a/OSX/include/security_cryptkit/curveParamDataOld.h +++ /dev/null @@ -1,350 +0,0 @@ -/* - * curveParamDataOld.h - prototype FEE curve parameters (obsolete as of 4/9/2001) - */ -#warning Using obsolete curveParam data! -/* - * q = 31 k = 1, Weierstrass - * a = 7 b = 1 c = 0 - */ -static arrayDigit ga_w31_1_a[] = {1, 7}; -static arrayDigit ga_w31_1_x1Plus[] = - {2,15438,14404}; - /* 943995982 */ -static arrayDigit ga_w31_1_x1Minus[] = - {2, 10400, 19905}; - /* 1304504480 */ -static arrayDigit ga_w31_1_plusOrder[] = - {2, 3848, 32769}; - /* 2147553032 */ -static arrayDigit ga_w31_1_minusOrder[] = - {2, 61688, 32766 }; - /* 2147414264 */ -static arrayDigit ga_w31_1_x1OrderPlus[] = - {2, 8673, 4096}; - /* 268444129 */ -static arrayDigit ga_w31_1_x1OrderMinus[] = - {2, 56863, 4095 }; - /* 268426783 */ -static arrayDigit ga_w31_1_x1OrderPlusRecip[] = - {2, 30845, 16383}; -static arrayDigit ga_w31_1_lesserX1OrderRecip[] = - {2, 8673, 4096}; - -/* - * q = 31 k = 1, Montgomery - * a = 1 b = 0 c = 666 - */ -static arrayDigit ga_m31_1_x1Plus[] = - {2, 61780, 6237}; - /* 408809812 */ -static arrayDigit ga_m31_1_x1Minus[] = - {2,12973,30585}; - /* 2004431533 */ -static arrayDigit ga_m31_1_plusOrder[] = - {2, 25928, 32768 }; - /* 2147509576 */ -static arrayDigit ga_m31_1_minusOrder[] = - {2, 39608, 32767 }; - /* 2147457720 */ -static arrayDigit ga_m31_1_x1OrderPlus[] = - {2, 3241, 4096}; - /* 268438697 */ -static arrayDigit ga_m31_1_x1OrderMinus[] = - {2, 4153, 273}; - /* 17895481 */ -static arrayDigit ga_m31_1_x1OrderPlusRecip[] = - {2, 52572, 16383}; -static arrayDigit ga_m31_1_lesserX1OrderRecip[] = - {2, 759, 960}; - -/* - * q = 31 k = 1, Montgomery, prime curve orders - * a = 5824692 b = 2067311435 c = 0 - */ -static arrayDigit ga_31_1P_x1Plus[] = - {1, 6 }; -static arrayDigit ga_31_1P_x1Minus[] = - {1, 7 }; -static arrayDigit ga_31_1P_plusOrder[] = - {2,59003,32766 }; - /* 2147411579 */ -static arrayDigit ga_31_1P_minusOrder[] = - {2,6533,32769 }; - /* 2147555717 */ -static arrayDigit ga_31_1P_x1OrderPlus[] = - {2,59003,32766}; - /* 2147411579 */ -static arrayDigit ga_31_1P_x1OrderMinus[] = - {2,6533,32769}; - /* 2147555717 */ -static arrayDigit ga_31_1P_x1OrderPlusRecip[] = - {2, 6535, 32769}; - -static arrayDigit ga_31_1P_a[] = - {2,57524,88}; - /* 5824692 */ -static arrayDigit ga_31_1P_b[] = - {2,43851,31544}; - /* 2067311435 */ - -/* - * q = 40 k = 213, Weierstrass - * a = 1627500953 b = 523907505 c = 0 - */ -static arrayDigit ga_40_213_x1Plus[] = - {1, 1 }; -static arrayDigit ga_40_213_x1Minus[] = - {1, 2 }; -static arrayDigit ga_40_213_plusOrder[] = - {3,11655,25,256}; - /* 1099513277831 */ -static arrayDigit ga_40_213_minusOrder[] = - {3,53457,65510,255}; - /* 1099509977297 */ -static arrayDigit ga_40_213_x1OrderPlus[] = - {3,11655,25,256}; - /* 1099513277831 */ -static arrayDigit ga_40_213_x1OrderMinus[] = - {3,53457,65510,255}; - /* 1099509977297 */ -static arrayDigit ga_40_213_x1OrderPlusRecip[] = - {3, 18925, 65435, 1023}; -static arrayDigit ga_40_213_lesserX1OrderRecip[] = - {3, 12081, 25, 256}; - -static arrayDigit ga_40_213_a[] = - {2,45465,24833}; - /* 1627500953 */ -static arrayDigit ga_40_213_b[] = - {2,12721,7994}; - /* 523907505 */ - -/* - * q = 127 k = 1 - * a = 1 b = 0 c = 666 - */ -static arrayDigit ga_127_1_x1Plus[] = - {8, 24044, 39922, 11050, - 24692, 34049, 9793, 1228, 31562}; - /* 163879370753099435779911346846180728300 */ -static arrayDigit ga_127_1_x1Minus[] = - {8,49015,6682,26772,63672,45560,46133,24769,8366}; - /* 43440717976631899041527862406676135799 */ -static arrayDigit ga_127_1_plusOrder[] = - { 8, 14612, 61088, 34331, - 32354, 65535, 65535, 65535, - 32767}; - /* 170141183460469231722347548493196835092 */ -static arrayDigit ga_127_1_minusOrder[] = - { 8, 50924, 4447, 31204, - 33181, 0, 0, 0, - 32768 }; - /* 170141183460469231741027058938571376364 */ -static arrayDigit ga_127_1_x1OrderPlus[] = - {6, 8201, 61942, 37082, - 53787, 49605, 7887 }; - /* 9535713005180210505588285449 */ -static arrayDigit ga_127_1_x1OrderMinus[] = - {6, 14659, 1977,16924, - 7446, 49030, 1}; - /* 2113371777483973234080067 */ -static arrayDigit ga_127_1_x1OrderPlusRecip[] = - {6, 21911, 8615, 0, 40960, 64107, 8507}; -static arrayDigit ga_127_1_lesserX1OrderRecip[] = - {6, 44759, 65533, 17695, 61560, 18883, 2}; - -/* - * This is only used for the FEE_DEPTH_127_GEN (FPT_General) case. - */ -static arrayDigit ga_127_1_bp[] = - {8, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 32767}; - -/* - * q = 127 k = 1, Weierstrass - * a = 666 b = 1 c = 0 - */ -static arrayDigit ga_127_1W_x1Plus[] = - {8, 8152, 12974, 29415, - 29630, 64916, 34821, 65368, - 29317}; - /* 152227746030289977478827896983637598168 */ -static arrayDigit ga_127_1W_x1Minus[] = - {8, 33297, 13207, 15262, - 22815, 21569, 49926, 18455, - 22807}; - /* 118422176668700242826570137796135584273 */ -static arrayDigit ga_127_1W_plusOrder[] = - {8, 7568, 62409, 28235, - 47403, 65534, 65535, 65535, - 32767 }; - /* 170141183460469231708136695161971875216 - = 2 * 2 * 2 * 2 * 11 * 17 * 47 * 103 * 10861 * - 1081540940469355570836125423 */ -static arrayDigit ga_127_1W_minusOrder[] = - {8, 57968, 3126,37300, 18132, 1, 0, 0, 32768 }; - /* 170141183460469231755237912269796336240 - = 2 * 2 * 2 * 2 * 3 * 5 * 19 * 34267 * - 1088851169917897274673487152937 */ -static arrayDigit ga_127_1W_x1OrderPlus[] = - { 6, 46831, 48825, 15584, 56652, 41267, 894 }; - /* 1081540940469355570836125423 */ -static arrayDigit ga_127_1W_x1OrderMinus[] = - {7, 1833, 34556, 10366, 60186, 37860, 48708, 13}; - /* 1088851169917897274673487152937 */ -static arrayDigit ga_127_1W_x1OrderPlusRecip[] = - {6, 48506, 2992, 0, 28160, 5127, 1172}; - -/* - * q = 160 k = 57 - * a = c = 0 b = 3 - */ -static arrayDigit ga_160_57_x1Plus[] = - {10,12520,51433,52060,51310,41288,18467,39861,56172,11574,31757}; - /* 708208703989516599321256243677211664634713026792 */ -static arrayDigit ga_160_57_x1Minus[] = - {10,40240,19544,56125,45242,10556,34052,10700,5155,57632,13213}; - /* 294679357488322649182890242541447794429265485104 */ -static arrayDigit ga_160_57_plusOrder[] = - {11,62853,63609,4196,64365,22452,1,0,0,0,0,1}; - /* 1461501637330902918203686455826517732113793021317 */ -static arrayDigit ga_160_57_minusOrder[] = - {10,2571,1926,61339,1170,43083,65534,65535,65535,65535,65535}; - /* 1461501637330902918203683209606048307198072064523 */ -static arrayDigit ga_160_57_x1OrderPlus[] = - {5,171,21451,35098,934,63868}; - /* 1178156913548056058331307 */ -static arrayDigit ga_160_57_x1OrderMinus[] = - {7,255,39523,10835,12387,25442,37088,9774}; - /* 774420897524543052406523561181439 */ -static arrayDigit ga_160_57_x1OrderPlusRecip[] = - {6, 49805, 35001, 38758, 35853, 1711, 1}; -static arrayDigit ga_160_57_b[] = {1, 3}; /* b = (giant)3 */ - -/* - * This is only used for the FEE_DEPTH_160_GEN (FPT_General) case. - */ -static arrayDigit ga_160_57_bp[] = - {10,65479,65535,65535,65535,65535,65535,65535,65535,65535,65535}; - /* 1461501637330902918203684832716283019655932542919 */ - - -/* - * q = 192 k = 1425 - * a = 0 b = -11 c = 0 - */ -static arrayDigit ga_192_1425_x1Plus[] = - {12, 44344, 60264, 44908, - 24163, 37728, 58781, 45290, - 62313, 45939, 59670, 20046, - 8781}; - /* 841082007613983662909216085212018592355989658924032240952 */ -static arrayDigit ga_192_1425_x1Minus[] = - {12,32855,61817,23700,48262,13770,23791,31597,23825,7973,37638, - 62245,25400}; - /* 2432927643133372385673335524462623851522707126886260637783 */ -static arrayDigit ga_192_1425_plusOrder[] = - {13, 7615, 52517, 60178, - 40906, 43135, 27853, 1, - 0, 0, 0, 0, 0, 1}; - /* 6277101735386680763835789423320567585182165941785488334271 */ -static arrayDigit ga_192_1425_minusOrder[] = - {12, 55073, 13018, 5357, - 24629, 22400, 37682, 65534, - 65535, 65535, 65535, 65535, - 65535}; - /* 6277101735386680763835789423094765247022544947142580688673 */ -static arrayDigit ga_192_1425_x1OrderPlus[] = - {11, 55217, 35908, 19375, - 13869, 14836, 18343, 39323, - 50251, 7215, 49984, 21171}; - /* 30942565846835947234516838572438382480699614724151217 */ -static arrayDigit ga_192_1425_x1OrderMinus[] = - {12, 42525, 5637, 42463, - 55864, 53758, 3234, 41914, - 27439, 9168, 44294, 64393, 2}; - /* 285673405333212613836790125294441598644816135581967901 */ -static arrayDigit ga_192_1425_x1OrderPlusRecip[] = - {11, 31243, 31728, 18067, - 25698, 58801, 65534, 65535, - 65535, 65535, 49151, 50715}; -static arrayDigit ga_192_1425_b[] = {-1, 11}; /* b = (giant)(-11) */ - -/* - * q = 192 k = -529891 - * a = -152 b = 722 c = 0 - */ -static arrayDigit ga_192_M529891_x1Plus[] = - {12, 27752, 118, 22193, - 28093, 63505, 16219, 38086, - 5777, 13552, 56652, 28149, - 56180}; - /* 5381016108938327910020782805833379575685074837329310805096 */ -static arrayDigit ga_192_M529891_x1Minus[] = - {12, 20031, 4376, 4872, - 24519, 24047, 14628, 60533, - 27380, 49464, 20541, 38806, - 59062}; - /* 5657072442654455186533371860713762559076927475376430009919 */ -static arrayDigit ga_192_M529891_plusOrder[] = - {13, 5604, 8, 0, - 0, 0, 0, 2, - 0, 0, 0, 0, - 0, 1}; - /* 6277101735386680763835789423366122741130884119651122943460 */ -static arrayDigit ga_192_M529891_minusOrder[] = - {12, 5604, 8, 0, - 0, 0, 0, 65534, - 65535, 65535, 65535, 65535, - 65535}; - /* 6277101735386680763835789423049210091073826769276947142116 */ -static arrayDigit ga_192_M529891_x1OrderPlus[] = - {12, 28623, 26214, 26214, - 26214, 26214, 58982, 16681, - 4766, 10724, 40513, 58386, - 297}; - /* 28532280615394003471980861015300557914231291452959649743 */ -static arrayDigit ga_192_M529891_x1OrderMinus[] = - {11, 18083, 10335, 12214, - 61896, 30741, 14099, 7255, - 33291, 27015, 23037, 196}; - /* 286968072376896521631921223217092198374509106906787 */ -static arrayDigit ga_192_M529891_x1OrderPlusRecip[] = - {12, 58420, 65535, 65535, - 65535, 65535, 63775, 65535, - 65535, 65535, 65535, 65535, 879}; -static arrayDigit ga_192_M529891_lesserX1OrderRecip[] = - {11, 65535, 65535, 65535, 35223, - 667, 0, 0, 0, 0, 50380, 333}; -static arrayDigit ga_192_M529891_a[] = {-1, 152}; /* a = -152 */ -static arrayDigit ga_192_M529891_b[] = { 1, 722}; /* b = 722 */ - -/* - * FPT_General, 161 bits - */ -static arrayDigit ga_161_gen_bp[] = - {11,41419,58349,36408,14563,25486,9098,29127,50972,7281,8647,1}; - /* baseprime = 1654338658923174831024422729553880293604080853451 */ -static arrayDigit ga_161_gen_x1Plus[] = - {10,59390,38748,49144,50217,32781,46057,53816,62856,18968,55868}; - /* 1245904487553815885170631576005220733978383542270 */ -static arrayDigit ga_161_gen_x1Minus[] = - {10,62588,37264,57758,58571,20023,11302,61317,50155,46534,18610}; - /* 415032703104741702601157337572231150005648422012 */ -static arrayDigit ga_161_gen_plusOrder[] = - {11,41420,58349,36408,14563,25486,9100,29127,50972,7281,8647,1}; - /* 1654338658923174831024425147405519522862430265804 */ -static arrayDigit ga_161_gen_minusOrder[] = - {11,41420,58349,36408,14563,25486,9096,29127,50972,7281,8647,1}; - /* 1654338658923174831024420311702241064345731441100 */ -static arrayDigit ga_161_gen_x1OrderPlus[] = - {8,59671,64703,58305,55887,34170,37971,15627,197}; - /* 1024120625531724089187207582052247831 */ -static arrayDigit ga_161_gen_x1OrderMinus[] = - {10,49675,56911,64364,6281,5543,59511,52057,44604,37151,2}; - /* 57243552211874561627142571339177891499852299 */ -static arrayDigit ga_161_gen_x1OrderPlusRecip[] = - {8, 7566, 37898, 14581, 2404, 52670, 23839, 17554, 332}; - -static arrayDigit ga_161_gen_a[] = {-1, 152}; /* a = -152 */ -static arrayDigit ga_161_gen_b[] = { 1, 722}; /* b = 722 */ - diff --git a/OSX/include/security_cryptkit/curveParams.c b/OSX/include/security_cryptkit/curveParams.c deleted file mode 100644 index 94ec2195..00000000 --- a/OSX/include/security_cryptkit/curveParams.c +++ /dev/null @@ -1,1399 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * curveParams.c - FEE curve parameter static data and functions - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 9 Sep 98 at NeXT - * Added y1Plus for IEEE P1363 compliance. - * Added curveParamsInferFields(). - * 08 Apr 98 at Apple - * Mods for giantDigit. - * 20 Jan 98 at Apple - * Added primeType, m, basePrimeRecip; added a few PT_GENERAL curves. - * 19 Jan 1998 at Apple - * New curve: q=160, k=57 - * 09 Jan 1998 at Apple - * Removed obsolete (i.e., incomplete) curves parameters. - * 11 Jun 1997 at Apple - * Added x1OrderPlusRecip and lesserX1OrderRecip fields - * Added curveParamsInitGiants() - * 9 Jan 1997 at NeXT - * Major mods for IEEE-style parameters. - * 7 Aug 1996 at NeXT - * Created. - */ - -#include "curveParams.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "ellipticProj.h" -#include "platform.h" -#include "falloc.h" -#include "feeDebug.h" -#include - -typedef unsigned short arrayDigit; - -static giant arrayToGiant(const arrayDigit *array); - -/* - * Can't declare giants statically; we declare them here via static arrayDigit - * arrays which contain the 'digits' in base 65536 of a giant - * used as a curve parameter. First element is sign; next element is - * l.s. digit; size of each array is abs(sign) + 1. These arrays are - * converted to a giant via arrayToGiant(). - * - * Static q and k values, as well as pointers to the arrayDigit arrays - * associated with the various giants for a given curve, are kept in an - * array of curveParamsStatic structs; a feeDepth is an index into this - * array. A curveParamsStatic struct is converted to a curveParams struct in - * curveParamsForDepth(). - */ -typedef struct { - feePrimeType primeType; - feeCurveType curveType; - unsigned q; - int k; - const arrayDigit *basePrime; // FPT_General only - arrayDigit m; // must be 1 for current release - const arrayDigit *a; - const arrayDigit *b; - const arrayDigit *c; - const arrayDigit *x1Plus; - const arrayDigit *y1Plus; // optional, currently only used for ECDSA curves - const arrayDigit *x1Minus; // optional, not used for ECDSA curves - const arrayDigit *cOrderPlus; - const arrayDigit *cOrderMinus; // optional, not used for ECDSA curves - const arrayDigit *x1OrderPlus; - const arrayDigit *x1OrderMinus; // optional, not used for ECDSA curves - const arrayDigit *x1OrderPlusRecip; - - /* - * A null lesserX1OrderRecip when x1OrderPlusRecip is non-null - * means that the two values are identical; in this case, only - * one giant is alloc'd in the actual curveParams struct. - */ - const arrayDigit *lesserX1OrderRecip; -} curveParamsStatic; - -/* - * First some common giant-arrays used in lots of curveGiants. - */ -static const arrayDigit ga_666[] = {1, 666 }; // a common value for 'c' -static const arrayDigit ga_zero[] = {1, 0 }; // (giant)0 -static const arrayDigit ga_one[] = {1, 1 }; // (giant)1 - -/* - * Here are the actual static arrays, one for each giant we know about. - * Since they're variable size, we have to allocate and name each one - * individually.... - */ - -#if FEE_PROTOTYPE_CURVES -#include "curveParamDataOld.h" -#else -#include "curveParamData.h" -#endif - -/* - * Now the curveParamsStatic structs, which provide templates for creating the - * fields in a specific curveParams struct. - * - * All giants in a curveParamsStatic struct except for basePrime are - * guaranteed valid. - * - * Note these are stored as an array, an index into which is a feeDepth - * parameter. - */ -#if FEE_PROTOTYPE_CURVES -static curveParamsStatic curveParamsArray[] = { - { // depth=0 - FPT_Mersenne, - FCT_Weierstrass, - 31, 1, // q=31, k=1 - NULL, // basePrime only used for FPT_General - 1, // m = 1 - ga_w31_1_a, // a = 7 - ga_one, // b = 1 - ga_zero, // c = 0 - ga_w31_1_x1Plus, - NULL, // y1Plus - ga_w31_1_x1Minus, - ga_w31_1_plusOrder, - ga_w31_1_minusOrder, - ga_w31_1_x1OrderPlus, - ga_w31_1_x1OrderMinus, - ga_w31_1_x1OrderPlusRecip, - ga_w31_1_lesserX1OrderRecip - }, - { // depth=1 - FPT_Mersenne, - FCT_Montgomery, - 31, 1, // q=31, k=1 - NULL, - 1, // m = 1 - ga_one, // a = 1 - ga_zero, // b = 0 - ga_666, // c = 666 - ga_m31_1_x1Plus, - NULL, // y1Plus - ga_m31_1_x1Minus, - ga_m31_1_plusOrder, - ga_m31_1_minusOrder, - ga_m31_1_x1OrderPlus, - ga_m31_1_x1OrderMinus, - ga_m31_1_x1OrderPlusRecip, - ga_m31_1_lesserX1OrderRecip - - }, - { // depth=2 - FPT_Mersenne, - FCT_Weierstrass, - 31, 1, // q=31, k=1, prime curve orders - NULL, - 1, // m = 1 - ga_31_1P_a, // a = 5824692 - ga_31_1P_b, // b = 2067311435 - ga_zero, // c = 0 - ga_31_1P_x1Plus, - NULL, // y1Plus - ga_31_1P_x1Minus, - ga_31_1P_plusOrder, - ga_31_1P_minusOrder, - ga_31_1P_x1OrderPlus, - ga_31_1P_x1OrderMinus, - ga_31_1P_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser - - }, - { // depth=3 - FPT_FEE, - FCT_Weierstrass, - 40, 213, // q=40, k=213, prime curve orders - NULL, - 1, // m = 1 - ga_40_213_a, // a = 1627500953 - ga_40_213_b, // b = 523907505 - ga_zero, // c = 0 - ga_40_213_x1Plus, - NULL, // y1Plus - ga_40_213_x1Minus, - ga_40_213_plusOrder, - ga_40_213_minusOrder, - ga_40_213_x1OrderPlus, - ga_40_213_x1OrderMinus, - ga_40_213_x1OrderPlusRecip, - ga_40_213_lesserX1OrderRecip - - }, - { // depth=4 - FPT_Mersenne, - FCT_Montgomery, - 127, 1, - NULL, - 1, // m = 1 - ga_one, // a = 1 - ga_zero, // b = 0 - ga_666, // c = 666 - ga_127_1_x1Plus, - NULL, // y1Plus - ga_127_1_x1Minus, - ga_127_1_plusOrder, - ga_127_1_minusOrder, - ga_127_1_x1OrderPlus, - ga_127_1_x1OrderMinus, - ga_127_1_x1OrderPlusRecip, - ga_127_1_lesserX1OrderRecip - - }, - { // depth=5 - FPT_Mersenne, - FCT_Weierstrass, - 127, 1, // q=127, k=1 Weierstrass - NULL, - 1, // m = 1 - ga_666, // a = 666 - ga_one, // b = 1 - ga_zero, // c = 0 - ga_127_1W_x1Plus, - NULL, // y1Plus - ga_127_1W_x1Minus, - ga_127_1W_plusOrder, - ga_127_1W_minusOrder, - ga_127_1W_x1OrderPlus, - ga_127_1W_x1OrderMinus, - ga_127_1W_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser - - }, - { // depth=6 - FPT_FEE, - FCT_Weierstrass, // also Atkin3 - 160, 57, - NULL, - 1, // m = 1 - ga_zero, // a = 0 - ga_160_57_b, // b = 3 - ga_zero, // c = 0 - ga_160_57_x1Plus, - NULL, // y1Plus - ga_160_57_x1Minus, - ga_160_57_plusOrder, - ga_160_57_minusOrder, - ga_160_57_x1OrderPlus, - ga_160_57_x1OrderMinus, - ga_160_57_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser - }, - { // depth=7 - FPT_FEE, - FCT_Weierstrass, // also Atkin3 - 192, 1425, - NULL, - 1, // m = 1 - ga_zero, // a = 0 - ga_192_1425_b, // b = -11 - ga_zero, // c = 0 - ga_192_1425_x1Plus, - NULL, // y1Plus - ga_192_1425_x1Minus, - ga_192_1425_plusOrder, - ga_192_1425_minusOrder, - ga_192_1425_x1OrderPlus, - ga_192_1425_x1OrderMinus, - ga_192_1425_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser - - }, - { // depth=8 - FPT_FEE, - FCT_Weierstrass, - 192, -529891, - NULL, - 1, // m = 1 - ga_192_M529891_a, // a = -152 - ga_192_M529891_b, // b = 722 - ga_zero, // c = 0 - ga_192_M529891_x1Plus, - NULL, // y1Plus - ga_192_M529891_x1Minus, - ga_192_M529891_plusOrder, - ga_192_M529891_minusOrder, - ga_192_M529891_x1OrderPlus, - ga_192_M529891_x1OrderMinus, - ga_192_M529891_x1OrderPlusRecip, - ga_192_M529891_lesserX1OrderRecip - - }, - /* - * FPT_General curves, currently just copies of known FPT_FEE or FPT_Mersenne - * curves with primeType set to FPT_General. These are just for - * verification the general curve are handled properly. - * We include the q parameter here for use by feeKeyBitsToDepth(). - */ - { // depth=9 - FPT_General, - FCT_General, - 127, 0, - ga_127_1_bp, // explicit basePrime - 1, // m = 1 - ga_one, // a = 1 - ga_zero, // b = 0 - ga_666, // c = 666 - ga_127_1_x1Plus, - NULL, // y1Plus - ga_127_1_x1Minus, - ga_127_1_plusOrder, - ga_127_1_minusOrder, - ga_127_1_x1OrderPlus, - ga_127_1_x1OrderMinus, - ga_127_1_x1OrderPlusRecip, - ga_127_1_lesserX1OrderRecip - - }, - - { // depth=10, FPT_General version of q=160 - FPT_General, - FCT_Weierstrass, - 160, 0, // we don't use these... - ga_160_57_bp, // explicit basePrime - 1, // m = 1 - ga_zero, // a = 0 - ga_160_57_b, // b = 3 - ga_zero, - ga_160_57_x1Plus, - NULL, // y1Plus - ga_160_57_x1Minus, - ga_160_57_plusOrder, - ga_160_57_minusOrder, - ga_160_57_x1OrderPlus, - ga_160_57_x1OrderMinus, - ga_160_57_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser - }, - - { // depth=11, FPT_General, 161 bits - FPT_General, - FCT_Weierstrass, - //161, 0, - 161, 0, // for verifying we don't use these... - ga_161_gen_bp, // explicit basePrime - 1, // m = 1 - ga_161_gen_a, // a = -152 - ga_161_gen_b, // b = 722 - ga_zero, // c = 0 - ga_161_gen_x1Plus, - NULL, // y1Plus - ga_161_gen_x1Minus, - ga_161_gen_plusOrder, - ga_161_gen_minusOrder, - ga_161_gen_x1OrderPlus, - ga_161_gen_x1OrderMinus, - ga_161_gen_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser - }, - -}; - -#else /* FEE_PROTOTYPE_CURVES */ - -static const curveParamsStatic curveParamsArray[] = { -{ - /* - * depth = 0 - * FEE CURVE: USE FOR FEE SIG. & FEED ONLY. - * primeType->Mersenne - * curveType->Montgomery - * q = 31; k = 1; p = 2^q - k; - * a = 1; b = 0; c = 666; - * Both orders composite. - */ - FPT_Mersenne, - FCT_Montgomery, - 31, 1, // q=31, k=1 - NULL, // basePrime only used for FPT_General - 1, // m = 1 - ga_one, // a = 1 - ga_zero, // b = 0 - ga_666, // c = 666 - ga_31m_x1Plus, - NULL, // y1Plus - ga_31m_x1Minus, - ga_31m_plusOrder, - ga_31m_minusOrder, - ga_31m_x1OrderPlus, - ga_31m_x1OrderMinus, - ga_31m_x1OrderPlusRecip, - ga_31m_lesserX1OrderRecip -}, -{ - /* - * depth = 1 - * IEEE P1363 COMPATIBLE. - * primeType->Mersenne - * curveType->Weierstrass - * q = 31; k = 1; p = 2^q-k; - * a = 5824692 b = 2067311435 c = 0 - * Both orders prime. - */ - FPT_Mersenne, - FCT_Weierstrass, - 31, 1, // q=31, k=1 - NULL, // basePrime only used for FPT_General - 1, // m = 1 - ga_31w_a, - ga_31w_b, - ga_zero, // c = 0 - ga_31w_x1Plus, - NULL, // y1Plus - ga_31w_x1Minus, - ga_31w_plusOrder, - ga_31w_minusOrder, - ga_31w_x1OrderPlus, - ga_31w_x1OrderMinus, - ga_31w_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser -}, -{ - /* - * depth = 2 - * FEE CURVE: USE FOR FEE SIG. & FEED ONLY. - * primeType->Mersenne - * curveType->Montgomery - * q = 127; k = 1; p = 2^q - k; - * a = 1; b = 0; c = 666; - * Both orders composite. - */ - FPT_Mersenne, - FCT_Montgomery, - 127, 1, // q = 127; k = 1 - NULL, // basePrime only used for FPT_General - 1, // m = 1 - ga_one, - ga_zero, - ga_666, - ga_127m_x1Plus, - NULL, // y1Plus - ga_127m_x1Minus, - ga_127m_plusOrder, - ga_127m_minusOrder, - ga_127m_x1OrderPlus, - ga_127m_x1OrderMinus, - ga_127m_x1OrderPlusRecip, - ga_127m_lesserX1OrderRecip -}, -{ - /* - * depth = 3 - * IEEE P1363 COMPATIBLE. - * primeType->feemod - * curveType->Weierstrass - * q = 127; k = -57675; p = 2^q - k; - * a = 170141183460469025572049133804586627403; - * b = 170105154311605172483148226534443139403; c = 0; - * Both orders prime. - */ - FPT_FEE, - FCT_Weierstrass, - 127, -57675, // q = 127; k = -57675 - NULL, // basePrime only used for FPT_General - 1, // m = 1 - ga_128w_a, - ga_128w_b, - ga_zero, - ga_128w_x1Plus, - NULL, // y1Plus - ga_128w_x1Minus, - ga_128w_plusOrder, - ga_128w_minusOrder, - ga_128w_x1OrderPlus, - ga_128w_x1OrderMinus, - ga_128w_x1OrderPlusRecip, - /* REC said NULL, dmitch says: */ - ga_128w_lesserX1OrderRecip // x1PlusOrder is lesser -}, -{ - /* - * depth = 4 - * IEEE P1363 COMPATIBLE. - * primeType->feemod - * curveType->Weierstrass - * q = 160; k = -5875; p = 2^q - k; - * a = 1461501637330902918203684832716283019448563798259; - * b = 36382017816364032; c = 0; - * Both orders prime.: - */ - FPT_FEE, - FCT_Weierstrass, - 160, -5875, // q = 160; k = -5875 - NULL, // basePrime only used for FPT_General - 1, // m = 1 - ga_161w_a, - ga_161w_b, - ga_zero, - ga_161w_x1Plus, - NULL, // y1Plus - ga_161w_x1Minus, - ga_161w_plusOrder, - ga_161w_minusOrder, - ga_161w_x1OrderPlus, - ga_161w_x1OrderMinus, - ga_161w_x1OrderPlusRecip, - /* dmitch addenda - REC said NULL */ - ga_161w_lesserX1OrderRecip -}, -{ - /* - * depth = 5 - * IEEE P1363 COMPATIBLE. - * primeType->General - * curveType->Weierstrass - * p is a 161-bit random prime (below, ga_161_gen_bp[]); - * a = -152; b = 722; c = 0; - * Both orders composite. - */ - FPT_General, - FCT_Weierstrass, - 161, 0, // not used - ga_161_gen_bp, // basePrime - 1, // m = 1 - ga_161_gen_a, - ga_161_gen_b, - ga_zero, - ga_161_gen_x1Plus, - NULL, // y1Plus - ga_161_gen_x1Minus, - ga_161_gen_plusOrder, - ga_161_gen_minusOrder, - ga_161_gen_x1OrderPlus, - ga_161_gen_x1OrderMinus, - ga_161_gen_x1OrderPlusRecip, - NULL // x1PlusOrder is lesser -}, -{ - /* - * depth = 6 - * IEEE P1363 COMPATIBLE. - * (NIST-P-192 RECOMMENDED PRIME) - * primeType->General - * curveType->Weierstrass - * p is a 192-bit random prime (below, ga_161_gen_bp[]); - * a = -3; - * b = 2455155546008943817740293915197451784769108058161191238065; - * c = 0; - * Plus-order is prime, minus-order is composite. - */ - FPT_General, - FCT_Weierstrass, - 192, 0, // only used for initGiantStacks(giantMaxDigits()) - ga_192_gen_bp, // basePrime - 1, // m = 1 - ga_192_gen_a, - ga_192_gen_b, - ga_zero, - ga_192_gen_x1Plus, - NULL, // y1Plus - ga_192_gen_x1Minus, - ga_192_gen_plusOrder, - ga_192_gen_minusOrder, - ga_192_gen_x1OrderPlus, - ga_192_gen_x1OrderMinus, - ga_192_gen_x1OrderPlusRecip, - ga_192_gen_lesserX1OrderRecip -}, - -/* ANSI X9.62/Certicom curves */ -{ - /* - * depth = 7 - * ANSI X9.62/Certicom secp192r1 - */ - FPT_General, - FCT_Weierstrass, - 192, 0, // only used for initGiantStacks(giantMaxDigits()) - ga_192_secp_bp, // basePrime - 1, // m = 1 - ga_192_secp_a, - ga_192_secp_b, - ga_zero, - ga_192_secp_x1Plus, - ga_192_secp_y1Plus, - NULL, // x1Minus - ga_192_secp_plusOrder, - NULL, // minusOrder, - ga_192_secp_x1OrderPlus, - NULL, // x1OrderMinus, - ga_192_secp_x1OrderPlusRecip, -}, -{ - /* - * depth = 8 - * ANSI X9.62/Certicom secp256r1 - */ - FPT_General, - FCT_Weierstrass, - 256, 0, // only used for initGiantStacks(giantMaxDigits()) - ga_256_secp_bp, // basePrime - 1, // m = 1 - ga_256_secp_a, - ga_256_secp_b, - ga_zero, - ga_256_secp_x1Plus, - ga_256_secp_y1Plus, - NULL, - ga_256_secp_plusOrder, - NULL, - ga_256_secp_x1OrderPlus, - NULL, - ga_256_secp_x1OrderPlusRecip, - NULL -}, -{ - /* - * depth = 9 - * ANSI X9.62/Certicom secp384r1 - */ - FPT_General, - FCT_Weierstrass, - 384, 0, // only used for initGiantStacks(giantMaxDigits()) - ga_384_secp_bp, // basePrime - 1, // m = 1 - ga_384_secp_a, - ga_384_secp_b, - ga_zero, - ga_384_secp_x1Plus, - ga_384_secp_y1Plus, - NULL, - ga_384_secp_plusOrder, - NULL, - ga_384_secp_x1OrderPlus, - NULL, - ga_384_secp_x1OrderPlusRecip, - NULL -}, -{ - /* - * depth = 10 - * ANSI X9.62/Certicom secp521r1 - */ - FPT_General, - FCT_Weierstrass, - 521, 0, - ga_521_secp_bp, // basePrime - 1, // m = 1 - ga_521_secp_a, - ga_521_secp_b, - ga_zero, - ga_521_secp_x1Plus, - ga_521_secp_y1Plus, - NULL, - ga_521_secp_plusOrder, - NULL, - ga_521_secp_x1OrderPlus, - NULL, - ga_521_secp_x1OrderPlusRecip, - NULL -} -}; -#endif /* FEE_PROTOTYPE_CURVES */ - -/* - * Convert the static form of a giant - i.e., an array of arrayDigits, - * the first of which is the sign, the remainder of which are base 65536 - * digits - into a giant. A null pointer on input results in a null return. - */ -static giant arrayToGiant(const arrayDigit *array) -{ - unsigned numBytes; // in result->n[] - int numDigits; // ditto - giant result; - giantDigit digit; - unsigned char byte; - unsigned i; - unsigned digitDex; // index into result->n[] - unsigned digitByte; // byte selector in digit - const arrayDigit *ap; // running ptr into array - short sign; - - if(array == NULL) { - CKRaise("arrayToGiant: NULL array"); - } - sign = (short)array[0]; - numBytes = abs(sign) * sizeof(unsigned short); - numDigits = BYTES_TO_GIANT_DIGITS(numBytes); - - /* note giantstruct has one explicit giantDigit */ - result = (giant) fmalloc(sizeof(giantstruct) + - ((numDigits - 1) * GIANT_BYTES_PER_DIGIT)); - result->capacity = numDigits; - - ap = array + 1; - digit = 0; - digitDex = 0; - - for(i=0; i> 8); - } - else { - /* even, i.e., l.s. byte */ - byte = (unsigned char)(*ap); - } - - /* add byte to current digit */ - digit |= (byte << (8 * digitByte)); - if(++i == numBytes) { - /* end of array, perhaps in the midst of a digit */ - break; - } - } - result->n[digitDex++] = digit; - digit = 0; - }; - - /* Careful: - * -- array elements are unsigned. The first element is - * he number of SHORTS in the array; convert to native - * digits. - * -- in the very odd (test only) case of giantDigit = unsigned char, - * we might have fewer valid digits than numDigits (might have - * leading zeros). - */ - if(sign < 0) { - result->sign = -numDigits; - } - else { - result->sign = numDigits; - } - gtrimSign(result); - return result; -} - -/* - * Obtain a malloc'd and uninitialized curveParams, to be init'd by caller. - */ -curveParams *newCurveParams(void) -{ - curveParams *params = (curveParams*) fmalloc(sizeof(curveParams)); - - bzero(params, sizeof(curveParams)); - return params; -} - -/* - * Alloc and zero reciprocal giants, when maxDigits is known. - * Currently only called when creating a curveParams from a public key. - * cp->primeType must be valid on input. - */ -void allocRecipGiants(curveParams *cp) -{ - cp->lesserX1OrderRecip = newGiant(cp->maxDigits); - cp->x1OrderPlusRecip = newGiant(cp->maxDigits); - int_to_giant(0, cp->lesserX1OrderRecip); - int_to_giant(0, cp->x1OrderPlusRecip); -} - -/* - * Obtain a malloc'd curveParams for a specified feeDepth. - */ -curveParams *curveParamsForDepth(feeDepth depth) -{ - curveParams *cp; - const curveParamsStatic *cps = &curveParamsArray[depth]; - - if(depth > FEE_DEPTH_MAX) { - return NULL; - } - #if GIANTS_VIA_STACK - curveParamsInitGiants(); - #endif - cp = newCurveParams(); - cp->primeType = cps->primeType; - cp->curveType = cps->curveType; - cp->q = cps->q; - cp->k = cps->k; - cp->m = cps->m; - if(cp->primeType == FPT_General) { - cp->basePrime = arrayToGiant(cps->basePrime); - } - cp->a = arrayToGiant(cps->a); - cp->b = arrayToGiant(cps->b); - cp->c = arrayToGiant(cps->c); - cp->x1Plus = arrayToGiant(cps->x1Plus); - if(cps->y1Plus) { - cp->y1Plus = arrayToGiant(cps->y1Plus); - } - if(cps->x1Minus) { - cp->x1Minus = arrayToGiant(cps->x1Minus); - } - cp->cOrderPlus = arrayToGiant(cps->cOrderPlus); - if(cps->cOrderMinus) { - cp->cOrderMinus = arrayToGiant(cps->cOrderMinus); - } - cp->x1OrderPlus = arrayToGiant(cps->x1OrderPlus); - if(cps->x1OrderMinus) { - cp->x1OrderMinus = arrayToGiant(cps->x1OrderMinus); - } - cp->x1OrderPlusRecip = arrayToGiant(cps->x1OrderPlusRecip); - - /* - * Special case optimization for equal reciprocals. - */ - if(cps->lesserX1OrderRecip == NULL) { - cp->lesserX1OrderRecip = cp->x1OrderPlusRecip; - } - else { - cp->lesserX1OrderRecip = arrayToGiant(cps->lesserX1OrderRecip); - } - - /* remainder calculated at runtime */ - curveParamsInferFields(cp); - return cp; -} - -/* - * Alloc a new curveParams struct as a copy of specified instance. - * This is the only way we can create a curveParams struct which doesn't - * match any existing known curve params. - */ -curveParams *curveParamsCopy(curveParams *cp) -{ - curveParams *newcp = newCurveParams(); - - newcp->primeType = cp->primeType; - newcp->curveType = cp->curveType; - newcp->q = cp->q; - newcp->k = cp->k; - newcp->m = cp->m; - newcp->basePrime = copyGiant(cp->basePrime); - newcp->minBytes = cp->minBytes; - newcp->maxDigits = cp->maxDigits; - - newcp->a = copyGiant(cp->a); - newcp->b = copyGiant(cp->b); - newcp->c = copyGiant(cp->c); - newcp->x1Plus = copyGiant(cp->x1Plus); - if(cp->x1Minus) { - newcp->x1Minus = copyGiant(cp->x1Minus); - } - newcp->y1Plus = copyGiant(cp->y1Plus); - newcp->cOrderPlus = copyGiant(cp->cOrderPlus); - if(cp->cOrderMinus) { - newcp->cOrderMinus = copyGiant(cp->cOrderMinus); - } - newcp->x1OrderPlus = copyGiant(cp->x1OrderPlus); - if(cp->x1OrderMinus) { - newcp->x1OrderMinus = copyGiant(cp->x1OrderMinus); - } - - newcp->x1OrderPlusRecip = copyGiant(cp->x1OrderPlusRecip); - if(cp->x1OrderPlusRecip == cp->lesserX1OrderRecip) { - /* - * Equal reciprocals; avoid new malloc - */ - newcp->lesserX1OrderRecip = newcp->x1OrderPlusRecip; - } - else { - newcp->lesserX1OrderRecip = copyGiant(cp->lesserX1OrderRecip); - } - if(cp->primeType == FPT_General) { - newcp->basePrimeRecip = copyGiant(cp->basePrimeRecip); - } - return newcp; -} - -/* - * Free a curveParams struct. - */ -void freeCurveParams(curveParams *cp) -{ - if(cp->basePrime != NULL) { - freeGiant(cp->basePrime); - } - if(cp->a != NULL) { - freeGiant(cp->a); - } - if(cp->b != NULL) { - freeGiant(cp->b); - } - if(cp->c != NULL) { - freeGiant(cp->c); - } - if(cp->x1Plus != NULL) { - freeGiant(cp->x1Plus); - } - if(cp->x1Minus != NULL) { - freeGiant(cp->x1Minus); - } - if(cp->y1Plus != NULL) { - freeGiant(cp->y1Plus); - } - if(cp->cOrderPlus != NULL) { - freeGiant(cp->cOrderPlus); - } - if(cp->cOrderMinus != NULL) { - freeGiant(cp->cOrderMinus); - } - if(cp->x1OrderPlus != NULL) { - freeGiant(cp->x1OrderPlus); - } - if(cp->x1OrderMinus != NULL) { - freeGiant(cp->x1OrderMinus); - } - if(cp->x1OrderPlusRecip != NULL) { - freeGiant(cp->x1OrderPlusRecip); - } - - /* - * Special case - if these are equal, we only alloc'd one giant - */ - if(cp->lesserX1OrderRecip != cp->x1OrderPlusRecip) { - freeGiant(cp->lesserX1OrderRecip); - } - if(cp->basePrimeRecip != NULL) { - freeGiant(cp->basePrimeRecip); - } - ffree(cp); -} - -/* - * Returns 1 if two sets of curve parameters are equivalent, else returns 0. - */ -int curveParamsEquivalent(curveParams *cp1, curveParams *cp2) -{ - if(cp1 == cp2) { - /* - * Trivial case, actually common for signature verify - */ - return 1; - } - if(cp1->primeType != cp2->primeType) { - return 0; - } - if(cp1->curveType != cp2->curveType) { - return 0; - } - if(cp1->k != cp2->k) { - return 0; - } - if(cp1->q != cp2->q) { - return 0; - } - if(cp1->m != cp2->m) { - return 0; - } - if(gcompg(cp1->basePrime, cp2->basePrime)) { - return 0; - } - if(gcompg(cp1->a, cp2->a)) { - return 0; - } - if(gcompg(cp1->b, cp2->b)) { - return 0; - } - if(gcompg(cp1->c, cp2->c)) { - return 0; - } - if(gcompg(cp1->x1Plus, cp2->x1Plus)) { - return 0; - } - if((cp1->x1Minus != NULL) && (cp2->x1Minus != NULL)) { - if(gcompg(cp1->x1Minus, cp2->x1Minus)) { - return 0; - } - } - if(gcompg(cp1->cOrderPlus, cp2->cOrderPlus)) { - return 0; - } - if((cp1->cOrderMinus != NULL) && (cp2->cOrderMinus != NULL)) { - if(gcompg(cp1->cOrderMinus, cp2->cOrderMinus)) { - return 0; - } - } - if(gcompg(cp1->x1OrderPlus, cp2->x1OrderPlus)) { - return 0; - } - if((cp1->x1OrderMinus != NULL) && (cp2->x1OrderMinus != NULL)) { - if(gcompg(cp1->x1OrderMinus, cp2->x1OrderMinus)) { - return 0; - } - } - /* - * If we got this far, reciprocals can't possibly be different - */ - return 1; -} - -/* - * Obtain the lesser of {x1OrderPlus, x1OrderMinus}. Returned value is not - * malloc'd; it's a pointer to one of the orders in *cp. - */ -giant lesserX1Order(curveParams *cp) -{ - CKASSERT(!isZero(cp->x1OrderPlus)); - - if(cp->x1OrderMinus == NULL) { - return(cp->x1OrderPlus); - } - else if(gcompg(cp->x1OrderPlus, cp->x1OrderMinus) >= 0) { - return(cp->x1OrderMinus); - } - else { - return(cp->x1OrderPlus); - } -} - -#if GIANTS_VIA_STACK - -/* - * Prime the curveParams and giants modules for quick allocs of giants. - */ -static int giantsInitd = 0; - -void curveParamsInitGiants(void) -{ - const curveParamsStatic *cps = &curveParamsArray[FEE_DEPTH_MAX]; - - if(giantsInitd) { - return; - } - - /* - * Figure the max giant size of the largest depth we know about... - */ - initGiantStacks(giantMaxDigits(giantMinBytes(cps->q, cps->k))); - giantsInitd = 1; -} - -#endif // GIANTS_VIA_STACK - -/* - * Infer the following fields from a partially constructed curveParams: - * - * basePrimeRecip if primeType == FPT_General - * basePrime if primeType != FPT_General - * y1Plus if curveType == FCT_Weierstrass and not pre-calculated - * minBytes - * maxDigits - * - * Assumes the following valid on entry: - * curveType - * primeType - * basePrime if primeType == FPT_General - * q, k if primeType != FPT_General - */ -void curveParamsInferFields(curveParams *cp) -{ - /* calc maxDigits, minBytes */ - calcGiantSizes(cp); - - /* basePrime or its reciprocal */ - if(cp->primeType == FPT_General) { - /* FIXME this should be declared statically! */ - cp->basePrimeRecip = newGiant(cp->maxDigits); - make_recip(cp->basePrime, cp->basePrimeRecip); - } - else { - /* - * FPT_FEE, FPT_Mersenne - */ - cp->basePrime = newGiant(cp->maxDigits); - make_base_prim(cp); - } - - /* y1Plus */ - #if CRYPTKIT_ELL_PROJ_ENABLE - if(cp->curveType == FCT_Weierstrass) { - if(cp->y1Plus == NULL) { - /* ECDSA Curves already have this */ - pointProj pt = newPointProj(cp->maxDigits); - findPointProj(pt, cp->x1Plus, cp); - - /* initial point is supposed to be on curve! */ - if(gcompg(pt->x, cp->x1Plus)) { - CKRaise("curveParamsInferFields failure"); - } - cp->y1Plus = copyGiant(pt->y); - freePointProj(pt); - } - } - else { - cp->y1Plus = newGiant(1); - } - #else /* CRYPTKIT_ELL_PROJ_ENABLE */ - cp->y1Plus = newGiant(1); - #endif - - if((cp->x1OrderPlusRecip == NULL) || isZero(cp->x1OrderPlusRecip)) { - /* - * an easy way of figuring this one out, this should not - * normally run. - */ - cp->x1OrderPlusRecip = newGiant(cp->maxDigits); - make_recip(cp->x1OrderPlus, cp->x1OrderPlusRecip); - if(cp->lesserX1OrderRecip != NULL) { - freeGiant(cp->lesserX1OrderRecip); - } - cp->lesserX1OrderRecip = cp->x1OrderPlusRecip; - } -} - -/* - * Given key size in bits, obtain the asssociated depth. - * Returns FR_IllegalDepth if specify key size not found - * in current curve tables. - */ -#define LOG_DEPTH 0 - -#if FEE_PROTOTYPE_CURVES -feeReturn feeKeyBitsToDepth(unsigned keySize, - feePrimeType primeType, /* FPT_Fefault means "best one" */ - feeCurveType curveType, /* FCT_Default means "best one" */ - feeDepth *depth) -{ - feeReturn frtn = FR_Success; - switch(keySize) { - case 31: - switch(curveType) { - case FCT_Montgomery: - default: - *depth = FEE_DEPTH_31_1_M; - break; - case FCT_Weierstrass: - *depth = FEE_DEPTH_31_1_P; - break; - } - break; - case 40: - switch(curveType) { - case FCT_Weierstrass: - default: - *depth = FEE_DEPTH_40_213; - break; - case FCT_Montgomery: - return FR_IllegalDepth; - } - break; - case 127: - switch(curveType) { - case FCT_Montgomery: - if(primeType == FPT_General) { - *depth = FEE_DEPTH_127_GEN; - } - else{ - *depth = FEE_DEPTH_127_1; - } - break; - case FCT_Weierstrass: - default: - *depth = FEE_DEPTH_127_1W; - break; - } - break; - case 160: - switch(curveType) { - case FCT_Montgomery: - return FR_IllegalDepth; - case FCT_Weierstrass: - default: - if(primeType == FPT_General) { - *depth = FEE_DEPTH_160_GEN; - } - else { - *depth = FEE_DEPTH_160_57; - } - break; - } - break; - case 192: - switch(curveType) { - case FCT_Montgomery: - *depth = FEE_DEPTH_192_M529891; - case FCT_Weierstrass: - default: - *depth = FEE_DEPTH_192_1425; - break; - } - break; - default: - frtn = FR_IllegalDepth; - break; - } - #if LOG_DEPTH - printf("feeKeyBitsToDepth: depth %d\n", *depth); - #endif - return frtn; -} - -#else /* FEE_PROTOTYPE_CURVES */ - -feeReturn feeKeyBitsToDepth(unsigned keySize, - feePrimeType primeType, /* FPT_Fefault means "best one" */ - feeCurveType curveType, /* FCT_Default means "best one" */ - feeDepth *depth) -{ - feeReturn frtn = FR_Success; - switch(keySize) { - case 31: - if(primeType == FPT_General) { - return FR_IllegalDepth; - } - /* note we cut a request for FPT_FEE some slack...this is actually - * FPT_Mersenne, but that is technically a subset of FEE. */ - switch(curveType) { - case FCT_Montgomery: - *depth = FEE_DEPTH_31M; - break; - case FCT_Weierstrass: - case FCT_Default: - *depth = FEE_DEPTH_31W; - break; - default: - return FR_IllegalDepth; - } - break; - case 127: - /* Montgomery only */ - if(primeType == FPT_General) { - return FR_IllegalDepth; - } - /* note we cut a request for FPT_FEE some slack...this is actually - * FPT_Mersenne, but that is technically a subset of FEE. */ - switch(curveType) { - case FCT_Montgomery: - case FCT_Default: - *depth = FEE_DEPTH_127M; - break; - case FCT_Weierstrass: - default: - return FR_IllegalDepth; - } - break; - case 128: - /* Weierstrass/feemod only */ - switch(primeType) { - case FPT_General: - case FPT_Mersenne: - return FR_IllegalDepth; - default: - /* FPT_Default, FPT_FEE */ - break; - } - switch(curveType) { - case FCT_Weierstrass: - case FCT_Default: - *depth = FEE_DEPTH_128W; - break; - default: - return FR_IllegalDepth; - } - break; - case 161: - switch(curveType) { - case FCT_Weierstrass: - case FCT_Default: - switch(primeType) { - case FPT_General: - *depth = FEE_DEPTH_161G; - break; - case FPT_FEE: - case FPT_Default: - *depth = FEE_DEPTH_161W; - break; - default: - /* i.e., FPT_Mersenne */ - return FR_IllegalDepth; - } - break; - default: - return FR_IllegalDepth; - } - break; - case 192: - switch(curveType) { - case FCT_Montgomery: - default: - return FR_IllegalDepth; - case FCT_Weierstrass: - case FCT_Default: - switch(primeType) { - case FPT_General: - case FPT_Default: - *depth = FEE_DEPTH_192G; - break; - default: - /* i.e., FPT_Mersenne, FPT_FEE */ - return FR_IllegalDepth; - } - break; - case FCT_ANSI: - switch(primeType) { - case FPT_General: - case FPT_Default: - break; - default: - return FR_IllegalDepth; - } - *depth = FEE_DEPTH_secp192r1; - break; - } - break; - case 256: - switch(curveType) { - case FCT_ANSI: - case FCT_Default: - break; - default: - return FR_IllegalDepth; - } - switch(primeType) { - case FPT_General: - case FPT_Default: - break; - default: - return FR_IllegalDepth; - } - *depth = FEE_DEPTH_secp256r1; - break; - case 384: - switch(curveType) { - case FCT_ANSI: - case FCT_Default: - break; - default: - return FR_IllegalDepth; - } - switch(primeType) { - case FPT_General: - case FPT_Default: - break; - default: - return FR_IllegalDepth; - } - *depth = FEE_DEPTH_secp384r1; - break; - case 521: - switch(curveType) { - case FCT_ANSI: - case FCT_Default: - break; - default: - return FR_IllegalDepth; - } - switch(primeType) { - case FPT_General: - case FPT_Default: - break; - default: - return FR_IllegalDepth; - } - *depth = FEE_DEPTH_secp521r1; - break; - - default: - frtn = FR_IllegalDepth; - break; - } - #if LOG_DEPTH - printf("feeKeyBitsToDepth: depth %d\n", *depth); - #endif - return frtn; -} - -#endif /* FEE_PROTOTYPE_CURVES */ - -/* - * Obtain depth for specified curveParams - */ -feeReturn curveParamsDepth( - curveParams *cp, - feeDepth *depth) -{ - if(cp == NULL) { - return FR_IllegalArg; - } - - /* We do it this way to allow reconstructing depth from an encoded curveParams */ - feeCurveType curveType = cp->curveType; - if((curveType == FCT_Weierstrass) && (cp->x1Minus == NULL)) { - /* actually an ANSI curve */ - curveType = FCT_ANSI; - } - return feeKeyBitsToDepth(cp->q, cp->primeType, curveType, depth); -} - - diff --git a/OSX/include/security_cryptkit/curveParams.h b/OSX/include/security_cryptkit/curveParams.h deleted file mode 100644 index 47a87756..00000000 --- a/OSX/include/security_cryptkit/curveParams.h +++ /dev/null @@ -1,230 +0,0 @@ -/* Copyright (c) 1998,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * curveParams.h - FEE curve parameter functions - * - * Revision History - * ---------------- - * 9 Sep 98 at NeXT - * Added y1Plus for IEEE P1363 compliance. - * 20 Jan 98 at Apple - * Added primeType, m, basePrimeRecip. - * 11 Jun 97 at Apple - * Added x1OrderPlusRecip and lesserX1OrderRecip - * Disabled CP_SET_GIANT_SIZE hack - * 9 Jan 1997 at NeXT - * Major mods for IEEE-style parameters. - * 7 Aug 1996 at NeXT - * Created. - */ - -#ifndef _CK_CURVEPARAMS_H_ -#define _CK_CURVEPARAMS_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "giantIntegers.h" -#include "feeTypes.h" - -/* - * Parameters defining a specific elliptic curve (and its initial points). - */ -typedef struct { - - /* - * Basic characteristic of prime field (PT_FEE, etc.) - */ - feePrimeType primeType; - - /* - * Basic curve type (CT_MONTGOMERY, etc.) - * Note that FCT_ANSI is stored here as FCT_Weierstrass. - */ - feeCurveType curveType; - - /* - * Parameters defining the base prime (2^q - k) for - * FPT_FEE and FPT_Mersenne. For FPT_General, q is the - * prime size in bits and k is 0. - */ - unsigned q; - int k; - - /* - * For all primeTypes, the field is defined as F(basePrime**m). - * This library can only deal with m == 1 for now. - */ - unsigned m; - - /* - * coefficients in the following equation: - * y^2 = x^3 + (c * x^2) + (a * x) + b - */ - giant a; - giant b; - giant c; - - /* - * Initial public point x-coordinates. - * x1Minus not used for ECDSA; X9.62 curves don't have this field. - */ - giant x1Plus; - giant x1Minus; - - /* - * Y coordinate of normalized projective initial public - * point for plus curve. I.e., Initial point = {x1Plus, p1Plus, 1}. - * Only valid for curveType == CT_WEIERSTRASS. This is calculated - * when a new curveParams is created. - */ - giant y1Plus; - - /* - * Curve orders. These are prime, or have large prime factors. - * cOrderMinus not used for ECDSA; X9.62 curves don't have this field. - */ - giant cOrderPlus; - giant cOrderMinus; - - /* - * Point orders (the large prime factors of the respective - * curve orders). - * x1OrderMinus not used for ECDSA; X9.62 curves don't have this field. - */ - giant x1OrderPlus; - giant x1OrderMinus; - - /* - * The base prime. For PT_GENERAL, this is a basic defining - * characteristic of a curve; otherwise, it is derived as 2**q - k. - */ - giant basePrime; - - /* - * The remaining fields are calculated and stored here as an - * optimization. - */ - - /* - * The minimum size of a giant, in bytes, to represent any point - * on this curve. This is generally used only when serializing - * giants of a known size. - */ - unsigned minBytes; - - /* - * The maximum size of a giant, in giantDigits, to be used with all - * FEE arithmetic for this curve. This is generally used to alloc - * giants. - */ - unsigned maxDigits; - - /* - * Reciprocals of lesserX1Order() and x1OrderPlus. Calculated - * lazily by clients in the case of creation of a curveParams - * struct from a byteRep representation. - */ - giant x1OrderPlusRecip; - giant lesserX1OrderRecip; - - /* - * Reciprocal of basePrime. Only used for PT_GENERAL. - */ - giant basePrimeRecip; -} curveParams; - -#if 0 -/* - * Values for primeType. - */ -#define PT_MERSENNE 0 /* basePrime = 2**q - 1 */ -#define PT_FEE 1 /* basePrime = 2**q - k, k is "small" */ -#define PT_GENERAL 2 /* other prime modulus */ - -/* - * Values for curveType. Note that Atkin3 (a=0) and Atkin4 (b=0) are - * subsets of CT_WEIERSTRASS. - */ -#define CT_MONTGOMERY 0 /* a=1, b=0 */ -#define CT_WEIERSTRASS 1 /* c=0 */ -#define CT_GENERAL 4 /* other */ -#endif /* 0 */ - -/* - * Obtain a malloc'd curveParams for a specified feeDepth. - */ -curveParams *curveParamsForDepth(feeDepth depth); - -/* - * Obtain a malloc'd and uninitialized curveParams, to be init'd by caller - * (when matching existing curve params). - */ -curveParams *newCurveParams(void); - -/* - * Alloc and zero reciprocal giants, when maxDigits is known. - */ -void allocRecipGiants(curveParams *cp); - -/* - * Alloc a new curveParams struct as a copy of specified instance. - */ -curveParams *curveParamsCopy(curveParams *cp); - -/* - * Free a curveParams struct. - */ -void freeCurveParams(curveParams *cp); - -/* - * Returns 1 if two sets of curve parameters are equivalent, else returns 0. - */ -int curveParamsEquivalent(curveParams *cp1, curveParams *cp2); - -/* - * Obtain the lesser of {x1OrderPlus, x1OrderMinus}. Returned value is not - * malloc'd; it's a pointer to one of the orders in *cp. - */ -giant lesserX1Order(curveParams *cp); - -/* - * Prime the curveParams and giants modules for quick allocs of giants. - */ -void curveParamsInitGiants(void); - -/* - * Infer run-time calculated fields from a partially constructed curveParams. - */ -void curveParamsInferFields(curveParams *cp); - -/* - * Given key size in bits, obtain the asssociated depth. - * Returns FR_IllegalDepth if specify key size not found - * in current curve tables. - */ -feeReturn feeKeyBitsToDepth(unsigned keyBits, - feePrimeType primeType, /* FPT_Fefault means "best one" */ - feeCurveType curveType, /* FCT_Default means "best one" */ - feeDepth *depth); - -/* - * Obtain depth for specified curveParams - */ -feeReturn curveParamsDepth( - curveParams *cp, - feeDepth *depth); - -#ifdef __cplusplus -} -#endif - -#endif /* _CK_CURVEPARAMS_H_ */ diff --git a/OSX/include/security_cryptkit/elliptic.c b/OSX/include/security_cryptkit/elliptic.c deleted file mode 100644 index 3f45d199..00000000 --- a/OSX/include/security_cryptkit/elliptic.c +++ /dev/null @@ -1,1437 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - - elliptic.c - Library for Apple-proprietary Fast Elliptic - Encryption. The algebra in this module ignores elliptic point's - y-coordinates. - - Patent information: - - FEE is patented, U.S. Patents #5159632 (1992), #5271061 (1993), - #5463690 (1994). These patents are implemented - in various elliptic algebra functions such as - numer/denom_plus/times(), and in the fact of special - forms for primes: p = 2^q-k. - - Digital signature using fast elliptic addition, in - U. S. Patent #5581616 (1996), is implemented in the - signature_compare() function. - - FEED (Fast Elliptic Encryption) is patent pending (as of Jan 1998). - Various functions such as elliptic_add() implement the patent ideas. - - - Modification history since the U.S. Patent: - ------------------------------------------- - 10/06/98 ap - Changed to compile with C++. - 9 Sep 98 at Apple - cp->curveType optimizations. - Removed code which handled "unknown" curve orders. - elliptic() now exported for timing measurements. - 21 Apr 98 at Apple - Used inline platform-dependent giant arithmetic. - 20 Jan 98 at Apple - feemod now handles PT_MERSENNE, PT_FEE, PT_GENERAL. - Added calcGiantSizes(), rewrote giantMinBytes(), giantMaxShorts(). - Updated heading comments on FEE curve algebra. - 11 Jan 98 at Apple - Microscopic feemod optimization. - 10 Jan 98 at Apple - ell_odd, ell_even() Montgomery optimization. - 09 Jan 98 at Apple - ell_odd, ell_even() Atkin3 optimization. - 08 Jan 97 at Apple - Cleaned up some debugging code; added gsquareTime - 11 Jun 97 at Apple - Mods for modg_via_recip(), divg_via_recip() math - Deleted a lot of obsolete code (previously ifdef'd out) - Added lesserX1OrderJustify(), x1OrderPlusJustify() - Added binvg_cp(), avoiding general modg in favor of feemod - 05 Feb 97 at Apple - New optimized numer_plus(), denom_double(), and numer_times() - All calls to borrowGiant() and newGiant have explicit giant size - 08 Jan 97 at NeXT - Major mods to accomodate IEEE-style curve parameters. - New functions feepowermodg() and curveOrderJustify(); - elliptic_add(), elliptic(), signature_compare(), and - which_curve() completely rewritten. - 19 Dec 96 at NeXT - Added mersennePrimes[24..26] - 08 Aug 96 at NeXT - Fixed giant leak in elliptic_add() - 05 Aug 96 at NeXT - Removed dead code - 24 Jul 96 at NeXT - Added ENGINE_127_BITS dependency for use of security engine - 24 Oct 92 at NeXT - Modified new_public_from_private() - Created. - - - FEE curve algebra, Jan 1997. - - Curves are: - - y^2 = x^3 + c x^2 + a x + b - - where useful parameterizations for practical purposes are: - - Montgomery: a = 1, b = 0. (The original 1991 FEE system.) - Weierstrass: c = 0. (The basic IEEE form.) - Atkin3: c = a = 0. - Atkin4: c = b = 0. - - However, the code is set up to work with any a, b, c. - The underlying fields F_{p^m} are of odd characteristic, - with all operations are (mod p). The special FEE-class - primes p are of the form: - - p = 2^q - k = 3 (mod 4) - - where k is single-precision. For such p, the mod operations - are especially fast (asymptotically vanishing time with respect - to a multiply). Note that the whole system - works equally well (except for slower execution) for arbitrary - primes p = 3 (mod 4) of the same bit length (q or q+1). - - The elliptic arithmetic now proceeds on the basis of - five fundamental operations that calculate various - numerator/denominator parts of the elliptic terms: - - numer_double(giant x, giant z, giant res, curveParams *par) - res := (x^2 - a z^2)^2 - 4 b (2 x + c z) z^3. - - numer_plus(giant x1, giant x2, giant res, curveParams *par) - res = (x1 x2 + a)(x1 + x2) + 2(c x1 x2 + b). - - denom_double(giant x, giant z, giant res, curveParams *par) - res = 4 z (x^3 + c x^2 z + a x z^2 + b z^3). - - denom_times(giant x1, giant z1, giant x2, giant z2, giant res, - curveParams *par) - res := (x1 z2 - x2 z1)^2 - - numer_times(giant x1, giant z1, giant x2, giant z2, giant res, - curveParams *par) - res := (x1 x2 - a z1 z2)^2 - 4 b(x1 z2 + x2 z1 + c z1 z2) z1 z2 - - If x(+-) represent the sum and difference x-coordinates - respectively, then, in pseudocode, - - For unequal starting coords: - x(+) + x(-) = U = 2 numer_plus/denom_times - x(+) x(-) = V = numer_times/denom_times - - and for equal starting coords: - x(+) = numer_double/denom_double - - The elliptic_add() function uses the fact that - - x(+) = U/2 + s*Sqrt[U^2/4 - V] - - where the sign s = +-1. - -*/ - -#include "ckconfig.h" -#include -#include -#include -#include "platform.h" - -#include "giantIntegers.h" -#include "elliptic.h" -#include "ellipticProj.h" -#include "ckutilities.h" -#include "curveParams.h" -#include "feeDebug.h" -#include "ellipticMeasure.h" -#include "falloc.h" -#include "giantPortCommon.h" - -#if FEE_PROFILE - -unsigned numerDoubleTime; -unsigned numerPlusTime; -unsigned numerTimesTime; -unsigned denomDoubleTime; -unsigned denomTimesTime; -unsigned ellipticTime; -unsigned sigCompTime; -unsigned powerModTime; -unsigned ellAddTime; -unsigned whichCurveTime; -unsigned modgTime; -unsigned mulgTime; -unsigned binvauxTime; -unsigned gsquareTime; - -unsigned numMulg; -unsigned numFeemod; -unsigned numGsquare; -unsigned numBorrows; - -void clearProfile() -{ - numerDoubleTime = 0; - numerPlusTime = 0; - numerTimesTime = 0; - denomDoubleTime = 0; - denomTimesTime = 0; - ellipticTime = 0; - sigCompTime = 0; - powerModTime = 0; - ellAddTime = 0; - whichCurveTime = 0; - modgTime = 0; - mulgTime = 0; - binvauxTime = 0; - gsquareTime = 0; - numMulg = 0; - numFeemod = 0; - numGsquare = 0; - numBorrows = 0; -} - -#endif // FEE_PROFILE - -#if ELL_PROFILE -unsigned ellOddTime; -unsigned ellEvenTime; -unsigned numEllOdds; -unsigned numEllEvens; - -void clearEllProfile() -{ - ellOddTime = 0; - ellEvenTime = 0; - numEllOdds = 0; - numEllEvens = 0; -} - -#endif /* ELL_PROFILE */ -#if ELLIPTIC_MEASURE - -int doEllMeasure; // gather stats on/off */ -int bitsInN; -int numFeeMods; -int numMulgs; - -void dumpEll() -{ - printf("\nbitlen(n) : %d\n", bitsInN); - printf("feemods : %d\n", numFeeMods); - printf("mulgs : %d\n", numMulgs); -} - -#endif // ELLIPTIC_MEASURE - -/********** Globals ********************************/ - -static void make_base(curveParams *par, giant result); // result = with 2^q-k -static int keys_inconsistent(key pub1, key pub2); -/* Return non-zero if pub1, pub2 have inconsistent parameters. - */ - - -static void ell_even(giant x1, giant z1, giant x2, giant z2, curveParams *par); -static void ell_odd(giant x1, giant z1, giant x2, giant z2, giant xxor, - giant zor, curveParams *par); -static void numer_double(giant x, giant z, giant res, curveParams *par); -static void numer_plus(giant x1, giant x2, giant res, curveParams *par); -static void denom_double(giant x, giant z, giant res, curveParams *par); -static void denom_times(giant x1, giant z1, giant x2, giant z2, giant res, - curveParams *par); -static void numer_times(giant x1, giant z1, giant x2, giant z2, giant res, - curveParams *par); -static void feepowermodg(curveParams *par, giant x, giant n); -static void curveOrderJustifyWithRecip(giant g, giant curveOrder, giant recip); - -/* - * Completely rewritten in CryptKit-18, 13 Jan 1997, for new IEEE-style - * curveParameters. - */ -int which_curve(giant x, curveParams *par) - /* Returns (+-1) depending on whether x is on curve - (+-)y^2 = x^3 + c x^2 + a x + b. - */ -{ - giant t1; - giant t2; - giant t3; - int result; - PROF_START; - - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - t3 = borrowGiant(par->maxDigits); - - /* First, set t2:= x^3 + c x^2 + a x + b. */ - gtog(x, t2); addg(par->c, t2); - mulg(x, t2); addg(par->a, t2); /* t2 := x^2 + c x + a. */ - feemod(par, t2); - mulg(x, t2); addg(par->b, t2); - feemod(par, t2); - /* Next, test whether t2 is a square. */ - gtog(t2, t1); - make_base(par, t3); iaddg(1, t3); gshiftright(1, t3); /* t3 = (p+1)/2. */ - feepowermodg(par, t1, t3); /* t1 := t2^((p+1)/2) (mod p). */ - if(gcompg(t1, t2) == 0) - result = CURVE_PLUS; - else - result = CURVE_MINUS; - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - PROF_END(whichCurveTime); - return result; -} - -key new_public(curveParams *cp, int twist) { - key k; - - k = (key) fmalloc(sizeof(keystruct)); - k->cp = cp; - k->twist = twist; - - k->x = newGiant(cp->maxDigits); - if((twist == CURVE_PLUS) && (cp->curveType == FCT_Weierstrass)) { - k->y = newGiant(cp->maxDigits); - } - else { - /* - * no projective algebra. We could optimize and save a few bytes - * here by setting y to NULL, but that really complicates things - * in may other places. Best to have a real giant. - */ - k->y = newGiant(1); - } - return(k); -} - -key new_public_with_key(key old_key, curveParams *cp) -{ - key result; - - result = new_public(cp, old_key->twist); - CKASSERT((old_key->x != NULL) && (old_key->y != NULL)); - CKASSERT((result->x != NULL) && (result->y != NULL)); - gtog(old_key->x, result->x); - gtog(old_key->y, result->y); - return result; -} - -void free_key(key pub) { - if(!pub) { - return; - } - if (pub->x) { - freeGiant(pub->x); - } - if (pub->y) { - freeGiant(pub->y); - } - ffree(pub); -} - -/* - * Specify private data for key created by new_public(). - * Generates k->x. - */ -void set_priv_key_giant(key k, giant privGiant) -{ - curveParams *cp = k->cp; - - /* elliptiy multiply of initial public point times private key */ - #if CRYPTKIT_ELL_PROJ_ENABLE - if((k->twist == CURVE_PLUS) && (cp->curveType == FCT_Weierstrass)) { - /* projective */ - - pointProj pt1 = newPointProj(cp->maxDigits); - - CKASSERT((cp->y1Plus != NULL) && (!isZero(cp->y1Plus))); - CKASSERT(k->y != NULL); - - /* pt1 := {x1Plus, y1Plus, 1} */ - gtog(cp->x1Plus, pt1->x); - gtog(cp->y1Plus, pt1->y); - int_to_giant(1, pt1->z); - - /* pt1 := pt1 * privateKey */ - ellMulProjSimple(pt1, privGiant, cp); - - /* result back to {k->x, k->y} */ - gtog(pt1->x, k->x); - gtog(pt1->y, k->y); - freePointProj(pt1); // FIXME - clear the giants - } - else { - #else - { - #endif /* CRYPTKIT_ELL_PROJ_ENABLE */ - /* FEE */ - if(k->twist == CURVE_PLUS) { - gtog(cp->x1Plus, k->x); - } - else { - gtog(cp->x1Minus, k->x); - } - elliptic_simple(k->x, privGiant, k->cp); - } -} - -int key_equal(key one, key two) { - if (keys_inconsistent(one, two)) return 0; - return !gcompg(one->x, two->x); -} - -static void make_base(curveParams *par, giant result) -/* Jams result with 2^q-k. */ -{ - gtog(par->basePrime, result); -} - -void make_base_prim(curveParams *cp) -/* Jams cp->basePrime with 2^q-k. Assumes valid maxDigits, q, k. */ -{ - giant tmp = borrowGiant(cp->maxDigits); - - CKASSERT(cp->primeType != FPT_General); - int_to_giant(1, cp->basePrime); - gshiftleft((int)cp->q, cp->basePrime); - int_to_giant(cp->k, tmp); - subg(tmp, cp->basePrime); - returnGiant(tmp); -} - -static int sequalg(int n, giant g) { - if((g->sign == 1) && (g->n[0] == n)) return(1); - return(0); -} - - -/* - * Elliptic multiply: x := n * {x, 1} - */ -void elliptic_simple(giant x, giant n, curveParams *par) { - giant ztmp = borrowGiant(par->maxDigits); - giant cur_n = borrowGiant(par->maxDigits); - - START_ELL_MEASURE(n); - int_to_giant(1, ztmp); - elliptic(x, ztmp, n, par); - binvg_cp(par, ztmp); - mulg(ztmp, x); - feemod(par, x); - END_ELL_MEASURE; - - returnGiant(cur_n); - returnGiant(ztmp); -} - -/* - * General elliptic multiply. - * - * {xx, zz} := k * {xx, zz} - */ -void elliptic(giant xx, giant zz, giant k, curveParams *par) { - int len = bitlen(k); - int pos = len - 2; - giant xs; - giant zs; - giant xorg; - giant zorg; - - PROF_START; - if(sequalg(1,k)) return; - if(sequalg(2,k)) { - ell_even(xx, zz, xx, zz, par); - goto out; - } - zs = borrowGiant(par->maxDigits); - xs = borrowGiant(par->maxDigits); - zorg = borrowGiant(par->maxDigits); - xorg = borrowGiant(par->maxDigits); - gtog(xx, xorg); gtog(zz, zorg); - ell_even(xx, zz, xs, zs, par); - do { - if(bitval(k, pos--)) { - ell_odd(xs, zs, xx, zz, xorg, zorg, par); - ell_even(xs, zs, xs, zs, par); - } else { - ell_odd(xx, zz, xs, zs, xorg, zorg, par); - ell_even(xx, zz, xx, zz, par); - } - } while (pos >= 0); // REC fix 9/23/94 - returnGiant(xs); - returnGiant(zs); - returnGiant(xorg); - returnGiant(zorg); -out: - PROF_END(ellipticTime); -} - -/* - * Completely rewritten in CryptKit-18, 13 Jan 1997, for new IEEE-style - * curveParameters. - */ -void elliptic_add(giant x1, giant x2, giant x3, curveParams *par, int s) { - - /* Addition algorithm for x3 = x1 + x2 on the curve, with sign ambiguity s. - From theory, we know that if {x1,1} and {x2,1} are on a curve, then - their elliptic sum (x1,1} + {x2,1} = {x3,1} must have x3 as one of two - values: - - x3 = U/2 + s*Sqrt[U^2/4 - V] - - where sign s = +-1, and U,V are functions of x1,x2. Tho present function - is called a maximum of twice, to settle which of +- is s. When a call - is made, it is guaranteed already that x1, x2 both lie on the same curve - (+- curve); i.e., which curve (+-) is not connected at all with sign s of - the x3 relation. - */ - - giant cur_n; - giant t1; - giant t2; - giant t3; - giant t4; - giant t5; - - PROF_START; - cur_n = borrowGiant(par->maxDigits); - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - t3 = borrowGiant(par->maxDigits); - t4 = borrowGiant(par->maxDigits); - t5 = borrowGiant(par->maxDigits); - - if(gcompg(x1, x2)==0) { - int_to_giant(1, t1); - numer_double(x1, t1, x3, par); - denom_double(x1, t1, t2, par); - binvg_cp(par, t2); - mulg(t2, x3); feemod(par, x3); - goto out; - } - numer_plus(x1, x2, t1, par); - int_to_giant(1, t3); - numer_times(x1, t3, x2, t3, t2, par); - int_to_giant(1, t4); int_to_giant(1, t5); - denom_times(x1, t4, x2, t5, t3, par); - binvg_cp(par, t3); - mulg(t3, t1); feemod(par, t1); /* t1 := U/2. */ - mulg(t3, t2); feemod(par, t2); /* t2 := V. */ - /* Now x3 will be t1 +- Sqrt[t1^2 - t2]. */ - gtog(t1, t4); gsquare(t4); feemod(par, t4); - subg(t2, t4); - make_base(par, cur_n); iaddg(1, cur_n); gshiftright(2, cur_n); - /* cur_n := (p+1)/4. */ - feepowermodg(par, t4, cur_n); /* t4 := t2^((p+1)/4) (mod p). */ - gtog(t1, x3); - if(s != SIGN_PLUS) negg(t4); - addg(t4, x3); - feemod(par, x3); - -out: - returnGiant(cur_n); - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - returnGiant(t4); - returnGiant(t5); - - PROF_END(ellAddTime); -} - -/* - * Key exchange atom. - */ -giant make_pad(giant privGiant, key publicKey) { - curveParams *par = publicKey->cp; - giant result = newGiant(par->maxDigits); - - gtog(publicKey->x, result); - elliptic_simple(result, privGiant, par); - return result; -} - -static void ell_even(giant x1, giant z1, giant x2, giant z2, curveParams *par) { - giant t1; - giant t2; - giant t3; - - EPROF_START; - - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - t3 = borrowGiant(par->maxDigits); - - if(par->curveType == FCT_Montgomery) { - /* Begin Montgomery OPT: 10 Jan 98 REC. */ - gtog(x1, t1); gsquare(t1); feemod(par, t1); /* t1 := x1^2. */ - gtog(z1, t2); gsquare(t2); feemod(par, t2); /* t2 := z1^2. */ - - gtog(x1, t3); mulg(z1, t3); feemod(par, t3); - gtog(t3, z2); mulg(par->c, z2); feemod(par, z2); - addg(t1, z2); addg(t2, z2); mulg(t3, z2); gshiftleft(2, z2); - feemod(par, z2); /* z2 := 4 x1 z1 (x1^2 + c x1 z1 + z1^2). */ - gtog(t1, x2); subg(t2, x2); gsquare(x2); feemod(par, x2); - /* x2 := (x1^2 - z1^2)^2. */ - /* End OPT: 10 Jan 98 REC. */ - } - else if((par->curveType == FCT_Weierstrass) && isZero(par->a)) { - /* Begin Atkin3 OPT: 9 Jan 98 REC. */ - gtog(x1, t1); - gsquare(t1); feemod(par, t1); - mulg(x1, t1); feemod(par, t1); /* t1 := x^3. */ - gtog(z1, t2); - gsquare(t2); feemod(par, t2); - mulg(z1, t2); feemod(par, t2); /* t2 := z1^3 */ - mulg(par->b, t2); feemod(par, t2); /* t2 := b z1^3. */ - gtog(t1, t3); addg(t2, t3); /* t3 := x^3 + b z1^3 */ - mulg(z1, t3); feemod(par, t3); /* t3 *= z1 - * = z1 ( x^3 + b z1^3 ) */ - gshiftleft(2, t3); feemod(par, t3); /* t3 = 4 z1 (x1^3 + b z1^3) */ - - gshiftleft(3, t2); /* t2 = 8 b z1^3 */ - subg(t2, t1); /* t1 = x^3 - 8 b z1^3 */ - mulg(x1, t1); feemod(par, t1); /* t1 = x1 (x1^3 - 8 b z1^3) */ - - gtog(t3, z2); - gtog(t1, x2); - /* End OPT: 9 Jan 98 REC. */ - } - else { - numer_double(x1, z1, t1, par); - denom_double(x1, z1, t2, par); - gtog(t1, x2); gtog(t2, z2); - } - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - - EPROF_END(ellEvenTime); - EPROF_INCR(numEllEvens); - - /* - printf("ell_even end\n"); - printf(" x1 : "); printGiant(x1); - printf(" z1 : "); printGiant(z1); - printf(" x2 : "); printGiant(x2); - printf(" z2 : "); printGiant(z2); - */ -} - -static void ell_odd(giant x1, giant z1, giant x2, giant z2, giant xxor, - giant zor, curveParams *par) -{ - - giant t1; - giant t2; - - EPROF_START; - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - - if(par->curveType == FCT_Montgomery) { - /* Begin Montgomery OPT: 10 Jan 98 REC. */ - giant t3 = borrowGiant(par->maxDigits); - giant t4 = borrowGiant(par->maxDigits); - - gtog(x1, t1); addg(z1, t1); /* t1 := x1 + z1. */ - gtog(x2, t2); subg(z2, t2); /* t2 := x2 - z2. */ - gtog(x1, t3); subg(z1, t3); /* t3 := x1 - z1. */ - gtog(x2, t4); addg(z2, t4); /* t4 := x2 + z2. */ - mulg(t2, t1); feemod(par, t1); /* t1 := (x1 + z1)(x2 - z2) */ - mulg(t4, t3); feemod(par, t3); /* t4 := (x2 + z2)(x1 - z1) */ - gtog(t1, z2); subg(t3, z2); /*???gshiftright(1, z2);*/ - /* z2 := ((x1 + z1)(x2 - z2) - x2)/2 */ - gsquare(z2); feemod(par, z2); - mulg(xxor, z2); feemod(par, z2); - gtog(t1, x2); addg(t3, x2); /*????gshiftright(1, x2);*/ - gsquare(x2); feemod(par, x2); - mulg(zor, x2); feemod(par, x2); - - returnGiant(t3); - returnGiant(t4); - } - else if((par->curveType == FCT_Weierstrass) && isZero(par->a)) { - /* Begin Atkin3 OPT: 9 Jan 98 REC. */ - - giant t3 = borrowGiant(par->maxDigits); - giant t4 = borrowGiant(par->maxDigits); - - gtog(x1, t1); mulg(x2, t1); feemod(par, t1); /* t1 := x1 x2. */ - gtog(z1, t2); mulg(z2, t2); feemod(par, t2); /* t2 := z1 z2. */ - gtog(x1, t3); mulg(z2, t3); feemod(par, t3); /* t3 := x1 z2. */ - gtog(z1, t4); mulg(x2, t4); feemod(par, t4); /* t4 := x2 z1. */ - gtog(t3, z2); subg(t4, z2); gsquare(z2); feemod(par, z2); - mulg(xxor, z2); feemod(par, z2); - gtog(t1, x2); gsquare(x2); feemod(par, x2); - addg(t4, t3); mulg(t2, t3); feemod(par, t3); - mulg(par->b, t3); feemod(par, t3); - addg(t3, t3); addg(t3, t3); - subg(t3, x2); mulg(zor, x2); feemod(par, x2); - - returnGiant(t3); - returnGiant(t4); - /* End OPT: 9 Jan 98 REC. */ - } - else { - numer_times(x1, z1, x2, z2, t1, par); - mulg(zor, t1); feemod(par, t1); - denom_times(x1, z1, x2, z2, t2, par); - mulg(xxor, t2); feemod(par, t2); - - gtog(t1, x2); gtog(t2, z2); - } - - returnGiant(t1); - returnGiant(t2); - - EPROF_END(ellOddTime); - EPROF_INCR(numEllOdds); - - /* - printf("ell_odd end\n"); - printf(" x2 : "); printGiant(x2); - printf(" z2 : "); printGiant(z2); - */ -} - -/* - * return codes from keys_inconsistent() and signature_compare(). The actual - * values are not public; they are defined here for debugging. - */ -#define CURVE_PARAM_MISMATCH 1 -#define TWIST_PARAM_MISMATCH 2 -#define SIGNATURE_INVALID 3 - - -/* - * Determine whether two keystructs have compatible parameters (i.e., same - * twist and curveParams). Return 0 if compatible, else non-zero. - */ -static int keys_inconsistent(key pub1, key pub2){ - if(!curveParamsEquivalent(pub1->cp, pub2->cp)) { - return CURVE_PARAM_MISMATCH; - } - if(pub1->twist != pub2->twist) { - return TWIST_PARAM_MISMATCH; - } - return 0; -} - -int signature_compare(giant p0x, giant p1x, giant p2x, curveParams *par) -/* Returns non-zero iff p0x cannot be the x-coordinate of the sum of two points whose respective x-coordinates are p1x, p2x. */ -{ - int ret = 0; - giant t1; - giant t2; - giant t3; - giant t4; - giant t5; - - PROF_START; - - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - t3 = borrowGiant(par->maxDigits); - t4 = borrowGiant(par->maxDigits); - t5 = borrowGiant(par->maxDigits); - - if(gcompg(p1x, p2x) == 0) { - int_to_giant(1, t1); - numer_double(p1x, t1, t2, par); - denom_double(p1x, t1, t3, par); - mulg(p0x, t3); subg(t3, t2); - feemod(par, t2); - } else { - numer_plus(p1x, p2x, t1, par); - gshiftleft(1, t1); feemod(par, t1); - int_to_giant(1, t3); - numer_times(p1x, t3, p2x, t3, t2, par); - int_to_giant(1, t4); int_to_giant(1, t5); - denom_times(p1x, t4 , p2x, t5, t3, par); - /* Now we require t3 x0^2 - t1 x0 + t2 == 0. */ - mulg(p0x, t3); feemod(par, t3); - subg(t1, t3); mulg(p0x, t3); - feemod(par, t3); - addg(t3, t2); - feemod(par, t2); - } - - if(!isZero(t2)) ret = SIGNATURE_INVALID; - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - returnGiant(t4); - returnGiant(t5); - PROF_END(sigCompTime); - return(ret); -} - - -static void numer_double(giant x, giant z, giant res, curveParams *par) -/* Numerator algebra. - res := (x^2 - a z^2)^2 - 4 b (2 x + c z) z^3. - */ -{ - giant t1; - giant t2; - - PROF_START; - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - - gtog(x, t1); gsquare(t1); feemod(par, t1); - gtog(z, res); gsquare(res); feemod(par, res); - gtog(res, t2); - if(!isZero(par->a) ) { - if(!isone(par->a)) { /* Speedup - REC 17 Jan 1997. */ - mulg(par->a, res); feemod(par, res); - } - subg(res, t1); feemod(par, t1); - } - gsquare(t1); feemod(par, t1); - /* t1 := (x^2 - a z^2)^2. */ - if(isZero(par->b)) { /* Speedup - REC 17 Jan 1997. */ - gtog(t1, res); - goto done; - } - if(par->curveType != FCT_Weierstrass) { // i.e., !isZero(par->c) - // Speedup - REC 17 Jan 1997. - gtog(z, res); mulg(par->c, res); feemod(par, res); - } else { - int_to_giant(0, res); - } - addg(x, res); addg(x, res); mulg(par->b, res); - feemod(par, res); - gshiftleft(2, res); mulg(z, res); feemod(par, res); - mulg(t2, res); feemod(par, res); - negg(res); addg(t1, res); - feemod(par, res); - -done: - returnGiant(t1); - returnGiant(t2); - PROF_END(numerDoubleTime); -} - -static void numer_plus(giant x1, giant x2, giant res, curveParams *par) -/* Numerator algebra. - res = (x1 x2 + a)(x1 + x2) + 2(c x1 x2 + b). - */ -{ - giant t1; - giant t2; - - PROF_START; - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - - gtog(x1, t1); mulg(x2, t1); feemod(par, t1); - gtog(x2, t2); addg(x1, t2); feemod(par, t2); - gtog(t1, res); - if(!isZero(par->a)) - addg(par->a, res); - mulg(t2, res); feemod(par, res); - if(par->curveType == FCT_Weierstrass) { // i.e., isZero(par->c) - int_to_giant(0, t1); - } - else { - mulg(par->c, t1); feemod(par, t1); - } - if(!isZero(par->b)) - addg(par->b, t1); - gshiftleft(1, t1); - addg(t1, res); feemod(par, res); - - returnGiant(t1); - returnGiant(t2); - PROF_END(numerPlusTime); -} - -static void denom_double(giant x, giant z, giant res, curveParams *par) -/* Denominator algebra. - res = 4 z (x^3 + c x^2 z + a x z^2 + b z^3). */ -{ - giant t1; - giant t2; - - PROF_START; - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - - gtog(x, res); gtog(z, t1); - if(par->curveType != FCT_Weierstrass) { // i.e., !isZero(par->c) - gtog(par->c, t2); mulg(t1, t2); feemod(par, t2); - addg(t2, res); - } - mulg(x, res); feemod(par, res); - gsquare(t1); feemod(par, t1); - if(!isZero(par->a)) { - gtog(t1, t2); - mulg(par->a, t2); feemod(par, t2); - addg(t2, res); - } - mulg(x, res); feemod(par, res); - if(!isZero(par->b)) { - mulg(z, t1); feemod(par, t1); - mulg(par->b, t1); feemod(par, t1); - addg(t1, res); - } - mulg(z, res); gshiftleft(2, res); - feemod(par, res); - - returnGiant(t1); - returnGiant(t2); - PROF_END(denomDoubleTime); -} - - - -static void denom_times(giant x1, giant z1, giant x2, giant z2, giant res, - curveParams *par) -/* Denominator algebra. - res := (x1 z2 - x2 z1)^2 - */ -{ - giant t1; - - PROF_START; - t1 = borrowGiant(par->maxDigits); - - gtog(x1, res); mulg(z2, res); feemod(par, res); - gtog(z1, t1); mulg(x2, t1); feemod(par, t1); - subg(t1, res); gsquare(res); feemod(par, res); - - returnGiant(t1); - PROF_END(denomTimesTime); -} - -static void numer_times(giant x1, giant z1, giant x2, giant z2, giant res, - curveParams *par) -/* Numerator algebra. - res := (x1 x2 - a z1 z2)^2 - - 4 b(x1 z2 + x2 z1 + c z1 z2) z1 z2 - */ -{ - giant t1; - giant t2; - giant t3; - giant t4; - - PROF_START; - t1 = borrowGiant(par->maxDigits); - t2 = borrowGiant(par->maxDigits); - t3 = borrowGiant(par->maxDigits); - t4 = borrowGiant(par->maxDigits); - - gtog(x1, t1); mulg(x2, t1); feemod(par, t1); - gtog(z1, t2); mulg(z2, t2); feemod(par, t2); - gtog(t1, res); - if(!isZero(par->a)) { - gtog(par->a, t3); - mulg(t2, t3); feemod(par, t3); - subg(t3, res); - } - gsquare(res); feemod(par, res); - if(isZero(par->b)) - goto done; - if(par->curveType != FCT_Weierstrass) { // i.e., !isZero(par->c) - gtog(par->c, t3); - mulg(t2, t3); feemod(par, t3); - } else int_to_giant(0, t3); - gtog(z1, t4); mulg(x2, t4); feemod(par, t4); - addg(t4, t3); - gtog(x1, t4); mulg(z2, t4); feemod(par, t4); - addg(t4, t3); mulg(par->b, t3); feemod(par, t3); - mulg(t2, t3); gshiftleft(2, t3); feemod(par, t3); - subg(t3, res); - feemod(par, res); - -done: - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - returnGiant(t4); - PROF_END(numerTimesTime); -} - -/* - * New, 13 Jan 1997. - */ -static void feepowermodg(curveParams *par, giant x, giant n) -/* Power ladder. - x := x^n (mod 2^q-k) - */ -{ - int len, pos; - giant t1; - - PROF_START; - t1 = borrowGiant(par->maxDigits); - gtog(x, t1); - int_to_giant(1, x); - len = bitlen(n); - pos = 0; - while(1) { - if(bitval(n, pos++)) { - mulg(t1, x); - feemod(par, x); - } - if(pos>=len) break; - gsquare(t1); - feemod(par, t1); - } - returnGiant(t1); - PROF_END(powerModTime); -} - -/* - * Set g := g mod curveOrder; - * force g to be between 2 and (curveOrder-2), inclusive. - * - * Tolerates zero curve orders (indicating "not known"). - */ - -/* - * This version is not normally used; it's for when the reciprocal of - * curveOrder is not known and won't be used again. - */ -void curveOrderJustify(giant g, giant curveOrder) -{ - giant recip; - - CKASSERT(!isZero(curveOrder)); - - recip = borrowGiant(2 * abs(g->sign)); - make_recip(curveOrder, recip); - curveOrderJustifyWithRecip(g, curveOrder, recip); - returnGiant(recip); -} - -/* - * New optimzation of curveOrderJustify using known reciprocal, 11 June 1997. - * g is set to be within [2, curveOrder-2]. - */ -static void curveOrderJustifyWithRecip(giant g, giant curveOrder, giant recip) -{ - giant tmp; - - CKASSERT(!isZero(curveOrder)); - - modg_via_recip(curveOrder, recip, g); // g now in [0, curveOrder-1] - - if(isZero(g)) { - /* - * First degenerate case - (g == 0) : set g := 2 - */ - dbgLog(("curveOrderJustify: case 1\n")); - int_to_giant(2, g); - return; - } - if(isone(g)) { - /* - * Second case - (g == 1) : set g := 2 - */ - dbgLog(("curveOrderJustify: case 2\n")); - int_to_giant(2, g); - return; - } - tmp = borrowGiant(g->capacity); - gtog(g, tmp); - iaddg(1, tmp); - if(gcompg(tmp, curveOrder) == 0) { - /* - * Third degenerate case - (g == (curveOrder-1)) : set g -= 1 - */ - dbgLog(("curveOrderJustify: case 3\n")); - int_to_giant(1, tmp); - subg(tmp, g); - } - returnGiant(tmp); - return; -} - -#define RECIP_DEBUG 0 -#if RECIP_DEBUG -#define recipLog(x) printf x -#else // RECIP_DEBUG -#define recipLog(x) -#endif // RECIP_DEBUG - -/* - * curveOrderJustify routines with specific orders, using (and possibly - * generating) associated reciprocals. - */ -void lesserX1OrderJustify(giant g, curveParams *cp) -{ - /* - * Note this is a pointer to a giant in *cp, not a newly - * malloc'd giant! - */ - giant lesserX1Ord = lesserX1Order(cp); - - if(isZero(lesserX1Ord)) { - return; - } - - /* - * Calculate reciprocal if we don't have it - */ - if(isZero(cp->lesserX1OrderRecip)) { - if((lesserX1Ord == cp->x1OrderPlus) && - (!isZero(cp->x1OrderPlusRecip))) { - /* - * lesserX1Ord happens to be x1OrderPlus, and we - * have a reciprocal for x1OrderPlus. Copy it over. - */ - recipLog(( - "x1OrderPlusRecip --> lesserX1OrderRecip\n")); - gtog(cp->x1OrderPlusRecip, cp->lesserX1OrderRecip); - } - else { - /* Calculate the reciprocal. */ - recipLog(("calc lesserX1OrderRecip\n")); - make_recip(lesserX1Ord, cp->lesserX1OrderRecip); - } - } - else { - recipLog(("using existing lesserX1OrderRecip\n")); - } - curveOrderJustifyWithRecip(g, lesserX1Ord, cp->lesserX1OrderRecip); -} - -/* - * Common code used by x1OrderPlusJustify() and x1OrderPlusMod() to generate - * reciprocal of x1OrderPlus. - * 8 Sep 1998 - also used by feeSigSign(). - */ -void calcX1OrderPlusRecip(curveParams *cp) -{ - if(isZero(cp->x1OrderPlusRecip)) { - if((cp->x1OrderPlus == lesserX1Order(cp)) && - (!isZero(cp->lesserX1OrderRecip))) { - /* - * lesserX1Order happens to be x1OrderPlus, and we - * have a reciprocal for lesserX1Order. Copy it over. - */ - recipLog(( - "lesserX1OrderRecip --> x1OrderPlusRecip\n")); - gtog(cp->lesserX1OrderRecip, cp->x1OrderPlusRecip); - } - else { - /* Calculate the reciprocal. */ - recipLog(("calc x1OrderPlusRecip\n")); - make_recip(cp->x1OrderPlus, cp->x1OrderPlusRecip); - } - } - else { - recipLog(("using existing x1OrderPlusRecip\n")); - } -} - -void x1OrderPlusJustify(giant g, curveParams *cp) -{ - CKASSERT(!isZero(cp->x1OrderPlus)); - - /* - * Calculate reciprocal if we don't have it - */ - calcX1OrderPlusRecip(cp); - curveOrderJustifyWithRecip(g, cp->x1OrderPlus, cp->x1OrderPlusRecip); -} - -/* - * g := g mod x1OrderPlus. Result may be zero. - */ -void x1OrderPlusMod(giant g, curveParams *cp) -{ - CKASSERT(!isZero(cp->x1OrderPlus)); - - /* - * Calculate reciprocal if we don't have it - */ - calcX1OrderPlusRecip(cp); - modg_via_recip(cp->x1OrderPlus, cp->x1OrderPlusRecip, g); -} - -/* - * New general-purpose giant mod routine, 8 Jan 97. - * x := x mod basePrime. - */ - -/* - * This stuff is used to analyze the critical loop behavior inside feemod(). - */ -#define FEEMOD_LOOP_TEST 0 -#if FEEMOD_LOOP_TEST -/* - * these two are only examined via debugger - */ -unsigned feemodCalls = 0; // calls to feemod() -unsigned feemodMultLoops = 0; // times while() loop runs > once -#define FEEMOD_LOOP_INCR feemodLoops++ -#define FEEMOD_CALL_INCR feemodCalls++ -#else // FEEMOD_LOOP_TEST -#define FEEMOD_LOOP_INCR -#define FEEMOD_CALL_INCR -#endif // FEEMOD_LOOP_TEST - - -void -feemod(curveParams *par, giant x) -{ - int sign, sign2; - giant t1; - giant t3; - giant t4; - giant t5; - #if FEEMOD_LOOP_TEST - unsigned feemodLoops = 0; - #endif // FEEMOD_LOOP_TEST - - FEEMOD_CALL_INCR; // for FEEMOD_LOOP_TEST - INCR_FEEMODS; // for ellipticMeasure - PROF_INCR(numFeemod); // for general profiling - - switch(par->primeType) { - case FPT_Mersenne: - /* - * Super-optimized Mersenne prime modulus case - */ - gmersennemod(par->q, x); - break; - - case FPT_FEE: - /* - * General 2**q-k case - */ - sign = (x->sign < 0) ? -1 : 1; - sign2 = 1; - x->sign = abs(x->sign); - if(gcompg(par->basePrime, x) >= 0) { - goto outFee; - } - t1 = borrowGiant(par->maxDigits); - t3 = borrowGiant(par->maxDigits); - t4 = borrowGiant(par->maxDigits); - t5 = borrowGiant(par->maxDigits); - - /* Begin OPT: 11 Jan 98 REC. */ - if( ((par->q & (GIANT_BITS_PER_DIGIT - 1)) == 0) && - (par->k >= 0) && - (par->k < GIANT_DIGIT_MASK)) { - - /* - * Microscopic mod for certain regions of {q,k} - * parameter space. - */ - int j, digits, excess, max; - giantDigit carry; - giantDigit termHi; // double precision - giantDigit termLo; - giantDigit *p1, *p2; - - digits = par->q >> GIANT_LOG2_BITS_PER_DIGIT; - while(bitlen(x) > par->q) { - excess = (x->sign) - digits; - max = (excess > digits) ? excess : digits; - carry = 0; - - p1 = &x->n[0]; - p2 = &x->n[digits]; - - if(excess <= digits) { - carry = VectorMultiply(par->k, - p2, - excess, - p1); - - /* propagate final carry */ - p1 += excess; - for(j = excess; j < digits; j++) { - - /* - * term = *p1 + carry; - * *p1++ = term & 65535; - * carry = term >> 16; - */ - termLo = giantAddDigits(*p1, carry, &carry); - *p1++ = termLo; - } - } else { - carry = VectorMultiply(par->k, - p2, - digits, - p1); - p1 += digits; - p2 += digits; - for(j = digits; j < excess; j++) { - /* - * term = (par->k)*(*p2++) + carry; - */ - giantMulDigits(par->k, - *p2++, - &termLo, - &termHi); - giantAddDouble(&termLo, &termHi, carry); - - /* - * *p1++ = term & 65535; - * carry = term >> 16; - */ - *p1++ = termLo; - carry = termHi; - } - } - - if(carry > 0) { - x->n[max] = carry; - } else { - while(--max){ - if(x->n[max] != 0) break; - } - } - x->sign = max + 1; - FEEMOD_LOOP_INCR; - } - } else { /* Macroscopic mod for general PT_FEE case. */ - int_to_giant(par->k, t4); - while(bitlen(x) > par->q) { - /* Enter fast loop, as in FEE patent. */ - int_to_giant(1, t5); - gtog(x, t3); - extractbits(par->q, t3, x); - while(bitlen(t3) > par->q) { - gshiftright(par->q, t3); - extractbits(par->q, t3, t1); - PAUSE_ELL_MEASURE; - mulg(t4, t5); - mulg(t5, t1); - RESUME_ELL_MEASURE; - addg(t1, x); - } - FEEMOD_LOOP_INCR; - } - } - /* End OPT: 11 Jan 98 REC. */ - - sign2 = (x->sign < 0)? -1: 1; - x->sign = abs(x->sign); - returnGiant(t1); - returnGiant(t3); - returnGiant(t4); - returnGiant(t5); - outFee: - if(gcompg(x, par->basePrime) >=0) subg(par->basePrime, x); - if(sign != sign2) { - giant t2 = borrowGiant(par->maxDigits); - gtog(par->basePrime, t2); - subg(x, t2); - gtog(t2, x); - returnGiant(t2); - } - break; - /* end case PT_FEE */ - - case FPT_General: - /* - * Use brute-force modg. - */ - #if FEE_DEBUG - if(par->basePrimeRecip == NULL) { - CKRaise("feemod(PT_GENERAL): No basePrimeRecip!\n"); - } - #endif /* FEE_DEBUG */ - modg_via_recip(par->basePrime, par->basePrimeRecip, x); - break; - - case FPT_Default: - /* never appears here */ - CKASSERT(0); - break; - } /* switch primeType */ - - #if FEEMOD_LOOP_TEST - if(feemodLoops > 1) { - feemodMultLoops++; - if(feemodLoops > 2) { - printf("feemod while loop executed %d times\n", feemodLoops); - } - } - #endif // FEEMOD_LOOP_TEST - - return; -} - -/* - * For a given curveParams, calculate minBytes and maxDigits. - * Assumes valid primeType, and also a valid basePrime for PT_GENERAL. - */ -void calcGiantSizes(curveParams *cp) -{ - - if(cp->primeType == FPT_General) { - cp->minBytes = (bitlen(cp->basePrime) + 7) / 8; - } - else { - cp->minBytes = giantMinBytes(cp->q, cp->k); - } - cp->maxDigits = giantMaxDigits(cp->minBytes); -} - -unsigned giantMinBytes(unsigned q, int k) -{ - unsigned kIsNeg = (k < 0) ? 1 : 0; - - return (q + 7 + kIsNeg) / 8; -} - -/* - * min value for "extra" bytes. Derived from the fact that during sig verify, - * we have to multiply a giant representing a digest - which may be - * 20 bytes for SHA1 - by a giant of minBytes. - */ -#define MIN_EXTRA_BYTES 20 - -unsigned giantMaxDigits(unsigned minBytes) -{ - unsigned maxBytes = 4 * minBytes; - - if((maxBytes - minBytes) < MIN_EXTRA_BYTES) { - maxBytes = minBytes + MIN_EXTRA_BYTES; - } - return BYTES_TO_GIANT_DIGITS(maxBytes); -} - - -/* - * Optimized binvg(basePrime, x). Avoids the general modg() in favor of - * feemod. - */ -int binvg_cp(curveParams *cp, giant x) -{ - feemod(cp, x); - return(binvaux(cp->basePrime, x)); -} - -/* - * Optimized binvg(x1OrderPlus, x). Uses x1OrderPlusMod(). - */ -int binvg_x1OrderPlus(curveParams *cp, giant x) -{ - x1OrderPlusMod(x, cp); - return(binvaux(cp->x1OrderPlus, x)); -} diff --git a/OSX/include/security_cryptkit/elliptic.h b/OSX/include/security_cryptkit/elliptic.h deleted file mode 100644 index 5b955194..00000000 --- a/OSX/include/security_cryptkit/elliptic.h +++ /dev/null @@ -1,165 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * elliptic.h - Fast Elliptic Encryption functions. - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 19 Feb 97 at NeXT - * Created. - */ - -#ifndef _CK_NSFEE_H_ -#define _CK_NSFEE_H_ - -#include "giantIntegers.h" -#include "feeTypes.h" -#include "curveParams.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Twist, or "which curve", parameter. - */ -#define CURVE_PLUS ((int)1) -#define CURVE_MINUS ((int)(-1)) - -typedef struct { - int twist; // CURVE_PLUS or CURVE_MINUS - giant x; // x coord of public key - - /* - * only valid for (twist == CURVE_PLUS) and curveType CT_WEIERSTRASS. - * Otherwise it's a zero-value giant. - */ - giant y; // y coord of public key - - /* - * Note: this module never allocs or frees a curveParams structs. - * This field is always maintained by clients of this module. - */ - curveParams *cp; // common curve parameters -} keystruct; - -typedef keystruct *key; - -/* - * Select which curve is the default curve for calculating signatures and - * doing key exchange. This *must* be CURVE_PLUS for key exchange to work - * with ECDSA keys and curves. - */ -#define DEFAULT_CURVE CURVE_PLUS - -key new_public(curveParams *cp, int twist); - -/* - * Specify private data for key created by new_public(). - * Generates k->x. - */ -void set_priv_key_giant(key k, giant privGiant); - -/* - * Generate new key with twist and k->x from old_key. - */ -key new_public_with_key(key old_key, curveParams *cp); - -/* - * Returns 1 if all parameters of two keys are equal, else returns 0. - */ -int key_equal(key first, key second); - -/* - * De-allocate an allocated key. - */ -void free_key(key pub); - -/* - * x3 = x1 + x2 on the curve, with sign ambiguity s. - * - * Note that int s is not just the twist field, because both s = +-1 must - * be tested in general. - */ -void elliptic_add(giant x1, giant x2, giant x3, curveParams *par, int s); - -/* - * Values for the 's', or sign, argument to elliptic_add(). - */ -#define SIGN_PLUS 1 -#define SIGN_MINUS (-1) - - -/* - * Elliptic multiply: x := n * {x, 1} - */ -void elliptic_simple(giant x, giant n, curveParams *par); - -/* - * General elliptic multiply: {xx, zz} := k * {xx, zz} - */ -void elliptic(giant xx, giant zz, giant k, curveParams *par); - -/* - * Returns CURVE_PLUS or CURVE_MINUS, indicating which curve a particular - * x coordinate resides on. - */ -int which_curve(giant x, curveParams *par); - -/* - * Generate (2**q)-k. - */ -void make_base_prim(curveParams *cp); - -/* - * return a new giant that is the pad from private data and public key - */ -giant make_pad(giant privGiant, key publicKey); - -/* - * Returns non-zero if x(p1) cannot be the x-coordinate of the - * sum of two points whose respective x-coordinates are x(p2), x(p3). - */ -int signature_compare(giant p0x, giant p1x, giant p2x, curveParams *par); - -/* - * Set g := g mod curveOrder; - * force g to be between 2 and (curveOrder-2), inclusive. - */ -void curveOrderJustify(giant g, giant curveOrder); - -void lesserX1OrderJustify(giant g, curveParams *cp); -void x1OrderPlusJustify(giant g, curveParams *cp); -void x1OrderPlusMod(giant g, curveParams *cp); - -void calcX1OrderPlusRecip(curveParams *cp); - -/* - * x := x mod basePrime. - */ -void feemod(curveParams *par, giant x); - -/* - * For a given curveParams, calculate minBytes and maxDigits. - */ -void calcGiantSizes(curveParams *cp); -unsigned giantMinBytes(unsigned q, int k); -unsigned giantMaxDigits(unsigned minBytes); - -int binvg_cp(curveParams *cp, giant x); -int binvg_x1OrderPlus(curveParams *cp, giant x); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_NSFEE_H_*/ diff --git a/OSX/include/security_cryptkit/ellipticMeasure.h b/OSX/include/security_cryptkit/ellipticMeasure.h deleted file mode 100644 index ed5e36c9..00000000 --- a/OSX/include/security_cryptkit/ellipticMeasure.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - File: ellipticMeasure.h - - Contains: xxx put contents here xxx - - - Copyright: Copyright (c) 1998,2011,2014 Apple Inc. - All rights reserved. - - Change History (most recent first): - - <7> 10/06/98 ap Changed to compile with C++. - - To Do: -*/ - -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * Measurement of feemods and mulgs withing an elliptic_simple() call. - */ - -#include "feeDebug.h" - -#ifdef FEE_DEBUG -#define ELLIPTIC_MEASURE 0 -#else // FEE_DEBUG -#define ELLIPTIC_MEASURE 0 /* always off */ -#endif // FEE_DEBUG - -#if ELLIPTIC_MEASURE - -extern int doEllMeasure; // gather stats on/off */ -extern int bitsInN; -extern int numFeeMods; -extern int numMulgs; - -#define START_ELL_MEASURE(n) \ - doEllMeasure = 1; \ - bitsInN = bitlen(n); \ - numFeeMods = 0; \ - numMulgs = 0; - -#define END_ELL_MEASURE doEllMeasure = 0; - -#define INCR_FEEMODS \ - if(doEllMeasure) { \ - numFeeMods++; \ - } - -#define INCR_MULGS \ - if(doEllMeasure) { \ - numMulgs++; \ - } - -/* - * These two are used around mulg() calls in feemod() itself; they - * inhibit the counting of those mulg() calls. - */ -#define PAUSE_ELL_MEASURE \ - { \ - int tempEllMeasure = doEllMeasure; \ - doEllMeasure = 0; - -#define RESUME_ELL_MEASURE \ - doEllMeasure = tempEllMeasure; \ - } - -#else // ELLIPTIC_MEASURE - -#define START_ELL_MEASURE(n) -#define END_ELL_MEASURE -#define INCR_FEEMODS -#define INCR_MULGS -#define PAUSE_ELL_MEASURE -#define RESUME_ELL_MEASURE - -#endif // ELLIPTIC_MEASURE diff --git a/OSX/include/security_cryptkit/ellipticProj.c b/OSX/include/security_cryptkit/ellipticProj.c deleted file mode 100644 index bdb24316..00000000 --- a/OSX/include/security_cryptkit/ellipticProj.c +++ /dev/null @@ -1,565 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ellipticProj.c - elliptic projective algebra routines. - * - * Revision History - * ---------------- - * 1 Sep 1998 at Apple - * Created. - * - ************************************************************** - - PROJECTIVE FORMAT - - Functions are supplied herein for projective format - of points. Alternative formats differ in their - range of applicability, efficiency, and so on. - Primary advantages of the projective format herein are: - -- No explicit inversions (until perhaps one such at the end of - an elliptic multiply operation) - -- Fairly low operation count (~11 muls for point doubling, - ~16 muls for point addition) - - The elliptic curve is over F_p, with p > 3 prime, and Weierstrass - parameterization: - - y^2 = x^3 + a x + b - - The projective-format coordinates are actually stored in - the form {X, Y, Z}, with true x,y - coordinates on the curve given by {x,y} = {X/Z^2, Y/Z^3}. - The function normalizeProj() performs the - transformation from projective->true. - (The other direction is trivial, i.e. {x,y} -> {x,y,1} will do.) - The basic point multiplication function is - - ellMulProj() - - which obtains the result k * P for given point P and integer - multiplier k. If true {x,y} are required for a multiple, one - passes a point P = {X, Y, 1} to ellMulProj(), then afterwards - calls normalizeProj(), - - Projective format is an answer to the typical sluggishness of - standard elliptic arithmetic, whose explicit inversion in the - field is, depending of course on the machinery and programmer, - costly. Projective format is thus especially interesting for - cryptography. - - REFERENCES - - perspective," Springer-Verlag, manuscript - - Solinas J 1998, IEEE P1363 Annex A (draft standard) - -***********************************************************/ - -#include "ckconfig.h" -#if CRYPTKIT_ELL_PROJ_ENABLE - -#include "ellipticProj.h" -#include "falloc.h" -#include "curveParams.h" -#include "elliptic.h" -#include "feeDebug.h" - -/* - * convert REC-style smulg to generic imulg - */ -#define smulg(s, g) imulg((unsigned)s, g) - -pointProj newPointProj(unsigned numDigits) -{ - pointProj pt; - - pt = (pointProj) fmalloc(sizeof(pointProjStruct)); - pt->x = newGiant(numDigits); - pt->y = newGiant(numDigits); - pt->z = newGiant(numDigits); - return(pt); -} - -void freePointProj(pointProj pt) -{ - clearGiant(pt->x); freeGiant(pt->x); - clearGiant(pt->y); freeGiant(pt->y); - clearGiant(pt->z); freeGiant(pt->z); - ffree(pt); -} - -void ptopProj(pointProj pt1, pointProj pt2) -{ - gtog(pt1->x, pt2->x); - gtog(pt1->y, pt2->y); - gtog(pt1->z, pt2->z); -} - -/************************************************************** - * - * Elliptic curve operations - * - **************************************************************/ - -/* Begin projective-format functions for - - y^2 = x^3 + a x + b. - - These are useful in elliptic curve cryptography (ECC). - A point is kept as a triple {X,Y,Z}, with the true (x,y) - coordinates given by - - {x,y} = {X/Z^2, Y/Z^3} - - The function normalizeProj() performs the inverse conversion to get - the true (x,y) pair. - */ - -void ellDoubleProj(pointProj pt, curveParams *cp) -/* pt := 2 pt on the curve. */ -{ - giant x = pt->x, y = pt->y, z = pt->z; - giant t1; - giant t2; - giant t3; - - if(isZero(y) || isZero(z)) { - int_to_giant(1,x); int_to_giant(1,y); int_to_giant(0,z); - return; - } - t1 = borrowGiant(cp->maxDigits); - t2 = borrowGiant(cp->maxDigits); - t3 = borrowGiant(cp->maxDigits); - - if((cp->a->sign >= 0) || (cp->a->n[0] != 3)) { /* Path prior to Apr2001. */ - gtog(z,t1); gsquare(t1); feemod(cp, t1); - gsquare(t1); feemod(cp, t1); - mulg(cp->a, t1); feemod(cp, t1); /* t1 := a z^4. */ - gtog(x, t2); gsquare(t2); feemod(cp, t2); - smulg(3, t2); /* t2 := 3x^2. */ - addg(t2, t1); feemod(cp, t1); /* t1 := slope m. */ - } else { /* New optimization for a = -3 (post Apr 2001). */ - gtog(z, t1); gsquare(t1); feemod(cp, t1); /* t1 := z^2. */ - gtog(x, t2); subg(t1, t2); /* t2 := x-z^2. */ - addg(x, t1); smulg(3, t1); /* t1 := 3(x+z^2). */ - mulg(t2, t1); feemod(cp, t1); /* t1 := slope m. */ - } - mulg(y, z); addg(z,z); feemod(cp, z); /* z := 2 y z. */ - gtog(y, t2); gsquare(t2); feemod(cp, t2); /* t2 := y^2. */ - gtog(t2, t3); gsquare(t3); feemod(cp, t3); /* t3 := y^4. */ - gshiftleft(3, t3); /* t3 := 8 y^4. */ - mulg(x, t2); gshiftleft(2, t2); feemod(cp, t2); /* t2 := 4xy^2. */ - gtog(t1, x); gsquare(x); feemod(cp, x); - subg(t2, x); subg(t2, x); feemod(cp, x); /* x done. */ - gtog(t1, y); subg(x, t2); mulg(t2, y); subg(t3, y); - feemod(cp, y); - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); -} - -void ellAddProj(pointProj pt0, pointProj pt1, curveParams *cp) -/* pt0 := pt0 + pt1 on the curve. */ -{ - giant x0 = pt0->x, y0 = pt0->y, z0 = pt0->z, - x1 = pt1->x, y1 = pt1->y, z1 = pt1->z; - giant t1; - giant t2; - giant t3; - giant t4; - giant t5; - giant t6; - giant t7; - - if(isZero(z0)) { - gtog(x1,x0); gtog(y1,y0); gtog(z1,z0); - return; - } - if(isZero(z1)) return; - - t1 = borrowGiant(cp->maxDigits); - t2 = borrowGiant(cp->maxDigits); - t3 = borrowGiant(cp->maxDigits); - t4 = borrowGiant(cp->maxDigits); - t5 = borrowGiant(cp->maxDigits); - t6 = borrowGiant(cp->maxDigits); - t7 = borrowGiant(cp->maxDigits); - - gtog(x0, t1); gtog(y0,t2); gtog(z0, t3); - gtog(x1, t4); gtog(y1, t5); - if(!isone(z1)) { - gtog(z1, t6); - gtog(t6, t7); gsquare(t7); feemod(cp, t7); - mulg(t7, t1); feemod(cp, t1); - mulg(t6, t7); feemod(cp, t7); - mulg(t7, t2); feemod(cp, t2); - } - gtog(t3, t7); gsquare(t7); feemod(cp, t7); - mulg(t7, t4); feemod(cp, t4); - mulg(t3, t7); feemod(cp, t7); - mulg(t7, t5); feemod(cp, t5); - negg(t4); addg(t1, t4); feemod(cp, t4); - negg(t5); addg(t2, t5); feemod(cp, t5); - if(isZero(t4)) { - if(isZero(t5)) { - ellDoubleProj(pt0, cp); - } else { - int_to_giant(1, x0); int_to_giant(1, y0); - int_to_giant(0, z0); - } - goto out; - } - addg(t1, t1); subg(t4, t1); feemod(cp, t1); - addg(t2, t2); subg(t5, t2); feemod(cp, t2); - if(!isone(z1)) { - mulg(t6, t3); feemod(cp, t3); - } - mulg(t4, t3); feemod(cp, t3); - gtog(t4, t7); gsquare(t7); feemod(cp, t7); - mulg(t7, t4); feemod(cp, t4); - mulg(t1, t7); feemod(cp, t7); - gtog(t5, t1); gsquare(t1); feemod(cp, t1); - subg(t7, t1); feemod(cp, t1); - subg(t1, t7); subg(t1, t7); feemod(cp, t7); - mulg(t7, t5); feemod(cp, t5); - mulg(t2, t4); feemod(cp, t4); - gtog(t5, t2); subg(t4,t2); feemod(cp, t2); - if(t2->n[0] & 1) { /* Test if t2 is odd. */ - addg(cp->basePrime, t2); - } - gshiftright(1, t2); - gtog(t1, x0); gtog(t2, y0); gtog(t3, z0); -out: - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - returnGiant(t4); - returnGiant(t5); - returnGiant(t6); - returnGiant(t7); -} - - -void ellNegProj(pointProj pt, curveParams *cp) -/* pt := -pt on the curve. */ -{ - negg(pt->y); feemod(cp, pt->y); -} - -void ellSubProj(pointProj pt0, pointProj pt1, curveParams *cp) -/* pt0 := pt0 - pt1 on the curve. */ -{ - ellNegProj(pt1, cp); - ellAddProj(pt0, pt1,cp); - ellNegProj(pt1, cp); -} - -/* - * Simple projective multiply. - * - * pt := pt * k, result normalized. - */ -void ellMulProjSimple(pointProj pt0, giant k, curveParams *cp) -{ - pointProjStruct pt1; // local, giants borrowed - - CKASSERT(isone(pt0->z)); - CKASSERT(cp->curveType == FCT_Weierstrass); - - /* ellMulProj assumes constant pt0, can't pass as src and dst */ - pt1.x = borrowGiant(cp->maxDigits); - pt1.y = borrowGiant(cp->maxDigits); - pt1.z = borrowGiant(cp->maxDigits); - ellMulProj(pt0, &pt1, k, cp); - normalizeProj(&pt1, cp); - CKASSERT(isone(pt1.z)); - - ptopProj(&pt1, pt0); - returnGiant(pt1.x); - returnGiant(pt1.y); - returnGiant(pt1.z); -} - -void ellMulProj(pointProj pt0, pointProj pt1, giant k, curveParams *cp) -/* General elliptic multiplication; - pt1 := k*pt0 on the curve, - with k an arbitrary integer. - */ -{ - giant x = pt0->x, y = pt0->y, z = pt0->z, - xx = pt1->x, yy = pt1->y, zz = pt1->z; - int ksign, hlen, klen, b, hb, kb; - giant t0; - - CKASSERT(cp->curveType == FCT_Weierstrass); - if(isZero(k)) { - int_to_giant(1, xx); - int_to_giant(1, yy); - int_to_giant(0, zz); - return; - } - t0 = borrowGiant(cp->maxDigits); - ksign = k->sign; - if(ksign < 0) negg(k); - gtog(x,xx); gtog(y,yy); gtog(z,zz); - gtog(k, t0); addg(t0, t0); addg(k, t0); /* t0 := 3k. */ - hlen = bitlen(t0); - klen = bitlen(k); - for(b = hlen-2; b > 0; b--) { - ellDoubleProj(pt1,cp); - hb = bitval(t0, b); - if(b < klen) kb = bitval(k, b); else kb = 0; - if((hb != 0) && (kb == 0)) - ellAddProj(pt1, pt0, cp); - else if((hb == 0) && (kb !=0)) - ellSubProj(pt1, pt0, cp); - } - if(ksign < 0) { - ellNegProj(pt1, cp); - k->sign = -k->sign; - } - returnGiant(t0); -} - -void normalizeProj(pointProj pt, curveParams *cp) -/* Obtain actual x,y coords via normalization: - {x,y,z} := {x/z^2, y/z^3, 1}. - */ - -{ giant x = pt->x, y = pt->y, z = pt->z; - giant t1; - - CKASSERT(cp->curveType == FCT_Weierstrass); - if(isZero(z)) { - int_to_giant(1,x); int_to_giant(1,y); - return; - } - t1 = borrowGiant(cp->maxDigits); - binvg_cp(cp, z); // was binvaux(p, z); - gtog(z, t1); - gsquare(z); feemod(cp, z); - mulg(z, x); feemod(cp, x); - mulg(t1, z); mulg(z, y); feemod(cp, y); - int_to_giant(1, z); - returnGiant(t1); -} - -static int -jacobi_symbol(giant a, curveParams *cp) -/* Standard Jacobi symbol (a/cp->basePrime). - basePrime must be odd, positive. */ -{ - int t = 1, u; - giant t5 = borrowGiant(cp->maxDigits); - giant t6 = borrowGiant(cp->maxDigits); - giant t7 = borrowGiant(cp->maxDigits); - int rtn; - - gtog(a, t5); feemod(cp, t5); - gtog(cp->basePrime, t6); - while(!isZero(t5)) { - u = (t6->n[0]) & 7; - while((t5->n[0] & 1) == 0) { - gshiftright(1, t5); - if((u==3) || (u==5)) t = -t; - } - gtog(t5, t7); gtog(t6, t5); gtog(t7, t6); - u = (t6->n[0]) & 3; - if(((t5->n[0] & 3) == 3) && ((u & 3) == 3)) t = -t; - modg(t6, t5); - } - if(isone(t6)) { - rtn = t; - } - else { - rtn = 0; - } - returnGiant(t5); - returnGiant(t6); - returnGiant(t7); - - return rtn; -} - -static void -powFp2(giant a, giant b, giant w2, giant n, curveParams *cp) -/* Perform powering in the field F_p^2: - a + b w := (a + b w)^n (mod p), where parameter w2 is a quadratic - nonresidue (formally equal to w^2). - */ -{ - int j; - giant t6; - giant t7; - giant t8; - giant t9; - - if(isZero(n)) { - int_to_giant(1,a); - int_to_giant(0,b); - return; - } - t6 = borrowGiant(cp->maxDigits); - t7 = borrowGiant(cp->maxDigits); - t8 = borrowGiant(cp->maxDigits); - t9 = borrowGiant(cp->maxDigits); - gtog(a, t8); gtog(b, t9); - for(j = bitlen(n)-2; j >= 0; j--) { - gtog(b, t6); - mulg(a, b); addg(b,b); feemod(cp, b); /* b := 2 a b. */ - gsquare(t6); feemod(cp, t6); - mulg(w2, t6); feemod(cp, t6); - gsquare(a); addg(t6, a); feemod(cp, a); - /* a := a^2 + b^2 w2. */ - if(bitval(n, j)) { - gtog(b, t6); mulg(t8, b); feemod(cp, b); - gtog(a, t7); mulg(t9, a); addg(a, b); feemod(cp, b); - mulg(t9, t6); feemod(cp, t6); - mulg(w2, t6); feemod(cp, t6); - mulg(t8, a); addg(t6, a); feemod(cp, a); - } - } - returnGiant(t6); - returnGiant(t7); - returnGiant(t8); - returnGiant(t9); - return; -} - -static void -powermodg( - giant x, - giant n, - curveParams *cp -) -/* x becomes x^n (mod basePrime). */ -{ - int len, pos; - giant scratch2 = borrowGiant(cp->maxDigits); - - gtog(x, scratch2); - int_to_giant(1, x); - len = bitlen(n); - pos = 0; - while (1) - { - if (bitval(n, pos++)) - { - mulg(scratch2, x); - feemod(cp, x); - } - if (pos>=len) - break; - gsquare(scratch2); - feemod(cp, scratch2); - } - returnGiant(scratch2); -} - -static int sqrtmod(giant x, curveParams *cp) -/* If Sqrt[x] (mod p) exists, function returns 1, else 0. - In either case x is modified, but if 1 is returned, - x:= Sqrt[x] (mod p). - */ -{ - int rtn; - giant t0 = borrowGiant(cp->maxDigits); - giant t1 = borrowGiant(cp->maxDigits); - giant t2 = borrowGiant(cp->maxDigits); - giant t3 = borrowGiant(cp->maxDigits); - giant t4 = borrowGiant(cp->maxDigits); - - giant p = cp->basePrime; - - feemod(cp, x); /* Justify the argument. */ - gtog(x, t0); /* Store x for eventual validity check on square root. */ - if((p->n[0] & 3) == 3) { /* The case p = 3 (mod 4). */ - gtog(p, t1); - iaddg(1, t1); gshiftright(2, t1); - powermodg(x, t1, cp); - goto resolve; - } - /* Next, handle case p = 5 (mod 8). */ - if((p->n[0] & 7) == 5) { - gtog(p, t1); int_to_giant(1, t2); - subg(t2, t1); gshiftright(2, t1); - gtog(x, t2); - powermodg(t2, t1, cp); /* t2 := x^((p-1)/4) % p. */ - iaddg(1, t1); - gshiftright(1, t1); /* t1 := (p+3)/8. */ - if(isone(t2)) { - powermodg(x, t1, cp); /* x^((p+3)/8) is root. */ - goto resolve; - } else { - int_to_giant(1, t2); subg(t2, t1); - /* t1 := (p-5)/8. */ - gshiftleft(2,x); - powermodg(x, t1, cp); - mulg(t0, x); addg(x, x); feemod(cp, x); - /* 2x (4x)^((p-5)/8. */ - goto resolve; - } - } - - /* Next, handle tougher case: p = 1 (mod 8). */ - int_to_giant(2, t1); - while(1) { /* Find appropriate nonresidue. */ - gtog(t1, t2); - gsquare(t2); subg(x, t2); feemod(cp, t2); - if(jacobi_symbol(t2, cp) == -1) break; - iaddg(1, t1); - } /* t2 is now w^2 in F_p^2. */ - int_to_giant(1, t3); - gtog(p, t4); iaddg(1, t4); gshiftright(1, t4); - powFp2(t1, t3, t2, t4, cp); - gtog(t1, x); - -resolve: - gtog(x,t1); gsquare(t1); feemod(cp, t1); - if(gcompg(t0, t1) == 0) { - rtn = 1; /* Success. */ - } - else { - rtn = 0; /* no square root */ - } - returnGiant(t0); - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); - returnGiant(t4); - return rtn; -} - - -void findPointProj(pointProj pt, giant seed, curveParams *cp) -/* Starting with seed, finds a random (projective) point {x,y,1} on curve. - */ -{ - giant x = pt->x, y = pt->y, z = pt->z; - - CKASSERT(cp->curveType == FCT_Weierstrass); - feemod(cp, seed); - while(1) { - gtog(seed, x); - gsquare(x); feemod(cp, x); // x := seed^2 - addg(cp->a, x); // x := seed^2 + a - mulg(seed,x); // x := seed^3 + a*seed - addg(cp->b, x); - feemod(cp, x); // x := seed^3 + a seed + b. - /* test cubic form for having root. */ - if(sqrtmod(x, cp)) break; - iaddg(1, seed); - } - gtog(x, y); - gtog(seed,x); - int_to_giant(1, z); -} - -#endif /* CRYPTKIT_ELL_PROJ_ENABLE */ diff --git a/OSX/include/security_cryptkit/ellipticProj.h b/OSX/include/security_cryptkit/ellipticProj.h deleted file mode 100644 index c71add72..00000000 --- a/OSX/include/security_cryptkit/ellipticProj.h +++ /dev/null @@ -1,76 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * ellipticProj.h - declaration of elliptic projective algebra routines. - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 1 Sep 1998 at Apple - * Created. - */ - -#ifndef _CRYPTKIT_ELLIPTIC_PROJ_H_ -#define _CRYPTKIT_ELLIPTIC_PROJ_H_ - -#include "ckconfig.h" - -#if CRYPTKIT_ELL_PROJ_ENABLE - -#include "giantIntegers.h" -#include "curveParams.h" - -/* - * A projective point. - */ -typedef struct { - giant x; - giant y; - giant z; -} pointProjStruct; - -typedef pointProjStruct *pointProj; - -pointProj /* Allocates a new projective point. */ -newPointProj(unsigned numDigits); - -void /* Frees point. */ -freePointProj(pointProj pt); - -void /* Copies point to point; pt2 := pt1. */ -ptopProj(pointProj pt1, pointProj pt2); - -void /* Point doubling. */ -ellDoubleProj(pointProj pt, curveParams *cp); - -void /* Point adding; pt0 := pt0 - pt1. */ -ellAddProj(pointProj pt0, pointProj pt1, curveParams *cp); - -void /* Point negation; pt := -pt. */ -ellNegProj(pointProj pt, curveParams *cp); - -void /* Point subtraction; pt0 := pt0 - pt1. */ -ellSubProj(pointProj pt0, pointProj pt1, curveParams *cp); - -void /* pt := pt * k, result normalized */ -ellMulProjSimple(pointProj pt0, giant k, curveParams *cp); - -void /* General elliptic mul; pt1 := k*pt0. */ -ellMulProj(pointProj pt0, pointProj pt1, giant k, curveParams *cp); - -void /* Generate normalized point (X, Y, 1) from given (x,y,z). */ -normalizeProj(pointProj pt, curveParams *cp); - -void /* Find a point (x, y, 1) on the curve. */ -findPointProj(pointProj pt, giant seed, curveParams *cp); - -#endif /* CRYPTKIT_ELL_PROJ_ENABLE*/ -#endif /* _CRYPTKIT_ELLIPTIC_PROJ_H_ */ diff --git a/OSX/include/security_cryptkit/enc64.c b/OSX/include/security_cryptkit/enc64.c deleted file mode 100644 index f49a8d6b..00000000 --- a/OSX/include/security_cryptkit/enc64.c +++ /dev/null @@ -1,417 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * enc64.c - encode/decode in 64-char IA5 format, per RFC 1421 - * - * Revision History - * ---------------- - * 11/27/98 dmitch - * Added ECDSA_VERIFY_ONLY dependencies. - * 10/06/98 ap - * Changed to compile with C++. - * 12 Dec 96 at NeXT - * Newlines optional in dec64() and isValidEnc64(). - * 9 Oct 96 at NeXT - * Created. - */ - -#include "enc64.h" -#include "falloc.h" - -/* - * 11/27/98 dmitch: The ECDSA_VERIFY_ONLY symbol, when #defined, disables all - * of the code in this module except that which is necessary for ECDSA - * siggnature verification. - */ - -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ - -/* - * map a 6-bit binary value to a printable character. - */ -static const -unsigned char bintoasc[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -/* - * Map an 7-bit printable character to its corresponding binary value. - * Any illegal characters return high bit set. - */ -static const -unsigned char asctobin[] = -{ - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x3e, 0x80, 0x80, 0x80, 0x3f, - 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, - 0x3c, 0x3d, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, - 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, - 0x17, 0x18, 0x19, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, 0x33, 0x80, 0x80, 0x80, 0x80, 0x80 -}; - -/* - * map 6 bits to a printing char - */ -#define ENC(c) (bintoasc[((c) & 0x3f)]) - -#define PAD '=' -//#define ENC_LINE_LEN 64 - -#ifndef ECDSA_VERIFY_ONLY - -/* - * map one group of up to 3 bytes at inp to 4 bytes at outp. - * Count is number of valid bytes in *inp; if less than 3, the - * 1 or two extras must be zeros. - */ -static void encChunk(const unsigned char *inp, - unsigned char *outp, - int count) -{ - unsigned char c1, c2, c3, c4; - - c1 = *inp >> 2; - c2 = ((inp[0] << 4) & 0x30) | ((inp[1] >> 4) & 0xf); - c3 = ((inp[1] << 2) & 0x3c) | ((inp[2] >> 6) & 0x3); - c4 = inp[2] & 0x3f; - *outp++ = ENC(c1); - *outp++ = ENC(c2); - if (count == 1) { - *outp++ = PAD; - *outp = PAD; - } else { - *outp++ = ENC(c3); - if (count == 2) { - *outp = PAD; - } - else { - *outp = ENC(c4); - } - } -} - -/* - * Given input buffer inbuf, length inlen, encode to 64-char IA5 format. - * Result is fmalloc'd and returned; it is terminated by Microsoft-style - * newline and NULL. Its length (including the trailing newline and NULL) - * is returned in *outlen. - */ - -unsigned char *enc64(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen) // RETURNED -{ - return enc64WithLines(inbuf, inlen, 0, outlen); -} - -unsigned char *enc64WithLines(const unsigned char *inbuf, - unsigned inlen, - unsigned linelen, - unsigned *outlen) -{ - unsigned outTextLen; - unsigned len; // to malloc, liberal - unsigned olen = 0; // actual output size - unsigned char *outbuf; - unsigned char endbuf[3]; - unsigned i; - unsigned char *outp; - unsigned numLines; - unsigned thisLine; - - outTextLen = ((inlen + 2) / 3) * 4; - if(linelen) { - /* - * linelen must be 0 mod 4 for this to work; round up... - */ - if((linelen & 0x03) != 0) { - linelen = (linelen + 3) & 0xfffffffc; - } - numLines = (outTextLen + linelen - 1)/ linelen; - } - else { - numLines = 1; - } - - /* - * Total output size = encoded text size plus one newline per - * line of output, plus trailing NULL. For Microsoft compatibility, - * we always generate newlines as \r\n; when decoding, we tolerate - * \r\n or \n. - */ - len = outTextLen + (2 * numLines) + 1; - outbuf = (unsigned char*) fmalloc(len); - outp = outbuf; - thisLine = 0; - - while(inlen) { - if(inlen < 3) { - for(i=0; i<3; i++) { - if(i < inlen) { - endbuf[i] = inbuf[i]; - } - else { - endbuf[i] = 0; - } - } - encChunk(endbuf, outp, inlen); - inlen = 0; - } - else { - encChunk(inbuf, outp, 3); - inlen -= 3; - inbuf += 3; - } - outp += 4; - thisLine += 4; - olen += 4; - if((linelen != 0) && (thisLine >= linelen) && inlen) { - /* - * last trailing newline added below - * Note we don't split 4-byte output chunks over newlines - */ - *outp++ = '\r'; - *outp++ = '\n'; - olen += 2; - thisLine = 0; - } - } - *outp++ = '\r'; - *outp++ = '\n'; - *outp = '\0'; - olen += 3; - *outlen = olen; - return outbuf; -} - -#endif /* ECDSA_VERIFY_ONLY */ - -static inline int isWhite(unsigned char c) -{ - switch(c) { - case '\n': - - case '\r': - - case ' ': - - case '\t': - - case '\0': - return 1; - - default: - - return 0; - - } -} - -/* - * Strip off all whitespace from a (supposedly) enc64-format string. - * Returns a malloc'd string. - */ -static unsigned char *stringCleanse(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen) -{ - unsigned char *news; // cleansed inbuf - unsigned newsDex; // index into news - unsigned i; - - news = (unsigned char*) fmalloc(inlen); - newsDex = 0; - for(i=0; i 0) { - goto errorOut; - } - } - else { - goto errorOut; - } - } else if (*bp & 0x80 || (c3 = asctobin[*bp]) & 0x80) { - goto errorOut; - } else { - bp++; - inlen--; - if (*bp == PAD) { - /* - * Three input bytes, two output - */ - c4 = 0; - thisOlen = 2; - if (c3 & 3) { - goto errorOut; - } - } else if (*bp & 0x80 || (c4 = asctobin[*bp]) & 0x80) { - goto errorOut; - } else { - /* - * Normal non-pad case - */ - thisOlen = 3; - } - bp++; - inlen--; - } - j = (c1 << 2) | (c2 >> 4); - *outp++ = j; - if(thisOlen > 1) { - j = (c2 << 4) | (c3 >> 2); - *outp++ = j; - if(thisOlen == 3) { - j = (c3 << 6) | c4; - *outp++ = j; - } - } - olen += thisOlen; - } - ffree(news); - *outlen = olen; - return outbuf; /* normal return */ - -errorOut: - ffree(news); - ffree(outbuf); - return (unsigned char*) NULL; -} - -/* - * Determine if specified input data is valid enc64 format. Returns 1 - * if valid, 0 if not. - * This doesn't do a full enc64 parse job; it scans for legal characters - * and proper sync when a possible pad is found. - */ -int isValidEnc64(const unsigned char *inbuf, - unsigned inlen) -{ - int padChars = 0; // running count of PAD chars - int validEncChars = 0; - unsigned char c; - - /* - * -- scan inbuf - * -- skip whitespace - * -- count valid chars - * -- ensure not more than 2 PAD chars, only at end - * -- ensure valid chars mod 4 == 0 - */ - - while(inlen) { - c = *inbuf++; - inlen--; - if(isWhite(c)) { - continue; - } - if(c == PAD) { - if(++padChars > 2) { - return 0; // max of 2 PAD chars at end - } - } - else if(padChars > 0) { - return 0; // no normal chars after seeing PAD - } - else if((c & 0x80) || ((asctobin[c]) & 0x80)) { - return 0; // invalid encoded char - } - validEncChars++; - } - if((validEncChars & 0x03) != 0) { - return 0; - } - else { - return 1; - } -} diff --git a/OSX/include/security_cryptkit/enc64.h b/OSX/include/security_cryptkit/enc64.h deleted file mode 100644 index 2a52ea24..00000000 --- a/OSX/include/security_cryptkit/enc64.h +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * enc64.h - encode/decode in 64-char IA5 format, per RFC 1421 - * - * Revision History - * ---------------- - * 9 Oct 96 at NeXT - * Created. - */ - -#ifndef _CK_ENC64_H_ -#define _CK_ENC64_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Given input buffer inbuf, length inlen, decode from 64-char IA5 format to - * binary. Result is fmalloced and returned; its length is returned in *outlen. - * NULL return indicates corrupted input. - */ -unsigned char *enc64(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen); // RETURNED - -/* - * Enc64, with embedded newlines every lineLen in result. A newline is - * the Microsoft-style "\r\n". - */ -unsigned char *enc64WithLines(const unsigned char *inbuf, - unsigned inlen, - unsigned linelen, - unsigned *outlen); // RETURNED - -/* - * Given input buffer inbuf, length inlen, decode from 64-char IA5 format to - * binary. Result is fmalloced and returned; its length is returned in *outlen. - * NULL return indicates corrupted input. All whitespace in inbuf is - * ignored. - */ -unsigned char *dec64(const unsigned char *inbuf, - unsigned inlen, - unsigned *outlen); - -/* - * Determine if specified input data is valid enc64 format. Returns 1 - * if valid, 0 if not. - */ -int isValidEnc64(const unsigned char *inbuf, - unsigned inbufLen); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_ENC64_H_*/ diff --git a/OSX/include/security_cryptkit/engineNSA127.c b/OSX/include/security_cryptkit/engineNSA127.c deleted file mode 100644 index 0e8ea4af..00000000 --- a/OSX/include/security_cryptkit/engineNSA127.c +++ /dev/null @@ -1,542 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - - CONFIDENTIAL CONFIDENTIAL CONFIDENTIAL - engineNSA.c - - Security Engine code, to be compiled prior to software - distribution. The code performs the - elliptic curve algebra fundamental to the patented FEE - system. - - This Engine is designed to be virtually nonmalleable - with respect to key size. This is achieved herein - via hard-coding of numerical algorithms with respect to - the DEPTH = 4 security level (127 bit Mersenne prime). - - In meetings between the NSA and NeXT Software, Inc. in - 1995-1996, the notion of Security Engine emerged as a - means by which one could discourage disassembly of - FEE compilations, especially when such disassembly - has the sinister goal of modifying encryption depth. - - DO NOT EVEN THINK ABOUT READING THE SOURCE CODE - BELOW UNLESS YOU ARE EXPLICITLY AUTHORIZED TO DO SO - BY NeXT OR ITS DESIGNEE. - - c. 1996, NeXT Software, Inc. - All Rights Reserved. -*/ - -/* This engine requires no initialization. There is one - function to becalled externally, namely elliptic(). - */ - - - - - - - - - - - - - - - - - - - -/* - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 6 Aug 06 at NeXT - * 'a' argument to elliptic() and ell_even() is now a giant. - * 25 Jul 96 at NeXT - * Wrapped ENGINEmul() with gmersennemod(127,.) to guarantee no - * overflow in the hard-coded mul. - * Fixed sign calculation bug in ENGINEmul(). - * 24 Jul 96 at NeXT - * Made conditional on ENGINE_127_BITS. - * Made all functions except for elliptic() static. - * Renamed some giants function calls via #define. - * Deleted use of array of static pseudo-giants. - * Cosmetic changes for debuggability. - * 19 Jun 96 at NeXT - * Created. - */ - -#include "ckconfig.h" - -#if ENGINE_127_BITS -/* - * This file is obsolete as of 8 January 1997. - */ -#error Hey! New curveParam-dependent 127-bit elliptic() needed! -#warning Using NSA-approved 127-bit security engine... - -#include "NSGiantIntegers.h" - -#define D 65536 -#define DM 65535 - -/* - * Size of 127-bit giantstruct n[] array, in shorts. - */ -#define SHORTCOUNT (8 * 2) -#define BORROW_SIZE 0 - - -static void -ENGINEmul(giant a, giant b) { - int a0,a1,a2,a3,a4,a5,a6,a7, - b0,b1,b2,b3,b4,b5,b6,b7; - int asign, bsign; - int i, j, car; - unsigned int prod; - unsigned short mult; - - gmersennemod(127, a); - gmersennemod(127, b); - asign = a->sign; - bsign = b->sign; - - for(j = abs(asign); j < SHORTCOUNT; j++) a->n[j] = 0; - for(j = abs(bsign); j < SHORTCOUNT; j++) b->n[j] = 0; - a0 = a->n[0]; - a1 = a->n[1]; - a2 = a->n[2]; - a3 = a->n[3]; - a4 = a->n[4]; - a5 = a->n[5]; - a6 = a->n[6]; - a7 = a->n[7]; - b0 = b->n[0]; - b1 = b->n[1]; - b2 = b->n[2]; - b3 = b->n[3]; - b4 = b->n[4]; - b5 = b->n[5]; - b6 = b->n[6]; - b7 = b->n[7]; - for(j = 0; j < SHORTCOUNT; j++) b->n[j] = 0; - - i = 0; - mult = b0; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 1; - mult = b1; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 2; - mult = b2; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 3; - mult = b3; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 4; - mult = b4; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 5; - mult = b5; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 6; - mult = b6; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - - i = 7; - mult = b7; - car = 0; - - prod = a0 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a1 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a2 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a3 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a4 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a5 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a6 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - prod = a7 * mult + b->n[i] + car; - b->n[i++] = prod & DM; - car = prod/D; - - b->n[i] = car; - b->sign = abs(b->sign) + abs(a->sign); - for(j = (b->sign)-1; j >= 0; j--) { - if(b->n[j] != 0) { - break; - } - } - b->sign = j+1; - gmersennemod(127,b); -} - -static void -ell_even(giant x1, giant z1, giant x2, giant z2, giant a, int q) -{ - giant t1, t2, t3; - - t1 = borrowGiant(BORROW_SIZE); - t2 = borrowGiant(BORROW_SIZE); - t3 = borrowGiant(BORROW_SIZE); - - gtog(x1, t1); gsquare(t1); gmersennemod(q, t1); - gtog(z1, t2); gsquare(t2); gmersennemod(q, t2); - gtog(x1, t3); ENGINEmul(z1, t3); - gtog(t1, x2); subg(t2, x2); gsquare(x2); gmersennemod(q, x2); - gtog(a, z2); - ENGINEmul(t3, z2); - addg(t1, z2); addg(t2, z2); ENGINEmul(t3, z2); - gshiftleft(2, z2); - gmersennemod(q, z2); - - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); -} - -static void -ell_odd(giant x1, giant z1, giant x2, giant z2, giant xor, giant zor, int q) -{ - giant t1, t2, t3; - - t1 = borrowGiant(BORROW_SIZE); - t2 = borrowGiant(BORROW_SIZE); - t3 = borrowGiant(BORROW_SIZE); - - gtog(x1, t1); subg(z1, t1); - gtog(x2, t2); addg(z2, t2); - ENGINEmul(t1, t2); - gtog(x1, t1); addg(z1, t1); - gtog(x2, t3); subg(z2, t3); - ENGINEmul(t3, t1); - gtog(t2, x2); addg(t1, x2); - gsquare(x2); gmersennemod(q, x2); //? - gtog(t2, z2); subg(t1, z2); - gsquare(z2); gmersennemod(q, z2); //? - ENGINEmul(zor, x2); - ENGINEmul(xor, z2); - - returnGiant(t1); - returnGiant(t2); - returnGiant(t3); -} - -/* Elliptic multiply. - For given curve parameter a and given prime p = 2^q-1, - the point (xx,zz) becomes k * (xx,zz), in place. - */ -void -elliptic(giant xx, giant zz, giant k, giant a, int q) -{ - int len = bitlen(k), pos = len-2; - giant xs; - giant zs; - giant xorg; - giant zorg; - - if(scompg(1,k)) return; - if(scompg(2,k)) { - ell_even(xx, zz, xx, zz, a, q); - return; - } - - zs = borrowGiant(BORROW_SIZE); - xs = borrowGiant(BORROW_SIZE); - zorg = borrowGiant(BORROW_SIZE); - xorg = borrowGiant(BORROW_SIZE); - - gtog(xx, xorg); gtog(zz, zorg); - ell_even(xx, zz, xs, zs, a, q); - do{ - if(bitval(k, pos--)) { - ell_odd(xs, zs, xx, zz, xorg, zorg, q); - ell_even(xs, zs, xs, zs, a, q); - } else { - ell_odd(xx, zz, xs, zs, xorg, zorg, q); - ell_even(xx, zz, xx, zz, a, q); - } - } while(pos >=0); - - returnGiant(xs); - returnGiant(zs); - returnGiant(xorg); - returnGiant(zorg); -} - -#endif /* ENGINE_127_BITS */ diff --git a/OSX/include/security_cryptkit/falloc.c b/OSX/include/security_cryptkit/falloc.c deleted file mode 100644 index 8a41af7b..00000000 --- a/OSX/include/security_cryptkit/falloc.c +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * falloc.c - FEE malloc routines - * - * Revision History - * ---------------- - * 28 May 98 at Apple - * Added Mac-specific allocators from temp memory - * 20 Aug 96 at NeXT - * Created. - */ - -#include "platform.h" -#include "falloc.h" -#include - -/* watchpoint emulator */ -#define FALLOC_WATCH 0 -#if FALLOC_WATCH -#include -/* set these with debugger */ -void *mallocWatchAddrs; -void *freeWatchAddrs; -#endif - -/* if NULL, use our own */ -static mallocExternFcn *mallocExt = NULL; -static freeExternFcn *freeExt = NULL; -static reallocExternFcn *reallocExt = NULL; - -void fallocRegister(mallocExternFcn *mallocExtern, - freeExternFcn *freeExtern, - reallocExternFcn *reallocExtern) -{ - mallocExt = mallocExtern; - freeExt = freeExtern; - reallocExt = reallocExtern; -} - -/* - * All this can be optimized and tailored to specific platforms, of course... - */ - -void *fmalloc(unsigned size) -{ - void *rtn; - if(mallocExt != NULL) { - rtn = (mallocExt)(size); - } - else { - rtn = malloc(size); - } - #if FALLOC_WATCH - if(rtn == mallocWatchAddrs) { - printf("====fmalloc watchpoint (0x%x) hit\n", - (unsigned)mallocWatchAddrs); - } - #endif - return rtn; -} - -void *fmallocWithData(const void *origData, - unsigned origDataLen) -{ - void *rtn = fmalloc(origDataLen); - - bcopy(origData, rtn, origDataLen); - return rtn; -} - -void ffree(void *data) -{ - #if FALLOC_WATCH - if(data == freeWatchAddrs) { - printf("====ffree watchpoint (0x%x) hit\n", - (unsigned)freeWatchAddrs); - } - #endif - if(freeExt != NULL) { - (freeExt)(data); - } - else { - free(data); - } -} - -void *frealloc(void *oldPtr, unsigned newSize) -{ - #if FALLOC_WATCH - if(oldPtr == freeWatchAddrs) { - printf("====frealloc watchpoint (0x%x) hit\n", - (unsigned)freeWatchAddrs); - } - #endif - if(reallocExt != NULL) { - return (reallocExt)(oldPtr, newSize); - } - else { - return realloc(oldPtr, newSize); - } -} diff --git a/OSX/include/security_cryptkit/falloc.h b/OSX/include/security_cryptkit/falloc.h deleted file mode 100644 index dba207c5..00000000 --- a/OSX/include/security_cryptkit/falloc.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * falloc.h - FEE malloc routines - * - * Revision History - * ---------------- - * 20 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FALLOC_H_ -#define _CK_FALLOC_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Clients can *optionally* register external memory alloc/free functions here. - */ -typedef void *(mallocExternFcn)(unsigned size); -typedef void (freeExternFcn)(void *data); -typedef void *(reallocExternFcn)(void *oldData, unsigned newSize); -void fallocRegister(mallocExternFcn *mallocExtern, - freeExternFcn *freeExtern, - reallocExternFcn *reallocExtern); - - -void *fmalloc(unsigned size); /* general malloc */ -void *fmallocWithData(const void *origData, - unsigned origDataLen); /* malloc, copy existing data */ -void ffree(void *data); /* general free */ -void *frealloc(void *oldPtr, unsigned newSize); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_FALLOC_H_*/ diff --git a/OSX/include/security_cryptkit/feeCipherFile.c b/OSX/include/security_cryptkit/feeCipherFile.c deleted file mode 100644 index 9c79156d..00000000 --- a/OSX/include/security_cryptkit/feeCipherFile.c +++ /dev/null @@ -1,280 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeCipherFile.c - general cipherfile support - * - * Revision History - * ---------------- - * 05 Feb 97 at Apple - * Added CFE_FEED and CFE_FEEDExp types. - * 24 Oct 96 at NeXT - * Created. - */ - -#include "feeCipherFile.h" -#include "falloc.h" -#include "feeFEEDExp.h" -#include "feeFEED.h" -#include "feeDebug.h" -#include "CipherFileFEED.h" -#include "CipherFileDES.h" - - -/* - * Create a cipherfile of specified cipherFileEncrType. - */ -feeReturn createCipherFile(feePubKey sendPrivKey, - feePubKey recvPubKey, - cipherFileEncrType encrType, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - int doEnc64, // 1 ==> perform enc64 - unsigned userData, // for caller's convenience - unsigned char **cipherFileData, // RETURNED - unsigned *cipherFileDataLen) // RETURNED -{ - feeReturn frtn = FR_Success; - feeCipherFile cipherFile = NULL; - unsigned char *cipherData = NULL; - unsigned cipherDataLen; - - /* - * Dispatch to encrType-specific code. - */ - switch(encrType) { - case CFE_RandDES: - frtn = createRandDES(sendPrivKey, - recvPubKey, - plainText, - plainTextLen, - genSig, - userData, - &cipherFile); - break; - case CFE_PublicDES: - frtn = createPubDES(sendPrivKey, - recvPubKey, - plainText, - plainTextLen, - genSig, - userData, - &cipherFile); - break; - case CFE_FEED: - frtn = createFEED(sendPrivKey, - recvPubKey, - plainText, - plainTextLen, - genSig, - userData, - &cipherFile); - break; - case CFE_FEEDExp: - frtn = createFEEDExp(sendPrivKey, - recvPubKey, - plainText, - plainTextLen, - genSig, - userData, - &cipherFile); - break; - default: - frtn = FR_Unimplemented; - break; - } - - if(frtn) { - goto out; - } - - /* - * Common logic for all encrTypes - */ - - /* - * Get the cipherfile's raw data - */ - frtn = feeCFileDataRepresentation(cipherFile, - (const unsigned char **)&cipherData, - &cipherDataLen); - if(frtn) { - goto out; - } - - /* - * Optionally encode in 64-char ASCII - */ - if(doEnc64) { - *cipherFileData = enc64(cipherData, - cipherDataLen, - cipherFileDataLen); - ffree(cipherData); - if(*cipherFileData == NULL) { - frtn = FR_Internal; - ffree(cipherData); - goto out; - } - } - else { - *cipherFileData = cipherData; - *cipherFileDataLen = cipherDataLen; - } -out: - /* free stuff */ - if(cipherFile) { - feeCFileFree(cipherFile); - } - return frtn; -} - -/* - * Parse a cipherfile. - * - * sendPubKey only needed for cipherFileEncrType CFE_RandDES if signature - * is present. If sendPubKey is present, it will be used for signature - * validation rather than the embedded sender's public key. - */ -feeReturn parseCipherFile(feePubKey recvPrivKey, - feePubKey sendPubKey, - const unsigned char *cipherFileData, - unsigned cipherFileDataLen, - int doDec64, // 1 ==> perform dec64 - cipherFileEncrType *encrType, // RETURNED - unsigned char **plainText, // RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus, // RETURNED - unsigned *userData) // RETURNED -{ - feeReturn frtn; - unsigned char *cipherData = NULL; - unsigned cipherDataLen; - int freeCipherData = 0; - feeCipherFile cipherFile = NULL; - - *plainText = NULL; - *plainTextLen = 0; - - if(recvPrivKey == NULL) { // always required - frtn = FR_BadPubKey; - goto out; - } - - /* - * First, optional dec64() - */ - if(doDec64) { - cipherData = dec64(cipherFileData, - cipherFileDataLen, - &cipherDataLen); - if(cipherData == NULL) { - frtn = FR_BadEnc64; - goto out; - } - else { - freeCipherData = 1; - } - } - else { - cipherData = (unsigned char *)cipherFileData; - cipherDataLen = cipherFileDataLen; - } - - /* - * Cons up a feeCipherFile object. - */ - frtn = feeCFileNewFromDataRep(cipherData, - cipherDataLen, - &cipherFile); - if(frtn) { - goto out; - } - *encrType = feeCFileEncrType(cipherFile); - *userData = feeCFileUserData(cipherFile); - frtn = decryptCipherFile(cipherFile, - recvPrivKey, - sendPubKey, - plainText, - plainTextLen, - sigStatus); - -out: - /* free stuff */ - - if(cipherData && freeCipherData) { - ffree(cipherData); - } - if(cipherFile) { - feeCFileFree(cipherFile); - } - return frtn; -} - -/* - * Decrypt a feeCipherFile obtained via feeCFileNewFromDataRep(). - * recvPrivKey is required in all cases. If sendPubKey is present, - * sendPubKey - rather than the embedded sender's public key - will be - * used for signature validation. - */ -feeReturn decryptCipherFile(feeCipherFile cipherFile, - feePubKey recvPrivKey, // required - feePubKey sendPubKey, // optional, for signature - unsigned char **plainText, // malloc'd & RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus) // RETURNED -{ - cipherFileEncrType encrType = feeCFileEncrType(cipherFile); - feeReturn frtn; - - *plainText = NULL; - *plainTextLen = 0; - - /* - * Dispatch to encrType-specific code. - */ - switch(encrType) { - case CFE_RandDES: - frtn = decryptRandDES(cipherFile, - recvPrivKey, - sendPubKey, - plainText, - plainTextLen, - sigStatus); - break; - case CFE_PublicDES: - frtn = decryptPubDES(cipherFile, - recvPrivKey, - sendPubKey, - plainText, - plainTextLen, - sigStatus); - break; - case CFE_FEED: - frtn = decryptFEED(cipherFile, - recvPrivKey, - sendPubKey, - plainText, - plainTextLen, - sigStatus); - break; - case CFE_FEEDExp: - frtn = decryptFEEDExp(cipherFile, - recvPrivKey, - sendPubKey, - plainText, - plainTextLen, - sigStatus); - break; - default: - frtn = FR_Unimplemented; - break; - } - return frtn; -} diff --git a/OSX/include/security_cryptkit/feeCipherFile.h b/OSX/include/security_cryptkit/feeCipherFile.h deleted file mode 100644 index a46f3baf..00000000 --- a/OSX/include/security_cryptkit/feeCipherFile.h +++ /dev/null @@ -1,164 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeCipherFile.h - * - * Revision History - * ---------------- - * 24 Oct 96 at NeXT - * Created. - */ - -#ifndef _CK_FEECIPHERFILE_H_ -#define _CK_FEECIPHERFILE_H_ - -#if !defined(__MACH__) -#include -#include -#include -#include -#else -#include "ckconfig.h" -#include "feeTypes.h" -#include "feePublicKey.h" -#include "CipherFileTypes.h" -#endif - -#if CRYPTKIT_CIPHERFILE_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Opaque cipherfile object. - */ -typedef void *feeCipherFile; - -/* - * Alloc and return a new feeCipherFile object associated with the specified - * data. - */ -feeCipherFile feeCFileNewFromCipherText(cipherFileEncrType encrType, - const unsigned char *cipherText, - unsigned cipherTextLen, - const unsigned char *sendPubKeyData, - unsigned sendPubKeyDataLen, - const unsigned char *otherKeyData, - unsigned otherKeyDataDataLen, - const unsigned char *sigData, // optional; NULL means no signature - unsigned sigDataLen, // 0 if sigData is NULL - unsigned userData); // for caller's convenience - -/* - * Obtain the contents of a feeCipherFile as a byte stream. Caller must free - * the returned data. - */ -feeReturn feeCFileDataRepresentation(feeCipherFile cipherFile, - const unsigned char **dataRep, // RETURNED - unsigned *dataRepLen); // RETURNED - -/* - * Alloc and return a new feeCipherFile object, given a byte stream (originally - * obtained from feeCFDataRepresentation()). - */ -feeReturn feeCFileNewFromDataRep(const unsigned char *dataRep, - unsigned dataRepLen, - feeCipherFile *cipherFile); // RETURNED if sucessful - -/* - * Free a feeCipherFile object. - */ -void feeCFileFree(feeCipherFile cipherFile); - -/* - * Given a feeCipherFile object (typically obtained from - * feeCFileNewFromDataRep()), obtain its constituent parts. - * - * Data returned must be freed by caller. - * feeCFileSigData(), feeCFileSendPubKeyData, and feeCFileOtherKeyData() - * may return NULL, indicating component not present. - */ -cipherFileEncrType feeCFileEncrType(feeCipherFile cipherFile); -unsigned char *feeCFileCipherText(feeCipherFile cipherFile, - unsigned *cipherTextLen); // RETURNED -unsigned char *feeCFileSendPubKeyData(feeCipherFile cipherFile, - unsigned *sendPubKeyDataLen); // RETURNED -unsigned char *feeCFileOtherKeyData(feeCipherFile cipherFile, - unsigned *otherKeyDataLen); // RETURNED -unsigned char *feeCFileSigData(feeCipherFile cipherFile, - unsigned *sigDataLen); // RETURNED -unsigned feeCFileUserData(feeCipherFile cipherFile); - -/* - * High-level feeCipherFile support. - */ - -/* - * Obtain the data representation of a feeCipherFile given the specified - * plainText and cipherFileEncrType. - * Receiver's public key is required for all encrTypes; sender's private - * key is required for signature generation and also for encrType - * CFE_PublicDES and CFE_FEED. - */ -feeReturn createCipherFile(feePubKey sendPrivKey, - feePubKey recvPubKey, - cipherFileEncrType encrType, - const unsigned char *plainText, - unsigned plainTextLen, - int genSig, // 1 ==> generate signature - int doEnc64, // 1 ==> perform enc64 - unsigned userData, // for caller's convenience - unsigned char **cipherFileData, // RETURNED - unsigned *cipherFileDataLen); // RETURNED - -/* - * Parse and decrypt a cipherfile given its data representation. - * - * recvPrivKey is required in all cases. If sendPubKey is present, - * sendPubKey - rather than the embedded sender's public key - will be - * used for signature validation. - */ -feeReturn parseCipherFile(feePubKey recvPrivKey, // required - feePubKey sendPubKey, // optional, for signature - const unsigned char *cipherFileData, - unsigned cipherFileDataLen, - int doDec64, // 1 ==> perform dec64 - cipherFileEncrType *encrType, // RETURNED - unsigned char **plainText, // malloc'd & RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus, // RETURNED - unsigned *userData); // RETURNED - -/* - * Decrypt a feeCipherFile object obtained via feeCFileNewFromDataRep(). - * recvPrivKey is required in all cases. If sendPubKey is present, - * sendPubKey - rather than the embedded sender's public key - will be - * used for signature validation. - * - * Note: this function is used (in conjunction with feeCFileNewFromDataRep()) - * rather than the simpler parseCipherFile(), in case the caller needs - * access to CipherFile fields not returned in parseCipherFile(). For - * example, the caller might want to get the sender's public key data - * via feeCFileSendPubKeyData(). - */ -feeReturn decryptCipherFile(feeCipherFile cipherFile, - feePubKey recvPrivKey, // required - feePubKey sendPubKey, // optional, for signature - unsigned char **plainText, // malloc'd & RETURNED - unsigned *plainTextLen, // RETURNED - feeSigStatus *sigStatus); // RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_CIPHERFILE_ENABLE */ -#endif /*_CK_FEECIPHERFILE_H_*/ diff --git a/OSX/include/security_cryptkit/feeCipherFileAtom.c b/OSX/include/security_cryptkit/feeCipherFileAtom.c deleted file mode 100644 index 3576551d..00000000 --- a/OSX/include/security_cryptkit/feeCipherFileAtom.c +++ /dev/null @@ -1,400 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeCipherFile.c - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 05 Feb 97 at Apple - * Modified to use portable byte representation. - * 23 Oct 96 at NeXT - * Created. - */ - -#include "feeCipherFile.h" -#include "falloc.h" -#include "platform.h" -#include "feeDebug.h" -#include "byteRep.h" - -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ - -/* - * These must match constants of same name in CipherFileAtom.java. - */ -#define CFILE_MAGIC 0xfeecf111 -#define CFILE_VERSION 1 -#define CFILE_MIN_VERSION 1 - -/* - * Format of a feeCipherFile header. - * Offsets and lengths refer to locations of components in cFileInst.dataRep. - * This struct appears at the start of a feeCipherFile data representation. - */ -typedef struct { - unsigned magic; - unsigned version; - unsigned minVersion; - unsigned totalLength; // equals dataRepLen - cipherFileEncrType encrType; - unsigned cipherTextOffset; // offset of ciphertext - unsigned cipherTextLen; // in bytes - unsigned sendPubKeyDataOffset; // optional - unsigned sendPubKeyDataLen; - unsigned otherKeyDataOffset; // optional - unsigned otherKeyDataLen; - unsigned sigDataOffset; // optional - unsigned sigDataLen; // 0 means no signature - unsigned userData; -} cFileHeader; - -/* - * Private data, represented by a feeCipherFile handle. - */ -typedef struct { - cFileHeader header; - unsigned char *dataRep; // raw data - unsigned dataRepLen; -} cFileInst; - -static unsigned lengthOfByteRepCfileHdr(void); -static unsigned cfileHdrToByteRep(cFileHeader *hdr, - unsigned char *s); -static void byteRepToCfileHdr(const unsigned char *s, - cFileHeader *hdr); - - -/* - * alloc, free cFileInst - */ -static cFileInst *cFileInstAlloc() -{ - cFileInst *cfinst = (cFileInst *) fmalloc(sizeof(cFileInst)); - - bzero(cfinst, sizeof(cFileInst)); - return cfinst; -} - -static void cFileInstFree(cFileInst *cfinst) -{ - if(cfinst->dataRep) { - ffree(cfinst->dataRep); - } - ffree(cfinst); -} - -/* - * Alloc and return a new feeCipherFile object associated with the specified - * data. - */ -feeCipherFile feeCFileNewFromCipherText(cipherFileEncrType encrType, - const unsigned char *cipherText, - unsigned cipherTextLen, - const unsigned char *sendPubKeyData, // optional - unsigned sendPubKeyDataLen, // 0 if sendPubKeyData is NULL - const unsigned char *otherKeyData, // optional - unsigned otherKeyDataLen, // 0 if otherKeyData is NULL - const unsigned char *sigData, // optional; NULL means no signature - unsigned sigDataLen, // 0 if sigData is NULL - unsigned userData) // for caller's convenience -{ - cFileInst *cfinst; - cFileHeader *header; - unsigned char *data; - - if(cipherTextLen == 0) { - return NULL; - } - cfinst = cFileInstAlloc(); - header = &cfinst->header; - - /* - * Init the header. - */ - header->magic = CFILE_MAGIC; - header->version = CFILE_VERSION; - header->minVersion = CFILE_MIN_VERSION; - header->totalLength = lengthOfByteRepCfileHdr() + cipherTextLen + - sendPubKeyDataLen + otherKeyDataLen + - sigDataLen; - header->encrType = encrType; - header->cipherTextOffset = lengthOfByteRepCfileHdr(); - header->cipherTextLen = cipherTextLen; - header->sendPubKeyDataOffset = header->cipherTextOffset + - cipherTextLen; - header->sendPubKeyDataLen = sendPubKeyDataLen; - header->otherKeyDataOffset = header->sendPubKeyDataOffset + - sendPubKeyDataLen; - header->otherKeyDataLen = otherKeyDataLen; - header->sigDataOffset = header->otherKeyDataOffset + - otherKeyDataLen; - header->sigDataLen = sigDataLen; - header->userData = userData; - - /* - * Alloc a data representation, copy various components to it. - */ - cfinst->dataRepLen = header->totalLength; - data = cfinst->dataRep = (unsigned char*) fmalloc(cfinst->dataRepLen); - cfileHdrToByteRep(header, data); - - data = cfinst->dataRep + header->cipherTextOffset; - bcopy(cipherText, data, cipherTextLen); - if(sendPubKeyDataLen) { - data = cfinst->dataRep + header->sendPubKeyDataOffset; - bcopy(sendPubKeyData, data, sendPubKeyDataLen); - } - if(otherKeyDataLen) { - data = cfinst->dataRep + header->otherKeyDataOffset; - bcopy(otherKeyData, data, otherKeyDataLen); - } - if(sigDataLen) { - data = cfinst->dataRep + header->sigDataOffset; - bcopy(sigData, data, sigDataLen); - } - return (feeCipherFile)cfinst; -} - -/* - * Obtain the contents of a feeCipherFile as a byte stream. - */ -feeReturn feeCFileDataRepresentation(feeCipherFile cipherFile, - const unsigned char **dataRep, - unsigned *dataRepLen) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - if(cfinst->dataRepLen == 0) { - *dataRep = NULL; - *dataRepLen = 0; - return FR_BadCipherFile; - } - *dataRep = (unsigned char*) fmallocWithData(cfinst->dataRep, cfinst->dataRepLen); - *dataRepLen = cfinst->dataRepLen; - return FR_Success; -} - -/* - * Alloc and return a new feeCipherFile object, given a byte stream (originally - * obtained from feeCFDataRepresentation()). - */ -feeReturn feeCFileNewFromDataRep(const unsigned char *dataRep, - unsigned dataRepLen, - feeCipherFile *cipherFile) // RETURNED if sucessful -{ - cFileInst *cfinst = cFileInstAlloc(); - cFileHeader *header; - - if(dataRepLen < lengthOfByteRepCfileHdr()) { - dbgLog(("datRep too short\n")); - goto abort; - } - cfinst->dataRep = (unsigned char*) fmallocWithData(dataRep, dataRepLen); - cfinst->dataRepLen = dataRepLen; - header = &cfinst->header; - byteRepToCfileHdr(dataRep, header); - - /* - * As much consistency checking as we can manage here. - */ - if(header->magic != CFILE_MAGIC) { - dbgLog(("Bad cipherFile magic number\n")); - goto abort; - } - if(header->minVersion > CFILE_VERSION) { - dbgLog(("Incompatible cipherFile version\n")); - goto abort; - } - if(header->totalLength != dataRepLen) { - dbgLog(("Bad totalLength in cipherFile header\n")); - goto abort; - } - if(((header->cipherTextOffset + header->cipherTextLen) > - header->totalLength) || - ((header->sendPubKeyDataOffset + header->sendPubKeyDataLen) > - header->totalLength) || - ((header->otherKeyDataOffset + header->otherKeyDataLen) > - header->totalLength) || - ((header->sigDataOffset + header->sigDataLen) > - header->totalLength)) { - dbgLog(("Bad element lengths in cipherFile header\n")); - goto abort; - } - - /* - * OK, looks good. - */ - *cipherFile = (feeCipherFile)cfinst; - return FR_Success; -abort: - cFileInstFree(cfinst); - *cipherFile = NULL; - return FR_BadCipherFile; -} - -/* - * Free a feeCipherFile object. - */ -void feeCFileFree(feeCipherFile cipherFile) -{ - cFileInstFree((cFileInst *)cipherFile); -} - -/* - * Given a feeCipherFile object (typically obtained from - * feeCFileNewFromData()), obtain its constituent parts. - * - * Data returned must be freed by caller. - * feeCFileSigData() may return NULL, indicating no signature present. - */ -cipherFileEncrType feeCFileEncrType(feeCipherFile cipherFile) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - return cfinst->header.encrType; -} - -unsigned char *feeCFileCipherText(feeCipherFile cipherFile, - unsigned *cipherTextLen) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - if(cfinst->header.cipherTextLen) { - *cipherTextLen = cfinst->header.cipherTextLen; - return (unsigned char*) fmallocWithData(cfinst->dataRep + - cfinst->header.cipherTextOffset, *cipherTextLen); - } - else { - dbgLog(("feeCFileCipherText: no cipherText\n")); - *cipherTextLen = 0; - return NULL; - } -} - -unsigned char *feeCFileSendPubKeyData(feeCipherFile cipherFile, - unsigned *sendPubKeyDataLen) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - if(cfinst->header.sendPubKeyDataLen) { - *sendPubKeyDataLen = cfinst->header.sendPubKeyDataLen; - return (unsigned char*) fmallocWithData(cfinst->dataRep + - cfinst->header.sendPubKeyDataOffset, - *sendPubKeyDataLen); - } - else { - *sendPubKeyDataLen = 0; - return NULL; - } -} - -unsigned char *feeCFileOtherKeyData(feeCipherFile cipherFile, - unsigned *otherKeyDataLen) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - if(cfinst->header.otherKeyDataLen) { - *otherKeyDataLen = cfinst->header.otherKeyDataLen; - return (unsigned char*) fmallocWithData(cfinst->dataRep + - cfinst->header.otherKeyDataOffset, *otherKeyDataLen); - } - else { - *otherKeyDataLen = 0; - return NULL; - } -} - -unsigned char *feeCFileSigData(feeCipherFile cipherFile, - unsigned *sigDataLen) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - if(cfinst->header.sigDataLen) { - *sigDataLen = cfinst->header.sigDataLen; - return (unsigned char*) fmallocWithData(cfinst->dataRep + - cfinst->header.sigDataOffset, *sigDataLen); - } - else { - /* - * Not an error - */ - *sigDataLen = 0; - return NULL; - } -} - -unsigned feeCFileUserData(feeCipherFile cipherFile) -{ - cFileInst *cfinst = (cFileInst *)cipherFile; - - return cfinst->header.userData; -} - -/* - * Convert between cFileHeader and portable byte representation. - */ - -/* - * Return size of byte rep of cFileHeader. We just happen to know that - * this is the same size as the header.... - */ -static unsigned lengthOfByteRepCfileHdr(void) -{ - return sizeof(cFileHeader); -} - -static unsigned cfileHdrToByteRep(cFileHeader *hdr, - unsigned char *s) -{ - s += intToByteRep(hdr->magic, s); - s += intToByteRep(hdr->version, s); - s += intToByteRep(hdr->minVersion, s); - s += intToByteRep(hdr->totalLength, s); - s += intToByteRep(hdr->encrType, s); - s += intToByteRep(hdr->cipherTextOffset, s); - s += intToByteRep(hdr->cipherTextLen, s); - s += intToByteRep(hdr->sendPubKeyDataOffset, s); - s += intToByteRep(hdr->sendPubKeyDataLen, s); - s += intToByteRep(hdr->otherKeyDataOffset, s); - s += intToByteRep(hdr->otherKeyDataLen, s); - s += intToByteRep(hdr->sigDataOffset, s); - s += intToByteRep(hdr->sigDataLen, s); - s += intToByteRep(hdr->userData, s); - return sizeof(cFileHeader); -} - -#define DEC_INT(n, b) \ - n = byteRepToInt(b); \ - b += sizeof(int); - -static void byteRepToCfileHdr(const unsigned char *s, - cFileHeader *hdr) -{ - DEC_INT(hdr->magic, s); - DEC_INT(hdr->version, s); - DEC_INT(hdr->minVersion, s); - DEC_INT(hdr->totalLength, s); -// DEC_INT(hdr->encrType, s); - hdr->encrType = (cipherFileEncrType) byteRepToInt(s); - s += sizeof(int); - DEC_INT(hdr->cipherTextOffset, s); - DEC_INT(hdr->cipherTextLen, s); - DEC_INT(hdr->sendPubKeyDataOffset, s); - DEC_INT(hdr->sendPubKeyDataLen, s); - DEC_INT(hdr->otherKeyDataOffset, s); - DEC_INT(hdr->otherKeyDataLen, s); - DEC_INT(hdr->sigDataOffset, s); - DEC_INT(hdr->sigDataLen, s); - DEC_INT(hdr->userData, s); -} diff --git a/OSX/include/security_cryptkit/feeDES.c b/OSX/include/security_cryptkit/feeDES.c deleted file mode 100644 index 57cc150a..00000000 --- a/OSX/include/security_cryptkit/feeDES.c +++ /dev/null @@ -1,529 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeDES.c - generic, portable DES encryption object - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 05 Jan 98 at Apple - * Avoid a bcopy() on encrypt/decrypt of each block - * 31 Mar 97 at Apple - * New per-instance API for DES.c - * 26 Aug 96 at NeXT - * Created. - */ - -#include "ckconfig.h" - -#if CRYPTKIT_SYMMETRIC_ENABLE - -#include "feeDES.h" -#include "feeTypes.h" -#include "ckDES.h" -#include "falloc.h" -#include "feeDebug.h" -#include "feeFunctions.h" -#include "platform.h" -#include - -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ - -typedef struct { - int blockMode; /* default = 0 */ - unsigned char lastBlock[DES_BLOCK_SIZE_BYTES]; /* for CBC */ - struct _desInst dinst; -} fdesInst; - -static void feeDESInit(desInst dinst) -{ - desinit(dinst, DES_MODE_STD); // detects redundant calls -} - -/* - * Alloc and init a feeDES object with specified initial state. - * State must be at least 8 bytes; only 8 bytes are used, ignoring - * MSB of each bytes. - */ -feeDES feeDESNewWithState(const unsigned char *state, - unsigned stateLen) -{ - fdesInst *fdinst; - - if(stateLen < FEE_DES_MIN_STATE_SIZE) { - return NULL; - } - fdinst = (fdesInst*) fmalloc(sizeof(fdesInst)); - bzero(fdinst, sizeof(fdesInst)); - feeDESInit(&fdinst->dinst); - feeDESSetState((feeDES)fdinst, state, stateLen); - return fdinst; -} - -void feeDESFree(feeDES des) -{ - memset(des, 0, sizeof(fdesInst)); - ffree(des); -} - -/* - * Set new initial state. - */ -feeReturn feeDESSetState(feeDES des, - const unsigned char *state, - unsigned stateLen) -{ - fdesInst *fdinst = (fdesInst*) des; - char Key[DES_KEY_SIZE_BYTES_EXTERNAL]; - // 'key' causes problems with - // some weird Unix header - unsigned byte; - - if(stateLen < (DES_KEY_SIZE_BYTES_EXTERNAL)) { - return FR_IllegalArg; - } - bzero(fdinst->lastBlock, DES_BLOCK_SIZE_BYTES); - bcopy(state, Key, DES_KEY_SIZE_BYTES_EXTERNAL); - - /* - * Set up parity bits - */ - for(byte=0; bytedinst, Key); - return FR_Success; -} - -void feeDESSetBlockMode(feeDES des) -{ - fdesInst *fdinst = (fdesInst*) des; - - fdinst->blockMode = 1; -} - -void feeDESSetChainMode(feeDES des) -{ - fdesInst *fdinst = (fdesInst*) des; - - fdinst->blockMode = 0; -} - -unsigned feeDESPlainBlockSize(feeDES des) -{ - return DES_BLOCK_SIZE_BYTES; -} - -unsigned feeDESCipherBlockSize(feeDES des) -{ - return DES_BLOCK_SIZE_BYTES; -} - -unsigned feeDESCipherBufSize(feeDES des) -{ - /* - * Normally DES_BLOCK_SIZE, two blocks for finalBlock - */ - return 2 * DES_BLOCK_SIZE_BYTES; -} - -/* - - * Return the size of ciphertext to hold specified size of plaintext. - - */ - -unsigned feeDESCipherTextSize(feeDES des, unsigned plainTextSize) - -{ - - unsigned blocks = (plainTextSize + DES_BLOCK_SIZE_BYTES - 1) / - DES_BLOCK_SIZE_BYTES; - - if((plainTextSize % DES_BLOCK_SIZE_BYTES) == 0) { - /* - * One more block for resid count - */ - blocks++; - } - - return blocks * DES_BLOCK_SIZE_BYTES; - -} - - -/* - * Key size in bits. - */ -unsigned feeDESKeySize(feeDES des) -{ - return DES_KEY_SIZE_BITS; -} - -/* - * Encrypt a block or less of data. Caller malloc's cipherText. - */ -feeReturn feeDESEncryptBlock(feeDES des, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // RETURNED - int finalBlock) -{ - fdesInst *fdinst = (fdesInst*) des; - feeReturn frtn = FR_Success; - unsigned cipherLen; - - if(plainTextLen > DES_BLOCK_SIZE_BYTES) { - return FR_IllegalArg; - } - if(plainTextLen) { - /* - * We're called with plainTextLen = 0 and finalBlock - * recursively to clean up last block. - */ - bcopy(plainText, cipherText, plainTextLen); - } - if(plainTextLen < DES_BLOCK_SIZE_BYTES) { - if(!finalBlock) { - /* - * odd-size block only legal last time thru - */ - return FR_IllegalArg; - } - - /* - * Last block, final byte = residual length. - */ - cipherText[DES_BLOCK_SIZE_BYTES - 1] = plainTextLen; - } - - if(!fdinst->blockMode) { - /* - * CBC mode; chain in last cipher word - */ - unsigned char *cp = cipherText; - unsigned char *cp1 = fdinst->lastBlock; - int i; - - for(i=0; idinst, (char *)cipherText); /* Encrypt block */ - if(!fdinst->blockMode){ - /* - * Save outgoing ciphertext for chain - */ - bcopy(cipherText, fdinst->lastBlock, DES_BLOCK_SIZE_BYTES); - } - cipherLen = DES_BLOCK_SIZE_BYTES; - - if(finalBlock) { - if(plainTextLen == DES_BLOCK_SIZE_BYTES) { - /* - * Special case: finalBlock true, plainTextLen == blockSize. - * In this case we generate one more block of ciphertext, - * with a resid length of zero. - */ - unsigned moreCipher; // additional cipherLen - - frtn = feeDESEncryptBlock(des, - NULL, // plainText not used - 0, // resid - cipherText + DES_BLOCK_SIZE_BYTES, // append... - &moreCipher, - 1); - if(frtn == FR_Success) { - cipherLen += moreCipher; - } - - } - if(plainTextLen != 0) { - /* - * Reset internal state in prep for next encrypt/decrypt. - * Note we avoid this in the recursive call (plainTextLen = 0). - */ - bzero(fdinst->lastBlock, DES_BLOCK_SIZE_BYTES); - } - } - - if(frtn == FR_Success) { - *cipherTextLen = cipherLen; - } - return frtn; -} - -/* - * Decrypt a block of data. Caller malloc's plainText. Always - * generates DES_BLOCK_SIZE_BYTES bytes or less of plainText. - */ -feeReturn feeDESDecryptBlock(feeDES des, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // RETURNED - int finalBlock) -{ - fdesInst *fdinst = (fdesInst*) des; - unsigned char work[DES_BLOCK_SIZE_BYTES]; - unsigned char ivtmp[DES_BLOCK_SIZE_BYTES]; - - if(cipherTextLen != DES_BLOCK_SIZE_BYTES) { - /* - * We always generate ciphertext in multiples of block size. - */ - return FR_IllegalArg; - } - - bcopy(cipherText, work, DES_BLOCK_SIZE_BYTES); - if(!fdinst->blockMode && !finalBlock) { - /* - * Save incoming ciphertext for chain - */ - bcopy(cipherText, ivtmp, DES_BLOCK_SIZE_BYTES); - } - dedes(&fdinst->dinst, (char *)work); - if(!fdinst->blockMode){ - /* - * Unchain block using previous block's ciphertext; - * save current ciphertext for next - */ - char *cp = (char *)work; - char *cp1 = (char*)fdinst->lastBlock; - int i; - - for(i=0; ilastBlock, DES_BLOCK_SIZE_BYTES); - } - } - if(finalBlock) { - /* - * deal with residual block; its size is in last byte of - * work[] - */ - unsigned resid = work[DES_BLOCK_SIZE_BYTES-1]; - - if(resid > (DES_BLOCK_SIZE_BYTES-1)) { - return FR_BadCipherText; - } - if(resid > 0) { - bcopy(work, plainText, resid); - } - *plainTextLen = resid; - - /* - * Reset internal state in prep for next encrypt/decrypt. - */ - bzero(fdinst->lastBlock, DES_BLOCK_SIZE_BYTES); - } - else { - bcopy(work, plainText, DES_BLOCK_SIZE_BYTES); - *plainTextLen = DES_BLOCK_SIZE_BYTES; - } - return FR_Success; -} - -/* - * Convenience routines to encrypt & decrypt multi-block data. - */ -feeReturn feeDESEncrypt(feeDES des, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char **cipherText, // malloc'd and RETURNED - unsigned *cipherTextLen) // RETURNED -{ - const unsigned char *ptext; // per block - unsigned ptextLen; // total to go - unsigned thisPtextLen; // per block - unsigned ctextLen; // per block - unsigned char *ctextResult; // to return - unsigned char *ctextPtr; - unsigned ctextLenTotal; // running total - feeReturn frtn; - int finalBlock; - unsigned ctextMallocd; - - if(plainTextLen == 0) { - dbgLog(("feeDESDecrypt: NULL plainText\n")); - return FR_IllegalArg; - } - - ptext = plainText; - ptextLen = plainTextLen; - ctextMallocd = feeDESCipherTextSize(des, plainTextLen); - ctextResult = (unsigned char*) fmalloc(ctextMallocd); - ctextPtr = ctextResult; - ctextLenTotal = 0; - - while(1) { - if(ptextLen <= DES_BLOCK_SIZE_BYTES) { - finalBlock = 1; - thisPtextLen = ptextLen; - } - else { - finalBlock = 0; - thisPtextLen = DES_BLOCK_SIZE_BYTES; - } - frtn = feeDESEncryptBlock(des, - ptext, - thisPtextLen, - ctextPtr, - &ctextLen, - finalBlock); - if(frtn) { - dbgLog(("feeDESEncrypt: encrypt error: %s\n", - feeReturnString(frtn))); - break; - } - if(ctextLen == 0) { - dbgLog(("feeDESEncrypt: null ciphertext\n")); - frtn = FR_Internal; - break; - } - ctextLenTotal += ctextLen; - if(ctextLenTotal > (plainTextLen + DES_BLOCK_SIZE_BYTES)) { - dbgLog(("feeDESEncrypt: ciphertext overflow\n")); - frtn = FR_Internal; - break; - } - if(finalBlock) { - break; - } - ctextPtr += ctextLen; - ptext += thisPtextLen; - ptextLen -= thisPtextLen; - } - if(frtn) { - ffree(ctextResult); - *cipherText = NULL; - *cipherTextLen = 0; - } - else { - #if FEE_DEBUG - if(ctextLenTotal != ctextMallocd) { - dbgLog(("feeDESEncrypt: ctextLen error\n")); - } - #endif /* FEE_DEBUG */ - *cipherText = ctextResult; - *cipherTextLen = ctextLenTotal; - } - return frtn; - -} - -feeReturn feeDESDecrypt(feeDES des, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char **plainText, // malloc'd and RETURNED - unsigned *plainTextLen) // RETURNED -{ - const unsigned char *ctext; - unsigned ctextLen; // total to go - unsigned ptextLen; // per block - unsigned char *ptextResult; // to return - unsigned char *ptextPtr; - unsigned ptextLenTotal; // running total - feeReturn frtn = FR_Success; - int finalBlock; - - if(cipherTextLen % DES_BLOCK_SIZE_BYTES) { - dbgLog(("feeDESDecrypt: unaligned cipherText\n")); - return FR_BadCipherText; - } - if(cipherTextLen == 0) { - dbgLog(("feeDESDecrypt: NULL cipherText\n")); - return FR_BadCipherText; - } - - ctext = cipherText; - ctextLen = cipherTextLen; - - /* - * Plaintext length always <= cipherTextLen - */ - ptextResult = (unsigned char*) fmalloc(cipherTextLen); - ptextPtr = ptextResult; - ptextLenTotal = 0; - - while(ctextLen) { - if(ctextLen == DES_BLOCK_SIZE_BYTES) { - finalBlock = 1; - } - else { - finalBlock = 0; - } - frtn = feeDESDecryptBlock(des, - ctext, - DES_BLOCK_SIZE_BYTES, - ptextPtr, - &ptextLen, - finalBlock); - if(frtn) { - dbgLog(("feeDESDecrypt decrypt: %s\n", - feeReturnString(frtn))); - break; - } - if(ptextLen == 0) { - /* - * Normal termination case for - * plainTextLen % DES_BLOCK_SIZE_BYTES == 0 - */ - if(!finalBlock) { - dbgLog(("feeDESDecrypt: decrypt sync" - " error!\n")); - frtn = FR_BadCipherText; - break; - } - else { - break; - } - } - else { - ptextPtr += ptextLen; - ptextLenTotal += ptextLen; - } - ctext += DES_BLOCK_SIZE_BYTES; - ctextLen -= DES_BLOCK_SIZE_BYTES; - } - - if(frtn) { - ffree(ptextResult); - *plainText = NULL; - *plainTextLen = 0; - } - else { - *plainText = ptextResult; - *plainTextLen = ptextLenTotal; - } - return frtn; -} - -#endif /* CRYPTKIT_SYMMETRIC_ENABLE */ diff --git a/OSX/include/security_cryptkit/feeDES.h b/OSX/include/security_cryptkit/feeDES.h deleted file mode 100644 index 07a8da9c..00000000 --- a/OSX/include/security_cryptkit/feeDES.h +++ /dev/null @@ -1,141 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeDES.h - generic, portable DES encryption object - * - * Revision History - * ---------------- - * 26 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEDES_H_ -#define _CK_FEEDES_H_ - -#if !defined(__MACH__) -#include -#include -#else -#include -#include -#endif - -#if CRYPTKIT_SYMMETRIC_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - -#define FEE_DES_MIN_STATE_SIZE 8 - -/* - * Opaque object handle. - */ -typedef void *feeDES; - -/* - * Alloc and init a feeDES object with specified initial state. - * State must be at least 8 bytes; only 8 bytes are used, ignoring - * MSB of each bytes. - */ -feeDES feeDESNewWithState(const unsigned char *state, - unsigned stateLen); - -void feeDESFree(feeDES des); - -/* - * Set new initial state. - */ -feeReturn feeDESSetState(feeDES des, - const unsigned char *state, - unsigned stateLen); - -/* - * Set block or chain (CBC) mode. CBC is default. - */ -void feeDESSetBlockMode(feeDES des); -void feeDESSetChainMode(feeDES des); - -/* - * Plaintext block size. - */ -unsigned feeDESPlainBlockSize(feeDES des); - -/* - * Ciphertext block size used for decryption. - */ -unsigned feeDESCipherBlockSize(feeDES des); - -/* - * Required size of buffer for ciphertext, upon encrypting one - * block of plaintext. - */ -unsigned feeDESCipherBufSize(feeDES des); - -/* - - * Return the size of ciphertext to hold specified size of plaintext. - - */ - -unsigned feeDESCipherTextSize(feeDES des, unsigned plainTextSize); - - -/* - * Key size in bits. - */ -unsigned feeDESKeySize(feeDES des); - -/* - * Encrypt a block or less of data. Caller malloc's cipherText. Generates - * up to (2 * feeDESBlockSize) bytes of cipherText. If plainTextLen is - * less than feeDESBlockSize, finalBlock must be true. - */ -feeReturn feeDESEncryptBlock(feeDES des, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // RETURNED - int finalBlock); - -/* - * Decrypt (exactly) a block of data. Caller malloc's plainText. Always - * generates feeDESBlockSize bytes of plainText, unless 'finalBlock' is - * non-zero (in which case feeDESBlockSize or less bytes of plainText are - * generated). - */ -feeReturn feeDESDecryptBlock(feeDES des, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // RETURNED - int finalBlock); - -/* - * Convenience routines to encrypt & decrypt multi-block data. - */ -feeReturn feeDESEncrypt(feeDES des, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char **cipherText, // malloc'd and RETURNED - unsigned *cipherTextLen); // RETURNED - -feeReturn feeDESDecrypt(feeDES des, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char **plainText, // malloc'd and RETURNED - unsigned *plainTextLen); // RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_SYMMETRIC_ENABLE */ -#endif /*_CK_FEEDES_H_*/ diff --git a/OSX/include/security_cryptkit/feeDebug.h b/OSX/include/security_cryptkit/feeDebug.h deleted file mode 100644 index 878e3c77..00000000 --- a/OSX/include/security_cryptkit/feeDebug.h +++ /dev/null @@ -1,194 +0,0 @@ -/* - File: feeDebug.h - - Contains: Debug macros. - - - Copyright: Copyright (c) 1998,2011,2014 Apple Inc. - All rights reserved. - - Change History (most recent first): - - <9> 10/06/98 ap Changed to compile with C++. - - To Do: -*/ - -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - */ - -#ifndef _CK_FEEDEBUG_H_ -#define _CK_FEEDEBUG_H_ - -#include "giantIntegers.h" -#include "elliptic.h" -#include "curveParams.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef NDEBUG -#define FEE_DEBUG 0 -#else -#define FEE_DEBUG 1 -#endif - -/* - * In utilities.c... - */ -extern void printGiant(const giant x); -extern void printGiantHex(const giant x); -extern void printGiantExp(const giant x); -extern void printKey(const key k); -extern void printCurveParams(const curveParams *p); - -#if FEE_DEBUG - -#define dbgLog(x) printf x - - -#else /* FEE_DEBUG */ - -#define dbgLog(x) - -#endif /* FEE_DEBUG */ - -/* - * Profiling. - */ -#define FEE_PROFILE 0 /* general purpose profile */ -#define ELL_PROFILE 0 /* ell_even/ell_odd only */ - -#if (FEE_PROFILE || ELL_PROFILE) -#include -#endif /* (FEE_PROFILE || ELL_PROFILE) */ - -/* - * Place this macro after the last local and before any code in a routine - * to profile. - */ -#define CPROF_START \ - struct tsval _profStartTime; \ - struct tsval _profEndTime; \ - kern_timestamp(&_profStartTime); - -/* - * This one goes at the end of the routine, just before the (only) return. - * There must be a static accumulator (an unsigned int) on a per-routine basis. - */ -#define CPROF_END(accum) \ - kern_timestamp(&_profEndTime); \ - accum += (_profEndTime.low_val - _profStartTime.low_val); - -/* - * Increment a profiling counter. - */ -#define CPROF_INCR(ctr) ctr++ - -#if FEE_PROFILE - -#define PROF_START CPROF_START -#define PROF_END(a) CPROF_END(a) -#define PROF_INCR(ctr) CPROF_INCR(ctr) - -/* - * As of 14 Apr 1998, we no longer time mulg or gsquare calls with this - * mechanism; the time overhead is the same magnitude as the mulg. Instead - * we'll just count the mulgs and gsquares. - */ -#define PROF_TIME_MULGS 0 - - -/* - * Fundamental ops - */ -extern unsigned ellAddTime; -extern unsigned whichCurveTime; -extern unsigned ellipticTime; -extern unsigned sigCompTime; - -/* - * low-level primitives - */ -extern unsigned numerDoubleTime; -extern unsigned numerPlusTime; -extern unsigned numerTimesTime; -extern unsigned denomDoubleTime; -extern unsigned denomTimesTime; -extern unsigned powerModTime; -extern unsigned modgTime; -extern unsigned binvauxTime; - -/* - * Counters for calculating microseconds per {mulg, feemod, ...} - */ -extern unsigned numMulg; -extern unsigned numFeemod; -extern unsigned numGsquare; -extern unsigned numBorrows; - -extern void clearProfile(); - -#else /* FEE_PROFILE */ -#define PROF_START -#define PROF_END(a) -#define PROF_INCR(ctr) -#endif /* FEE_PROFILE */ - -#if ELL_PROFILE -extern unsigned ellOddTime; -extern unsigned ellEvenTime; -extern unsigned numEllOdds; -extern unsigned numEllEvens; -extern void clearEllProfile(); - -#define EPROF_START CPROF_START -#define EPROF_END(a) CPROF_END(a) -#define EPROF_INCR(ctr) CPROF_INCR(ctr) - -#else /* ELL_PROFILE */ -#define EPROF_START -#define EPROF_END(a) -#define EPROF_INCR(ctr) -#endif /* ELL_PROFILE */ - -/* - * NULL gets defined externally if FEE_DEBUG is true.. - */ -#if !FEE_DEBUG -#ifndef NULL -#define NULL ((void *)0) -#endif /* NULL */ -#endif /* !FEE_DEBUG */ - -#if FEE_DEBUG - -#include "platform.h" - -#define CKASSERT(expression) \ - ((expression) ? (void)0 : \ - (printf ("Assertion failed: " #expression \ - ", file " __FILE__ ", line %d.\n", __LINE__), \ - CKRaise("Assertion Failure"))) - -#else /* FEE_DEBUG */ - -#define CKASSERT(expression) - -#endif /* FEE_DEBUG */ - -#ifdef __cplusplus -} -#endif - -#endif /* _CK_FEEDEBUG_H_ */ diff --git a/OSX/include/security_cryptkit/feeDigitalSignature.c b/OSX/include/security_cryptkit/feeDigitalSignature.c deleted file mode 100644 index 77851ade..00000000 --- a/OSX/include/security_cryptkit/feeDigitalSignature.c +++ /dev/null @@ -1,674 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeDigitalSignature.c - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 9 Sep 98 at NeXT - * Major changes to use projective elliptic algebra for - * Weierstrass curves. - * 15 Jan 97 at NeXT - * FEE_SIG_VERSION = 3 (removed code for compatibilty with all older - * versions). - * Was modg(), is curveOrderJustify() - * Use plus curve for ellipic algebra per IEEE standards - * 22 Aug 96 at NeXT - * Ported guts of Blaine Garst's NSFEEDigitalSignature.m to C. - */ - -#include "ckconfig.h" -#include "feeTypes.h" -#include "feePublicKey.h" -#include "feePublicKeyPrivate.h" -#include "feeDigitalSignature.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "feeRandom.h" -#include "curveParams.h" -#include "falloc.h" -#include "ckutilities.h" -#include "feeDebug.h" -#include "platform.h" -#include "byteRep.h" -#include "feeECDSA.h" -#if CRYPTKIT_DER_ENABLE -#include "CryptKitDER.h" -#endif - -#include -#include "ellipticProj.h" - -#define SIG_DEBUG 0 -#if SIG_DEBUG -int sigDebug=1; // tweakable at runtime via debugger -#endif // SIG_DEBUG - -#define SIG_CURVE DEFAULT_CURVE - -/* - * true : justify randGiant to [2, x1OrderPlus-2] - * false : no truncate or mod of randGiant - */ -#define RAND_JUST_X1_ORDER_PLUS 1 - -#define FEE_SIG_VERSION 4 -#define FEE_SIG_VERSION_MIN 4 - -#ifndef max -#define max(a,b) ((a)>(b)? (a) : (b)) -#endif // max - -typedef struct { - giant PmX; // m 'o' P1; m = random - #if CRYPTKIT_ELL_PROJ_ENABLE - giant PmY; // y-coord of m 'o' P1 if we're - // using projective coords - #endif /* CRYPTKIT_ELL_PROJ_ENABLE */ - - giant u; - giant randGiant; // random m as giant - only known - // when signing -} sigInst; - -static sigInst *sinstAlloc() -{ - sigInst *sinst = (sigInst*) fmalloc(sizeof(sigInst)); - - bzero(sinst, sizeof(sigInst)); - return sinst; -} - -/* - * Create new feeSig object, including a random large integer 'randGiant' for - * possible use in salting a feeHash object, and 'PmX', equal to - * randGiant 'o' P1. Note that this is not called when *verifying* a - * signature, only when signing. - */ -feeSig feeSigNewWithKey( - feePubKey pubKey, - feeRandFcn randFcn, /* optional */ - void *randRef) -{ - sigInst *sinst = sinstAlloc(); - feeRand frand; - unsigned char *randBytes; - unsigned randBytesLen; - curveParams *cp; - - if(pubKey == NULL) { - return NULL; - } - cp = feePubKeyCurveParams(pubKey); - if(cp == NULL) { - return NULL; - } - - /* - * Generate random m, a little larger than key size, save as randGiant - */ - randBytesLen = (feePubKeyBitsize(pubKey) / 8) + 1 + 8; // +8bytes (64bits) to reduce the biais when with reduction mod prime. Per FIPS186-4 - "Using Extra Random Bits" - randBytes = (unsigned char*) fmalloc(randBytesLen); - if(randFcn) { - randFcn(randRef, randBytes, randBytesLen); - } - else { - frand = feeRandAlloc(); - feeRandBytes(frand, randBytes, randBytesLen); - feeRandFree(frand); - } - sinst->randGiant = giant_with_data(randBytes, randBytesLen); - memset(randBytes, 0, randBytesLen); - ffree(randBytes); - - #if FEE_DEBUG - if(isZero(sinst->randGiant)) { - printf("feeSigNewWithKey: randGiant = 0!\n"); - } - #endif // FEE_DEBUG - - /* - * Justify randGiant to be in [2, x1OrderPlus] - */ - x1OrderPlusJustify(sinst->randGiant, cp); - - /* PmX := randGiant 'o' P1 */ - sinst->PmX = newGiant(cp->maxDigits); - - #if CRYPTKIT_ELL_PROJ_ENABLE - - if(cp->curveType == FCT_Weierstrass) { - - pointProjStruct pt0; - - sinst->PmY = newGiant(cp->maxDigits); - - /* cook up pt0 as P1 */ - pt0.x = sinst->PmX; - pt0.y = sinst->PmY; - pt0.z = borrowGiant(cp->maxDigits); - gtog(cp->x1Plus, pt0.x); - gtog(cp->y1Plus, pt0.y); - int_to_giant(1, pt0.z); - - /* pt0 := P1 'o' randGiant */ - ellMulProjSimple(&pt0, sinst->randGiant, cp); - - returnGiant(pt0.z); - } - else { - if(SIG_CURVE == CURVE_PLUS) { - gtog(cp->x1Plus, sinst->PmX); - } - else { - gtog(cp->x1Minus, sinst->PmX); - } - elliptic_simple(sinst->PmX, sinst->randGiant, cp); - } - #else /* CRYPTKIT_ELL_PROJ_ENABLE */ - - if(SIG_CURVE == CURVE_PLUS) { - gtog(cp->x1Plus, sinst->PmX); - } - else { - gtog(cp->x1Minus, sinst->PmX); - } - elliptic_simple(sinst->PmX, sinst->randGiant, cp); - - #endif /* CRYPTKIT_ELL_PROJ_ENABLE */ - - return sinst; -} - -void feeSigFree(feeSig sig) -{ - sigInst *sinst = (sigInst*) sig; - - if(sinst->PmX) { - clearGiant(sinst->PmX); - freeGiant(sinst->PmX); - } - #if CRYPTKIT_ELL_PROJ_ENABLE - if(sinst->PmY) { - clearGiant(sinst->PmY); - freeGiant(sinst->PmY); - } - #endif /* CRYPTKIT_ELL_PROJ_ENABLE */ - if(sinst->u) { - clearGiant(sinst->u); - freeGiant(sinst->u); - } - if(sinst->randGiant) { - clearGiant(sinst->randGiant); - freeGiant(sinst->randGiant); - } - ffree(sinst); -} - -/* - * Obtain Pm after feeSigNewWithKey() or feeSigParse() - */ -unsigned char *feeSigPm(feeSig sig, - unsigned *PmLen) -{ - sigInst *sinst = (sigInst*) sig; - unsigned char *Pm; - - if(sinst->PmX == NULL) { - dbgLog(("feeSigPm: no PmX!\n")); - return NULL; - } - else { - Pm = mem_from_giant(sinst->PmX, PmLen); - #if SIG_DEBUG - if(sigDebug) - { - int i; - - printf("Pm : "); printGiant(sinst->PmX); - printf("PmData: "); - for(i=0; i<*PmLen; i++) { - printf("%x:", Pm[i]); - } - printf("\n"); - } - #endif // SIG_DEBUG - } - return Pm; -} - -/* - * Sign specified block of data (most likely a hash result) using - * specified feePubKey. - */ -feeReturn feeSigSign(feeSig sig, - const unsigned char *data, // data to be signed - unsigned dataLen, // in bytes - feePubKey pubKey) -{ - sigInst *sinst = (sigInst*) sig; - giant messageGiant = NULL; - unsigned maxlen; - giant privGiant; - unsigned privGiantBytes; - feeReturn frtn = FR_Success; - unsigned randBytesLen; - unsigned uDigits; // alloc'd digits in sinst->u - curveParams *cp; - - if(pubKey == NULL) { - return FR_BadPubKey; - } - cp = feePubKeyCurveParams(pubKey); - if(cp == NULL) { - return FR_BadPubKey; - } - - privGiant = feePubKeyPrivData(pubKey); - if(privGiant == NULL) { - dbgLog(("Attempt to Sign without private data\n")); - frtn = FR_IllegalArg; - goto abort; - } - privGiantBytes = abs(privGiant->sign) * GIANT_BYTES_PER_DIGIT; - - /* - * Note PmX = m 'o' P1. - * Get message/digest as giant. May be significantly different - * in size from pubKey's basePrime. - */ - messageGiant = giant_with_data(data, dataLen); // M(text) - randBytesLen = feePubKeyBitsize(pubKey) / 8; - maxlen = max(randBytesLen, dataLen); - - /* leave plenty of room.... */ - uDigits = (3 * (privGiantBytes + maxlen)) / GIANT_BYTES_PER_DIGIT; - sinst->u = newGiant(uDigits); - gtog(privGiant, sinst->u); // u := ourPri - mulg(messageGiant, sinst->u); // u *= M(text) - addg(sinst->randGiant, sinst->u); // u += m - - /* - * Paranoia: we're using the curveParams from the caller's pubKey; - * this cp will have a valid x1OrderPlusRecip if pubKey is the same - * as the one passed to feeSigNewWithKey() (since feeSigNewWithKey - * called x1OrderPlusJustify()). But the caller could conceivably be - * using a different instance of their pubKey, in which case - * the key's cp->x1OrderPlusRecip may not be valid. - */ - calcX1OrderPlusRecip(cp); - - /* u := u mod x1OrderPlus */ - #if SIG_DEBUG - if(sigDebug) { - printf("sigSign:\n"); - printf("u pre-modg : "); - printGiant(sinst->u); - } - #endif - modg_via_recip(cp->x1OrderPlus, cp->x1OrderPlusRecip, sinst->u); - - #if SIG_DEBUG - if(sigDebug) { - printf("privGiant : "); - printGiant(privGiant); - printf("u : "); - printGiant(sinst->u); - printf("messageGiant: "); - printGiant(messageGiant); - printf("curveParams :\n"); - printCurveParams(cp); - } - #endif // SIG_DEBUG -abort: - if(messageGiant) { - freeGiant(messageGiant); - } - return frtn; -} - -/* - * Given a feeSig processed by feeSigSign, obtain a malloc'd byte - * array representing the signature. - * See ByteRep.doc for info on the format of the signature string; - * PLEASE UPDATE THIS DOCUMENT WHEN YOU MAKE CHANGES TO THE STRING FORMAT. - */ -feeReturn feeSigData(feeSig sig, - unsigned char **sigData, // IGNORED....malloc'd and RETURNED - unsigned *sigDataLen) // RETURNED -{ - sigInst *sinst = (sigInst*) sig; - - #if CRYPTKIT_DER_ENABLE - return feeDEREncodeElGamalSignature(sinst->u, sinst->PmX, sigData, sigDataLen); - #else - *sigDataLen = lengthOfByteRepSig(sinst->u, sinst->PmX); - *sigData = (unsigned char*) fmalloc(*sigDataLen); - sigToByteRep(FEE_SIG_MAGIC, - FEE_SIG_VERSION, - FEE_SIG_VERSION_MIN, - sinst->u, - sinst->PmX, - *sigData); - return FR_Success; - #endif -} - -/* - * Obtain a feeSig object by parsing an existing signature block. - * Note that if Pm is used to salt a hash of the signed data, this must - * function must be called prior to hashing. - */ -feeReturn feeSigParse(const unsigned char *sigData, - size_t sigDataLen, - feeSig *sig) // RETURNED -{ - sigInst *sinst = NULL; - feeReturn frtn; - #if !CRYPTKIT_DER_ENABLE - int version; - int magic; - int minVersion; - int rtn; - #endif - - sinst = sinstAlloc(); - #if CRYPTKIT_DER_ENABLE - frtn = feeDERDecodeElGamalSignature(sigData, sigDataLen, &sinst->u, &sinst->PmX); - if(frtn) { - goto abort; - } - #else - rtn = byteRepToSig(sigData, - sigDataLen, - FEE_SIG_VERSION, - &magic, - &version, - &minVersion, - &sinst->u, - &sinst->PmX); - if(rtn == 0) { - frtn = FR_BadSignatureFormat; - goto abort; - } - switch(magic) { - case FEE_ECDSA_MAGIC: - frtn = FR_WrongSignatureType; // ECDSA! - goto abort; - case FEE_SIG_MAGIC: - break; // proceed - default: - frtn = FR_BadSignatureFormat; - goto abort; - } - #endif /* CRYPTKIT_DER_ENABLE */ - - #if SIG_DEBUG - if(sigDebug) { - printf("sigParse: \n"); - printf("u: "); - printGiant(sinst->u); - } - #endif // SIG_DEBUG - - *sig = sinst; - return FR_Success; - -abort: - if(sinst) { - feeSigFree(sinst); - } - return frtn; -} - -/* - * Verify signature, obtained via feeSigParse, for specified - * data (most likely a hash result) and feePubKey. Returns non-zero if - * signature valid. - */ - -#define LOG_BAD_SIG 0 - -#if CRYPTKIT_ELL_PROJ_ENABLE - -feeReturn feeSigVerifyNoProj(feeSig sig, - const unsigned char *data, - unsigned dataLen, - feePubKey pubKey); - -static void borrowPointProj(pointProj pt, unsigned maxDigits) -{ - pt->x = borrowGiant(maxDigits); - pt->y = borrowGiant(maxDigits); - pt->z = borrowGiant(maxDigits); -} - -static void returnPointProj(pointProj pt) -{ - returnGiant(pt->x); - returnGiant(pt->y); - returnGiant(pt->z); -} - -feeReturn feeSigVerify(feeSig sig, - const unsigned char *data, - unsigned dataLen, - feePubKey pubKey) -{ - pointProjStruct Q; - giant messageGiant = NULL; - pointProjStruct scratch; - sigInst *sinst = (sigInst*) sig; - feeReturn frtn; - curveParams *cp; - key origKey; // may be plus or minus key - - if(sinst->PmX == NULL) { - dbgLog(("sigVerify without parse!\n")); - return FR_IllegalArg; - } - - cp = feePubKeyCurveParams(pubKey); - if(cp->curveType != FCT_Weierstrass) { - return feeSigVerifyNoProj(sig, data, dataLen, pubKey); - } - - borrowPointProj(&Q, cp->maxDigits); - borrowPointProj(&scratch, cp->maxDigits); - - /* - * Q := P1 - */ - gtog(cp->x1Plus, Q.x); - gtog(cp->y1Plus, Q.y); - int_to_giant(1, Q.z); - - messageGiant = giant_with_data(data, dataLen); // M(ciphertext) - - /* Q := u 'o' P1 */ - ellMulProjSimple(&Q, sinst->u, cp); - - /* scratch := theirPub */ - origKey = feePubKeyPlusCurve(pubKey); - gtog(origKey->x, scratch.x); - gtog(origKey->y, scratch.y); - int_to_giant(1, scratch.z); - - #if SIG_DEBUG - if(sigDebug) { - printf("verify origKey:\n"); - printKey(origKey); - printf("messageGiant: "); - printGiant(messageGiant); - printf("curveParams:\n"); - printCurveParams(cp); - } - #endif // SIG_DEBUG - - /* scratch := M 'o' theirPub */ - ellMulProjSimple(&scratch, messageGiant, cp); - - #if SIG_DEBUG - if(sigDebug) { - printf("signature_compare, with\n"); - printf("p0 = Q:\n"); - printGiant(Q.x); - printf("p1 = Pm:\n"); - printGiant(sinst->PmX); - printf("p2 = scratch = R:\n"); - printGiant(scratch.x); - } - #endif // SIG_DEBUG - - if(signature_compare(Q.x, sinst->PmX, scratch.x, cp)) { - - frtn = FR_InvalidSignature; - #if LOG_BAD_SIG - printf("***yup, bad sig***\n"); - #endif // LOG_BAD_SIG - } - else { - frtn = FR_Success; - } - freeGiant(messageGiant); - - returnPointProj(&Q); - returnPointProj(&scratch); - return frtn; -} - -#else /* CRYPTKIT_ELL_PROJ_ENABLE */ - -#define feeSigVerifyNoProj(s, d, l, k) feeSigVerify(s, d, l, k) - -#endif /* CRYPTKIT_ELL_PROJ_ENABLE */ - -/* - * FEE_SIG_USING_PROJ true : this is the "no Weierstrass" case - * feeSigVerifyNoProj false : this is redefined to feeSigVerify - */ -feeReturn feeSigVerifyNoProj(feeSig sig, - const unsigned char *data, - unsigned dataLen, - feePubKey pubKey) -{ - giant Q = NULL; - giant messageGiant = NULL; - giant scratch = NULL; - sigInst *sinst = (sigInst*) sig; - feeReturn frtn; - curveParams *cp; - key origKey; // may be plus or minus key - - if(sinst->PmX == NULL) { - dbgLog(("sigVerify without parse!\n")); - frtn = FR_IllegalArg; - goto out; - } - - cp = feePubKeyCurveParams(pubKey); - Q = newGiant(cp->maxDigits); - - /* - * pick a key (+/-) - * Q := P1 - */ - if(SIG_CURVE == CURVE_PLUS) { - origKey = feePubKeyPlusCurve(pubKey); - gtog(cp->x1Plus, Q); - } - else { - origKey = feePubKeyMinusCurve(pubKey); - gtog(cp->x1Minus, Q); - } - - messageGiant = giant_with_data(data, dataLen); // M(ciphertext) - - /* Q := u 'o' P1 */ - elliptic_simple(Q, sinst->u, cp); - - /* scratch := theirPub */ - scratch = newGiant(cp->maxDigits); - gtog(origKey->x, scratch); - - #if SIG_DEBUG - if(sigDebug) { - printf("verify origKey:\n"); - printKey(origKey); - printf("messageGiant: "); - printGiant(messageGiant); - printf("curveParams:\n"); - printCurveParams(cp); - } - #endif // SIG_DEBUG - - /* scratch := M 'o' theirPub */ - elliptic_simple(scratch, messageGiant, cp); - - #if SIG_DEBUG - if(sigDebug) { - printf("signature_compare, with\n"); - printf("p0 = Q:\n"); - printGiant(Q); - printf("p1 = Pm:\n"); - printGiant(sinst->PmX); - printf("p2 = scratch = R:\n"); - printGiant(scratch); - } - #endif // SIG_DEBUG - - if(signature_compare(Q, sinst->PmX, scratch, cp)) { - - frtn = FR_InvalidSignature; - #if LOG_BAD_SIG - printf("***yup, bad sig***\n"); - #endif // LOG_BAD_SIG - } - else { - frtn = FR_Success; - } -out: - if(messageGiant != NULL) { - freeGiant(messageGiant); - } - if(Q != NULL) { - freeGiant(Q); - } - if(scratch != NULL) { - freeGiant(scratch); - } - return frtn; -} - -/* - * For given key, calculate maximum signature size. - */ -feeReturn feeSigSize( - feePubKey pubKey, - unsigned *maxSigLen) -{ - /* For now, assume that u and Pm.x in the signature are - * same size as the key's associated curveParams->basePrime. - * We might have to pad this a bit.... - */ - curveParams *cp = feePubKeyCurveParams(pubKey); - - if(cp == NULL) { - return FR_BadPubKey; - } - #if CRYPTKIT_DER_ENABLE - *maxSigLen = feeSizeOfDERSig(cp->basePrime, cp->basePrime); - #else - *maxSigLen = (unsigned)lengthOfByteRepSig(cp->basePrime, cp->basePrime); - #endif - return FR_Success; -} diff --git a/OSX/include/security_cryptkit/feeDigitalSignature.h b/OSX/include/security_cryptkit/feeDigitalSignature.h deleted file mode 100644 index 7429cbab..00000000 --- a/OSX/include/security_cryptkit/feeDigitalSignature.h +++ /dev/null @@ -1,111 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeDigitalSignature.h - generic, portable FEE Digital Signature object - * - * Revision History - * ---------------- - * 22 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEDIGITALSIG_H_ -#define _CK_FEEDIGITALSIG_H_ - -#if !defined(__MACH__) -#include -#include -#else -#include -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#define FEE_SIG_MAGIC 0xfee00516 - -/* - * Opaque signature handle. - */ -typedef void *feeSig; - -/* - * Create new feeSig object, including a random large integer 'Pm' for - * possible use in salting a feeHash object. - */ -feeSig feeSigNewWithKey( - feePubKey pubKey, - feeRandFcn randFcn, /* optional */ - void *randRef); /* optional */ - -void feeSigFree( - feeSig sig); - -/* - * Obtain a malloc'd Pm after or feeSigNewWithKey() feeSigParse() - */ -unsigned char *feeSigPm( - feeSig sig, - unsigned *PmLen); /* RETURNED */ - -/* - * Sign specified block of data (most likely a hash result) using - * specified feePubKey. - */ -feeReturn feeSigSign( - feeSig sig, - const unsigned char *data, // data to be signed - unsigned dataLen, // in bytes - feePubKey pubKey); - -/* - * Given a feeSig processed by feeSigSign, obtain a malloc'd byte - * array representing the signature. - */ -feeReturn feeSigData( - feeSig sig, - unsigned char **sigData, // malloc'd and RETURNED - unsigned *sigDataLen); // RETURNED - -/* - * Obtain a feeSig object by parsing an existing signature block. - * Note that if Pm is used to salt a hash of the signed data, this must - * be performed prior to hashing. - */ -feeReturn feeSigParse( - const unsigned char *sigData, - size_t sigDataLen, - feeSig *sig); // RETURNED - -/* - * Verify signature, obtained via feeSigParse, for specified - * data (most likely a hash result) and feePubKey. Returns FR_Success or - * FR_InvalidSignature. - */ -feeReturn feeSigVerify( - feeSig sig, - const unsigned char *data, - unsigned dataLen, - feePubKey pubKey); - -/* - * For given key, calculate maximum signature size. - */ -feeReturn feeSigSize( - feePubKey pubKey, - unsigned *maxSigLen); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_FEEDIGITALSIG_H_*/ diff --git a/OSX/include/security_cryptkit/feeECDSA.c b/OSX/include/security_cryptkit/feeECDSA.c deleted file mode 100644 index 601bc6a4..00000000 --- a/OSX/include/security_cryptkit/feeECDSA.c +++ /dev/null @@ -1,697 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeECDSA.c - Elliptic Curve Digital Signature Algorithm (per IEEE 1363) - * - * Revision History - * ---------------- - * 11/27/98 dmitch - * Added ECDSA_VERIFY_ONLY dependencies. - * 10/06/98 ap - * Changed to compile with C++. - * 3 Sep 98 at Apple - * Rewrote using projective elliptic algebra, per IEEE P1363. - * 17 Dec 97 at Apple - * Fixed c==0 bug in feeECDSAVerify() - * Created. - */ - -/**** - Nomenclature, per IEEE P1363 D1, Dec. 1997 - - G = initial public point = (x1Plus, y1Plus) as usual - x1OrderPlus = IEEE r = (always prime) order of x1Plus - f = message to be signed, generally a SHA1 message digest - s = signer's private key - W = signer's public key - * : integer multiplication, as in (x * y) - 'o' : elliptic multiply, as in (u 'o' G) - - Signing algorithm: - - 1) Obtain random u in [2, x1OrderPlus-2]; - 2) Compute x coordinate, call it c, of u 'o' G (elliptic mul); - 3) Reduce: c := c mod x1OrderPlus; - 4) If c = 0, goto (1); - 5) Compute u^(-1) (mod x1OrderPlus); - 6) Compute signature s as: - - d = [u^(-1) (f + (s*c))] (mod x1OrderPlus) - - 7) If d = 0, goto (1); - 8) Signature is the integer pair (c, d). Each integer - in the pair must be in [1, x1OrderPlus-1]. - - Note: therefore a component of the signature could be slightly - larger than base prime. - - Verification algorithm, given signature (c, d): - - 1) Compute h = d^(-1) (mod x1OrderPlus); - 2) Compute h1 = digest as giant integer (skips assigning to 'f' as in - IEEE spec) - 3) Compute h1 = h1 * h (mod x1OrderPlus) (i.e., = f * h) - 4) Compute h2 = c * h (mod x1OrderPlus); - 5) Compute h2W = h2 'o' W - 6) Compute h1G = h1 'o' G - 7) Compute elliptic sum of h1G + h2W - 8) If elliptic sum is point at infinity, signature is bad; stop. - 9) cPrime = x coordinate of elliptic sum, mod x1OrderPlus - 10) Signature is good iff cPrime == c. - -***********/ - -#include "ckconfig.h" - -#if CRYPTKIT_ECDSA_ENABLE - -#include "feeTypes.h" -#include "feePublicKey.h" -#include "feePublicKeyPrivate.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "feeRandom.h" -#include "curveParams.h" -#include "falloc.h" -#include "ckutilities.h" -#include "feeDebug.h" -#include "platform.h" -#include "byteRep.h" -#include -#include "feeECDSA.h" -#include "byteRep.h" -#include "feeDigitalSignature.h" -#include "ECDSA_Profile.h" -#include "ellipticProj.h" -#if CRYPTKIT_DER_ENABLE -#include "CryptKitDER.h" -#endif - -#ifndef ECDSA_VERIFY_ONLY -static void ECDSA_encode( - feeSigFormat format, // Signature format DER 9.62 / RAW - unsigned groupBytesLen, - giant c, - giant d, - unsigned char **sigData, // malloc'd and RETURNED - unsigned *sigDataLen); // RETURNED -#endif /* ECDSA_VERIFY_ONLY */ - -static feeReturn ECDSA_decode( - feeSigFormat format, // Signature format DER 9.62 / RAW - unsigned groupBytesLen, - const unsigned char *sigData, - size_t sigDataLen, - giant *gs, // alloc'd & RETURNED - giant *x0, // alloc'd & RETURNED - unsigned *sigVersion); // RETURNED - - -#define ECDSA_DEBUG 0 -#if ECDSA_DEBUG -int ecdsaDebug=1; /* tweakable at runtime via debugger */ -#define sigDbg(x) \ - if(ecdsaDebug) { \ - printf x; \ - } -#define sigLogGiant(s, g) \ - if(ecdsaDebug) { \ - printf(s); \ - printGiant(g) /*printGiantExp(g)*/; \ - } -#else // ECDSA_DEBUG -#define sigDbg(x) -#define sigLogGiant(s, g) -#endif // ECDSA_DEBUG - -#if ECDSA_PROFILE -/* - * Profiling accumulators. - */ -unsigned signStep1; -unsigned signStep2; -unsigned signStep34; -unsigned signStep5; -unsigned signStep67; -unsigned signStep8; -unsigned vfyStep1; -unsigned vfyStep3; -unsigned vfyStep4; -unsigned vfyStep5; -unsigned vfyStep6; -unsigned vfyStep7; -unsigned vfyStep8; -#endif // ECDSA_PROFILE - -/* - * Totally incompatible with feeDigitalSignature.c. Caller must be aware of - * signature format. We will detect an ElGamal signature, however, and - * return FR_WrongSignatureType from feeECDSAVerify(). - */ -#define FEE_ECDSA_VERSION 2 -#define FEE_ECDSA_VERSION_MIN 2 - -/* - * When true, use ellMulProjSimple rather than elliptic_simple in - * sign operation. Using ellMulProjSimple is a *big* win. - */ -#define ECDSA_SIGN_USE_PROJ 1 - -/* - * Sign specified block of data (most likely a hash result) using - * specified private key. Result, an enc64-encoded signature block, - * is returned in *sigData. - */ - -#ifndef ECDSA_VERIFY_ONLY - -feeReturn feeECDSASign( - feePubKey pubKey, - feeSigFormat format, // Signature format DER 9.62 / RAW - const unsigned char *data, // data to be signed - unsigned dataLen, // in bytes - feeRandFcn randFcn, // optional - void *randRef, // optional - unsigned char **sigData, // malloc'd and RETURNED - unsigned *sigDataLen) // RETURNED -{ - curveParams *cp; - - /* giant integers per IEEE P1363 notation */ - - giant c; // both 1363 'c' and 'i' - // i.e., x-coord of u's pub key - giant d; - giant u; // random private key - giant s; // private key as giant - giant f; // data (message) as giant - - feeReturn frtn = FR_Success; - feeRand frand; - unsigned char *randBytes; - unsigned randBytesLen; - unsigned groupBytesLen; - giant privGiant; - #if ECDSA_SIGN_USE_PROJ - pointProjStruct pt; // pt->x = c - giant pty; // pt->y - giant ptz; // pt->z - #endif // ECDSA_SIGN_USE_PROJ - - if(pubKey == NULL) { - return FR_BadPubKey; - } - cp = feePubKeyCurveParams(pubKey); - if(cp == NULL) { - return FR_BadPubKey; - } - if(cp->curveType != FCT_Weierstrass) { - return FR_IllegalCurve; - } - - CKASSERT(!isZero(cp->x1OrderPlus)); - - /* - * Private key and message to be signed as giants - */ - privGiant = feePubKeyPrivData(pubKey); - if(privGiant == NULL) { - dbgLog(("Attempt to Sign without private data\n")); - return FR_IllegalArg; - } - s = borrowGiant(cp->maxDigits); - gtog(privGiant, s); - if(dataLen > (cp->maxDigits * GIANT_BYTES_PER_DIGIT)) { - f = borrowGiant(BYTES_TO_GIANT_DIGITS(dataLen)); - } - else { - f = borrowGiant(cp->maxDigits); - } - deserializeGiant(data, f, dataLen); - - /* - * Certicom SEC1 states that if the digest is larger than the modulus, - * use the left q bits of the digest. - */ - unsigned hashBits = dataLen * 8; - if(hashBits > cp->q) { - gshiftright(hashBits - cp->q, f); - } - - sigDbg(("ECDSA sign:\n")); - sigLogGiant(" s : ", s); - sigLogGiant(" f : ", f); - - c = borrowGiant(cp->maxDigits); - d = borrowGiant(cp->maxDigits); - u = borrowGiant(cp->maxDigits); - if(randFcn == NULL) { - frand = feeRandAlloc(); - } - else { - frand = NULL; - } - - /* - * Random size is just larger than base prime - */ - groupBytesLen = ((feePubKeyBitsize(pubKey)+7) / 8); - randBytesLen = groupBytesLen+8; // +8bytes (64bits) to reduce the biais when with reduction mod prime. Per FIPS186-4 - "Using Extra Random Bits" - randBytes = (unsigned char*) fmalloc(randBytesLen); - - #if ECDSA_SIGN_USE_PROJ - /* quick temp pointProj */ - pty = borrowGiant(cp->maxDigits); - ptz = borrowGiant(cp->maxDigits); - pt.x = c; - pt.y = pty; - pt.z = ptz; - #endif // ECDSA_SIGN_USE_PROJ - - while(1) { - /* Repeat this loop until we have a non-zero c and d */ - - /* - * 1) Obtain random u in [2, x1OrderPlus-2] - */ - SIGPROF_START; - if(randFcn) { - randFcn(randRef, randBytes, randBytesLen); - } - else { - feeRandBytes(frand, randBytes, randBytesLen); - } - deserializeGiant(randBytes, u, randBytesLen); - sigLogGiant(" raw u : ", u); - sigLogGiant(" order : ", cp->x1OrderPlus); - x1OrderPlusJustify(u, cp); - SIGPROF_END(signStep1); - sigLogGiant(" in range u : ", u); - - /* - * note 'o' indicates elliptic multiply, * is integer mult. - * - * 2) Compute x coordinate, call it c, of u 'o' G - * 3) Reduce: c := c mod x1OrderPlus; - * 4) If c == 0, goto (1); - */ - SIGPROF_START; - gtog(cp->x1Plus, c); - - #if ECDSA_SIGN_USE_PROJ - - /* projective coordinates */ - gtog(cp->y1Plus, pty); - int_to_giant(1, ptz); - ellMulProjSimple(&pt, u, cp); - - #else /* ECDSA_SIGN_USE_PROJ */ - - /* the FEE way */ - elliptic_simple(c, u, cp); - - #endif /* ECDSA_SIGN_USE_PROJ */ - - SIGPROF_END(signStep2); - SIGPROF_START; - x1OrderPlusMod(c, cp); - SIGPROF_END(signStep34); - if(isZero(c)) { - dbgLog(("feeECDSASign: zero modulo (1)\n")); - continue; - } - - /* - * 5) Compute u^(-1) mod x1OrderPlus; - */ - SIGPROF_START; - gtog(u, d); - binvg_x1OrderPlus(cp, d); - SIGPROF_END(signStep5); - sigLogGiant(" u^(-1) : ", d); - - /* - * 6) Compute signature d as: - * d = [u^(-1) (f + s*c)] (mod x1OrderPlus) - */ - SIGPROF_START; - mulg(c, s); // s *= c - x1OrderPlusMod(s, cp); - addg(f, s); // s := f + (s * c) - x1OrderPlusMod(s, cp); - mulg(s, d); // d := u^(-1) (f + (s * c)) - x1OrderPlusMod(d, cp); - SIGPROF_END(signStep67); - - /* - * 7) If d = 0, goto (1); - */ - if(isZero(d)) { - dbgLog(("feeECDSASign: zero modulo (2)\n")); - continue; - } - sigLogGiant(" c : ", c); - sigLogGiant(" d : ", d); - break; // normal successful exit - } - - /* - * 8) signature is now the integer pair (c, d). - */ - - /* - * Cook up raw data representing the signature. - */ - SIGPROF_START; - ECDSA_encode(format,groupBytesLen, c, d, sigData, sigDataLen); - SIGPROF_END(signStep8); - - if(frand != NULL) { - feeRandFree(frand); - } - ffree(randBytes); - returnGiant(u); - returnGiant(d); - returnGiant(c); - returnGiant(f); - returnGiant(s); - #if ECDSA_SIGN_USE_PROJ - returnGiant(pty); - returnGiant(ptz); - #endif /* ECDSA_SIGN_USE_PROJ */ - return frtn; -} - -#endif /* ECDSA_VERIFY_ONLY */ - -/* - * Verify signature for specified data (most likely a hash result) and - * feePubKey. Returns FR_Success or FR_InvalidSignature. - */ - -#define LOG_BAD_SIG 0 - -feeReturn feeECDSAVerify(const unsigned char *sigData, - size_t sigDataLen, - const unsigned char *data, - unsigned dataLen, - feePubKey pubKey, - feeSigFormat format) -{ - /* giant integers per IEEE P1363 notation */ - giant h; // s^(-1) - giant h1; // f h - giant h2; // c times h - giant littleC; // newGiant from ECDSA_decode - giant littleD; // ditto - giant c; // borrowed, full size - giant d; // ditto - giant cPrime = NULL; // i mod r - pointProj h1G = NULL; // h1 'o' G - pointProj h2W = NULL; // h2 'o' W - key W; // i.e., their public key - - unsigned version; - feeReturn frtn; - curveParams *cp = feePubKeyCurveParams(pubKey); - unsigned groupBytesLen = ((feePubKeyBitsize(pubKey)+7) / 8); - int result; - - if(cp == NULL) { - return FR_BadPubKey; - } - - /* - * First decode the byteRep string. - */ - frtn = ECDSA_decode( - format, - groupBytesLen, - sigData, - sigDataLen, - &littleC, - &littleD, - &version); - if(frtn) { - return frtn; - } - - /* - * littleC and littleD have capacity = abs(sign), probably - * not big enough.... - */ - c = borrowGiant(cp->maxDigits); - d = borrowGiant(cp->maxDigits); - gtog(littleC, c); - gtog(littleD, d); - freeGiant(littleC); - freeGiant(littleD); - - sigDbg(("ECDSA verify:\n")); - - /* - * W = signer's public key - */ - W = feePubKeyPlusCurve(pubKey); - - /* - * 1) Compute h = d^(-1) (mod x1OrderPlus); - */ - SIGPROF_START; - h = borrowGiant(cp->maxDigits); - gtog(d, h); - binvg_x1OrderPlus(cp, h); - SIGPROF_END(vfyStep1); - - /* - * 2) h1 = digest as giant (skips assigning to 'f' in P1363) - */ - if(dataLen > (cp->maxDigits * GIANT_BYTES_PER_DIGIT)) { - h1 = borrowGiant(BYTES_TO_GIANT_DIGITS(dataLen)); - } - else { - h1 = borrowGiant(cp->maxDigits); - } - deserializeGiant(data, h1, dataLen); - - /* - * Certicom SEC1 states that if the digest is larger than the modulus, - * use the left q bits of the digest. - */ - unsigned hashBits = dataLen * 8; - if(hashBits > cp->q) { - gshiftright(hashBits - cp->q, h1); - } - - sigLogGiant(" Wx : ", W->x); - sigLogGiant(" f : ", h1); - sigLogGiant(" c : ", c); - sigLogGiant(" d : ", d); - sigLogGiant(" s^(-1) : ", h); - - /* - * 3) Compute h1 = f * h mod x1OrderPlus; - */ - SIGPROF_START; - mulg(h, h1); // h1 := f * h - x1OrderPlusMod(h1, cp); - SIGPROF_END(vfyStep3); - - /* - * 4) Compute h2 = c * h (mod x1OrderPlus); - */ - SIGPROF_START; - h2 = borrowGiant(cp->maxDigits); - gtog(c, h2); - mulg(h, h2); // h2 := c * h - x1OrderPlusMod(h2, cp); - SIGPROF_END(vfyStep4); - - /* - * 5) Compute h2W = h2 'o' W (W = theirPub) - */ - CKASSERT((W->y != NULL) && !isZero(W->y)); - h2W = newPointProj(cp->maxDigits); - gtog(W->x, h2W->x); - gtog(W->y, h2W->y); - int_to_giant(1, h2W->z); - ellMulProjSimple(h2W, h2, cp); - - /* - * 6) Compute h1G = h1 'o' G (G = {x1Plus, y1Plus, 1} ) - */ - CKASSERT((cp->y1Plus != NULL) && !isZero(cp->y1Plus)); - h1G = newPointProj(cp->maxDigits); - gtog(cp->x1Plus, h1G->x); - gtog(cp->y1Plus, h1G->y); - int_to_giant(1, h1G->z); - ellMulProjSimple(h1G, h1, cp); - - /* - * 7) h1G := (h1 'o' G) + (h2 'o' W) - */ - ellAddProj(h1G, h2W, cp); - - /* - * 8) If elliptic sum is point at infinity, signature is bad; stop. - */ - if(isZero(h1G->z)) { - dbgLog(("feeECDSAVerify: h1 * G = point at infinity\n")); - result = 1; - goto vfyDone; - } - normalizeProj(h1G, cp); - - /* - * 9) cPrime = x coordinate of elliptic sum, mod x1OrderPlus - */ - cPrime = borrowGiant(cp->maxDigits); - gtog(h1G->x, cPrime); - x1OrderPlusMod(cPrime, cp); - - /* - * 10) Good sig iff cPrime == c - */ - result = gcompg(c, cPrime); - -vfyDone: - if(result) { - frtn = FR_InvalidSignature; - #if LOG_BAD_SIG - printf("***yup, bad sig***\n"); - #endif // LOG_BAD_SIG - } - else { - frtn = FR_Success; - } - - returnGiant(c); - returnGiant(d); - returnGiant(h); - returnGiant(h1); - returnGiant(h2); - if(h1G != NULL) { - freePointProj(h1G); - } - if(h2W != NULL) { - freePointProj(h2W); - } - if(cPrime != NULL) { - returnGiant(cPrime); - } - return frtn; -} - -#ifndef ECDSA_VERIFY_ONLY - -/* - * Encode to/from byteRep. - */ -static void ECDSA_encode( - feeSigFormat format, // Signature format DER 9.62 / RAW - unsigned groupBytesLen, - giant c, - giant d, - unsigned char **sigData, // malloc'd and RETURNED - unsigned *sigDataLen) // RETURNED -{ - #if CRYPTKIT_DER_ENABLE - if (format==FSF_RAW) { - feeRAWEncodeECDSASignature(groupBytesLen,c, d, sigData, sigDataLen); - } else { - feeDEREncodeECDSASignature(c, d, sigData, sigDataLen); - } - #else - *sigDataLen = lengthOfByteRepSig(c, d); - *sigData = (unsigned char*) fmalloc(*sigDataLen); - sigToByteRep(FEE_ECDSA_MAGIC, - FEE_ECDSA_VERSION, - FEE_ECDSA_VERSION_MIN, - c, - d, - *sigData); - #endif -} - -#endif /* ECDSA_VERIFY_ONLY */ - -static feeReturn ECDSA_decode( - feeSigFormat format, // Signature format DER 9.62 / RAW - unsigned groupBytesLen, - const unsigned char *sigData, - size_t sigDataLen, - giant *c, // alloc'd & RETURNED - giant *d, // alloc'd & RETURNED - unsigned *sigVersion) // RETURNED -{ - #if CRYPTKIT_DER_ENABLE - feeReturn frtn; - if (format==FSF_RAW) { - frtn = feeRAWDecodeECDSASignature(groupBytesLen, sigData, sigDataLen, c, d); - } else { - frtn = feeDERDecodeECDSASignature(sigData, sigDataLen, c, d); - } - if(frtn == FR_Success) { - *sigVersion = FEE_ECDSA_VERSION; - } - return frtn; - #else - int magic; - int minVersion; - int rtn; - - rtn = byteRepToSig(sigData, - sigDataLen, - FEE_ECDSA_VERSION, - &magic, - (int *)sigVersion, - &minVersion, - c, - d); - if(rtn == 0) { - return FR_BadSignatureFormat; - } - switch(magic) { - case FEE_ECDSA_MAGIC: - return FR_Success; - case FEE_SIG_MAGIC: // ElGamal sig! - return FR_WrongSignatureType; - default: - return FR_BadSignatureFormat; - } - #endif -} - -/* - * For given key, calculate maximum signature size. - */ -feeReturn feeECDSASigSize( - feePubKey pubKey, - unsigned *maxSigLen) -{ - /* For now, assume that c and d in the signature are - * same size as the key's associated curveParams->basePrime. - * We might have to pad this a bit.... - */ - curveParams *cp = feePubKeyCurveParams(pubKey); - - if(cp == NULL) { - return FR_BadPubKey; - } - #if CRYPTKIT_DER_ENABLE - *maxSigLen = feeSizeOfDERSig(cp->basePrime, cp->basePrime); - #else - *maxSigLen = (unsigned)lengthOfByteRepSig(cp->basePrime, cp->basePrime); - #endif - return FR_Success; -} - -#endif /* CRYPTKIT_ECDSA_ENABLE */ - diff --git a/OSX/include/security_cryptkit/feeECDSA.h b/OSX/include/security_cryptkit/feeECDSA.h deleted file mode 100644 index fc0cb28b..00000000 --- a/OSX/include/security_cryptkit/feeECDSA.h +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeECDSA.h - Elliptic Curve Digital Signature Algorithm (per IEEE 1363) - * - * Revision History - * ---------------- - * 16 Jul 97 at Apple - * Created. - */ - -#ifndef _CK_FEEECDSA_H_ -#define _CK_FEEECDSA_H_ - -#if !defined(__MACH__) -#include -#include -#include -#else -#include -#include -#include -#endif - -/* - * Keep this one defined and visible even if we can't actually do ECDSA - feeSigParse() - * uses it to detect "wriong signature type". - */ -#define FEE_ECDSA_MAGIC 0xfee00517 - -#if CRYPTKIT_ECDSA_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - - -/* - * Sign specified block of data (most likely a hash result) using - * specified private key. Result, an enc64-encoded signature block, - * is returned in *sigData. - */ -feeReturn feeECDSASign(feePubKey pubKey, - feeSigFormat format, // Format of the signature DER/RAW - const unsigned char *data, // data to be signed - unsigned dataLen, // in bytes - feeRandFcn randFcn, // optional - void *randRef, // optional - unsigned char **sigData, // malloc'd and RETURNED - unsigned *sigDataLen); // RETURNED - -/* - * Verify signature, obtained via feeECDSASign, for specified - * data (most likely a hash result) and feePubKey. Returns FR_Success or - * FR_InvalidSignature. - */ -feeReturn feeECDSAVerify(const unsigned char *sigData, - size_t sigDataLen, - const unsigned char *data, - unsigned dataLen, - feePubKey pubKey, - feeSigFormat format); // Format of the signature DER/RAW - -/* - * For given key, calculate maximum signature size. - */ -feeReturn feeECDSASigSize( - feePubKey pubKey, - unsigned *maxSigLen); - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_ECDSA_ENABLE */ - -#endif /*_CK_FEEECDSA_H_*/ diff --git a/OSX/include/security_cryptkit/feeFEED.c b/OSX/include/security_cryptkit/feeFEED.c deleted file mode 100644 index 144f7345..00000000 --- a/OSX/include/security_cryptkit/feeFEED.c +++ /dev/null @@ -1,1233 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeFEED.c - generic, portable FEED encryption object, expanionless version - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 20 Jan 1998 at Apple - * Mods for primeType == PT_GENERAL case. - * 12 Jun 1997 at Apple - * Was curveOrderJustify(), is lesserX1OrderJustify() - * 31 Mar 1997 at Apple - * Fixed initialRS leak - * 3 Mar 1997 at Apple - * Trimmed plainBlockSize by one byte if q mod 8 = 0 - * 30 Jan 1997 at NeXT - * Created. - */ - -/* - * FIXME - a reusable init function would be nice (i.e., free up - * session-dependent state and re-init it)... - */ -#include "ckconfig.h" - -#if CRYPTKIT_ASYMMETRIC_ENABLE - -#include "feeTypes.h" -#include "feeFEED.h" -#include "feeFEEDExp.h" -#include "feePublicKey.h" -#include "feePublicKeyPrivate.h" -#include "elliptic.h" -#include "falloc.h" -#include "feeRandom.h" -#include "ckutilities.h" -#include "feeFunctions.h" -#include "platform.h" -#include "curveParams.h" -#include "feeDebug.h" -#include -#include - -#define FEED_DEBUG 0 -#define BUFFER_DEBUG 0 -#if BUFFER_DEBUG -#define bprintf(s) printf s -#else -#define bprintf(s) -#endif - -/* - * Minimum combined size of random r and s, in bytes. For small q sizes, - * r and s may be even smaller, but we never truncate them to smaller than - * this. - * This must be kept in sync with constant of same name in FEED.java. - */ -#define RS_MIN_SIZE 16 - -/* - * Private data. - */ -typedef struct { - curveParams *cp; - - /* - * the clues are initially (r * ourPriv * theirPub(+/-)). - */ - giant cluePlus; - giant clueMinus; - - /* - * sPlus and sMinus are based on the random s generated at encrypt - * time. Values are s * x1{Plus,Minus}. - */ - giant sPlus; - giant sMinus; - giant r; /* random, generated at encrypt time */ - unsigned plainBlockSize; /* plaintext block size */ - unsigned cipherBlockSize; /* ciphertext block size */ - unsigned char *initialRS; /* initial random R,S as bytes */ - unsigned initialRSSize; /* in bytes */ - feeFEEDExp feedExp; /* for encr/decr r+s params */ - - /* - * The first few blocks of ciphertext in a stream are the 2:1-FEED - * encrypted r and s parameters. While decrypting, we stash incoming - * ciphertext in rsCtext until we get enough ciphertext to decrypt - * initialRS. RsBlockCount keeps a running count of the - * cipherBlocks received. When rsBlockCount == rsSizeCipherBlocks, we - * FEEDExp-decrypt rsCtext to get r and s (actually, to get - * initialRS; r and s are extraced later in initFromRS()). - * - * During encrypt, if rsBlockCount is zero, the first thing we send as - * ciphertext is the FEED-encrypted initialRS. - */ - unsigned char *rsCtext; /* buffer for encrypted initialRS */ - unsigned rsBlockCount; /* running total of incoming rs - * cipherblocks */ - - int forEncrypt; /* added for feeFEED*TextSize() */ - - /* - * These are calculated at init time - for encrypt and - * decrypt - as an optimization. - */ - unsigned rsCtextSize; /* number of meaningful bytes in - * rsCtext */ - unsigned rsSizeCipherBlocks; /* # of our cipherblocks holding - * rsCtext */ - - /* - * temporary variables used for encrypt/decrypt. The values in these - * are not needed to be kept from block to block; we just - * alloc them once per lifetime of a feeFEED object as an optimization. - */ - giant xp; /* plaintext */ - giant xm; /* ciphertext */ - giant tmp1; /* scratch */ - giant tmp2; /* scratch */ -} feedInst; - -/* - * "zero residue" indicator. - */ -#define RESID_ZERO 0xff - -/* - * cons up: - * cluePlus(0) - * clueMinus(0) - * sPlus - * sMinus - * r - * Assumes: - * cluePlus = clueMinus = ourPriv * theirPub - * initialRS - * initialRSSize - * cp - * - * Called at feeFEEDNewWithPubKey while encrypting, or upon decrypting - * first block of data. - */ -static feeReturn initFromRS(feedInst *finst) -{ - giant s; - unsigned rSize = finst->initialRSSize / 2; - - #if FEED_DEBUG - if((finst->initialRS == NULL) || - (finst->cp == NULL) || - (finst->cluePlus == NULL) || - (finst->clueMinus == NULL) || - (finst->initialRSSize == 0)) { - dbgLog(("initFromRS: resource shortage\n")); - return FR_Internal; - } - #endif // FEED_DEBUG - - finst->r = giant_with_data(finst->initialRS, rSize); - s = giant_with_data(finst->initialRS+rSize, rSize); - - #if FEED_DEBUG - if(isZero(finst->r)) { - printf("initFromRS: r = 0! initialRSSize = %d; encr = %s\n", - finst->initialRSSize, - (finst->rsCtext == NULL) ? "TRUE" : "FALSE"); - } - if(isZero(s)) { - printf("initFromRS: s = 0! initialRSSize = %d; encr = %s\n", - finst->initialRSSize, - (finst->rsCtext == NULL) ? "TRUE" : "FALSE"); - } - #endif // FEE_DEBUG - /* - * Justify r and s to be in [2, minimumX1Order]. - */ - lesserX1OrderJustify(finst->r, finst->cp); - lesserX1OrderJustify(s, finst->cp); - - /* - * sPlus = s * x1Plus - * sMinus = s * x1Minus - */ - finst->sPlus = newGiant(finst->cp->maxDigits); - finst->sMinus = newGiant(finst->cp->maxDigits); - gtog(finst->cp->x1Plus, finst->sPlus); - elliptic_simple(finst->sPlus, s, finst->cp); - gtog(finst->cp->x1Minus, finst->sMinus); - elliptic_simple(finst->sMinus, s, finst->cp); - - /* - * And finally, the initial clues. They are currently set to - * ourPriv * theirPub. - */ - #if FEED_DEBUG - printf("cluePlus : "); printGiant(finst->cluePlus); - printf("clueMinus: "); printGiant(finst->clueMinus); - #endif // FEED_EEBUG - - elliptic_simple(finst->cluePlus, finst->r, finst->cp); - elliptic_simple(finst->clueMinus, finst->r, finst->cp); - - #if FEED_DEBUG - printf("r : "); printGiant(finst->r); - printf("s : "); printGiant(s); - printf("sPlus : "); printGiant(finst->sPlus); - printf("sMinus : "); printGiant(finst->sMinus); - printf("cluePlus : "); printGiant(finst->cluePlus); - printf("clueMinus: "); printGiant(finst->clueMinus); - #endif // FEED_DEBUG - - freeGiant(s); - return FR_Success; -} - -/* - * Alloc and init a feeFEED object associated with specified public and - * private keys. - */ -feeFEED feeFEEDNewWithPubKey(feePubKey myPrivKey, - feePubKey theirPubKey, - int forEncrypt, // 0 ==> decrypt 1 ==> encrypt - feeRandFcn randFcn, // optional - void *randRef) -{ - feedInst *finst; - giant privGiant; - key k; - unsigned expPlainSize; - unsigned expCipherSize; - unsigned expBlocks; - - if(!curveParamsEquivalent(feePubKeyCurveParams(theirPubKey), - feePubKeyCurveParams(myPrivKey))) { - dbgLog(("feeFEEDNewWithPubKey: Incompatible Keys\n")); - return NULL; - } - finst = (feedInst*) fmalloc(sizeof(feedInst)); - bzero(finst, sizeof(feedInst)); - finst->forEncrypt = forEncrypt; - finst->cp = curveParamsCopy(feePubKeyCurveParams(theirPubKey)); - finst->rsBlockCount = 0; - finst->xp = newGiant(finst->cp->maxDigits); - finst->xm = newGiant(finst->cp->maxDigits); - finst->tmp1 = newGiant(finst->cp->maxDigits); - if(forEncrypt) { - finst->tmp2 = newGiant(finst->cp->maxDigits); - } - - /* - * cluePlus = ourPriv * theirPub+ - * clueMinus = ourPriv * theirPub- - */ - finst->cluePlus = newGiant(finst->cp->maxDigits); - finst->clueMinus = newGiant(finst->cp->maxDigits); - privGiant = feePubKeyPrivData(myPrivKey); - if(privGiant == NULL) { - dbgLog(("feeFEEDNewWithPubKey: no private key\n")); - goto abort; - } - k = feePubKeyPlusCurve(theirPubKey); - gtog(k->x, finst->cluePlus); // cluePlus = theirPub+ - elliptic_simple(finst->cluePlus, privGiant, finst->cp); - k = feePubKeyMinusCurve(theirPubKey); - gtog(k->x, finst->clueMinus); // theirPub- - elliptic_simple(finst->clueMinus, privGiant, finst->cp); - - /* - * Set up block sizes. - */ - if(finst->cp->primeType == FPT_General) { - unsigned blen = bitlen(finst->cp->basePrime); - - finst->plainBlockSize = blen / 8; - if((blen & 0x7) == 0) { - /* - * round down some more... - */ - finst->plainBlockSize--; - } - } - else { - finst->plainBlockSize = finst->cp->q / 8; - if(((finst->cp->q & 0x7) == 0) && (finst->cp->k > 0)) { - /* - * Special case, with q mod 8 == 0. Here we have to - * trim back the plainBlockSize by one byte. - */ - finst->plainBlockSize--; - } - } - finst->cipherBlockSize = finst->cp->minBytes + 1; - - /* - * the size of initialRS is subject to tweaking - if we make it - * not a multiple of plainBlockSize, we save one FEEDExp cipherBlock - * in our ciphertext. - */ - finst->initialRSSize = finst->plainBlockSize * 2; - if(finst->initialRSSize > RS_MIN_SIZE) { - unsigned minPlainBlocks; - unsigned maxSize; - - /* - * How many plainblocks to hold RS_MIN_SIZE? - */ - minPlainBlocks = (RS_MIN_SIZE + finst->plainBlockSize - 1) / - finst->plainBlockSize; - - /* - * Max size = that many plainblocks, less 2 bytes (to avoid - * extra residue block). - */ - maxSize = minPlainBlocks * finst->plainBlockSize - 2; - - /* - * But don't bother with more than 2 plainblocks worth - */ - if(finst->initialRSSize > maxSize) { - finst->initialRSSize = maxSize; - } - } - /* else leave it alone, that's small enough */ - - if(forEncrypt) { - feeRand frand = NULL; - - /* - * Encrypt-capable FEEDExp object - */ - finst->feedExp = feeFEEDExpNewWithPubKey(theirPubKey, - randFcn, - randRef); - if(finst->feedExp == NULL) { - goto abort; - } - - /* - * Generate initial r and s data. - */ - finst->initialRS = (unsigned char*) fmalloc(finst->initialRSSize); - if(randFcn != NULL) { - randFcn(randRef, finst->initialRS, finst->initialRSSize); - } - else { - frand = feeRandAlloc(); - feeRandBytes(frand, finst->initialRS, finst->initialRSSize); - feeRandFree(frand); - } - if(initFromRS(finst)) { - goto abort; - } - } - else { - /* - * Decrypt-capable FEEDExp object - */ - finst->feedExp = feeFEEDExpNewWithPubKey(myPrivKey, - randFcn, - randRef); - if(finst->feedExp == NULL) { - goto abort; - } - - } - - /* - * Figure out how many of our cipherblocks it takes to hold - * a FEEDExp-encrypted initialRS. If initialRSSize is an exact - * multiple of expPlainSize, we get an additional feedExp - * residue block. - */ - expPlainSize = feeFEEDExpPlainBlockSize(finst->feedExp); - expCipherSize = feeFEEDExpCipherBlockSize(finst->feedExp); - expBlocks = (finst->initialRSSize + expPlainSize - 1) / - expPlainSize; - if((finst->initialRSSize % expPlainSize) == 0) { - expBlocks++; - } - - /* - * Total meaningful bytes of encrypted initialRS - */ - finst->rsCtextSize = expBlocks * expCipherSize; - - /* - * Number of our cipherblocks it takes to hold rsCtextSize - */ - finst->rsSizeCipherBlocks = (finst->rsCtextSize + - finst->cipherBlockSize - 1) / finst->cipherBlockSize; - if(!forEncrypt) { - finst->rsCtext = (unsigned char*) fmalloc(finst->rsSizeCipherBlocks * - finst->cipherBlockSize); - } - - /* - * Sanity check... - */ - #if FEED_DEBUG - { - unsigned fexpBlockSize = feeFEEDExpCipherBlockSize(finst->feedExp); - - /* - * FEEDExp has one more giant in ciphertext, plaintext is - * same size - */ - if((finst->cipherBlockSize + finst->cp->minBytes) != - fexpBlockSize) { - dbgLog(("feeFEEDNewWithPubKey: FEEDExp CBlock Size " - "screwup\n")); - goto abort; - } - fexpBlockSize = feeFEEDExpPlainBlockSize(finst->feedExp); - if(fexpBlockSize != finst->plainBlockSize) { - dbgLog(("feeFEEDNewWithPubKey: FEEDExp PBlock Size " - "screwup\n")); - goto abort; - } - } - #endif // FEED_DEBUG - - return finst; - -abort: - feeFEEDFree(finst); - return NULL; -} - -void feeFEEDFree(feeFEED feed) -{ - feedInst *finst = (feedInst*) feed; - - if(finst->cp) { - freeCurveParams(finst->cp); - } - if(finst->initialRS) { - ffree(finst->initialRS); - } - if(finst->cluePlus) { - freeGiant(finst->cluePlus); - } - if(finst->clueMinus) { - freeGiant(finst->clueMinus); - } - if(finst->sPlus) { - freeGiant(finst->sPlus); - } - if(finst->sMinus) { - freeGiant(finst->sMinus); - } - if(finst->r) { - freeGiant(finst->r); - } - if(finst->feedExp) { - feeFEEDExpFree(finst->feedExp); - } - if(finst->rsCtext) { - ffree(finst->rsCtext); - } - if(finst->xp) { - freeGiant(finst->xp); - } - if(finst->xm) { - freeGiant(finst->xm); - } - if(finst->tmp1) { - freeGiant(finst->tmp1); - } - if(finst->tmp2) { - freeGiant(finst->tmp2); - } - ffree(finst); -} - -unsigned feeFEEDPlainBlockSize(feeFEED feed) -{ - feedInst *finst = (feedInst *) feed; - - return finst->plainBlockSize; -} - -unsigned feeFEEDCipherBlockSize(feeFEED feed) -{ - feedInst *finst = (feedInst *) feed; - - return finst->cipherBlockSize; -} - -/* - * Calculate size of buffer currently needed to encrypt one block of - * plaintext. Also used to calculate required input during decrypt - * to get any output. - */ -unsigned feeFEEDCipherBufSize(feeFEED feed, - int finalBlock) -{ - feedInst *finst = (feedInst *) feed; - unsigned blocks = 1; // always at least one block of ciphertext - - if(finst->rsBlockCount == 0) { - /* haven't sent/seen encrypted RS yet */ - blocks += finst->rsSizeCipherBlocks; - } - - if(finalBlock) { - /* only needed if ptext is aligned, but tell caller to malloc */ - blocks++; - } - bprintf(("$$$ feeFEEDCipherBufSize( %s, %s): rtn 0x%x\n", - finst->forEncrypt ? "encrypt" : "decrypt", - finalBlock ? " final" : "!final", - blocks * finst->cipherBlockSize)); - return blocks * finst->cipherBlockSize; -} - -/* - * Return the size of ciphertext currently needed to encrypt specified - * size of plaintext. Also can be used to calculate size of ciphertext - * which can be decrypted into specified size of plaintext. - */ -unsigned feeFEEDCipherTextSize(feeFEED feed, - unsigned plainTextSize, - int finalBlock) -{ - feedInst *finst = (feedInst *) feed; - - /* how many blocks of plaintext? */ - unsigned blocks = (plainTextSize + finst->plainBlockSize - 1) / - finst->plainBlockSize; - - if(finst->forEncrypt) { - /* have we generated RS? */ - if(finst->rsBlockCount == 0) { - /* haven't sent encrypted RS yet */ - blocks += finst->rsSizeCipherBlocks; - } - - /* final? residue? */ - if(finalBlock) { - if((plainTextSize % finst->plainBlockSize) == 0) { - blocks++; - } - } - } /* encrypting */ - else { - /* - * Decrypting - how much ciphertext can we decrypt safely into - * specified plaintext? Add in RS if we haven't seen it all - * yet. - */ - #if BUFFER_DEBUG - if(finst->rsBlockCount > finst->rsSizeCipherBlocks) { - printf("******HEY! rsBlockCount overflow! (blockCount %d rsSize %d)\n", - finst->rsBlockCount, finst->rsSizeCipherBlocks); - } - #endif - blocks += (finst->rsSizeCipherBlocks - finst->rsBlockCount); - } - bprintf(("$$$ feeFEEDCipherTextSize(%s, %s, 0x%x): rtn 0x%x\n", - finst->forEncrypt ? "encrypt" : "decrypt", - finalBlock ? " final" : "!final", - plainTextSize, blocks * finst->cipherBlockSize)); - return blocks * finst->cipherBlockSize; -} - -/* - * Return the size of plaintext currently needed to decrypt specified size - * of ciphertext. Also can be used to calculate size of plaintext - * which can be encrypted into specified size of ciphertext. - */ -unsigned feeFEEDPlainTextSize(feeFEED feed, - unsigned cipherTextSize, - int finalBlock) // ignored if !forEncrypt -{ - feedInst *finst = (feedInst *) feed; - - /* start with basic cipher block count */ - unsigned cipherBlocks = (cipherTextSize + finst->cipherBlockSize - 1) / - finst->cipherBlockSize; - - /* where are we in the RS stream? */ - unsigned rsBlocksToGo = finst->rsSizeCipherBlocks - finst->rsBlockCount; - if(finst->forEncrypt) { - /* - * Encrypting, seeking plaintext size we can encrypt given - * a specified size of ciphertext. - */ - if(rsBlocksToGo >= cipherBlocks) { - /* no room! next encrypt would overflow ctext buffer! */ - return 0; - } - cipherBlocks -= rsBlocksToGo; - - /* another constraint - residue */ - if(finalBlock) { - if(cipherBlocks) { - /* skip if already zero... */ - cipherBlocks--; - } - } - } /* encrypting */ - else { - /* decrypting */ - if(rsBlocksToGo >= cipherBlocks) { - /* still processing RS, no plaintext will be generated. Play it real - * safe and just tell caller one block. */ - cipherBlocks = 1; - } - else { - /* diminish by size of RS to be gobbled with no output */ - cipherBlocks -= rsBlocksToGo; - } - } - bprintf(("$$$ feeFEEDPlainTextSize( %s, %s, 0x%x): rtn 0x%x\n", - finst->forEncrypt ? "encrypt" : "decrypt", - finalBlock ? " final" : "!final", - cipherTextSize, cipherBlocks * finst->plainBlockSize)); - return cipherBlocks * finst->plainBlockSize; -} - -/* - * Bits in last byte of cipherblock - */ -#define CLUE_BIT 0x01 /* 1 ==> plus curve */ -#define CLUE_PLUS 0x01 -#define CLUE_MINUS 0x00 -#define PARITY_BIT 0x02 /* 1 ==> plus 's' arg to elliptic_add() */ -#define PARITY_PLUS 0x02 -#define PARITY_MINUS 0x00 - -/* - * Encrypt a block or less of data. Caller malloc's cipherText. - * Generates up to feeFEEDCipherBufSize() bytes of ciphertext. - */ -feeReturn feeFEEDEncryptBlock(feeFEED feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // RETURNED - int finalBlock) -{ - feedInst *finst = (feedInst *) feed; - unsigned ctextLen = 0; - feeReturn frtn = FR_Success; - int whichCurve; - giant thisClue; // not alloc'd or freed - giant thisS; // ditto - unsigned char clueByte; - - if(plainTextLen > finst->plainBlockSize) { - return FR_IllegalArg; - } - if((plainTextLen < finst->plainBlockSize) && !finalBlock) { - return FR_IllegalArg; - } - if(finst->initialRS == NULL) { - /* - * Init'd for decrypt? - */ - return FR_IllegalArg; - } - - /* - * First block - encrypt initialRS via FEEDExp - */ - if(finst->rsBlockCount == 0) { - unsigned char *thisCtext; // malloc's by FEEDExp - unsigned padLen; - - if(finst->initialRS == NULL) { - /* - * init'd for decrypt or reused - */ - dbgLog(("feeFEEDEncryptBlock: NULL initialRS!\n")); - return FR_IllegalArg; - } - - frtn = feeFEEDExpEncrypt(finst->feedExp, - finst->initialRS, - finst->initialRSSize, - &thisCtext, - &ctextLen); - if(frtn) { - /* - * Should never happen... - */ - dbgLog(("feeFEEDEncryptBlock: error writing encrypted" - " initialRS (%s)\n", feeReturnString(frtn))); - return FR_Internal; - } - bcopy(thisCtext, cipherText, ctextLen); - cipherText += ctextLen; - ffree(thisCtext); - - finst->rsBlockCount = finst->rsSizeCipherBlocks; - padLen = finst->cipherBlockSize - - (ctextLen % finst->cipherBlockSize); // zeros to write - - #if 0 /* FEED_DEBUG */ - - /* - * Hard-coded assumptions and tests about initRSSize... - * Currently we assume that initRSSize % expBlockSize = 0 - */ - if((ctextLen / finst->cipherBlockSize) != 5) { - dbgLog(("feeFEEDEncryptBlock: cipherblock size screwup (1)\n")); - return FR_Internal; - } - if(padLen != 3) { - dbgLog(("feeFEEDEncryptBlock: cipherblock size screwup (2)\n")); - return FR_Internal; - } - #endif // FEED_DEBUG - - /* - * pad to multiple of (our) cipherblock size. - */ - while(padLen) { - *cipherText++ = 0; - ctextLen++; - padLen--; - } - } - - /* - * plaintext to giant xp - */ - if(finalBlock) { - unsigned char *ptext = (unsigned char*) fmalloc(finst->plainBlockSize); - bzero(ptext, finst->plainBlockSize); - if(plainTextLen) { - /* - * skip for empty block with resid length 0 - */ - bcopy(plainText, ptext, plainTextLen); - } - if(plainTextLen < finst->plainBlockSize) { - if(plainTextLen == 0) { - /* - * Special case - resid block with no actual plaintext. - * Can't actually write zero here; it screws up - * deserializing the giant during decrypt - */ - ptext[finst->plainBlockSize - 1] = RESID_ZERO; - bprintf(("=== FEED encrypt: RESID_ZERO\n")); - } - else { - ptext[finst->plainBlockSize - 1] = plainTextLen; - bprintf(("=== FEED encrypt: resid len 0x%x\n", plainTextLen)); - } - } - /* - * else handle evenly aligned case (i.e., finalBlock true - * and (plainTextLen == plainBlockSize)) below... - */ - deserializeGiant(ptext, finst->xp, finst->plainBlockSize); - ffree(ptext); - } - else { - deserializeGiant(plainText, finst->xp, plainTextLen); - } - - /* - * encrypt xp - * xm = xp + clue(+/-) - * determine parity needed to restore xp - * parity = ((xm + clue(+/-) == xp) ? 1 : -1 - * and adjust clue - * clue[n+1] = r * clue[n] + (s * P1) - */ - whichCurve = which_curve(finst->xp, finst->cp); - if(whichCurve == CURVE_PLUS) { - thisClue = finst->cluePlus; - thisS = finst->sPlus; - clueByte = CLUE_PLUS; - } - else { - thisClue = finst->clueMinus; - thisS = finst->sMinus; - clueByte = CLUE_MINUS; - } - // calculate xm - elliptic_add(thisClue, finst->xp, finst->xm, finst->cp, SIGN_PLUS); - // save xm + clue in tmp1 - elliptic_add(finst->xm, thisClue, finst->tmp1, finst->cp, SIGN_PLUS); - // Adjust clue - elliptic_simple(thisClue, finst->r, finst->cp); - gtog(thisClue, finst->tmp2); - elliptic_add(finst->tmp2, thisS, thisClue, finst->cp, SIGN_PLUS); - - /* - * Calculate parity - */ - if(gcompg(finst->tmp1, finst->xp) == 0) { - clueByte |= PARITY_PLUS; - } - - /* - * Ciphertext = (xm, clueByte) - */ - serializeGiant(finst->xm, cipherText, finst->cp->minBytes); - cipherText += finst->cp->minBytes; - ctextLen += finst->cp->minBytes; - *cipherText++ = clueByte; - ctextLen++; - - #if FEED_DEBUG - printf("encrypt clue %d\n", clueByte); - printf(" xp : "); printGiant(finst->xp); - printf(" xm : "); printGiant(finst->xm); - printf(" cluePlus :"); printGiant(finst->cluePlus); - printf(" clueMinus :"); printGiant(finst->clueMinus); - #endif // FEED_DEBUG - - if(finalBlock && (plainTextLen == finst->plainBlockSize)) { - /* - * Special case: finalBlock true, plainTextLen == blockSize. - * In this case we generate one more block of ciphertext, - * with a resid length of zero. - */ - unsigned moreCipher; // additional cipherLen - - frtn = feeFEEDEncryptBlock(feed, - NULL, // plainText not used - 0, // resid - cipherText, // append... - &moreCipher, - 1); - if(frtn == FR_Success) { - ctextLen += moreCipher; - } - } - bprintf(("=== FEED encryptBlock ptextLen 0x%x ctextLen 0x%x\n", - plainTextLen, ctextLen)); - - *cipherTextLen = ctextLen; - return frtn; -} - -/* - * Decrypt (exactly) a block of data. Caller malloc's plainText. Always - * generates feeFEEDPlainBlockSize of plaintext, unless finalBlock is - * non-zero (in which case feeFEEDPlainBlockSize or less bytes of plainText are - * generated). - */ -feeReturn feeFEEDDecryptBlock(feeFEED feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // RETURNED - int finalBlock) -{ - feedInst *finst = (feedInst *) feed; - feeReturn frtn = FR_Success; - unsigned char clueByte; - giant thisClue; // not alloc'd - giant thisS; // ditto - int parity; - - if(finst->rsCtext == NULL) { - /* - * Init'd for encrypt? - */ - return FR_IllegalArg; - } - if(cipherTextLen != finst->cipherBlockSize) { - dbgLog(("feeFEEDDecryptBlock: bad cipherTextLen\n")); - return FR_IllegalArg; - } - if(finst->rsBlockCount < finst->rsSizeCipherBlocks) { - /* - * Processing initialRS, FEEDExp-encrypted - */ - unsigned char *rsPtr = finst->rsCtext + - (finst->rsBlockCount * finst->cipherBlockSize); - unsigned feedExpCipherSize; - - if(finalBlock) { - dbgLog(("feeFEEDDecryptBlock: incomplete initialRS\n")); - return FR_BadCipherText; - } - bcopy(cipherText, rsPtr, finst->cipherBlockSize); - finst->rsBlockCount++; - if(finst->rsBlockCount < finst->rsSizeCipherBlocks) { - /* - * Not done with this yet... - */ - bprintf(("=== FEED Decrypt: gobbled 0x%x bytes ctext, no ptext (1)\n", - cipherTextLen)); - *plainTextLen = 0; - return FR_Success; - } - - #if FEED_DEBUG - if((finst->rsBlockCount * finst->cipherBlockSize) < - finst->rsCtextSize) { - dbgLog(("feeFEEDDecryptBlock: rsCtextSize underflow!\n")); - return FR_Internal; - } - #endif // FEED_DEBUG - - /* - * OK, we should have the FEEDExp ciphertext for initialRS - * in rsCtext. Note the last few bytes are extra; we don't - * pass them to FEEDExp. - */ - feedExpCipherSize = feeFEEDCipherBlockSize(finst->feedExp); - frtn = feeFEEDExpDecrypt(finst->feedExp, - finst->rsCtext, - finst->rsCtextSize, - &finst->initialRS, - &finst->initialRSSize); - if(frtn) { - dbgLog(("feeFEEDDecryptBlock: error decrypting " - "initialRS (%s)\n", feeReturnString(frtn))); - return FR_BadCipherText; - } - - /* - * we already know how long this should be... - */ - if(finst->initialRSSize != finst->initialRSSize) { - dbgLog(("feeFEEDDecryptBlock: initialRS sync error\n")); - return FR_BadCipherText; - } - - /* - * Set up clues - */ - if(initFromRS(finst)) { - dbgLog(("feeFEEDDecryptBlock: bad initialRS\n")); - return FR_BadCipherText; - } - else { - /* - * Normal completion of last cipherblock containing - * initialRS. - */ - bprintf(("=== FEED Decrypt: gobbled 0x%x bytes ctext, no ptext (2)\n", - cipherTextLen)); - *plainTextLen = 0; - return FR_Success; - } - } - - /* - * grab xm and clueByte from cipherText - */ - deserializeGiant(cipherText, finst->xm, finst->cp->minBytes); - cipherText += finst->cp->minBytes; - clueByte = *cipherText; - - if((clueByte & CLUE_BIT) == CLUE_PLUS) { - thisClue = finst->cluePlus; - thisS = finst->sPlus; - } - else { - thisClue = finst->clueMinus; - thisS = finst->sMinus; - } - if((clueByte & PARITY_BIT) == PARITY_PLUS) { - parity = SIGN_PLUS; - } - else { - parity = SIGN_MINUS; - } - - /* - * recover xp - * xp = xm + clue(+/-) w/parity - * adjust clue - * clue[n+1] = r * clue[n] + (s * P1) - */ - elliptic_add(thisClue, finst->xm, finst->xp, finst->cp, parity); - - elliptic_simple(thisClue, finst->r, finst->cp); - gtog(thisClue, finst->tmp1); - elliptic_add(finst->tmp1, thisS, thisClue, finst->cp, SIGN_PLUS); - - /* - * plaintext in xp - */ - #if FEED_DEBUG - printf("decrypt clue %d\n", clueByte); - printf(" xp : "); printGiant(finst->xp); - printf(" xm : "); printGiant(finst->xm); - printf(" cluePlus :"); printGiant(finst->cluePlus); - printf(" clueMinus :"); printGiant(finst->clueMinus); - #endif // FEED_DEBUG - - if(finalBlock) { - /* - * Snag data from xp in order to find out how much to move to - * *plainText - */ - unsigned char *ptext = (unsigned char*) fmalloc(finst->plainBlockSize); - - serializeGiant(finst->xp, ptext, finst->plainBlockSize); - *plainTextLen = ptext[finst->plainBlockSize - 1]; - if(*plainTextLen == RESID_ZERO) { - bprintf(("=== FEED Decrypt: RESID_ZERO\n")); - *plainTextLen = 0; - } - else if(*plainTextLen > (finst->plainBlockSize - 1)) { - dbgLog(("feeFEEDDecryptBlock: ptext overflow!\n")); - bprintf(("feeFEEDDecryptBlock: ptext overflow!\n")); - frtn = FR_BadCipherText; - } - else { - bprintf(("=== FEED Decrypt: resid len 0x%x\n", *plainTextLen)); - bcopy(ptext, plainText, *plainTextLen); - } - ffree(ptext); - } - else { - *plainTextLen = finst->plainBlockSize; - serializeGiant(finst->xp, plainText, *plainTextLen); - } - bprintf(("=== FEED decryptBlock ptextLen 0x%x ctextLen 0x%x\n", - *plainTextLen, cipherTextLen)); - - return frtn; -} - -/* - * Convenience routines to encrypt & decrypt multi-block data. - */ -feeReturn feeFEEDEncrypt(feeFEED feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char **cipherText, // malloc'd and RETURNED - unsigned *cipherTextLen) // RETURNED -{ - const unsigned char *ptext; // per block - unsigned ptextLen; // total to go - unsigned thisPtextLen; // per block - unsigned char *ctext; // per block - unsigned ctextLen; // per block - unsigned char *ctextResult; // to return - unsigned ctextResultLen; // size of ctextResult - unsigned char *ctextPtr; - unsigned ctextLenTotal; // running total - feeReturn frtn; - int finalBlock; - unsigned numBlocks; - unsigned plainBlockSize; - #if FEE_DEBUG - unsigned expectedCtextSize; - - expectedCtextSize = feeFEEDCipherTextSize(feed, plainTextLen, 1); - #endif - - if(plainTextLen == 0) { - dbgLog(("feeFEEDDecrypt: NULL plainText\n")); - return FR_IllegalArg; - } - - ptext = plainText; - ptextLen = plainTextLen; - ctext = (unsigned char*) fmalloc(feeFEEDCipherBufSize(feed, 1)); - plainBlockSize = feeFEEDPlainBlockSize(feed); - numBlocks = (plainTextLen + plainBlockSize - 1)/plainBlockSize; - - /* - * Calculate the worst-case size needed to hold all of the ciphertext - */ - ctextResultLen = feeFEEDCipherTextSize(feed, plainTextLen, 1); - ctextResult = (unsigned char*) fmalloc(ctextResultLen); - ctextPtr = ctextResult; - ctextLenTotal = 0; - - while(1) { - if(ptextLen <= plainBlockSize) { - finalBlock = 1; - thisPtextLen = ptextLen; - } - else { - finalBlock = 0; - thisPtextLen = plainBlockSize; - } - frtn = feeFEEDEncryptBlock(feed, - ptext, - thisPtextLen, - ctext, - &ctextLen, - finalBlock); - if(frtn) { - dbgLog(("feeFEEDEncrypt: encrypt error: %s\n", - feeReturnString(frtn))); - break; - } - if(ctextLen == 0) { - dbgLog(("feeFEEDEncrypt: null ciphertext\n")); - frtn = FR_Internal; - break; - } - bcopy(ctext, ctextPtr, ctextLen); - ctextLenTotal += ctextLen; - if(ctextLenTotal > ctextResultLen) { - dbgLog(("feeFEEDEncrypt: ciphertext overflow\n")); - frtn = FR_Internal; - break; - } - if(finalBlock) { - break; - } - ctextPtr += ctextLen; - ptext += thisPtextLen; - ptextLen -= thisPtextLen; - } - - ffree(ctext); - if(frtn) { - ffree(ctextResult); - *cipherText = NULL; - *cipherTextLen = 0; - } - else { - *cipherText = ctextResult; - *cipherTextLen = ctextLenTotal; - #if FEE_DEBUG - if(expectedCtextSize != ctextLenTotal) { - printf("feeFEEDEncrypt: feeFEEDCipherTextSize error!\n"); - printf("ptext %d exp ctext %d actual ctext %d\n", - plainTextLen, - expectedCtextSize, - ctextLenTotal); - } - #endif // FEE_DEBUG - } - return frtn; - -} - -feeReturn feeFEEDDecrypt(feeFEED feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char **plainText, // malloc'd and RETURNED - unsigned *plainTextLen) // RETURNED -{ - const unsigned char *ctext; - unsigned ctextLen; // total to go - unsigned char *ptext; // per block - unsigned ptextLen; // per block - unsigned char *ptextResult; // to return - unsigned char *ptextPtr; - unsigned ptextLenTotal; // running total - feeReturn frtn = FR_Success; - int finalBlock; - unsigned numBlocks; - unsigned plainBlockSize = feeFEEDPlainBlockSize(feed); - unsigned cipherBlockSize = feeFEEDCipherBlockSize(feed); - - if(cipherTextLen % cipherBlockSize) { - dbgLog(("feeFEEDDecrypt: unaligned cipherText\n")); - return FR_BadCipherText; - } - if(cipherTextLen == 0) { - dbgLog(("feeFEEDDecrypt: NULL cipherText\n")); - return FR_BadCipherText; - } - - ptext = (unsigned char*) fmalloc(plainBlockSize); - ctext = cipherText; - ctextLen = cipherTextLen; - numBlocks = cipherTextLen / cipherBlockSize; - ptextResult = (unsigned char*) fmalloc(plainBlockSize * numBlocks); - ptextPtr = ptextResult; - ptextLenTotal = 0; - - while(ctextLen) { - if(ctextLen == cipherBlockSize) { - finalBlock = 1; - } - else { - finalBlock = 0; - } - frtn = feeFEEDDecryptBlock(feed, - ctext, - cipherBlockSize, - ptext, - &ptextLen, - finalBlock); - if(frtn) { - dbgLog(("feeFEEDDecryptBlock: %s\n", - feeReturnString(frtn))); - break; - } - if(ptextLen) { - if(ptextLen > plainBlockSize) { - dbgLog(("feeFEEDDecrypt: ptext overflow!\n")); - frtn = FR_Internal; - break; - } - bcopy(ptext, ptextPtr, ptextLen); - ptextPtr += ptextLen; - ptextLenTotal += ptextLen; - } - /* - * note ptextLen == 0 is normal termination case for - * plainTextLen % plainBlockSize == 0. - * Also expected for first 4 blocks of ciphertext; - * proceed (we break when ctextLen is exhausted). - */ - ctext += cipherBlockSize; - ctextLen -= cipherBlockSize; - } - - ffree(ptext); - if(frtn) { - ffree(ptextResult); - *plainText = NULL; - *plainTextLen = 0; - } - else { - *plainText = ptextResult; - *plainTextLen = ptextLenTotal; - } - return frtn; - -} - -#endif /* CRYPTKIT_ASYMMETRIC_ENABLE */ diff --git a/OSX/include/security_cryptkit/feeFEED.h b/OSX/include/security_cryptkit/feeFEED.h deleted file mode 100644 index ce84de8a..00000000 --- a/OSX/include/security_cryptkit/feeFEED.h +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeFEED.h - generic, portable FEED encryption object - * - * Revision History - * ---------------- - * 28 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEFEED_H_ -#define _CK_FEEFEED_H_ - -#if !defined(__MACH__) -#include -#include -#include -#else -#include -#include -#include -#endif - -#if CRYPTKIT_ASYMMETRIC_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Opaque object handle. - */ -typedef void *feeFEED; - -/* - * forEncrypt argument values. - */ -#define FF_DECRYPT 0 -#define FF_ENCRYPT 1 - -/* - * Alloc and init a feeFEED object associated with specified feePubKey - * objects. - */ -feeFEED feeFEEDNewWithPubKey(feePubKey myPrivKey, - feePubKey theirPubKey, - int forEncrypt, // FF_DECRYPT, FF_ENCRYPT - feeRandFcn randFcn, // optional - void *randRef); - -void feeFEEDFree(feeFEED feed); - -/* - * Plaintext block size. - */ -unsigned feeFEEDPlainBlockSize(feeFEED feed); - -/* - * Ciphertext block size used for decryption. - */ -unsigned feeFEEDCipherBlockSize(feeFEED feed); - -/* - * Calculate size of buffer currently needed to encrypt one block of - * plaintext. - */ -unsigned feeFEEDCipherBufSize(feeFEED feed, - int finalBlock); - -/* - * Return the size of ciphertext currently needed to encrypt specified - * size of plaintext. Also can be used to calculate size of ciphertext - * which can be decrypted into specified size of plaintext. - */ -unsigned feeFEEDCipherTextSize(feeFEED feed, - unsigned plainTextSize, - int finalBlock); - -/* - * Return the size of plaintext currently needed to decrypt specified size - * of ciphertext. Also can be used to calculate size of plaintext - * which can be encrypted into specified size of ciphertext. - */ -unsigned feeFEEDPlainTextSize(feeFEED feed, - unsigned cipherTextSize, - int finalBlock); // ignored if decrypting - -/* - * Encrypt a block or less of data. Caller malloc's cipherText. - */ -feeReturn feeFEEDEncryptBlock(feeFEED feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // RETURNED - int finalBlock); - -/* - * Decrypt (exactly) a block of data. Caller malloc's plainText. Always - * generates feeFEEDBlockSize bytes of plainText, unless 'finalBlock' is - * non-zero (in which case feeFEEDBlockSize or less bytes of plainText are - * generated). - */ -feeReturn feeFEEDDecryptBlock(feeFEED feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // RETURNED - int finalBlock); - -/* - * Convenience routines to encrypt & decrypt multi-block data. - */ -feeReturn feeFEEDEncrypt(feeFEED feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char **cipherText, // malloc'd and RETURNED - unsigned *cipherTextLen); // RETURNED - -feeReturn feeFEEDDecrypt(feeFEED feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char **plainText, // malloc'd and RETURNED - unsigned *plainTextLen); // RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_ASYMMETRIC_ENABLE */ - -#endif /*_CK_FEEFEED_H_*/ diff --git a/OSX/include/security_cryptkit/feeFEEDExp.c b/OSX/include/security_cryptkit/feeFEEDExp.c deleted file mode 100644 index 673289bb..00000000 --- a/OSX/include/security_cryptkit/feeFEEDExp.c +++ /dev/null @@ -1,735 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeFEEDExp.c - generic FEED encryption object, 2:1 expansion - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 20 Jan 1998 at Apple - * Mods for primeType == PT_GENERAL case. - * 12 Jun 1997 at Apple - * Was curveOrderJustify(), is lesserX1OrderJustify() - * 03 Mar 1997 at Apple - * Trimmed plainBlockSize by one byte if q mod 8 = 0 - * 03 Feb 97 at NeXT - * Renamed to feeFEEDExp.c - * Justified random xaux to [2, minimumX1Order] - * Added feeFEEDExpCipherTextSize() - * 15 Jan 97 at NeXT - * Cleaned up which_curve/index code to use CURVE_MINUS/CURVE_PLUS - * 28 Aug 96 at NeXT - * Created from Blaine Garst's NSFEECryptor.m. - */ - -#include "ckconfig.h" - -#if CRYPTKIT_ASYMMETRIC_ENABLE - -#include "feeTypes.h" -#include "feeFEEDExp.h" -#include "feePublicKey.h" -#include "feePublicKeyPrivate.h" -#include "elliptic.h" -#include "falloc.h" -#include "feeRandom.h" -#include "ckutilities.h" -#include "feeFunctions.h" -#include "platform.h" -#include "feeDebug.h" -#include - -#define FEED_DEBUG 0 - -#define PRINT_GIANT(g) printGiant(g) - -/* - * Format of clue byte. Currently just one bit. - */ -#define CLUE_ELL_ADD_SIGN 0x01 -#define CLUE_ELL_ADD_SIGN_PLUS 0x01 -#define CLUE_ELL_ADD_SIGN_MINUS 0x00 - -/* - * Private data. - */ -typedef struct { - key plus; - key minus; - unsigned plainBlockSize; /* plaintext block size */ - unsigned cipherBlockSize;/* ciphertext block size */ - curveParams *cp; - giant gPriv; /* private data, only for decrypt */ - /* one of the follow two is valid for encrypt */ - feeRand rand; /* only created for encrypt */ - feeRandFcn randFcn; - void *randRef; - - /* - * temporary variables used for encrypt/decrypt. The values in these - * is not needed to be kept from block to block; we just - * alloc them once per lifetime of a feeFEED object as an optimization. - */ - giant xp; /* plaintext */ - giant xc; /* clue = r(P1?) */ - giant xq; /* r(pubB?) or priB?(xc) */ - giant xm; /* ciphertext */ - giant xaux; /* scratch */ - unsigned char *randData; /* only created for encrypt */ -} feedInst; - -/* - * "zero residue" indicator. - */ -#define RESID_ZERO 0xff - -/* - * Alloc and init a feeFEEDExp object associated with specified feePubKey. - */ -feeFEEDExp feeFEEDExpNewWithPubKey( - feePubKey pubKey, - feeRandFcn randFcn, // optional - void *randRef) -{ - feedInst *finst = (feedInst *) fmalloc(sizeof(feedInst)); - giant privGiant; - - finst->cp = curveParamsCopy(feePubKeyCurveParams(pubKey)); - finst->plus = new_public_with_key(feePubKeyPlusCurve(pubKey), - finst->cp); - finst->minus = new_public_with_key(feePubKeyMinusCurve(pubKey), - finst->cp); - - /* - * These might yield NULL data; we can only encrypt in that case. - */ - privGiant = feePubKeyPrivData(pubKey); - if(privGiant) { - finst->gPriv = newGiant(finst->cp->maxDigits); - gtog(privGiant, finst->gPriv); - } - else { - finst->gPriv = NULL; - } - - /* - * Conservative, rounding down, on plaintext blocks since we don't - * want to split bytes. - */ - if(finst->cp->primeType == FPT_General) { - unsigned blen = bitlen(finst->cp->basePrime); - - finst->plainBlockSize = blen / 8; - if((blen % 8) == 0) { - /* - * round down some more... - */ - finst->plainBlockSize--; - } - } - else { - finst->plainBlockSize = finst->cp->q / 8; - if(((finst->cp->q & 0x7) == 0) && (finst->cp->k > 0)) { - /* - * Special case, with q mod 8 == 0. Here we have to trim back - * the plainBlockSize by one byte. - */ - finst->plainBlockSize--; - } - } - - /* - * One block of ciphertext - two giants (with implied sign) and a - * parity byte - */ - finst->cipherBlockSize = (2 * finst->cp->minBytes) + 1; - - finst->xp = newGiant(finst->cp->maxDigits); - finst->xc = newGiant(finst->cp->maxDigits); - finst->xq = newGiant(finst->cp->maxDigits); - finst->xm = newGiant(finst->cp->maxDigits); - finst->xaux = newGiant(finst->cp->maxDigits); - finst->rand = NULL; - finst->randData = NULL; - finst->randFcn = randFcn; - finst->randRef = randRef; - return finst; -} - -void feeFEEDExpFree(feeFEEDExp feed) -{ - feedInst *finst = (feedInst *) feed; - - free_key(finst->plus); - free_key(finst->minus); - freeGiant(finst->xc); - clearGiant(finst->xp); freeGiant(finst->xp); - clearGiant(finst->xq); freeGiant(finst->xq); - freeGiant(finst->xm); - clearGiant(finst->xaux); freeGiant(finst->xaux); - if(finst->gPriv) { - clearGiant(finst->gPriv); - freeGiant(finst->gPriv); - } - if(finst->rand) { - feeRandFree(finst->rand); - } - if(finst->randData) { - ffree(finst->randData); - } - if(finst->cp) { - freeCurveParams(finst->cp); - } - ffree(finst); -} - -unsigned feeFEEDExpPlainBlockSize(feeFEEDExp feed) -{ - feedInst *finst = (feedInst *) feed; - - return finst->plainBlockSize; -} - -unsigned feeFEEDExpCipherBlockSize(feeFEEDExp feed) -{ - feedInst *finst = (feedInst *) feed; - - return finst->cipherBlockSize; -} - -unsigned feeFEEDExpCipherBufSize(feeFEEDExp feed) -{ - feedInst *finst = (feedInst *) feed; - - return 2 * finst->cipherBlockSize; -} - -/* - * Return the size of ciphertext to hold specified size of plaintext. - */ -unsigned feeFEEDExpCipherTextSize(feeFEEDExp feed, unsigned plainTextSize) -{ - /* - * Normal case is one block of ciphertext for each block of - * plaintext. Add one cipherBlock if - * plainTextSize % plainBlockSize == 0. - */ - feedInst *finst = (feedInst *) feed; - unsigned blocks = (plainTextSize + finst->plainBlockSize - 1) / - finst->plainBlockSize; - - if((plainTextSize % finst->plainBlockSize) == 0) { - blocks++; - } - return blocks * finst->cipherBlockSize; -} - -/* - * Return the size of plaintext to hold specified size of decrypted ciphertext. - */ -unsigned feeFEEDExpPlainTextSize(feeFEEDExp feed, unsigned cipherTextSize) -{ - feedInst *finst = (feedInst *) feed; - unsigned blocks = (cipherTextSize + finst->cipherBlockSize - 1) / - finst->cipherBlockSize; - - return blocks * finst->plainBlockSize; -} - -/* - * Encrypt a block or less of data. Caller malloc's cipherText. - */ -feeReturn feeFEEDExpEncryptBlock(feeFEEDExp feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // RETURNED - int finalBlock) -{ - feedInst *finst = (feedInst *) feed; - int index; /* which curve (+/- 1) */ - char g = 0; /* parity, which_curve bits in ciphertext */ - key B; - unsigned char *ptext; /* for final block */ - unsigned ctextLen; - feeReturn frtn = FR_Success; - giant x1; - unsigned randLen; - curveParams *cp = finst->cp; - randLen = cp->minBytes+8; // +8bytes (64bits) to reduce the biais when with reduction mod prime. Per FIPS186-4 - "Using Extra Random Bits" - - if(plainTextLen > finst->plainBlockSize) { - return FR_IllegalArg; - } - else if ((plainTextLen < finst->plainBlockSize) && !finalBlock) { - return FR_IllegalArg; - } - - /* - * Init only on first encrypt - */ - if((finst->randFcn == NULL) && (finst->rand == NULL)) { - finst->rand = feeRandAlloc(); - } - if(finst->randData == NULL) { - finst->randData = (unsigned char*) fmalloc(randLen); - } - - /* - * plaintext as giant xp - */ - if(finalBlock) { - ptext = (unsigned char*) fmalloc(finst->plainBlockSize); - bzero(ptext, finst->plainBlockSize); - if(plainTextLen) { - /* - * 0 for empty block with resid length 0 - */ - bcopy(plainText, ptext, plainTextLen); - } - if(plainTextLen < finst->plainBlockSize) { - if(plainTextLen == 0) { - /* - * Special case - can't actually write zero here; - * it screws up deserializing the giant during - * decrypt - */ - ptext[finst->plainBlockSize - 1] = RESID_ZERO; - } - else { - ptext[finst->plainBlockSize - 1] = plainTextLen; - } - #if FEED_DEBUG - printf("encrypt: resid 0x%x\n", ptext[finst->plainBlockSize - 1]); - #endif - } - /* - * else handle evenly aligned case below... - */ - deserializeGiant(ptext, finst->xp, finst->plainBlockSize); - ffree(ptext); - } - else { - deserializeGiant(plainText, finst->xp, plainTextLen); - } - #if FEED_DEBUG - printf("encrypt:\n"); - printf(" xp : "); PRINT_GIANT(finst->xp); - #endif // FEED_DEBUG - - /* - * pick curve B? that data lies upon - */ - index = which_curve(finst->xp, finst->cp); - if(index == CURVE_PLUS) { - B = finst->plus; - x1 = finst->cp->x1Plus; - } - else { - B = finst->minus; - x1 = finst->cp->x1Minus; - } - #if FEED_DEBUG - printf(" which_curve: %s\n", - (index == CURVE_PLUS) ? "CURVE_PLUS" : "CURVE_MINUS"); - #endif - - /* - * random number as giant xaux - */ - if(finst->randFcn != NULL) { - finst->randFcn(finst->randRef, finst->randData, randLen); - } - else { - feeRandBytes(finst->rand, finst->randData, randLen); - } - deserializeGiant(finst->randData, finst->xaux, randLen); - - #if FEE_DEBUG - if(isZero(finst->xaux)) { - printf("feeFEEDExpEncryptBlock: random xaux = 0!\n"); - } - #endif // FEE_DEBUG - /* - * Justify random # to be in [2, minimumX1Order]. - */ - lesserX1OrderJustify(finst->xaux, cp); - #if FEED_DEBUG - printf(" xaux: "); PRINT_GIANT(finst->xaux); - #endif // FEED_DEBUG - - gtog(B->x, finst->xq); // xq = pubB? - elliptic_simple(finst->xq, finst->xaux, cp); - // xq = r(pubB?) - #if FEED_DEBUG - printf(" r(pubB?): "); PRINT_GIANT(finst->xq); - #endif - elliptic_add(finst->xp, finst->xq, finst->xm, cp, SIGN_PLUS); - // xm = data + r(pubB?) - gtog(x1, finst->xc); - elliptic_simple(finst->xc, finst->xaux, cp); - // xc = r(P1?) - elliptic_add(finst->xm, finst->xq, finst->xaux, cp, SIGN_PLUS); - // xaux = xm + xq (for curve +1) - // = (data + r(pubB?)) + r(pubB?) - if(gcompg(finst->xaux, finst->xp) == 0) { - g |= CLUE_ELL_ADD_SIGN_PLUS; - } - else { - g |= CLUE_ELL_ADD_SIGN_MINUS; - #if FEED_DEBUG - /* this better be true.... */ - elliptic_add(finst->xm, finst->xq, finst->xaux, cp, SIGN_MINUS); - if(gcompg(finst->xaux, finst->xp)) { - printf("*******elliptic_add(xm, xq, -1) != xp! *************\n"); - printf(" xq : "); PRINT_GIANT(finst->xq); - printf(" ell_add(xm, xq, -1) : "); PRINT_GIANT(finst->xaux); - } - #endif - } // g = (xaux == data) ? add : subtract - - /* - * Ciphertext = (xm, xc, g) - */ - serializeGiant(finst->xm, cipherText, cp->minBytes); - cipherText += cp->minBytes; - serializeGiant(finst->xc, cipherText, cp->minBytes); - cipherText += cp->minBytes; - *cipherText++ = g; - ctextLen = finst->cipherBlockSize; - #if FEED_DEBUG - printf(" xm : "); PRINT_GIANT(finst->xm); - printf(" xc : "); PRINT_GIANT(finst->xc); - printf(" g : %d\n", g); - #endif // FEED_DEBUG - if(finalBlock && (plainTextLen == finst->plainBlockSize)) { - /* - * Special case: finalBlock true, plainTextLen == blockSize. - * In this case we generate one more block of ciphertext, - * with a resid length of zero. - */ - unsigned moreCipher; // additional cipherLen - - #if FEED_DEBUG - printf("encrypt: one more empty block\n"); - #endif - frtn = feeFEEDExpEncryptBlock(feed, - NULL, // plainText not used - 0, // resid - cipherText, // append... - &moreCipher, - 1); - if(frtn == FR_Success) { - ctextLen += moreCipher; - } - } - - *cipherTextLen = ctextLen; - return frtn; -} - -/* - * Decrypt (exactly) a block of data. Caller malloc's plainText. Always - * generates feeFEEDExpPlainBlockSize of plaintext, unless finalBlock is - * non-zero (in which case feeFEEDExpPlainBlockSize or less bytes of - * plainText are generated). - */ -feeReturn feeFEEDExpDecryptBlock(feeFEEDExp feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // RETURNED - int finalBlock) -{ - feedInst *finst = (feedInst *) feed; - char g; - int s; - feeReturn frtn = FR_Success; - curveParams *cp = finst->cp; - - if(finst->gPriv == NULL) { - /* - * Can't decrypt without private data - */ - return FR_BadPubKey; - } - - /* - * grab xm, xc, and g from cipherText - */ - deserializeGiant(cipherText, finst->xm, finst->cp->minBytes); - cipherText += finst->cp->minBytes; - deserializeGiant(cipherText, finst->xc, finst->cp->minBytes); - cipherText += finst->cp->minBytes; - g = *cipherText; - #if FEED_DEBUG - printf("decrypt g=%d\n", g); - printf(" privKey : "); PRINT_GIANT(finst->gPriv); - printf(" xm : "); PRINT_GIANT(finst->xm); - printf(" xc : "); PRINT_GIANT(finst->xc); - #endif // FEED_DEBUG - - if((g & CLUE_ELL_ADD_SIGN) == CLUE_ELL_ADD_SIGN_PLUS) { - s = SIGN_PLUS; - } - else { - s = SIGN_MINUS; - } - - /* - * xc = r(P1?) - * xc := r(P1?)(pri) = xq - * xp = data + r(priB+) +/- pri(rB?) - */ - elliptic_simple(finst->xc, finst->gPriv, cp); - #if FEED_DEBUG - printf(" xc1 : "); PRINT_GIANT(finst->xc); - #endif - elliptic_add(finst->xm, finst->xc, finst->xp, cp, s); - - /* - * plaintext in xp - */ - #if FEED_DEBUG - printf(" xp : "); PRINT_GIANT(finst->xp); - #endif // FEED_DEBUG - - if(finalBlock) { - /* - * Snag data from xp in order to find out how much to move to - * *plainText - */ - unsigned char *ptext = (unsigned char*) fmalloc(finst->plainBlockSize); - - serializeGiant(finst->xp, ptext, finst->plainBlockSize); - *plainTextLen = ptext[finst->plainBlockSize - 1]; - #if FEED_DEBUG - printf("decrypt: resid 0x%x\n", *plainTextLen); - #endif - if(*plainTextLen == RESID_ZERO) { - *plainTextLen = 0; - } - else if(*plainTextLen > (finst->plainBlockSize - 1)) { - dbgLog(("feeFEEDExpDecryptBlock: ptext overflow!\n")); - frtn = FR_BadCipherText; - } - else { - bcopy(ptext, plainText, *plainTextLen); - } - ffree(ptext); - } - else { - *plainTextLen = finst->plainBlockSize; - serializeGiant(finst->xp, plainText, *plainTextLen); - } - return frtn; -} - -/* - * Convenience routines to encrypt & decrypt multi-block data. - */ -feeReturn feeFEEDExpEncrypt(feeFEEDExp feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char **cipherText, // malloc'd and RETURNED - unsigned *cipherTextLen) // RETURNED -{ - const unsigned char *ptext; // per block - unsigned ptextLen; // total to go - unsigned thisPtextLen; // per block - unsigned char *ctext; // per block - unsigned ctextLen; // per block - unsigned char *ctextResult; // to return - unsigned ctextResultLen; - unsigned char *ctextPtr; - unsigned ctextLenTotal; // running total - feeReturn frtn; - int finalBlock; - unsigned numBlocks; - unsigned plainBlockSize; - - if(plainTextLen == 0) { - dbgLog(("feeFEEDExpDecrypt: NULL plainText\n")); - return FR_IllegalArg; - } - - ptext = plainText; - ptextLen = plainTextLen; - ctext = (unsigned char*) fmalloc(feeFEEDExpCipherBufSize(feed)); - plainBlockSize = feeFEEDExpPlainBlockSize(feed); - numBlocks = (plainTextLen + plainBlockSize - 1)/plainBlockSize; - ctextResultLen = (numBlocks + 1) * feeFEEDExpCipherBlockSize(feed); - ctextResult = (unsigned char*) fmalloc(ctextResultLen); - ctextPtr = ctextResult; - ctextLenTotal = 0; - - while(1) { - if(ptextLen <= plainBlockSize) { - finalBlock = 1; - thisPtextLen = ptextLen; - } - else { - finalBlock = 0; - thisPtextLen = plainBlockSize; - } - frtn = feeFEEDExpEncryptBlock(feed, - ptext, - thisPtextLen, - ctext, - &ctextLen, - finalBlock); - if(frtn) { - dbgLog(("feeFEEDExpEncrypt: encrypt error: %s\n", - feeReturnString(frtn))); - break; - } - if(ctextLen == 0) { - dbgLog(("feeFEEDExpEncrypt: null ciphertext\n")); - frtn = FR_Internal; - break; - } - bcopy(ctext, ctextPtr, ctextLen); - ctextLenTotal += ctextLen; - if(ctextLenTotal > ctextResultLen) { - dbgLog(("feeFEEDExpEncrypt: ciphertext overflow\n")); - frtn = FR_Internal; - break; - } - if(finalBlock) { - break; - } - ctextPtr += ctextLen; - ptext += thisPtextLen; - ptextLen -= thisPtextLen; - } - - ffree(ctext); - if(frtn) { - ffree(ctextResult); - *cipherText = NULL; - *cipherTextLen = 0; - } - else { - *cipherText = ctextResult; - *cipherTextLen = ctextLenTotal; - #if FEE_DEBUG - if(feeFEEDExpCipherTextSize(feed, plainTextLen) != - ctextLenTotal) { - printf("feeFEEDExpEncrypt: feeFEEDCipherTextSize " - "error!\n"); - printf("ptext %d exp ctext %d actual ctext %d\n", - plainTextLen, - feeFEEDExpCipherTextSize(feed, plainTextLen), - ctextLenTotal); - } - #endif // FEE_DEBUG - } - return frtn; - -} - -feeReturn feeFEEDExpDecrypt(feeFEEDExp feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char **plainText, // malloc'd and RETURNED - unsigned *plainTextLen) // RETURNED -{ - const unsigned char *ctext; - unsigned ctextLen; // total to go - unsigned char *ptext; // per block - unsigned ptextLen; // per block - unsigned char *ptextResult; // to return - unsigned char *ptextPtr; - unsigned ptextLenTotal; // running total - feeReturn frtn = FR_Success; - int finalBlock; - unsigned numBlocks; - unsigned plainBlockSize = - feeFEEDExpPlainBlockSize(feed); - unsigned cipherBlockSize = - feeFEEDExpCipherBlockSize(feed); - - if(cipherTextLen % cipherBlockSize) { - dbgLog(("feeFEEDExpDecrypt: unaligned cipherText\n")); - return FR_BadCipherText; - } - if(cipherTextLen == 0) { - dbgLog(("feeFEEDExpDecrypt: NULL cipherText\n")); - return FR_BadCipherText; - } - - ptext = (unsigned char*) fmalloc(plainBlockSize); - ctext = cipherText; - ctextLen = cipherTextLen; - numBlocks = cipherTextLen / cipherBlockSize; - ptextResult = (unsigned char*) fmalloc(plainBlockSize * numBlocks); - ptextPtr = ptextResult; - ptextLenTotal = 0; - - while(ctextLen) { - if(ctextLen == cipherBlockSize) { - finalBlock = 1; - } - else { - finalBlock = 0; - } - frtn = feeFEEDExpDecryptBlock(feed, - ctext, - cipherBlockSize, - ptext, - &ptextLen, - finalBlock); - if(frtn) { - dbgLog(("feeFEEDExpDecryptBlock: %s\n", - feeReturnString(frtn))); - break; - } - if(ptextLen == 0) { - /* - * Normal termination case for - * plainTextLen % plainBlockSize == 0 - */ - if(!finalBlock) { - dbgLog(("feeFEEDExpDecrypt: decrypt sync" - " error!\n")); - frtn = FR_BadCipherText; - } - break; - } - else if(ptextLen > plainBlockSize) { - dbgLog(("feeFEEDExpDecrypt: ptext overflow!\n")); - frtn = FR_Internal; - break; - } - else { - bcopy(ptext, ptextPtr, ptextLen); - ptextPtr += ptextLen; - ptextLenTotal += ptextLen; - } - ctext += cipherBlockSize; - ctextLen -= cipherBlockSize; - } - - ffree(ptext); - if(frtn) { - ffree(ptextResult); - *plainText = NULL; - *plainTextLen = 0; - } - else { - *plainText = ptextResult; - *plainTextLen = ptextLenTotal; - } - return frtn; - -} - -#endif /* CRYPTKIT_ASYMMETRIC_ENABLE */ diff --git a/OSX/include/security_cryptkit/feeFEEDExp.h b/OSX/include/security_cryptkit/feeFEEDExp.h deleted file mode 100644 index aa190379..00000000 --- a/OSX/include/security_cryptkit/feeFEEDExp.h +++ /dev/null @@ -1,126 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeFEEDExp.h - generic FEED encryption object using 2:1 expansion - * - * Revision History - * ---------------- - * 28 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEFEEDEXP_H_ -#define _CK_FEEFEEDEXP_H_ - -#if !defined(__MACH__) -#include -#include -#include -#else -#include -#include -#include -#endif - -#if CRYPTKIT_ASYMMETRIC_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Opaque object handle. - */ -typedef void *feeFEEDExp; - -/* - * Alloc and init a feeFEEDExp object associated with specified feePubKey. - */ -feeFEEDExp feeFEEDExpNewWithPubKey( - feePubKey pubKey, - feeRandFcn randFcn, // optional - void *randRef); - -void feeFEEDExpFree(feeFEEDExp feed); - -/* - * Plaintext block size. - */ -unsigned feeFEEDExpPlainBlockSize(feeFEEDExp feed); - -/* - * Ciphertext block size used for decryption. - */ -unsigned feeFEEDExpCipherBlockSize(feeFEEDExp feed); - -/* - * Required size of buffer for ciphertext, upon encrypting one - * block of plaintext. - */ -unsigned feeFEEDExpCipherBufSize(feeFEEDExp feed); - -/* - * Return the size of ciphertext to hold specified size of encrypted plaintext. - */ -unsigned feeFEEDExpCipherTextSize(feeFEEDExp feed, unsigned plainTextSize); - -/* - * Return the size of plaintext to hold specified size of decrypted ciphertext. - */ -unsigned feeFEEDExpPlainTextSize(feeFEEDExp feed, unsigned cipherTextSize); - -/* - * Encrypt a block or less of data. Caller malloc's cipherText. Generates - * feeFEEDExpCipherBlockSize() bytes of cipherText if finalBlock is false; - * if finalBlock is true it could produce twice as much ciphertext. - * If plainTextLen is less than feeFEEDExpPlainBlockSize(), finalBlock must be true. - */ -feeReturn feeFEEDExpEncryptBlock(feeFEEDExp feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char *cipherText, - unsigned *cipherTextLen, // RETURNED - int finalBlock); - -/* - * Decrypt (exactly) a block of data. Caller malloc's plainText. Always - * generates feeFEEDExpBlockSize bytes of plainText, unless 'finalBlock' is - * non-zero (in which case feeFEEDExpBlockSize or less bytes of plainText are - * generated). - */ -feeReturn feeFEEDExpDecryptBlock(feeFEEDExp feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char *plainText, - unsigned *plainTextLen, // RETURNED - int finalBlock); - -/* - * Convenience routines to encrypt & decrypt multi-block data. - */ -feeReturn feeFEEDExpEncrypt(feeFEEDExp feed, - const unsigned char *plainText, - unsigned plainTextLen, - unsigned char **cipherText, // malloc'd and RETURNED - unsigned *cipherTextLen); // RETURNED - -feeReturn feeFEEDExpDecrypt(feeFEEDExp feed, - const unsigned char *cipherText, - unsigned cipherTextLen, - unsigned char **plainText, // malloc'd and RETURNED - unsigned *plainTextLen); // RETURNED - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_ASYMMETRIC_ENABLE */ - -#endif /*_CK_FEEFEEDEXP_H_*/ diff --git a/OSX/include/security_cryptkit/feeFunctions.h b/OSX/include/security_cryptkit/feeFunctions.h deleted file mode 100644 index 928fb5c5..00000000 --- a/OSX/include/security_cryptkit/feeFunctions.h +++ /dev/null @@ -1,69 +0,0 @@ -/* Copyright (c) 1998,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeFunctions.h - general public function declarations - * - * Revision History - * ---------------- - * 8/25/98 ap - * Fixed previous check-in comment. - * 8/24/98 ap - * Added tags around #endif comment. - * 23 Mar 98 at Apple - * Added initCryptKit(). - * 27 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEFUNCTIONS_H_ -#define _CK_FEEFUNCTIONS_H_ - -#ifdef macintosh -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * One-time only init of CryptKit library. - */ -void initCryptKit(void); - -/* - * Shutdown. - */ -void terminateCryptKit(void); - -#if defined(NeXT) && !defined(WIN32) - -#define PHRASELEN 128 - -/* - * Prompt for password, get it in secure manner. Max password length is - * PHRASELEN. NEXTSTEP only. - */ -extern void getpassword(const char *prompt, char *pbuf); - -#endif /* NeXT */ - -/* - * obtain a string describing a feeReturn. - */ -extern const char *feeReturnString(feeReturn frtn); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_FEEFUNCTIONS_H_*/ diff --git a/OSX/include/security_cryptkit/feeHash.c b/OSX/include/security_cryptkit/feeHash.c deleted file mode 100644 index b193af24..00000000 --- a/OSX/include/security_cryptkit/feeHash.c +++ /dev/null @@ -1,110 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeHash.c - generic, portable MD5 hash object - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 22 Aug 96 at NeXT - * Created. - */ - -#include "ckconfig.h" - -#if CRYPTKIT_MD5_ENABLE - -#include "feeTypes.h" -#include "feeHash.h" -#include "ckMD5.h" -#include "falloc.h" -#include "platform.h" - -/* - * Private data for this object. A feeHash handle is cast to aa pointer - * to one of these. - */ -typedef struct { - MD5Context context; - int isDone; - unsigned char digest[MD5_DIGEST_SIZE]; -} hashInst; - -/* - * Alloc and init an empty hash object. - */ -feeHash feeHashAlloc(void) -{ - hashInst *hinst; - - hinst = (hashInst *) fmalloc(sizeof(hashInst)); - MD5Init(&hinst->context); - hinst->isDone = 0; - return hinst; -} - -void feeHashReinit(feeHash hash) -{ - hashInst *hinst = (hashInst *) hash; - - MD5Init(&hinst->context); - hinst->isDone = 0; -} - -/* - * Free a hash object. - */ -void feeHashFree(feeHash hash) -{ - hashInst *hinst = (hashInst *) hash; - - memset(hinst, 0, sizeof(hashInst)); - ffree(hinst); -} - -/* - * Add some data to the hash object. - */ -void feeHashAddData(feeHash hash, - const unsigned char *data, - unsigned dataLen) -{ - hashInst *hinst = (hashInst *) hash; - - if(hinst->isDone) { - /* - * Log some kind of error here... - */ - return; - } - MD5Update(&hinst->context, data, dataLen); -} - -/* - * Obtain a pointer to completed message digest, and the length of the digest. - */ -unsigned char *feeHashDigest(feeHash hash) -{ - hashInst *hinst = (hashInst *) hash; - - if(!hinst->isDone) { - MD5Final(&hinst->context, hinst->digest); - hinst->isDone = 1; - } - return hinst->digest; -} - -unsigned feeHashDigestLen(void) -{ - return MD5_DIGEST_SIZE; -} - -#endif /* CRYPTKIT_MD5_ENABLE*/ diff --git a/OSX/include/security_cryptkit/feeHash.h b/OSX/include/security_cryptkit/feeHash.h deleted file mode 100644 index bcb66398..00000000 --- a/OSX/include/security_cryptkit/feeHash.h +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeHash.h - generic, portable MD5 hash object - * - * Revision History - * ---------------- - * 22 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEHASH_H_ -#define _CK_FEEHASH_H_ - -#if !defined(__MACH__) -#include -#include -#else -#include -#include -#endif - -#if CRYPTKIT_MD5_ENABLE - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Opaque hash object handle. - */ -typedef void *feeHash; - -/* - * Alloc and init an empty hash object. - */ -feeHash feeHashAlloc(void); - -/* - * reinitialize a hash object for reuse. - */ -void feeHashReinit(feeHash hash); - -/* - * Free a hash object. - */ -void feeHashFree(feeHash hash); - -/* - * Add some data to the hash object. - */ -void feeHashAddData(feeHash hash, - const unsigned char *data, - unsigned dataLen); - -/* - * Obtain a pointer to completed message digest. This disables further calls - * to feeHashAddData(). This pointer is NOT malloc'd; the associated data - * persists only as long as this object does. - */ -unsigned char *feeHashDigest(feeHash hash); - -/* - * Obtain the length of the message digest. - */ -unsigned feeHashDigestLen(void); - -#ifdef __cplusplus -} -#endif - -#endif /* CRYPTKIT_MD5_ENABLE */ - -#endif /*_CK_FEEHASH_H_*/ diff --git a/OSX/include/security_cryptkit/feePublicKey.c b/OSX/include/security_cryptkit/feePublicKey.c deleted file mode 100644 index 3105723a..00000000 --- a/OSX/include/security_cryptkit/feePublicKey.c +++ /dev/null @@ -1,1612 +0,0 @@ -/* Copyright (c) 1998,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feePublicKey.c - Portable FEE public key object. - * - * Revision History - * ---------------- - * 11/27/98 dmitch - * Added ECDSA_VERIFY_ONLY dependencies. - * 10/06/98 ap - * Changed to compile with C++. - * 9 Sep 98 at NeXT - * Major changes for IEEE P1363 compliance. - * 23 Mar 98 at Apple - * Added blob support. - * 21 Jan 98 at Apple - * Fixed feePubKeyBitsize bitlen bug for PT_GENERAL case. - * 05 Jan 98 at Apple - * ECDSA now uses SHA-1 hash. Imcompatible with old ECDSA signatures. - * 17 Jul 97 at Apple - * Added ECDSA signature routines. - * 12 Jun 97 at Apple - * Added feePubKeyInitGiants() - * Deleted obsolete code - * Changes for lesserX1OrderJustify (was curveOrderJustify) - * 31 Mar 97 at Apple - * Fixed leak in feePubKeyCreateKeyString() - * 15 Jan 97 at NeXT - * PUBLIC_KEY_STRING_VERSION = 3; broke compatibility with all older - * versions. - * Cleaned up which_curve/index code to use CURVE_MINUS/CURVE_PLUS. - * 12 Dec 96 at NeXT - * Added initFromEnc64KeyStr(). - * 20 Aug 96 at NeXT - * Ported to C. - * ???? 1994 Blaine Garst at NeXT - * Created. - */ - -#include "ckconfig.h" -#include "feePublicKey.h" -#include "feePublicKeyPrivate.h" -#include "ckutilities.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "curveParams.h" -#include "falloc.h" -#include "feeTypes.h" -#include "feeDebug.h" -#include "feeHash.h" -#include "ckSHA1.h" -#include "feeDigitalSignature.h" -#include "feeECDSA.h" -#include "platform.h" -#include "enc64.h" -#include "feeDES.h" -#include "byteRep.h" -#if CRYPTKIT_DER_ENABLE -#include "CryptKitDER.h" -#endif -#include - -/* - * 11/27/98 dmitch: The ECDSA_VERIFY_ONLY symbol, when #defined, disables all - * of the code in this module except that which is necessary for ECDSA - * siggnature verification. - */ - -#ifndef NULL -#define NULL ((void *)0) -#endif // NULL - -/* - * Magic number for a portable key blobs. Must be in sync with static - * final PUBLIC_KEY_STRING_MAGIC in JavaFee/PublicKey.java. - */ -#define PUBLIC_KEY_BLOB_MAGIC_PUB 0xfeeddeef -#define PUBLIC_KEY_BLOB_MAGIC_PRIV 0xfeeddeed -#define PUBLIC_KEY_BLOB_VERSION 6 -#define PUBLIC_KEY_BLOB_MINVERSION 6 - -#if CRYPTKIT_DER_ENABLE -#define PUBLIC_DER_KEY_BLOB_VERSION 1 -#endif - -/* - * Private data. All "instance" routines are passed a feePubKey (actually - * a void *) which is actually a pointer to one of these. - */ -typedef struct { - key plus; - key minus; // not needed for ECDSA - curveParams *cp; // common params shared by minus, plus - giant privGiant; // private key -} pubKeyInst; - -static feeReturn feeGenPrivate(pubKeyInst *pkinst, - const unsigned char *passwd, - unsigned passwdLen, - char hashPasswd); -static pubKeyInst *pubKeyInstAlloc(void); -static void pubKeyInstFree(pubKeyInst *pkinst); -#if GIANTS_VIA_STACK -static void feePubKeyInitGiants(void); -#endif -static feeReturn createKeyBlob(pubKeyInst *pkinst, - int isPrivate, // 0 : public 1 : private - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED -static feeReturn feePubKeyInitFromKeyBlob(feePubKey pubKey, - unsigned char *keyBlob, - unsigned keyBlobLen); - -#pragma mark --- General public API function --- - -/* - * Obatin a newly allocated feePubKey. - */ -feePubKey feePubKeyAlloc(void) -{ - pubKeyInst *pkinst = pubKeyInstAlloc(); - - #if GIANTS_VIA_STACK - feePubKeyInitGiants(); - #endif - return pkinst; -} - -void feePubKeyFree(feePubKey pubKey) -{ - pubKeyInstFree((pubKeyInst*) pubKey); -} - -#ifndef ECDSA_VERIFY_ONLY -/* - * Init feePubKey from private key data. - */ -feeReturn feePubKeyInitFromPrivDataKeyBits(feePubKey pubKey, - const unsigned char *privData, - unsigned privDataLen, - unsigned keyBits, /* key size in bits */ - feePrimeType primeType, /* FPT_Fefault means "best one" */ - feeCurveType curveType, /* FCT_Default means "best one" */ - char hashPrivData) -{ - feeReturn frtn; - feeDepth depth; - - frtn = feeKeyBitsToDepth(keyBits, primeType, curveType, &depth); - if(frtn) { - return frtn; - } - return feePubKeyInitFromPrivDataDepth(pubKey, - privData, - privDataLen, - depth, - hashPrivData); -} - -feeReturn feePubKeyInitFromPrivDataDepth(feePubKey pubKey, - const unsigned char *privData, - unsigned privDataLen, - feeDepth depth, - char hashPrivData) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - feeReturn frtn; - - #if ENGINE_127_BITS - if(depth != FEE_DEPTH_127_1) { - dbgLog(("Illegal Depth\n")); - return FR_IllegalDepth; - } - #endif // ENGINE_127_BITS - if(depth > FEE_DEPTH_MAX) { - dbgLog(("Illegal Depth\n")); - return FR_IllegalDepth; - } - - pkinst->cp = curveParamsForDepth(depth); - pkinst->plus = new_public(pkinst->cp, CURVE_PLUS); - if(pkinst->cp->x1Minus != NULL) { - pkinst->minus = new_public(pkinst->cp, CURVE_MINUS); - } - /* else only usable for ECDSA */ - - frtn = feeGenPrivate(pkinst, privData, privDataLen, hashPrivData); - if(frtn) { - return frtn; - } - set_priv_key_giant(pkinst->plus, pkinst->privGiant); - if(pkinst->cp->x1Minus != NULL) { - set_priv_key_giant(pkinst->minus, pkinst->privGiant); - } - return FR_Success; -} - -#endif /* ECDSA_VERIFY_ONLY */ - -/* - * Init feePubKey from curve parameters matching existing oldKey. - */ -feeReturn feePubKeyInitFromKey(feePubKey pubKey, - const unsigned char *privData, - unsigned privDataLen, - feePubKey oldKey, - char hashPrivData) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - pubKeyInst *oldInst = (pubKeyInst *) oldKey; - feeReturn frtn; - - if(oldKey == NULL) { - dbgLog(("NULL existing key\n")); - return FR_BadPubKey; - } - - pkinst->cp = curveParamsCopy(oldInst->cp); - if(pkinst->cp->x1Minus != NULL) { - pkinst->minus = new_public(pkinst->cp, CURVE_MINUS); - if(pkinst->minus == NULL) { - goto abort; - } - } - /* else this curve only usable for ECDSA */ - - pkinst->plus = new_public(pkinst->cp, CURVE_PLUS); - if(pkinst->plus == NULL) { - goto abort; - } - frtn = feeGenPrivate(pkinst, privData, privDataLen, hashPrivData); - if(frtn) { - return frtn; - } - set_priv_key_giant(pkinst->plus, pkinst->privGiant); - if(pkinst->cp->x1Minus != NULL) { - set_priv_key_giant(pkinst->minus, pkinst->privGiant); - } - return FR_Success; - -abort: - dbgLog(("Bad Existing Public Key\n")); - return FR_BadPubKey; -} - -/*** - *** Public KeyString support. - ***/ -/* - * Init feePubKey from a public key string. - * - * See ByteRep.doc for info on the format of the public key string and blobs; - * PLEASE UPDATE THIS DOCUMENT WHEN YOU MAKE CHANGES TO THE STRING FORMAT. - */ -feeReturn feePubKeyInitFromKeyString(feePubKey pubKey, - const char *keyStr, - unsigned keyStrLen) -{ - unsigned char *blob = NULL; - unsigned blobLen; - feeReturn frtn; - - blob = dec64((unsigned char *)keyStr, keyStrLen, &blobLen); - if(blob == NULL) { - dbgLog(("Bad Public Key String (not enc64)\n")); - return FR_BadPubKeyString; - } - frtn = feePubKeyInitFromKeyBlob(pubKey, blob, blobLen); - ffree(blob); - return frtn; -} - -/* - * Create a public key in the form of a null-terminated C string. - * This string contains an encoded version of all of our ivars except for - * privGiant. - * - * See ByteRep.doc for info on the format of the public key string and blobs; - * PLEASE UPDATE THIS DOCUMENT WHEN YOU MAKE CHANGES TO THE STRING FORMAT. - */ -feeReturn feePubKeyCreateKeyString(feePubKey pubKey, - char **pubKeyString, /* RETURNED */ - unsigned *pubKeyStringLen) /* RETURNED */ -{ - unsigned char *blob; - unsigned blobLen; - feeReturn frtn; - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - - /* get binary pub blob, encode the blob, free the blob */ - frtn = createKeyBlob(pkinst, - 0, // isPrivate - &blob, - &blobLen); - if(frtn) { - return frtn; - } - - *pubKeyString = (char *)enc64(blob, blobLen, pubKeyStringLen); - ffree(blob); - return FR_Success; -} - -/*** - *** Native key blob support. - ***/ - -#ifndef ECDSA_VERIFY_ONLY - -/* - * Obtain portable public and private key blobs from a key. - */ -feeReturn feePubKeyCreatePubBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - - return createKeyBlob(pkinst, - 0, - keyBlob, - keyBlobLen); -} - -feeReturn feePubKeyCreatePrivBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - - if(pkinst->privGiant == NULL) { - return FR_IncompatibleKey; - } - return createKeyBlob(pkinst, - 1, - keyBlob, - keyBlobLen); -} - -/* - * Given private-capable privKey, initialize pubKey to be its corresponding - * public key. - */ -feeReturn feePubKeyInitPubKeyFromPriv(feePubKey privKey, - feePubKey pubKey) -{ - pubKeyInst *privInst = (pubKeyInst *)privKey; - pubKeyInst *pubInst = (pubKeyInst *)pubKey; - - if((privInst == NULL) || (pubInst == NULL)) { - return FR_BadPubKey; - } - if(privInst->privGiant == NULL) { - return FR_IncompatibleKey; - } - pubInst->cp = curveParamsCopy(privInst->cp); - if(pubInst == NULL) { - return FR_Memory; - } - pubInst->plus = new_public_with_key(privInst->plus, pubInst->cp); - if(pubInst->plus == NULL) { - return FR_Memory; - } - if(pubInst->cp->x1Minus != NULL) { - pubInst->minus = new_public_with_key(privInst->minus, pubInst->cp); - if(pubInst->minus == NULL) { - return FR_Memory; - } - } - return FR_Success; -} - -#endif /* ECDSA_VERIFY_ONLY */ - -/* - * Returns non-zero if two keys are equivalent. - */ -int feePubKeyIsEqual(feePubKey key1, feePubKey key2) -{ - pubKeyInst *pkinst1 = (pubKeyInst *) key1; - pubKeyInst *pkinst2 = (pubKeyInst *) key2; - - if ((pkinst1 == NULL) || (pkinst2 == NULL)) { - return 0; - } - if((pkinst1->minus != NULL) && (pkinst2->minus != NULL)) { - if(key_equal(pkinst1->minus, pkinst2->minus) == 0) { - return 0; - } - } - if(key_equal(pkinst1->plus, pkinst2->plus) == 0) { - return 0; - } - return 1; -} - -/* - * Returns non-zero if key is private-capable (i.e., capable of signing - * and decrypting). - */ -int feePubKeyIsPrivate(feePubKey key) -{ - pubKeyInst *myPkinst = (pubKeyInst *)key; - - return ((myPkinst->privGiant != NULL) ? 1 : 0); -} - -#ifndef ECDSA_VERIFY_ONLY - -#if CRYPTKIT_KEY_EXCHANGE - -feeReturn feePubKeyCreatePad(feePubKey myKey, - feePubKey theirKey, - unsigned char **padData, /* RETURNED */ - unsigned *padDataLen) /* RETURNED padData length in bytes */ -{ - pubKeyInst *myPkinst = (pubKeyInst *) myKey; - pubKeyInst *theirPkinst = (pubKeyInst *) theirKey; - giant pad; - unsigned char *result; - unsigned padLen; - key pkey; - - /* - * Do some compatibility checking (myKey, theirKey) here...? - */ - if(DEFAULT_CURVE == CURVE_PLUS) { - pkey = theirPkinst->plus; - } - else { - pkey = theirPkinst->minus; - } - pad = make_pad(myPkinst->privGiant, pkey); - result = mem_from_giant(pad, &padLen); - freeGiant(pad); - - /* - * Ensure we have a the minimum necessary for DES. A bit of a hack, - * to be sure. - */ - if(padLen >= FEE_DES_MIN_STATE_SIZE) { - *padData = result; - *padDataLen = padLen; - } - else { - *padData = (unsigned char*) fmalloc(FEE_DES_MIN_STATE_SIZE); - *padDataLen = FEE_DES_MIN_STATE_SIZE; - bzero(*padData, FEE_DES_MIN_STATE_SIZE); - bcopy(result, *padData, padLen); - ffree(result); - } - return FR_Success; -} - -#endif /* CRYPTKIT_KEY_EXCHANGE */ - -#if CRYPTKIT_HIGH_LEVEL_SIG - -#warning HLS -/* - * Generate digital signature, ElGamal style. - */ -feeReturn feePubKeyCreateSignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - unsigned char **signature, /* fmalloc'd and RETURNED */ - unsigned *signatureLen) /* RETURNED */ -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - feeHash hash; - feeSig sig; - unsigned char *Pm = NULL; - unsigned PmLen; - feeReturn frtn; - - if(pkinst->privGiant == NULL) { - dbgLog(("feePubKeyCreateSignature: Attempt to Sign without" - " private data\n")); - return FR_BadPubKey; - } - hash = feeHashAlloc(); - sig = feeSigNewWithKey(pubKey, NULL, NULL); - if(sig == NULL) { - /* - * Shouldn't happen, but... - */ - feeHashFree(hash); - return FR_BadPubKey; - } - - /* - * Get Pm to salt hash object - */ - Pm = feeSigPm(sig, &PmLen); - feeHashAddData(hash, Pm, PmLen); - - /* - * Now hash the data proper, then sign the hash - */ - feeHashAddData(hash, data, dataLen); - frtn = feeSigSign(sig, - feeHashDigest(hash), - feeHashDigestLen(), - pubKey); - if(frtn == FR_Success) { - frtn = feeSigData(sig, signature, signatureLen); - } - feeHashFree(hash); - feeSigFree(sig); - ffree(Pm); - return frtn; -} - -/* - * Verify digital signature, ElGamal style. If the signature is ECDSA, - * we'll use that format for compatibility. - */ -feeReturn feePubKeyVerifySignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - const unsigned char *signature, - unsigned signatureLen) -{ - feeHash hash; - feeSig sig; - unsigned char *Pm = NULL; - unsigned PmLen; - feeReturn frtn; - - hash = feeHashAlloc(); - frtn = feeSigParse(signature, signatureLen, &sig); - if(frtn) { - feeHashFree(hash); - #if CRYPTKIT_ECDSA_ENABLE - if(frtn == FR_WrongSignatureType) { - return feePubKeyVerifyECDSASignature(pubKey, - data, - dataLen, - signature, - signatureLen); - } - #endif /* CRYPTKIT_ECDSA_ENABLE */ - return frtn; - } - - /* - * Get PM as salt; eat salt, then hash data - */ - Pm = feeSigPm(sig, &PmLen); - feeHashAddData(hash, Pm, PmLen); - feeHashAddData(hash, data, dataLen); - frtn = feeSigVerify(sig, - feeHashDigest(hash), - feeHashDigestLen(), - pubKey); - - feeHashFree(hash); - feeSigFree(sig); - ffree(Pm); - return frtn; -} - -#pragma mark --- ECDSA signature: high level routines --- - -#if CRYPTKIT_ECDSA_ENABLE -/* - * Generate digital signature, ECDSA style. - */ -feeReturn feePubKeyCreateECDSASignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - unsigned char **signature, /* fmalloc'd and RETURNED */ - unsigned *signatureLen) /* RETURNED */ -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - sha1Obj sha1; - feeReturn frtn; - - if(pkinst->privGiant == NULL) { - dbgLog(("feePubKeyCreateECDSASignature: Attempt to Sign " - "without private data\n")); - return FR_BadPubKey; - } - sha1 = sha1Alloc(); - sha1AddData(sha1, data, dataLen); - frtn = feeECDSASign(pubKey, - sha1Digest(sha1), - sha1DigestLen(), - NULL, // randFcn - NULL, - signature, - signatureLen); - sha1Free(sha1); - return frtn; -} -#endif /* CRYPTKIT_ECDSA_ENABLE */ -#endif /* CRYPTKIT_HIGH_LEVEL_SIG */ -#endif /* ECDSA_VERIFY_ONLY */ - -#if CRYPTKIT_HIGH_LEVEL_SIG - -#if CRYPTKIT_ECDSA_ENABLE - -/* - * Verify digital signature, ECDSA style. - */ -feeReturn feePubKeyVerifyECDSASignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - const unsigned char *signature, - unsigned signatureLen) -{ - sha1Obj sha1; - feeReturn frtn; - - sha1 = sha1Alloc(); - sha1AddData(sha1, data, dataLen); - frtn = feeECDSAVerify(signature, - signatureLen, - sha1Digest(sha1), - sha1DigestLen(), - pubKey); - sha1Free(sha1); - return frtn; -} - -#endif /* CRYPTKIT_ECDSA_ENABLE */ - -#endif /* CRYPTKIT_HIGH_LEVEL_SIG */ - -#pragma mark --- ECDH --- - -/* - * Diffie-Hellman. Public key is specified either as a feePubKey or - * a ANSI X9.62 format public key string (0x04 | x | y). In either case - * the caller must ensure that the two keys are on the same curve. - * Output data is fmalloc'd here; caller must free. Output data is - * exactly the size of the curve's modulus in bytes. - */ -feeReturn feePubKeyECDH( - feePubKey privKey, - /* one of the following two is non-NULL */ - feePubKey pubKey, - const unsigned char *pubKeyStr, - unsigned pubKeyStrLen, - /* output fmallocd and RETURNED here */ - unsigned char **output, - unsigned *outputLen) -{ - feePubKey theirPub = pubKey; - feeReturn frtn = FR_Success; - pubKeyInst *privInst = (pubKeyInst *) privKey; - - if(privInst->privGiant == NULL) { - dbgLog(("feePubKeyECDH: privKey not a private key\n")); - return FR_IncompatibleKey; - } - - if(theirPub == NULL) { - if(pubKeyStr == NULL) { - return FR_IllegalArg; - } - - /* Cook up a public key with the same curveParams as the private key */ - feeDepth depth; - frtn = curveParamsDepth(privInst->cp, &depth); - if(frtn) { - return frtn; - } - theirPub = feePubKeyAlloc(); - if(theirPub == NULL) { - return FR_Memory; - } - frtn = feePubKeyInitFromECDSAPubBlob(theirPub, pubKeyStr, pubKeyStrLen, depth); - if(frtn) { - goto errOut; - } - } - - pubKeyInst *pubInst = (pubKeyInst *) theirPub; - - giant outputGiant = make_pad(privInst->privGiant, pubInst->plus); - if(outputGiant == NULL) { - dbgLog(("feePubKeyECDH: make_pad error\n")); - frtn = FR_Internal; - } - else { - *outputLen = (privInst->cp->q + 7) / 8; - *output = (unsigned char *)fmalloc(*outputLen); - if(*output == NULL) { - frtn = FR_Memory; - goto errOut; - } - serializeGiant(outputGiant, *output, *outputLen); - freeGiant(outputGiant); - } -errOut: - if((pubKey == NULL) && (theirPub != NULL)) { - feePubKeyFree(theirPub); - } - return frtn; -} - -#pragma mark --- feePubKey data accessors --- - -unsigned feePubKeyBitsize(feePubKey pubKey) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - switch(pkinst->cp->primeType) { - case FPT_General: /* cp->q is here for just this purpose */ - case FPT_Mersenne: - return pkinst->cp->q; - case FPT_FEE: /* could be larger or smaller than 2^q-1 */ - default: - return bitlen(pkinst->cp->basePrime); - } - /* NOT REACHED */ - return 0; -} - -/* - * Accessor routines. - */ -/* private only...*/ -key feePubKeyPlusCurve(feePubKey pubKey) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - - return pkinst->plus; -} - -key feePubKeyMinusCurve(feePubKey pubKey) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - - return pkinst->minus; -} - -curveParams *feePubKeyCurveParams(feePubKey pubKey) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - - return pkinst->cp; -} - -giant feePubKeyPrivData(feePubKey pubKey) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - - return pkinst->privGiant; -} - -const char *feePubKeyAlgorithmName(void) -{ - return "Elliptic Curve - FEE by Apple Computer"; -} - -#pragma mark --- Private functions --- - -/* - * alloc, free pubKeyInst - */ -static pubKeyInst *pubKeyInstAlloc(void) -{ - pubKeyInst *pkinst = (pubKeyInst *) fmalloc(sizeof(pubKeyInst)); - - bzero(pkinst, sizeof(pubKeyInst)); - return pkinst; -} - -static void pubKeyInstFree(pubKeyInst *pkinst) -{ - if(pkinst->minus) { - free_key(pkinst->minus); - } - if(pkinst->plus) { - free_key(pkinst->plus); - } - if(pkinst->cp) { - freeCurveParams(pkinst->cp); - } - if(pkinst->privGiant) { - /* - * Zero out the private data... - */ - clearGiant(pkinst->privGiant); - freeGiant(pkinst->privGiant); - } - ffree(pkinst); -} - -#ifndef ECDSA_VERIFY_ONLY - -/* - * Create a pubKeyInst.privGiant given a password of - * arbitrary length. - * Currently, the only error is "private data too short" (FR_IllegalArg). - */ - -#define NO_PRIV_MUNGE 0 /* skip this step */ - -static feeReturn feeGenPrivate(pubKeyInst *pkinst, - const unsigned char *passwd, - unsigned passwdLen, - char hashPasswd) -{ - unsigned privLen; // desired size of pkinst->privData - feeHash *hash = NULL; // a malloc'd array - unsigned digestLen; // size of MD5 digest - unsigned dataSize; // min(privLen, passwdLen) - unsigned numDigests = 0; - unsigned i; - unsigned char *cp; - unsigned toMove; // for this digest - unsigned moved; // total digested - unsigned char *digest = NULL; - unsigned char *privData = NULL; // temp, before modg(curveOrder) - giant corder; // lesser of two curve orders - - /* - * generate privData which is just larger than the smaller - * curve order. - * We'll take the result mod the curve order when we're done. - * Note we do *not* have to free corder - it's a pointer to a giant - * in pkinst->cp. - */ - corder = lesserX1Order(pkinst->cp); - CKASSERT(!isZero(corder)); - privLen = (bitlen(corder) / 8) + 1; - - if(!hashPasswd) { - /* - * Caller trusts the incoming entropy. Verify it's big enough and proceed. - */ - if(passwdLen < privLen) { - return FR_ShortPrivData; - } - privLen = passwdLen; - privData = (unsigned char *)passwd; - goto finishUp; - } - if(passwdLen < 2) { - return FR_IllegalArg; - } - - - /* - * Calculate how many MD5 digests we'll generate. - */ - if(privLen > passwdLen) { - dataSize = passwdLen; - } - else { - dataSize = privLen; - } - digestLen = feeHashDigestLen(); - numDigests = (dataSize + digestLen - 1) / digestLen; - - hash = (void**) fmalloc(numDigests * sizeof(feeHash)); - for(i=0; i privLen), last digest will hash all - * remaining passwd data. - */ - cp = (unsigned char *)passwd; - moved = 0; - for(i=0; i privLen) { - toMove = privLen - moved; - } - else { - toMove = digestLen; - } - digest = feeHashDigest(hash[i++]); - bcopy(digest, cp, toMove); - cp += toMove; - moved += toMove; - if(i == numDigests) { - i = 0; // wrap to 0, start padding - } - } - -finishUp: - /* - * Convert to giant, justify result to within [2, lesserX1Order] - */ - pkinst->privGiant = giant_with_data(privData, privLen); - - #if FEE_DEBUG - if(isZero(pkinst->privGiant)) { - printf("feeGenPrivate: privData = 0!\n"); - } - #endif // FEE_DEBUG - - lesserX1OrderJustify(pkinst->privGiant, pkinst->cp); - if(hashPasswd) { - memset(privData, 0, privLen); - ffree(privData); - for(i=0; icp); - printf("plus:\n"); - printKey(pkinst->plus); - printf("minus:\n"); - printKey(pkinst->minus); - if(pkinst->privGiant != NULL) { - printf("privGiant : "); - printGiant(pkinst->privGiant); - } -} - -#else // FEE_DEBUG -void printPubKey(feePubKey pubKey) {} -#endif // FEE_DEBUG - -/* - * Prime the curveParams and giants modules for quick allocs of giants. - */ -#if GIANTS_VIA_STACK - -static int giantsInitd = 0; - -static void feePubKeyInitGiants(void) -{ - if(giantsInitd) { - return; - } - curveParamsInitGiants(); - giantsInitd = 1; -} -#endif - -#pragma mark --- Native (custom) key blob formatting --- - -/* - * Exported key blob support. New, 23 Mar 1998. - * - * Convert to public or private key blob. - */ - -#ifndef ECDSA_VERIFY_ONLY - -/*** - *** Common native blob support - ***/ -static feeReturn createKeyBlob(pubKeyInst *pkinst, - int isPrivate, // 0 : public 1 : private - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - unsigned char *s; // running ptr into *origS - unsigned sLen; - int magic; - - /* common blob elements */ - sLen = (4 * sizeof(int)) + // magic, version, minVersion, - // spare - lengthOfByteRepCurveParams(pkinst->cp); - if(isPrivate) { - /* private only */ - sLen += lengthOfByteRepGiant(pkinst->privGiant); - magic = PUBLIC_KEY_BLOB_MAGIC_PRIV; - } - else { - /* public only */ - sLen += (lengthOfByteRepKey(pkinst->plus) + - lengthOfByteRepKey(pkinst->minus)); - magic = PUBLIC_KEY_BLOB_MAGIC_PUB; - } - *keyBlob = s = (unsigned char*) fmalloc(sLen); - s += intToByteRep(magic, s); - s += intToByteRep(PUBLIC_KEY_BLOB_VERSION, s); - s += intToByteRep(PUBLIC_KEY_BLOB_MINVERSION, s); - s += intToByteRep(0, s); // spare - s += curveParamsToByteRep(pkinst->cp, s); - if(isPrivate) { - s += giantToByteRep(pkinst->privGiant, s); - } - else { - /* keyToByteRep writes y for plus curve only */ - s += keyToByteRep(pkinst->plus, s); - if(pkinst->minus != NULL) { - s += keyToByteRep(pkinst->minus, s); - } - else { - /* TBD */ - dbgLog(("work needed here for blobs with no minus key\n")); - } - } - *keyBlobLen = sLen; - return FR_Success; -} - -#endif /* ECDSA_VERIFY_ONLY */ - -/* - * Init an empty feePubKey from a native blob (non-DER format). - */ -static feeReturn feePubKeyInitFromKeyBlob(feePubKey pubKey, - unsigned char *keyBlob, - unsigned keyBlobLen) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - unsigned char *s; // running pointer - unsigned sLen; // bytes remaining in *s - int magic; - unsigned len; // for length of individual components - int minVersion; - int version; - int isPrivate; - - s = keyBlob; - sLen = keyBlobLen; - if(sLen < (4 * sizeof(int))) { // magic, version, minVersion, spare - /* - * Too short for all the ints we need - */ - dbgLog(("feePublicKey: key blob (1)\n")); - return FR_BadKeyBlob; - } - - magic = byteRepToInt(s); - s += sizeof(int); - sLen -= sizeof(int); - switch(magic) { - case PUBLIC_KEY_BLOB_MAGIC_PUB: - isPrivate = 0; - break; - case PUBLIC_KEY_BLOB_MAGIC_PRIV: - isPrivate = 1; - break; - default: - dbgLog(("feePublicKey: Bad Public Key Magic Number\n")); - return FR_BadKeyBlob; - } - - /* - * Switch on this for version-specific cases - */ - version = byteRepToInt(s); - s += sizeof(int); - sLen -= sizeof(int); - - minVersion = byteRepToInt(s); - s += sizeof(int); - sLen -= sizeof(int); - if(minVersion > PUBLIC_KEY_BLOB_VERSION) { - /* - * old code, newer key blob - can't parse - */ - dbgLog(("feePublicKey: Incompatible Public Key (1)\n")); - return FR_BadKeyBlob; - } - - s += sizeof(int); // skip spare - sLen -= sizeof(int); - - pkinst->cp = byteRepToCurveParams(s, sLen, &len); - if(pkinst->cp == NULL) { - dbgLog(("feePublicKey: Bad Key Blob(2)\n")); - return FR_BadKeyBlob; - } - s += len; - sLen -= len; - - /* - * Private key blob: privGiant. - * Public Key blob: plusX, minusX, plusY. - */ - if(isPrivate) { - pkinst->privGiant = byteRepToGiant(s, sLen, &len); - if(pkinst->privGiant == NULL) { - dbgLog(("feePublicKey: Bad Key Blob(3)\n")); - return FR_BadKeyBlob; - } - s += len; - sLen -= len; - } - else { - /* this writes x and y */ - pkinst->plus = byteRepToKey(s, - sLen, - CURVE_PLUS, // twist - pkinst->cp, - &len); - if(pkinst->plus == NULL) { - dbgLog(("feePublicKey: Bad Key Blob(4)\n")); - return FR_BadKeyBlob; - } - s += len; - sLen -= len; - - /* this only writes x */ - pkinst->minus = byteRepToKey(s, - sLen, - CURVE_MINUS, // twist - pkinst->cp, - &len); - if(pkinst->minus == NULL) { - dbgLog(("feePublicKey: Bad Key Blob(5)\n")); - return FR_BadKeyBlob; - } - s += len; - sLen -= len; - } - - /* - * One more thing: cook up public plusX and minusX for private key - * blob case. - */ - if(isPrivate) { - pkinst->plus = new_public(pkinst->cp, CURVE_PLUS); - pkinst->minus = new_public(pkinst->cp, CURVE_MINUS); - set_priv_key_giant(pkinst->plus, pkinst->privGiant); - set_priv_key_giant(pkinst->minus, pkinst->privGiant); - } - return FR_Success; - -} - -feeReturn feePubKeyInitFromPubBlob(feePubKey pubKey, - unsigned char *keyBlob, - unsigned keyBlobLen) -{ - return feePubKeyInitFromKeyBlob(pubKey, keyBlob, keyBlobLen); -} - -#ifndef ECDSA_VERIFY_ONLY - -feeReturn feePubKeyInitFromPrivBlob(feePubKey pubKey, - unsigned char *keyBlob, - unsigned keyBlobLen) -{ - return feePubKeyInitFromKeyBlob(pubKey, keyBlob, keyBlobLen); -} - -#endif /* ECDSA_VERIFY_ONLY */ - -#if CRYPTKIT_DER_ENABLE -#ifndef ECDSA_VERIFY_ONLY - -/* - * DER format support. - * Obtain portable public and private DER-encoded key blobs from a key. - */ -feeReturn feePubKeyCreateDERPubBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - - if(pkinst == NULL) { - return FR_BadPubKey; - } - if(pkinst->minus == NULL) { - /* Only ECDSA key formats supported */ - return FR_IncompatibleKey; - } - return feeDEREncodePublicKey(PUBLIC_DER_KEY_BLOB_VERSION, - pkinst->cp, - pkinst->plus->x, - pkinst->minus->x, - isZero(pkinst->plus->y) ? NULL : pkinst->plus->y, - keyBlob, - keyBlobLen); -} - -feeReturn feePubKeyCreateDERPrivBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - - if(pkinst == NULL) { - return FR_BadPubKey; - } - if(pkinst->privGiant == NULL) { - return FR_IncompatibleKey; - } - if(pkinst->minus == NULL) { - /* Only ECDSA key formats supported */ - return FR_IncompatibleKey; - } - return feeDEREncodePrivateKey(PUBLIC_DER_KEY_BLOB_VERSION, - pkinst->cp, - pkinst->privGiant, - keyBlob, - keyBlobLen); -} - -#endif /* ECDSA_VERIFY_ONLY */ - -/* - * Init an empty feePubKey from a DER-encoded blob, public and private key versions. - */ -feeReturn feePubKeyInitFromDERPubBlob(feePubKey pubKey, - unsigned char *keyBlob, - size_t keyBlobLen) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - feeReturn frtn; - int version; - - if(pkinst == NULL) { - return FR_BadPubKey; - } - - /* kind of messy, maybe we should clean this up. But new_public() does too - * much - e.g., it allocates the x and y which we really don't want */ - memset(pkinst, 0, sizeof(pubKeyInst)); - pkinst->plus = (key) fmalloc(sizeof(keystruct)); - pkinst->minus = (key) fmalloc(sizeof(keystruct)); - if((pkinst->plus == NULL) || (pkinst->minus == NULL)) { - return FR_Memory; - } - memset(pkinst->plus, 0, sizeof(keystruct)); - memset(pkinst->minus, 0, sizeof(keystruct)); - pkinst->cp = NULL; - pkinst->privGiant = NULL; - pkinst->plus->twist = CURVE_PLUS; - pkinst->minus->twist = CURVE_MINUS; - frtn = feeDERDecodePublicKey(keyBlob, - (unsigned)keyBlobLen, - &version, // currently unused - &pkinst->cp, - &pkinst->plus->x, - &pkinst->minus->x, - &pkinst->plus->y); - if(frtn) { - return frtn; - } - /* minus curve, y is not used */ - pkinst->minus->y = newGiant(1); - int_to_giant(0, pkinst->minus->y); - pkinst->plus->cp = pkinst->minus->cp = pkinst->cp; - return FR_Success; -} - -#ifndef ECDSA_VERIFY_ONLY - -feeReturn feePubKeyInitFromDERPrivBlob(feePubKey pubKey, - unsigned char *keyBlob, - size_t keyBlobLen) -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - int version; - feeReturn frtn; - - if(pkinst == NULL) { - return FR_BadPubKey; - } - memset(pkinst, 0, sizeof(pubKeyInst)); - frtn = feeDERDecodePrivateKey(keyBlob, - (unsigned)keyBlobLen, - &version, // currently unused - &pkinst->cp, - &pkinst->privGiant); - if(frtn) { - return frtn; - } - - /* since this blob only had the private data, infer the remaining fields */ - pkinst->plus = new_public(pkinst->cp, CURVE_PLUS); - pkinst->minus = new_public(pkinst->cp, CURVE_MINUS); - set_priv_key_giant(pkinst->plus, pkinst->privGiant); - set_priv_key_giant(pkinst->minus, pkinst->privGiant); - return FR_Success; -} - -#endif /* ECDSA_VERIFY_ONLY */ - -#pragma mark --- X509 (public) and PKCS8 (private) key formatting --- - -feeReturn feePubKeyCreateX509Blob( - feePubKey pubKey, // public key - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - unsigned char *xyStr = NULL; - unsigned xyStrLen = 0; - feeReturn frtn = feeCreateECDSAPubBlob(pubKey, &xyStr, &xyStrLen); - if(frtn) { - return frtn; - } - frtn = feeDEREncodeX509PublicKey(xyStr, xyStrLen, pkinst->cp, keyBlob, keyBlobLen); - ffree(xyStr); - return frtn; -} - -feeReturn feePubKeyCreatePKCS8Blob( - feePubKey pubKey, // private key - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - unsigned char *privStr = NULL; - unsigned privStrLen = 0; - feeReturn frtn = feeCreateECDSAPrivBlob(pubKey, &privStr, &privStrLen); - if(frtn) { - return frtn; - } - unsigned char *pubStr = NULL; - unsigned pubStrLen = 0; - frtn = feeCreateECDSAPubBlob(pubKey, &pubStr, &pubStrLen); - if(frtn) { - goto errOut; - } - frtn = feeDEREncodePKCS8PrivateKey(privStr, privStrLen, - pubStr, pubStrLen, - pkinst->cp, keyBlob, keyBlobLen); -errOut: - if(privStr) { - ffree(privStr); - } - if(pubStr) { - ffree(pubStr); - } - return frtn; -} - -feeReturn feePubKeyInitFromX509Blob( - feePubKey pubKey, // public key - unsigned char *keyBlob, - size_t keyBlobLen) -{ - feeDepth depth; - unsigned char *xyStr = NULL; - unsigned xyStrLen = 0; - - /* obtain x/y and depth from X509 encoding */ - feeReturn frtn = feeDERDecodeX509PublicKey(keyBlob, (unsigned)keyBlobLen, &depth, - &xyStr, &xyStrLen); - if(frtn) { - return frtn; - } - - frtn = feePubKeyInitFromECDSAPubBlob(pubKey, xyStr, xyStrLen, depth); - ffree(xyStr); - return frtn; -} - - -feeReturn feePubKeyInitFromPKCS8Blob( - feePubKey pubKey, // private key - unsigned char *keyBlob, - size_t keyBlobLen) -{ - feeDepth depth; - unsigned char *privStr = NULL; - unsigned privStrLen = 0; - - /* obtain x/y and depth from PKCS8 encoding */ - /* For now we ignore the possible public key string */ - feeReturn frtn = feeDERDecodePKCS8PrivateKey(keyBlob, (unsigned)keyBlobLen, &depth, - &privStr, &privStrLen, NULL, NULL); - if(frtn) { - return frtn; - } - - frtn = feePubKeyInitFromECDSAPrivBlob(pubKey, privStr, privStrLen, depth); - ffree(privStr); - return frtn; -} - -#pragma mark --- OpenSSL key formatting --- - -/* - * The native OpenSSL ECDSA key format contains both the private and public - * components in one blob. This throws a bit of a monkey wrench into the API - * here, as we only have one encoder - which requires a private key - and one - * decoder, which can result in the decoding of either a public or a private - * key. - */ -feeReturn feePubKeyCreateOpenSSLBlob( - feePubKey pubKey, // private key - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen) // RETURNED -{ - pubKeyInst *pkinst = (pubKeyInst *) pubKey; - unsigned char *privStr = NULL; - unsigned privStrLen = 0; - feeReturn frtn = feeCreateECDSAPrivBlob(pubKey, &privStr, &privStrLen); - if(frtn) { - return frtn; - } - unsigned char *pubStr = NULL; - unsigned pubStrLen = 0; - frtn = feeCreateECDSAPubBlob(pubKey, &pubStr, &pubStrLen); - if(frtn) { - goto errOut; - } - frtn = feeDEREncodeOpenSSLPrivateKey(privStr, privStrLen, - pubStr, pubStrLen, - pkinst->cp, keyBlob, keyBlobLen); -errOut: - if(privStr) { - ffree(privStr); - } - if(pubStr) { - ffree(pubStr); - } - return frtn; -} - -feeReturn feePubKeyInitFromOpenSSLBlob( - feePubKey pubKey, // private or public key - int pubOnly, - unsigned char *keyBlob, - size_t keyBlobLen) -{ - feeDepth depth; - unsigned char *privStr = NULL; - unsigned privStrLen = 0; - unsigned char *pubStr = NULL; - unsigned pubStrLen = 0; - - /* obtain x/y, public bit string, and depth from PKCS8 encoding */ - feeReturn frtn = feeDERDecodeOpenSSLKey(keyBlob, (unsigned)keyBlobLen, &depth, - &privStr, &privStrLen, &pubStr, &pubStrLen); - if(frtn) { - return frtn; - } - - if(pubOnly) { - frtn = feePubKeyInitFromECDSAPubBlob(pubKey, pubStr, pubStrLen, depth); - } - else { - frtn = feePubKeyInitFromECDSAPrivBlob(pubKey, privStr, privStrLen, depth); - } - if(privStr) { - ffree(privStr); - } - if(pubStr) { - ffree(pubStr); - } - return frtn; -} - -#endif /* CRYPTKIT_DER_ENABLE */ - -/* - * ANSI X9.62/Certicom key support. - * Public key is 04 || x || y - * Private key is privData per Certicom SEC1 C.4. - */ -feeReturn feeCreateECDSAPubBlob(feePubKey pubKey, - unsigned char **keyBlob, - unsigned *keyBlobLen) -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - if(pkinst == NULL) { - return FR_BadPubKey; - } - - unsigned giantBytes = (pkinst->cp->q + 7) / 8; - unsigned blobSize = 1 + (2 * giantBytes); - unsigned char *blob = fmalloc(blobSize); - if(blob == NULL) { - return FR_Memory; - } - *blob = 0x04; - serializeGiant(pkinst->plus->x, blob+1, giantBytes); - serializeGiant(pkinst->plus->y, blob+1+giantBytes, giantBytes); - *keyBlob = blob; - *keyBlobLen = blobSize; - return FR_Success; -} - -feeReturn feeCreateECDSAPrivBlob(feePubKey pubKey, - unsigned char **keyBlob, - unsigned *keyBlobLen) -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - if(pkinst == NULL) { - return FR_BadPubKey; - } - if(pkinst->privGiant == NULL) { - return FR_IncompatibleKey; - } - - /* - * Return the raw private key bytes padded with zeroes in - * the m.s. end to fill exactly one prime-size byte array. - */ - unsigned giantBytes = (pkinst->cp->q + 7) / 8; - unsigned char *blob = fmalloc(giantBytes); - if(blob == NULL) { - return FR_Memory; - } - serializeGiant(pkinst->privGiant, blob, giantBytes); - *keyBlob = blob; - *keyBlobLen = giantBytes; - return FR_Success; -} - -/* Caller determines depth from other sources (e.g. AlgId.Params) */ -feeReturn feePubKeyInitFromECDSAPubBlob(feePubKey pubKey, - const unsigned char *keyBlob, - unsigned keyBlobLen, - feeDepth depth) -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - if(pkinst == NULL) { - return FR_BadPubKey; - } - curveParams *cp = curveParamsForDepth(depth); - if(cp == NULL) { - return FR_IllegalDepth; - } - unsigned giantBytes = (cp->q + 7) / 8; - unsigned blobSize = 1 + (2 * giantBytes); - if(keyBlobLen != blobSize) { - dbgLog(("feePubKeyInitFromECDSAPubBlob: bad blobLen\n")); - return FR_BadKeyBlob; - } - if(*keyBlob != 0x04) { - dbgLog(("feePubKeyInitFromECDSAPubBlob: bad blob leader\n")); - return FR_BadKeyBlob; - } - - pkinst->cp = cp; - pkinst->plus = new_public(cp, CURVE_PLUS); - deserializeGiant(keyBlob+1, pkinst->plus->x, giantBytes); - deserializeGiant(keyBlob+1+giantBytes, pkinst->plus->y, giantBytes); - return FR_Success; -} - -feeReturn feePubKeyInitFromECDSAPrivBlob(feePubKey pubKey, - const unsigned char *keyBlob, - unsigned keyBlobLen, - feeDepth depth) -{ - pubKeyInst *pkinst = (pubKeyInst *)pubKey; - if(pkinst == NULL) { - return FR_BadPubKey; - } - curveParams *cp = curveParamsForDepth(depth); - if(cp == NULL) { - return FR_IllegalDepth; - } - unsigned giantDigits = cp->basePrime->sign; - unsigned giantBytes = (cp->q + 7) / 8; - - /* - * The specified private key can be one byte smaller than the modulus */ - if((keyBlobLen > giantBytes) || (keyBlobLen < (giantBytes - 1))) { - dbgLog(("feePubKeyInitFromECDSAPrivBlob: bad blobLen\n")); - return FR_BadKeyBlob; - } - - pkinst->cp = cp; - - /* cook up a new private giant */ - pkinst->privGiant = newGiant(giantDigits); - if(pkinst->privGiant == NULL) { - return FR_Memory; - } - deserializeGiant(keyBlob, pkinst->privGiant, keyBlobLen); - - /* since this blob only had the private data, infer the remaining fields */ - pkinst->plus = new_public(pkinst->cp, CURVE_PLUS); - set_priv_key_giant(pkinst->plus, pkinst->privGiant); - return FR_Success; -} - diff --git a/OSX/include/security_cryptkit/feePublicKey.h b/OSX/include/security_cryptkit/feePublicKey.h deleted file mode 100644 index 6f88fa62..00000000 --- a/OSX/include/security_cryptkit/feePublicKey.h +++ /dev/null @@ -1,341 +0,0 @@ -/* Copyright (c) 1998,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feePublicKey.h - * - * Revision History - * ---------------- - * 23 Mar 98 at Apple - * Added blob support. - * 17 Jul 97 at Apple - * Added ECDSA signature routines. - * 20 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEPUBLICKEY_H_ -#define _CK_FEEPUBLICKEY_H_ - -#include "ckconfig.h" - -#include /* size_t */ - -#if !defined(__MACH__) -#include -#else -#include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Obatin a newly allocated feePubKey. - */ -feePubKey feePubKeyAlloc(void); - -void feePubKeyFree(feePubKey pubKey); - -/* - * Init feePubKey from private "password" data. Incoming password data will - * be processed with digests before use if hashPrivData is true, otherwise - * it'll be used as is. In the 'as is' case, the privData must be at least - * as large as the key being created. - * - * Currently two versions - one in which the size of the key is specified as - * a feeDepth; one for key size in bits and optional primeType and curveType. - */ -feeReturn feePubKeyInitFromPrivDataDepth(feePubKey pubKey, - const unsigned char *privData, - unsigned privDataLen, - feeDepth depth, - char hashPrivData); - -feeReturn feePubKeyInitFromPrivDataKeyBits(feePubKey pubKey, - const unsigned char *privData, - unsigned privDataLen, - unsigned keyBits, /* key size in bits */ - feePrimeType primeType, /* FPT_Fefault means "best one" */ - feeCurveType curveType, /* FCT_Default means "best one" */ - char hashPrivData); - -/* - * Init feePubKey from private "password" and from data curve parameters - * matching existing oldKey. Incoming password data will - * be processed with digests before use if hashPrivData is true, otherwise - * it'll be used as is. In the 'as is' case, the privData must be at least - * as large as the key being created. - - */ -feeReturn feePubKeyInitFromKey(feePubKey pubKey, - const unsigned char *privData, - unsigned privDataLen, - feePubKey oldKey, - char hashPrivData); - -/*** - *** Exportable key blob support. - *** - *** Currently there are three different ways of representing a feePubKey in - *** an exportable format. - *** - *** Raw blob: basic native blob format. - *** DER blob: DER-encoded. Currently not available in ANSI C version of - *** CryptKit library without additional porting; the OS X version of - *** Apple implements this functionality via SNACC-generated C++ classes. - *** KeyString: NULL-terminated ASCII C string, suitable for application such as - *** distributing one's public key via email. Only public keys (not - *** private) can be exported and imported via KeyStrings. - ***/ - -/* - * Obtain portable public and private key blobs from a key. - */ -feeReturn feePubKeyCreatePubBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feePubKeyCreatePrivBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -/* - * Init an empty feePubKey from a blob, public and private key versions. - */ -feeReturn feePubKeyInitFromPubBlob(feePubKey pubKey, - unsigned char *keyBlob, - unsigned keyBlobLen); -feeReturn feePubKeyInitFromPrivBlob(feePubKey pubKey, - unsigned char *keyBlob, - unsigned keyBlobLen); - -/* - * Create a public key in the form of a null-terminated C string. - */ -feeReturn feePubKeyCreateKeyString(feePubKey pubKey, - char **pubKeyString, /* fmalloc'd & RETURNED */ - unsigned *pubKeyStringLen); /* RETURNED */ - -/* - * Init feePubKey from a public key string. - */ -feeReturn feePubKeyInitFromKeyString(feePubKey pubKey, - const char *keyStr, - unsigned keyStrLen); - -#if CRYPTKIT_DER_ENABLE - -/* - * DER format support. - * Obtain portable public and private DER-encoded key blobs from a key. - */ -feeReturn feePubKeyCreateDERPubBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feePubKeyCreateDERPrivBlob(feePubKey pubKey, - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -/* - * Init an empty feePubKey from a DER-encoded blob, public and private key versions. - */ -feeReturn feePubKeyInitFromDERPubBlob(feePubKey pubKey, - unsigned char *keyBlob, - size_t keyBlobLen); -feeReturn feePubKeyInitFromDERPrivBlob(feePubKey pubKey, - unsigned char *keyBlob, - size_t keyBlobLen); - -/* - * X509 (public) and PKCS8 (private) key formatting. - */ -feeReturn feePubKeyCreateX509Blob( - feePubKey pubKey, // public key - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feePubKeyCreatePKCS8Blob( - feePubKey pubKey, // private key - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feePubKeyInitFromX509Blob( - feePubKey pubKey, // public key - unsigned char *keyBlob, - size_t keyBlobLen); - -feeReturn feePubKeyInitFromPKCS8Blob( - feePubKey pubKey, // private key - unsigned char *keyBlob, - size_t keyBlobLen); - -/* - * The native OpenSSL ECDSA key format contains both the private and public - * components in one blob. This throws a bit of a monkey wrench into the API - * here, as we only have one encoder - which requires a private key - and one - * decoder, which can result in the decoding of either a public or a private - * key. - */ -feeReturn feePubKeyCreateOpenSSLBlob( - feePubKey pubKey, // private key - unsigned char **keyBlob, // mallocd and RETURNED - unsigned *keyBlobLen); // RETURNED - -feeReturn feePubKeyInitFromOpenSSLBlob( - feePubKey pubKey, // private or public key - int pubOnly, - unsigned char *keyBlob, - size_t keyBlobLen); - -#endif /* CRYPTKIT_DER_ENABLE */ - -/* - * ANSI X9.62/Certicom key support. - * Public key is 04 || x || y - * Private key is privData per Certicom SEC1 C.4. - */ -feeReturn feeCreateECDSAPubBlob(feePubKey pubKey, - unsigned char **keyBlob, - unsigned *keyBlobLen); - -feeReturn feeCreateECDSAPrivBlob(feePubKey pubKey, - unsigned char **keyBlob, - unsigned *keyBlobLen); - -/* Caller determines depth from other sources (e.g. AlgId.Params) */ -feeReturn feePubKeyInitFromECDSAPubBlob(feePubKey pubKey, - const unsigned char *keyBlob, - unsigned keyBlobLen, - feeDepth depth); - -feeReturn feePubKeyInitFromECDSAPrivBlob(feePubKey pubKey, - const unsigned char *keyBlob, - unsigned keyBlobLen, - feeDepth depth); - - -/*** - *** Miscellaneous feePubKey functions. - ***/ - -/* - * Given private-capable privKey, initialize pubKey to be its corresponding - * public key. - */ -feeReturn feePubKeyInitPubKeyFromPriv(feePubKey privKey, - feePubKey pubKey); - -/* - * Returns non-zero if two keys are equivalent. - */ -int feePubKeyIsEqual(feePubKey key1, - feePubKey key2); - -/* - * Returns non-zero if key is private-capable (i.e., capable of signing - * and decrypting). - */ -int feePubKeyIsPrivate(feePubKey key); - -#if CRYPTKIT_KEY_EXCHANGE - -/* - * Generate a pad, for use with symmetric encryption, derived from two keys. - * 'myKey' must be created with private data (via feePubKeyInitFromPrivData() - * or feePubKeyInitFromKey(). - */ -feeReturn feePubKeyCreatePad(feePubKey myKey, - feePubKey theirKey, - unsigned char **padData, /* fmalloc'd & RETURNED */ - unsigned *padDataLen); /* RETURNED padData length in bytes */ - -#endif /* CRYPTKIT_KEY_EXCHANGE */ - -#if CRYPTKIT_HIGH_LEVEL_SIG - -/* - * The following two routines are implemented using primitives in the - * feeHash and feeDigitalSignature objects. - * - * Generate digital signature, ElGamal style. - */ -feeReturn feePubKeyCreateSignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - unsigned char **signature, /* fmalloc'd and RETURNED */ - unsigned *signatureLen); /* RETURNED */ - -/* - * Verify digital signature, ElGamal style. - */ -feeReturn feePubKeyVerifySignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - const unsigned char *signature, - unsigned signatureLen); - -#if CRYPTKIT_ECDSA_ENABLE - -/* - * The following two routines are implemented using primitives in the - * feeHash and feeECDSA objects. - * - * Generate digital signature, ECDSA style. - */ -feeReturn feePubKeyCreateECDSASignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - unsigned char **signature, /* fmalloc'd and RETURNED */ - unsigned *signatureLen); /* RETURNED */ - -/* - * Verify digital signature, ECDSA style. - */ -feeReturn feePubKeyVerifyECDSASignature(feePubKey pubKey, - const unsigned char *data, - unsigned dataLen, - const unsigned char *signature, - unsigned signatureLen); - -#endif /* CRYPTKIT_ECDSA_ENABLE */ - -#endif /* CRYPTKIT_HIGH_LEVEL_SIG */ - -/* - * Diffie-Hellman. Public key is specified either as a feePubKey or - * a ANSI X9.62 format public key string (0x04 | x | y). In either case - * the caller must ensure that the two keys are on the same curve. - * Output data is falloc'd here; caller must free. Output data is - * exactly the size of the curve's modulus in bytes. - */ -feeReturn feePubKeyECDH( - feePubKey privKey, - /* one of the following two is non-NULL */ - feePubKey pubKey, - const unsigned char *pubKeyStr, - unsigned pubKeyStrLen, - /* output fallocd and RETURNED here */ - unsigned char **output, - unsigned *outputLen); - -/* - * Accessor routines. - */ -const char *feePubKeyAlgorithmName(void); - -unsigned feePubKeyBitsize(feePubKey pubKey); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_FEEPUBLICKEY_H_*/ diff --git a/OSX/include/security_cryptkit/feePublicKeyPrivate.h b/OSX/include/security_cryptkit/feePublicKeyPrivate.h deleted file mode 100644 index 9aa2f2ad..00000000 --- a/OSX/include/security_cryptkit/feePublicKeyPrivate.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feePublicKeyPrivate.h - feePublicKey private function declarations - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 28 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEEPUBKEYPRIV_H_ -#define _CK_FEEPUBKEYPRIV_H_ - -#include "feeTypes.h" -#include "feePublicKey.h" -#include "feeDebug.h" -#include "elliptic.h" - -#ifdef __cplusplus -extern "C" { -#endif - -key feePubKeyPlusCurve(feePubKey pubKey); -key feePubKeyMinusCurve(feePubKey pubKey); -curveParams *feePubKeyCurveParams(feePubKey pubKey); -giant feePubKeyPrivData(feePubKey pubKey); -void printPubKey(feePubKey pubKey); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_FEEPUBKEYPRIV_H_*/ diff --git a/OSX/include/security_cryptkit/feeRandom.c b/OSX/include/security_cryptkit/feeRandom.c deleted file mode 100644 index 1fedc6ca..00000000 --- a/OSX/include/security_cryptkit/feeRandom.c +++ /dev/null @@ -1,206 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeRandom.c - generic, portable random number generator object - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 19 Jun 97 at Apple - * Eliminated predictability of bytes 4 thru 15 of random data - * 18 Jun 97 at Apple - * Reduced size of per-instance giants from 128 to 32 shorts - * 23 Aug 96 at NeXT - * Created, based on Blaine Garst's NSRandomNumberGenerator class - */ - -#include "feeRandom.h" -#include "giantIntegers.h" -#include "elliptic.h" -#include "falloc.h" -#include "feeDebug.h" -#include "byteRep.h" -#include -#include "platform.h" - -/* - * 1 ==> do extra nextNum on feeRandAllocWithSeed() - */ -#define EXTRA_NEXT_NUM 0 - -#define RANDBITS 128 /* must be 0 mod GIANT_BITS_PER_DIGIT */ -#define RAND_GIANT_DIGITS (RANDBITS/GIANT_BITS_PER_DIGIT) - -typedef struct { - giant A; - giant C; - giant SEED; - giant x; -} randInst; - -#if GIANTS_VIA_STACK - -/* - * Prime the curveParams and giants modules for quick allocs of giants. - */ -static int giantsInitd = 0; - -static void feeRandInitGiants() -{ - if(giantsInitd) { - return; - } - curveParamsInitGiants(); - giantsInitd = 1; -} -#endif - -static void pmod(giant x, int bits) { - /* Force x to be x (mod 2^bits). */ - int j; - int digits = bits / GIANT_BITS_PER_DIGIT; - - for(j = (digits-1); j >= 0; j--) { - if(x->n[j] != 0) break; - } - x->sign = j+1; -} - - -feeRand feeRandAllocWithSeed(unsigned seed) -{ - randInst *rinst = (randInst *) fmalloc(sizeof(randInst)); - int digits = RAND_GIANT_DIGITS * 4; - unsigned j; - - #if GIANTS_VIA_STACK - feeRandInitGiants(); - #endif - rinst->SEED = newGiant(digits); - rinst->C = newGiant(digits); - rinst->A = newGiant(digits); - rinst->x = newGiant(digits); - rinst->C->sign = rinst->A->sign = rinst->SEED->sign = RAND_GIANT_DIGITS; - for(j=0; jC->n[j] = (giantDigit)(seed + 0xdddddddd - j); - rinst->A->n[j] = (giantDigit)(seed + 0xfff12223 + j); - rinst->SEED->n[j] = (giantDigit)(seed + j); - } - - /* - * on the first feeRandBytes or feeRandNextNum, bytes 4 and 5 of - * the result are duplicated 4.5 times (up to byte 15). Subsequent - * data is indeed random. Thus... - */ - #if EXTRA_NEXT_NUM - feeRandNextNum(rinst); - #endif // EXTRA_NEXT_NUM - return rinst; -} - -feeRand feeRandAlloc(void) -{ - return feeRandAllocWithSeed(createRandomSeed()); -} - -void feeRandFree(feeRand frand) -{ - randInst *rinst = (randInst *) frand; - - clearGiant(rinst->A); - freeGiant(rinst->A); - clearGiant(rinst->C); - freeGiant(rinst->C); - clearGiant(rinst->SEED); - freeGiant(rinst->SEED); - clearGiant(rinst->x); - freeGiant(rinst->x); - ffree(rinst); -} - -unsigned feeRandNextNum(feeRand frand) -{ - randInst *rinst = (randInst *) frand; - unsigned rtn; - - mulg(rinst->A, rinst->SEED); - addg(rinst->C, rinst->SEED); - pmod(rinst->SEED, RANDBITS); - gtog(rinst->SEED, rinst->x); - - /* - * FIXME - this is not quite correct; rinst->x only has 4 bytes - * of valid data if RANDBITS is known to be greater than or equal - * to 32. - */ - rtn = byteRepToInt((unsigned char *)&rinst->x->n); - return rtn; -} - -void feeRandBytes(feeRand frand, - unsigned char *bytes, /* must be alloc'd by caller */ - unsigned numBytes) -{ - randInst *rinst = (randInst *) frand; - int length; - unsigned toCopy; - unsigned char *cp = bytes; - - for (length = numBytes; length > 0; length -= RANDBITS/8) { - mulg(rinst->A, rinst->SEED); - addg(rinst->C, rinst->SEED); - pmod(rinst->SEED, RANDBITS); - gtog(rinst->SEED, rinst->x); - - toCopy = RANDBITS/8; - if(length < toCopy) { - toCopy = length; - } - - /* - * FIXME - not 100% platform independent.... - */ - bcopy(rinst->x->n, cp, toCopy); - cp += toCopy; - } -} - -/* new function, 5 March 1999 - dmitch */ -void feeRandAddEntropy(feeRand frand, unsigned entropy) -{ - randInst *rinst = (randInst *) frand; - giant tmp = borrowGiant(RAND_GIANT_DIGITS); - unsigned i; - - if(entropy == 0) { - /* boy would that be a mistake */ - entropy = 0x12345; - } - for(i=0; in[i] = (giantDigit)entropy; - } - tmp->sign = RAND_GIANT_DIGITS; - mulg(tmp, rinst->SEED); - addg(rinst->C, rinst->SEED); - pmod(rinst->SEED, RANDBITS); - entropy ^= 0xff0ff0ff; - if(entropy == 0) { - entropy = 0x12345; - } - for(i=0; in[i] = (giantDigit)entropy; - } - mulg(tmp, rinst->A); - addg(rinst->C, rinst->A); - pmod(rinst->A, RANDBITS); - /* leave C alone */ - returnGiant(tmp); -} diff --git a/OSX/include/security_cryptkit/feeRandom.h b/OSX/include/security_cryptkit/feeRandom.h deleted file mode 100644 index 1bffef06..00000000 --- a/OSX/include/security_cryptkit/feeRandom.h +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * FeeRandom.h - generic, portable random number generator object - * - * Revision History - * ---------------- - * 8/25/98 ap - * Fixed previous check-in comment. - * 8/24/98 ap - * Added tags around #endif comment. - * 23 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEERANDOM_H_ -#define _CK_FEERANDOM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void *feeRand; - -feeRand feeRandAllocWithSeed(unsigned seed); -feeRand feeRandAlloc(void); - -void feeRandFree(feeRand frand); - -unsigned feeRandNextNum(feeRand frand); - -void feeRandBytes(feeRand frand, - unsigned char *bytes, /* must be alloc'd by caller */ - unsigned numBytes); - -void feeRandAddEntropy(feeRand frand, unsigned entropy); - -#ifdef __cplusplus -} -#endif - -#endif /* _CK_FEERANDOM_H_ */ diff --git a/OSX/include/security_cryptkit/feeTypes.h b/OSX/include/security_cryptkit/feeTypes.h deleted file mode 100644 index 87db4052..00000000 --- a/OSX/include/security_cryptkit/feeTypes.h +++ /dev/null @@ -1,174 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * feeTypes.h - general purpose FEE typedefs and constants - * - * Revision History - * ---------------- - * 23 Mar 98 at Apple - * Added FR_BadKeyBlob. - * 20 Jan 98 at Apple - * New PT_GENERAL depth values. - * 09 Jan 98 at Apple - * Removed obsolete FEE_DEPTH_* values. - * 20 Aug 96 at NeXT - * Created. - */ - -#ifndef _CK_FEETYPES_H_ -#define _CK_FEETYPES_H_ - -/* - * Opaque public key object. - */ -typedef void *feePubKey; - -/* - * Standard return codes. - * Remember to update frtnStrings[] in utilities.c when adding new items. - */ -typedef enum { - FR_Success = 0, - FR_BadPubKey, - FR_BadPubKeyString, - FR_IncompatibleKey, /* incompatible key */ - FR_IllegalDepth, - FR_BadUsageName, /* bad usageName */ - FR_BadSignatureFormat, /* signature corrupted */ - FR_InvalidSignature, /* signature intact, but not valid */ - FR_IllegalArg, /* illegal argument */ - FR_BadCipherText, /* malformed ciphertext */ - FR_Unimplemented, /* unimplemented function */ - FR_BadCipherFile, - FR_BadEnc64, /* bad enc64() format */ - FR_WrongSignatureType, /* ElGamal vs. ECDSA */ - FR_BadKeyBlob, - FR_IllegalCurve, /* e.g., ECDSA with Montgomery curve */ - FR_Internal, /* internal library error */ - FR_Memory, /* out of memory */ - FR_ShortPrivData /* insufficient privData for creating - * private key */ - /* etc. */ -} feeReturn; - -typedef enum { - FSF_Default, /* default */ - FSF_DER, /* DER */ - FSF_RAW, /* RAW (for ECDSA, first half is r, second half is s */ -} feeSigFormat; - -/* - * The feeDepth parameter defines one of 'n' known curves. From a user's - * perspective, the most interesting parameter indicated by feeDepth is - * the size (in bits) of the key. - */ -typedef unsigned feeDepth; - -/* - * Prime and curve description parameters. - */ -typedef enum { - FPT_Default, /* default per key size */ - FPT_Mersenne, /* (2 ** q) - 1 */ - FPT_FEE, /* (2 ** q) - k */ - FPT_General /* random prime */ -} feePrimeType; - -typedef enum { - FCT_Default, /* default per key size */ - FCT_Montgomery, /* a==1, b==0 */ - FCT_Weierstrass, /* c==0. IEEE P1363 compliant. */ - FCT_ANSI, /* ANSI X9.62/Certicom, also FCT_Weierstrass */ - FCT_General /* Other */ -} feeCurveType; - -/* - * Some commonly used feeDepth values. In these definitions, q and k are - * from the expression (2^q - k), the base modulus of the curve. The case - * k=1 implies a Mersenne prime as the modulus. - */ -#define FEE_PROTOTYPE_CURVES 0 - -#if FEE_PROTOTYPE_CURVES - - /* q k a b c */ - /* ---- ---- ---- ---- ---- */ -#define FEE_DEPTH_31_1_W 0 /* 31 1 7 1 0 */ -#define FEE_DEPTH_31_1_M 1 /* 31 1 1 0 666 */ -#define FEE_DEPTH_31_1_P 2 /* 31 1 5824692 2067311435 0 */ -#define FEE_DEPTH_40_213 3 /* 40 213 1627500953 523907505 0 */ -#define FEE_DEPTH_127_1 4 /* 127 1 1 0 666 */ -#define FEE_DEPTH_127_1W 5 /* 127 1 666 1 0 */ -#define FEE_DEPTH_160_57 6 /* 160 57 0 3 0 */ -#define FEE_DEPTH_192_1425 7 /* 192 1425 0 -11 0 */ -#define FEE_DEPTH_192_M529891 8 /* 192 -529891 -152 722 0 */ - -/* - * The remaining curves are implemented as PT_GENERAL curves; modulo - * arithmetic does not utilize any FEE or Mersenne optimizations. These - * are here for performance measurements and DVT. - */ -#define FEE_DEPTH_127_GEN 9 /* 127 1 1 0 666 */ -#define FEE_DEPTH_160_GEN 10 /* 160 57 0 3 0 */ -#define FEE_DEPTH_161_GEN 11 /* 161 .. -152 722 0 */ - -/* - * The default depth. - */ -#define FEE_DEPTH_DEFAULT FEE_DEPTH_160_57 - -/* - * Last enumerated depth. - */ -#define FEE_DEPTH_MAX FEE_DEPTH_161_GEN - -#else /* FEE_PROTOTYPE_CURVES */ - -/* - * The real curves as of 4/9/2001. - * Note that ECDSA signatures can only be performed with curve of - * curveType FCT_Weierstrass. - * - * Default curveType for curves with same prime size is FCT_Weierstrass. - */ -#define FEE_DEPTH_31M 0 /* size=31 FPT_Mersenne FCT_Montgomery */ -#define FEE_DEPTH_31W 1 /* size=31 FPT_Mersenne FCT_Weierstrass */ -#define FEE_DEPTH_127M 2 /* size=127 FPT_Mersenne FCT_Montgomery */ -#define FEE_DEPTH_128W 3 /* size=128 FPT_FEE FCT_Weierstrass */ -#define FEE_DEPTH_161W 4 /* size=161 FPT_FEE FCT_Weierstrass */ -#define FEE_DEPTH_161G 5 /* size=161 FPT_General FCT_Weierstrass */ -#define FEE_DEPTH_192G 6 /* size=192 FPT_General FCT_Weierstrass */ - -/* ANSI X9.62/Certicom curves */ -#define FEE_DEPTH_secp192r1 7 /* size=192 FPT_General FCT_ANSI */ -#define FEE_DEPTH_secp256r1 8 /* size=256 FPT_General FCT_ANSI */ -#define FEE_DEPTH_secp384r1 9 /* size=384 FPT_General FCT_ANSI */ -#define FEE_DEPTH_secp521r1 10 /* size=521 FPT_General FCT_ANSI */ -/* - * The default depth. - */ -#define FEE_DEPTH_DEFAULT FEE_DEPTH_161W - -/* - * Last enumerated depth. - */ -#define FEE_DEPTH_MAX FEE_DEPTH_secp521r1 - -#endif /* FEE_PROTOTYPE_CURVES */ - -/* - * Random number generator callback function. - */ -typedef feeReturn (*feeRandFcn)( - void *ref, - unsigned char *bytes, /* must be alloc'd by caller */ - unsigned numBytes); - -#endif /* _CK_FEETYPES_H_ */ diff --git a/OSX/include/security_cryptkit/giantFFT.c b/OSX/include/security_cryptkit/giantFFT.c deleted file mode 100644 index 21e91983..00000000 --- a/OSX/include/security_cryptkit/giantFFT.c +++ /dev/null @@ -1,519 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - - giantFFT.c - Library for large-integer arithmetic via FFT. Currently unused - in CryptKit. - - - Revision History - ---------------- - 19 Jan 1998 at Apple - Split off from NSGiantIntegers.c. - -*/ - -/* - * FIXME - make sure platform-specific math lib has floor(), fmod(), - * sin(), pow() - */ -#include -#include "NSGiantIntegers.h" - -#define AUTO_MUL 0 -#define GRAMMAR_MUL 1 -#define FFT_MUL 2 - -#define TWOPI (double)(2*3.1415926535897932384626433) -#define SQRT2 (double)(1.414213562373095048801688724209) -#define SQRTHALF (double)(0.707106781186547524400844362104) -#define TWO16 (double)(65536.0) -#define TWOM16 (double)(0.0000152587890625) -#define BREAK_SHORTS 400 // Number of shorts at which FFT breaks over. - -static int lpt(int n, int *lambda); -static void mul_hermitian(double *a, double *b, int n) ; -static void square_hermitian(double *b, int n); -static void addsignal(giant x, double *zs, int n); -static void scramble_real(double *x, int n); -static void fft_real_to_hermitian(double *zs, int n); -static void fftinv_hermitian_to_real(double *zs, int n); -static void GiantFFTSquare(giant gx); -static void GiantFFTMul(giant,giant); -static void giant_to_double(giant x, int sizex, double *zs, int L); - -static int mulmode = AUTO_MUL; - -void mulg(giant a, giant b) { /* b becomes a*b. */ - PROF_START; - INCR_MULGS; - GiantAuxMul(a,b); - #if FEE_DEBUG - (void)bitlen(b); // XXX - #endif FEE_DEBUG - PROF_END(mulgTime); - PROF_INCR(numMulg); -} - -static void GiantAuxMul(giant a, giant b) { -/* Optimized general multiply, b becomes a*b. Modes are: - AUTO_MUL: switch according to empirical speed criteria. - GRAMMAR_MUL: force grammar-school algorithm. - FFT_MUL: force floating point FFT method. -*/ - int square = (a==b); - - if (isZero(b)) return; - if (isZero(a)) { - gtog(a, b); - return; - } - switch(mulmode) { - case GRAMMAR_MUL: - GiantGrammarMul(a,b); - break; - case FFT_MUL: - if (square) { - GiantFFTSquare(b); - } - else { - GiantFFTMul(a,b); - } - break; - case AUTO_MUL: { - int sizea, sizeb; - float grammartime; - sizea = abs(a->sign); - sizeb = abs(b->sign); - grammartime = sizea; grammartime *= sizeb; - if(grammartime < BREAK_SHORTS*BREAK_SHORTS) { - GiantGrammarMul(a,b); - } - else { - if (square) GiantFFTSquare(b); - else GiantFFTMul(a,b); - } - break; - } - } -} - -/***************** Commence FFT multiply routines ****************/ - -static int CurrentRun = 0; -double *sincos = NULL; -static void init_sincos(int n) { - int j; - double e = TWOPI/n; - - if (n <= CurrentRun) return; - CurrentRun = n; - if (sincos) free(sincos); - sincos = (double *)malloc(sizeof(double)*(1+(n>>2))); - for(j=0;j<=(n>>2);j++) { - sincos[j] = sin(e*j); - } -} - -static double s_sin(int n) { - int seg = n/(CurrentRun>>2); - - switch(seg) { - case 0: return(sincos[n]); - case 1: return(sincos[(CurrentRun>>1)-n]); - case 2: return(-sincos[n-(CurrentRun>>1)]); - case 3: - default: return(-sincos[CurrentRun-n]); - } -} - -static double s_cos(int n) { - int quart = (CurrentRun>>2); - - if (n < quart) return(s_sin(n+quart)); - return(-s_sin(n-quart)); -} - - -static int lpt(int n, int *lambda) { -/* returns least power of two greater than n */ - register int i = 1; - - *lambda = 0; - while(imaxerr) maxerr = err; - */ - - zs[j] =0; - k = 0; - do{ - g = floor(f*TWOM16); - zs[j+k] += f-g*TWO16; - ++k; - f=g; - } while(f != 0.0); - } - car = 0; - for(j=0;jn[j] = m & 0xffff; - car = (m>>16); - } - if(car) x->n[j] = car; - else --j; - while(!(x->n[j])) --j; - x->sign = j+1; - if (abs(x->sign) > x->capacity) NSGiantRaise("addsignal overflow"); -} - -static void GiantFFTSquare(giant gx) { - int j,size = abs(gx->sign); - register int L; - - if(size<4) { GiantGrammarMul(gx,gx); return; } - L = lpt(size+size, &j); - { - //was...double doubles[L]; - //is... - double *doubles = malloc(sizeof(double) * L); - // end - giant_to_double(gx, size, doubles, L); - fft_real_to_hermitian(doubles, L); - square_hermitian(doubles, L); - fftinv_hermitian_to_real(doubles, L); - addsignal(gx, doubles, L); - // new - free(doubles); - } - gx->sign = abs(gx->sign); - bitlen(gx); // XXX - if (abs(gx->sign) > gx->capacity) NSGiantRaise("GiantFFTSquare overflow"); -} - -static void GiantFFTMul(giant y, giant x) { /* x becomes y*x. */ - int lambda, size, sizex = abs(x->sign), sizey = abs(y->sign); - int finalsign = gsign(x)*gsign(y); - register int L; - - if((sizex<=4)||(sizey<=4)) { GiantGrammarMul(y,x); return; } - size = sizex; if(sizesign = finalsign*abs(x->sign); - bitlen(x); // XXX - if (abs(x->sign) > x->capacity) NSGiantRaise("GiantFFTMul overflow"); -} - -static void scramble_real(double *x, int n) { - register int i,j,k; - register double tmp; - - for(i=0,j=0;i>=1; - } - j += k; - } -} - -static void fft_real_to_hermitian(double *zs, int n) { -/* Output is {Re(z^[0]),...,Re(z^[n/2),Im(z^[n/2-1]),...,Im(z^[1]). - This is a decimation-in-time, split-radix algorithm. - */ - register double cc1, ss1, cc3, ss3; - register int is, iD, i0, i1, i2, i3, i4, i5, i6, i7, i8, - a, a3, b, b3, nminus = n-1, dil, expand; - register double *x, e; - int nn = n>>1; - double t1, t2, t3, t4, t5, t6; - register int n2, n4, n8, i, j; - - init_sincos(n); - expand = CurrentRun/n; - scramble_real(zs, n); - x = zs-1; /* FORTRAN compatibility. */ - is = 1; - iD = 4; - do{ - for(i0=is;i0<=n;i0+=iD) { - i1 = i0+1; - e = x[i0]; - x[i0] = e + x[i1]; - x[i1] = e - x[i1]; - } - is = (iD<<1)-1; - iD <<= 2; - } while(is>=1) { - n2 <<= 1; - n4 = n2>>2; - n8 = n2>>3; - is = 0; - iD = n2<<1; - do { - for(i=is;i>1; - double t1, t2, t3, t4, t5; - int n2, n4, n8, i, j; - - init_sincos(n); - expand = CurrentRun/n; - x = zs-1; - n2 = n<<1; - while(nn >>= 1) { - is = 0; - iD = n2; - n2 >>= 1; - n4 = n2>>2; - n8 = n4>>1; - do { - for(i=is;i>1; - register double aa, bb, am, bm; - - b[0] *= a[0]; - b[half] *= a[half]; - for(k=1;k>1; - register double c, d; - - b[0] *= b[0]; - b[half] *= b[half]; - for(k=1;kn[j]; - } -} diff --git a/OSX/include/security_cryptkit/giantIntegers.c b/OSX/include/security_cryptkit/giantIntegers.c deleted file mode 100644 index e7872b58..00000000 --- a/OSX/include/security_cryptkit/giantIntegers.c +++ /dev/null @@ -1,1744 +0,0 @@ -/* Copyright (c) 1998,2011-2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - - giantIntegers.c - library for large-integer arithmetic. - - Revision History - ---------------- - Fixed a==b bug in addg(). - 10/06/98 ap - Changed to compile with C++. - 13 Apr 98 Fixed shiftright(1) bug in modg_via_recip. - 09 Apr 98 at Apple - Major rewrite of core arithmetic routines to make this module - independent of size of giantDigit. - Removed idivg() and radixdiv(). - 20 Jan 98 at Apple - Deleted FFT arithmetic; simplified mulg(). - 09 Jan 98 at Apple - gshiftright() optimization. - 08 Jan 98 at Apple - newGiant() returns NULL on malloc failure - 24 Dec 97 at Apple - New grammarSquare(); optimized modg_via_recip() - 11 Jun 97 at Apple - Added modg_via_recip(), divg_via_recip(), make_recip() - Added new multiple giant stack mechanism - Fixed potential packing/alignment bug in copyGiant() - Added profiling for borrowGiant(), returnGiant() - Deleted obsolete ifdef'd code - Deleted newgiant() - All calls to borrowGiant() now specify required size (no more - borrowGiant(0) calls) - 08 May 97 at Apple - Changed size of giantstruct.n to 1 for Mac build - 05 Feb 97 at Apple - newGiant() no longer modifies CurrentMaxShorts or giant stack - Added modg profiling - 01 Feb 97 at NeXT - Added iszero() check in gcompg - 17 Jan 97 at NeXT - Fixed negation bug in gmersennemod() - Fixed n[words-1] == 0 bug in extractbits() - Cleaned up lots of static declarations - 19 Sep 96 at NeXT - Fixed --size underflow bug in normal_subg(). - 4 Sep 96 at NeXT - Fixed (b -#include -#include -#include "platform.h" -#include "giantIntegers.h" -#include "feeDebug.h" -#include "ckconfig.h" -#include "ellipticMeasure.h" -#include "falloc.h" -#include "giantPortCommon.h" - -#ifdef FEE_DEBUG -#if (GIANT_LOG2_BITS_PER_DIGIT == 4) -#warning Compiling with two-byte giantDigits -#endif -#endif - -#if 0 -#if FEE_DEBUG -char printbuf1[200]; -char printbuf2[200]; -char printbuf3[200]; -void printGiantBuf(giant x) -{ - int i; - - sprintf(printbuf2, "sign=%d cap=%d n[]=", x->sign, x->capacity); - for(i=0; isign); i++) { - sprintf(printbuf3 + 10*i, "%u:", x->n[i]); - } -} - -char printbuf4[200]; -char printbuf5[200]; -void printGiantBuf2(giant x) -{ - int i; - - sprintf(printbuf4, "sign=%d cap=%d n[]=", x->sign, x->capacity); - for(i=0; isign); i++) { - sprintf(printbuf5 + 10*i, "%u:", x->n[i]); - } -} -#endif /* FEE_DEBUG */ -#endif /* 0 */ - -/******** debugging flags *********/ - -/* - * Flag use of unoptimized divg, modg, binvg - */ -//#define WARN_UNOPTIMIZE FEE_DEBUG -#define WARN_UNOPTIMIZE 0 - -/* - * Log interesting giant stack events - */ -#define LOG_GIANT_STACK 0 - -/* - * Log allocation of giant larger than stack size - */ -#define LOG_GIANT_STACK_OVERFLOW 1 - -/* - * Flag newGiant(0) and borrowGiant(0) calls - */ -#define WARN_ZERO_GIANT_SIZE FEE_DEBUG - -/* temp mac-only giant initialization debug */ -#define GIANT_MAC_DEBUG 0 -#if GIANT_MAC_DEBUG - -#include -#include - -/* this one needs a writable string */ -static void logCom(unsigned char *str) { - c2pstr((char *)str); - DebugStr(str); -} - -/* constant strings */ -void dblog0(const char *str) { - Str255 outStr; - strcpy((char *)outStr, str); - logCom(outStr); -} - -#else -#define dblog0(s) - -#endif /* GIANT_MAC_DEBUG */ - -#ifndef min -#define min(a,b) ((a)<(b)? (a) : (b)) -#endif // min -#ifndef max -#define max(a,b) ((a)>(b)? (a) : (b)) -#endif // max - -#ifndef TRUE -#define TRUE 1 -#endif // TRUE -#ifndef FALSE -#define FALSE 0 -#endif // FALSE - -static void absg(giant g); /* g := |g|. */ - -/************** globals *******************/ - - -/* ------ giant stack package ------ */ - -/* - * The giant stack package is a local cache which allows us to avoid calls - * to malloc() for borrowGiant(). On a 90 Mhz Pentium, enabling the - * giant stack package shows about a 1.35 speedup factor over an identical - * CryptKit without the giant stacks enabled. - */ - -#if GIANTS_VIA_STACK - -#if LOG_GIANT_STACK -#define gstackDbg(x) printf x -#else // LOG_GIANT_STACK -#define gstackDbg(x) -#endif // LOG_GIANT_STACK - -typedef struct { - unsigned numDigits; // capacity of giants in this stack - unsigned numFree; // number of free giants in stack - unsigned totalGiants; // total number in *stack - giant *stack; -} gstack; - -static gstack *gstacks = NULL; // array of stacks -static unsigned numGstacks = 0; // # of elements in gstacks -static int gstackInitd = 0; // this module has been init'd - -#define INIT_NUM_GIANTS 16 /* initial # of giants / stack */ -#define MIN_GIANT_SIZE 4 /* numDigits for gstack[0] */ -#define GIANT_SIZE_INCR 2 /* in << bits */ - -/* - * Initialize giant stacks, with up to specified max giant size. - */ -void initGiantStacks(unsigned maxDigits) -{ - unsigned curSize = MIN_GIANT_SIZE; - unsigned sz; - unsigned i; - - dblog0("initGiantStacks\n"); - - if(gstackInitd) { - /* - * Shouldn't be called more than once... - */ - printf("multiple initGiantStacks calls\n"); - return; - } - gstackDbg(("initGiantStacks(%d)\n", maxDigits)); - - /* - * How many stacks? - */ - numGstacks = 1; - while(curSize<=maxDigits) { - curSize <<= GIANT_SIZE_INCR; - numGstacks++; - } - - sz = sizeof(gstack) * numGstacks; - gstacks = (gstack*) fmalloc(sz); - bzero(gstacks, sz); - - curSize = MIN_GIANT_SIZE; - for(i=0; inumFree; j++) { - freeGiant(gs->stack[j]); - gs->stack[j] = NULL; - } - /* and the stack itself - may be null if this was never used */ - if(gs->stack != NULL) { - ffree(gs->stack); - gs->stack = NULL; - } - } - ffree(gstacks); - gstacks = NULL; - gstackInitd = 0; -} - -#endif // GIANTS_VIA_STACK - -giant borrowGiant(unsigned numDigits) -{ - giant result; - - #if GIANTS_VIA_STACK - - unsigned stackNum; - gstack *gs = gstacks; - - #if WARN_ZERO_GIANT_SIZE - if(numDigits == 0) { - printf("borrowGiant(0)\n"); - numDigits = gstacks[numGstacks-1].numDigits; - } - #endif // WARN_ZERO_GIANT_SIZE - - /* - * Find appropriate stack - */ - if(numDigits <= MIN_GIANT_SIZE) - stackNum = 0; - else if (numDigits <= (MIN_GIANT_SIZE << GIANT_SIZE_INCR)) - stackNum = 1; - else if (numDigits <= (MIN_GIANT_SIZE << (2 * GIANT_SIZE_INCR))) - stackNum = 2; - else if (numDigits <= (MIN_GIANT_SIZE << (3 * GIANT_SIZE_INCR))) - stackNum = 3; - else if (numDigits <= (MIN_GIANT_SIZE << (4 * GIANT_SIZE_INCR))) - stackNum = 4; - else - stackNum = numGstacks; - - if(stackNum >= numGstacks) { - /* - * out of bounds; just malloc - */ - #if LOG_GIANT_STACK_OVERFLOW - gstackDbg(("giantFromStack overflow; numDigits %d\n", - numDigits)); - #endif // LOG_GIANT_STACK_OVERFLOW - return newGiant(numDigits); - } - gs = &gstacks[stackNum]; - - #if GIANT_MAC_DEBUG - if((gs->numFree != 0) && (gs->stack == NULL)) { - dblog0("borrowGiant: null stack!\n"); - } - #endif - - if(gs->numFree != 0) { - result = gs->stack[--gs->numFree]; - } - else { - /* - * Stack empty; malloc - */ - result = newGiant(gs->numDigits); - } - - #else /* GIANTS_VIA_STACK */ - - result = newGiant(numDigits); - - #endif /* GIANTS_VIA_STACK */ - - PROF_INCR(numBorrows); - return result; -} - -void returnGiant(giant g) -{ - - #if GIANTS_VIA_STACK - - unsigned stackNum; - gstack *gs; - unsigned cap = g->capacity; - - - #if FEE_DEBUG - if(!gstackInitd) { - CKRaise("returnGiant before stacks initialized!"); - } - #endif // FEE_DEBUG - - #if GIANT_MAC_DEBUG - if(g == NULL) { - dblog0("returnGiant: null g!\n"); - } - #endif - - /* - * Find appropriate stack. Note we expect exact match of - * capacity and stack's giant size. - */ - /* - * Optimized unrolled loop. Just make sure there are enough cases - * to handle all of the stacks. Errors in this case will be flagged - * via LOG_GIANT_STACK_OVERFLOW. - */ - switch(cap) { - case MIN_GIANT_SIZE: - stackNum = 0; - break; - case MIN_GIANT_SIZE << GIANT_SIZE_INCR: - stackNum = 1; - break; - case MIN_GIANT_SIZE << (2 * GIANT_SIZE_INCR): - stackNum = 2; - break; - case MIN_GIANT_SIZE << (3 * GIANT_SIZE_INCR): - stackNum = 3; - break; - case MIN_GIANT_SIZE << (4 * GIANT_SIZE_INCR): - stackNum = 4; - break; - default: - stackNum = numGstacks; - break; - } - - if(stackNum >= numGstacks) { - /* - * out of bounds; just free - */ - #if LOG_GIANT_STACK_OVERFLOW - gstackDbg(("giantToStack overflow; numDigits %d\n", cap)); - #endif // LOG_GIANT_STACK_OVERFLOW - freeGiant(g); - return; - } - gs = &gstacks[stackNum]; - if(gs->numFree == gs->totalGiants) { - if(gs->totalGiants == 0) { - gstackDbg(("Initial alloc of gstack(%d)\n", - gs->numDigits)); - gs->totalGiants = INIT_NUM_GIANTS; - } - else { - gs->totalGiants *= 2; - gstackDbg(("Bumping gstack(%d) to %d\n", - gs->numDigits, gs->totalGiants)); - } - gs->stack = (giantstruct**) frealloc(gs->stack, gs->totalGiants*sizeof(giant)); - } - g->sign = 0; // not sure this is important... - gs->stack[gs->numFree++] = g; - - #if GIANT_MAC_DEBUG - if((gs->numFree != 0) && (gs->stack == NULL)) { - dblog0("borrowGiant: null stack!\n"); - } - #endif - - #else /* GIANTS_VIA_STACK */ - - freeGiant(g); - - #endif /* GIANTS_VIA_STACK */ -} - -void freeGiant(giant x) { - ffree(x); -} - -giant newGiant(unsigned numDigits) { - // giant sufficient for 2^numbits+16 sized ops - int size; - giant result; - - #if WARN_ZERO_GIANT_SIZE - if(numDigits == 0) { - printf("newGiant(0)\n"); - #if GIANTS_VIA_STACK - numDigits = gstacks[numGstacks-1].totalGiants; - #else - /* HACK */ - numDigits = 20; - #endif - } - #endif // WARN_ZERO_GIANT_SIZE - - size = (numDigits-1) * GIANT_BYTES_PER_DIGIT + sizeof(giantstruct); - result = (giant)fmalloc(size); - if(result == NULL) { - return NULL; - } - result->sign = 0; - result->capacity = numDigits; - return result; -} - -giant copyGiant(giant x) -{ - int bytes; - - giant result = newGiant(x->capacity); - - /* - * 13 Jun 1997 - * NO! this assumes packed alignment - */ - bytes = sizeof(giantstruct) + - ((x->capacity - 1) * GIANT_BYTES_PER_DIGIT); - bcopy(x, result, bytes); - return result; -} - -/* ------ initialization and utility routines ------ */ - - -unsigned bitlen(giant n) { - unsigned b = GIANT_BITS_PER_DIGIT; - giantDigit c = 1 << (GIANT_BITS_PER_DIGIT - 1); - giantDigit w; - - if (isZero(n)) { - return(0); - } - w = n->n[abs(n->sign) - 1]; - if (!w) { - CKRaise("bitlen - no bit set!"); - } - while((w&c) == 0) { - b--; - c >>= 1; - } - return(GIANT_BITS_PER_DIGIT * (abs(n->sign)-1) + b); -} - -int bitval(giant n, int pos) { - int i = abs(pos) >> GIANT_LOG2_BITS_PER_DIGIT; - giantDigit c = 1 << (pos & (GIANT_BITS_PER_DIGIT - 1)); - - return((n->n[i]) & c); -} - -int gsign(giant g) -/* returns the sign of g */ -{ - if (isZero(g)) return(0); - if (g->sign > 0) return(1); - return(-1); -} - -/* - * Adjust sign for possible leading (m.s.) zero digits - */ -void gtrimSign(giant g) -{ - int numDigits = abs(g->sign); - int i; - - for(i=numDigits-1; i>=0; i--) { - if(g->n[i] == 0) { - numDigits--; - } - else { - break; - } - } - if(g->sign < 0) { - g->sign = -numDigits; - } - else { - g->sign = numDigits; - } -} - - -int isone(giant g) { - return((g->sign==1)&&(g->n[0]==1)); -} - -int isZero(giant thegiant) { -/* Returns TRUE if thegiant == 0. */ - int count; - int length = abs(thegiant->sign); - giantDigit *numpointer; - - if (length) { - numpointer = thegiant->n; - - for(count = 0; countb, respectively */ -{ - int sa = a->sign; - int j; - int sb = b->sign; - giantDigit va; - giantDigit vb; - int sgn; - - if(isZero(a) && isZero(b)) return 0; - if(sa > sb) return(1); - if(sa < sb) return(-1); - if(sa < 0) { - sa = -sa; /* Take absolute value of sa */ - sgn = -1; - } else sgn = 1; - for(j = sa-1; j >= 0; j--) { - va = a->n[j]; vb = b->n[j]; - if (va > vb) return(sgn); - if (va < vb) return(-sgn); - } - return(0); -} - -/* destgiant becomes equal to srcgiant */ -void gtog(giant srcgiant, giant destgiant) { - - int numbytes; - - CKASSERT(srcgiant != NULL); - numbytes = abs(srcgiant->sign) * GIANT_BYTES_PER_DIGIT; - if (destgiant->capacity < abs(srcgiant->sign)) - CKRaise("gtog overflow!!"); - memcpy((char *)destgiant->n, (char *)srcgiant->n, numbytes); - destgiant->sign = srcgiant->sign; -} - -void int_to_giant(int i, giant g) { -/* The giant g becomes set to the integer value i. */ - int isneg = (i<0); - unsigned int j = abs(i); - unsigned dex; - - g->sign = 0; - if (i==0) { - g->n[0] = 0; - return; - } - - if(GIANT_BYTES_PER_DIGIT == sizeof(int)) { - g->n[0] = j; - g->sign = 1; - } - else { - /* one loop per digit */ - unsigned scnt = GIANT_BITS_PER_DIGIT; // fool compiler - - for(dex=0; dexn[dex] = j & GIANT_DIGIT_MASK; - j >>= scnt; - g->sign++; - if(j == 0) { - break; - } - } - } - if (isneg) { - g->sign = -(g->sign); - } -} - -/*------------- Arithmetic --------------*/ - -void negg(giant g) { -/* g becomes -g */ - g->sign = -g->sign; -} - -void iaddg(int i, giant g) { /* positive g becomes g + (int)i */ - int j; - giantDigit carry; - int size = abs(g->sign); - - if (isZero(g)) { - int_to_giant(i,g); - } - else { - carry = i; - for(j=0; ((jn[j] = giantAddDigits(g->n[j], carry, &carry); - } - if(carry) { - ++g->sign; - // realloc - if (g->sign > (int)g->capacity) CKRaise("iaddg overflow!"); - g->n[size] = carry; - } - } -} - -/* - * g *= (int n) - * - * FIXME - we can improve this... - */ -void imulg(unsigned n, giant g) -{ - giant tmp = borrowGiant(abs(g->sign) + sizeof(int)); - - int_to_giant(n, tmp); - mulg(tmp, g); - returnGiant(tmp); -} - -static void normal_addg(giant a, giant b) -/* b := a + b, both a,b assumed non-negative. */ -{ - giantDigit carry1 = 0; - giantDigit carry2 = 0; - int asize = a->sign, bsize = b->sign; - giantDigit *an = a->n; - giantDigit *bn = b->n; - giantDigit tmp; - int j; - int comSize; - int maxSize; - - if(asize < bsize) { - comSize = asize; - maxSize = bsize; - } - else { - comSize = bsize; - maxSize = asize; - } - - /* first handle the common digits */ - for(j=0; jsign = maxSize; - if(carry1) { - // realloc? - bn[j] = 1; - b->sign++; - if (b->sign > (int)b->capacity) CKRaise("iaddg overflow!"); - } - -} - -static void normal_subg(giant a, giant b) -/* b := b - a; requires b, a non-negative and b >= a. */ -{ - int j; - int size = b->sign; - giantDigit tmp; - giantDigit borrow1 = 0; - giantDigit borrow2 = 0; - giantDigit *an = a->n; - giantDigit *bn = b->n; - - if(a->sign == 0) { - return; - } - - for (j=0; jsign; ++j) { - if(borrow1 || borrow2) { - tmp = giantSubDigits(bn[j], (giantDigit)1, &borrow1); - } - else { - tmp = bn[j]; - borrow1 = 0; - } - bn[j] = giantSubDigits(tmp, an[j], &borrow2); - } - if(borrow1 || borrow2) { - /* propagate borrow thru remainder of bn[] */ - borrow1 = 1; - for (j=a->sign; j 0) && (b->n[size] == 0)) - ; - b->sign = (b->n[size] == 0)? 0 : size+1; -} - -static void reverse_subg(giant a, giant b) -/* b := a - b; requires b, a non-negative and a >= b. */ -{ - int j; - int size = a->sign; - giantDigit tmp; - giantDigit borrow1 = 0; - giantDigit borrow2 = 0; - giantDigit *an = a->n; - giantDigit *bn = b->n; - - if(b->sign == 0) { - gtog(a, b); - return; - } - for (j=0; jsign; ++j) { - if(borrow1 || borrow2) { - tmp = giantSubDigits(an[j], (giantDigit)1, &borrow1); - } - else { - tmp = an[j]; - borrow1 = 0; - } - bn[j] = giantSubDigits(tmp, bn[j], &borrow2); - } - if(borrow1 || borrow2) { - /* propagate borrow thru remainder of bn[] */ - borrow1 = 1; - } - for (j=b->sign; jsign = size; /* REC, 21 Apr 1996. */ - while(!b->n[--size]); - b->sign = size+1; -} - - -void addg(giant a, giant b) -/* b := b + a, any signs any result. */ -{ int asgn = a->sign, bsgn = b->sign; - if(asgn == 0) return; - if(bsgn == 0) { - gtog(a,b); - return; - } - if((asgn < 0) == (bsgn < 0)) { - if(bsgn > 0) { - normal_addg(a,b); - return; - } - negg(a); if(a != b) negg(b); normal_addg(a,b); /* Fix REC 1 Dec 98. */ - negg(a); if(a != b) negg(b); return; /* Fix REC 1 Dec 98. */ - } - if(bsgn > 0) { - negg(a); - if(gcompg(b,a) >= 0) { - normal_subg(a,b); - negg(a); - return; - } - reverse_subg(a,b); - negg(a); - negg(b); - return; - } - negg(b); - if(gcompg(b,a) < 0) { - reverse_subg(a,b); - return; - } - normal_subg(a,b); - negg(b); - return; -} - -void subg(giant a, giant b) -/* b := b - a, any signs, any result. */ -{ - int asgn = a->sign, bsgn = b->sign; - if(asgn == 0) return; - if(bsgn == 0) { - gtog(a,b); - negg(b); - return; - } - if((asgn < 0) != (bsgn < 0)) { - if(bsgn > 0) { - negg(a); - normal_addg(a,b); - negg(a); - return; - } - negg(b); - normal_addg(a,b); - negg(b); - return; - } - if(bsgn > 0) { - if(gcompg(b,a) >= 0) { - normal_subg(a,b); - return; - } - reverse_subg(a,b); - negg(b); - return; - } - negg(a); negg(b); - if(gcompg(b,a) >= 0) { - normal_subg(a,b); - negg(a); - negg(b); - return; - } - reverse_subg(a,b); - negg(a); - return; -} - -static void bdivg(giant v, giant u) -/* u becomes greatest power of two not exceeding u/v. */ -{ - int diff = bitlen(u) - bitlen(v); - giant scratch7; - - if (diff<0) { - int_to_giant(0,u); - return; - } - scratch7 = borrowGiant(u->capacity); - gtog(v, scratch7); - gshiftleft(diff,scratch7); - if(gcompg(u,scratch7) < 0) diff--; - if(diff<0) { - int_to_giant(0,u); - returnGiant(scratch7); - return; - } - int_to_giant(1,u); - gshiftleft(diff,u); - returnGiant(scratch7); -} - -int binvaux(giant p, giant x) -/* Binary inverse method. - Returns zero if no inverse exists, in which case x becomes - GCD(x,p). */ -{ - giant scratch7; - giant u0; - giant u1; - giant v0; - giant v1; - int result = 1; - int giantSize; - PROF_START; - - if(isone(x)) return(result); - giantSize = 4 * abs(p->sign); - scratch7 = borrowGiant(giantSize); - u0 = borrowGiant(giantSize); - u1 = borrowGiant(giantSize); - v0 = borrowGiant(giantSize); - v1 = borrowGiant(giantSize); - int_to_giant(1, v0); gtog(x, v1); - int_to_giant(0,x); gtog(p, u1); - while(!isZero(v1)) { - gtog(u1, u0); bdivg(v1, u0); - gtog(x, scratch7); - gtog(v0, x); - mulg(u0, v0); - subg(v0,scratch7); - gtog(scratch7, v0); - - gtog(u1, scratch7); - gtog(v1, u1); - mulg(u0, v1); - subg(v1,scratch7); - gtog(scratch7, v1); - } - if (!isone(u1)) { - gtog(u1,x); - if(x->sign<0) addg(p, x); - result = 0; - goto done; - } - if (x->sign<0) addg(p, x); - done: - returnGiant(scratch7); - returnGiant(u0); - returnGiant(u1); - returnGiant(v0); - returnGiant(v1); - PROF_END(binvauxTime); - return(result); -} - -/* - * Superceded by binvg_cp() - */ -#if 0 -int binvg(giant p, giant x) -{ - modg(p, x); - return(binvaux(p,x)); -} -#endif - -static void absg(giant g) { -/* g becomes the absolute value of g */ - if (g->sign < 0) g->sign = -g->sign; -} - -void gshiftleft(int bits, giant g) { -/* shift g left bits bits. Equivalent to g = g*2^bits */ - int rem = bits & (GIANT_BITS_PER_DIGIT - 1); - int crem = GIANT_BITS_PER_DIGIT - rem; - int digits = 1 + (bits >> GIANT_LOG2_BITS_PER_DIGIT); - int size = abs(g->sign); - int j; - int k; - int sign = gsign(g); - giantDigit carry; - giantDigit dat; - - #if FEE_DEBUG - if(bits < 0) { - CKRaise("gshiftleft(-bits)\n"); - } - #endif /* FEE_DEBUG */ - - if(!bits) return; - if(!size) return; - if((size+digits) > (int)g->capacity) { - CKRaise("gshiftleft overflow"); - return; - } - k = size - 1 + digits; // (MSD of result + 1) - carry = 0; - - /* bug fix for 32-bit giantDigits; this is also an optimization for - * other sizes. rem=0 means we're shifting strictly by digits, no - * bit shifts. */ - if(rem == 0) { - g->n[k] = 0; // XXX hack - for sign fixup - for(j=size-1; j>=0; j--) { - g->n[--k] = g->n[j]; - } - do{ - g->n[--k] = 0; - } while(k>0); - } - else { - /* - * normal unaligned case - * FIXME - this writes past g->n[size-1] the first time thru! - */ - for(j=size-1; j>=0; j--) { - dat = g->n[j]; - g->n[k--] = (dat >> crem) | carry; - carry = (dat << rem); - } - do{ - g->n[k--] = carry; - carry = 0; - } while(k>=0); - } - k = size - 1 + digits; - if(g->n[k] == 0) --k; - g->sign = sign * (k+1); - if (abs(g->sign) > g->capacity) { - CKRaise("gshiftleft overflow"); - } -} - -void gshiftright(int bits, giant g) { -/* shift g right bits bits. Equivalent to g = g/2^bits */ - int j; - int size=abs(g->sign); - giantDigit carry; - int digits = bits >> GIANT_LOG2_BITS_PER_DIGIT; - int remain = bits & (GIANT_BITS_PER_DIGIT - 1); - int cremain = GIANT_BITS_PER_DIGIT - remain; - - #if FEE_DEBUG - if(bits < 0) { - CKRaise("gshiftright(-bits)\n"); - } - #endif /* FEE_DEBUG */ - if(bits==0) return; - if(isZero(g)) return; - if (digits >= size) { - g->sign = 0; - return; - } - - size -= digits; - -/* Begin OPT: 9 Jan 98 REC. */ - if(remain == 0) { - if(g->sign > 0) { - g->sign = size; - } - else { - g->sign = -size; - } - for(j=0; j < size; j++) { - g->n[j] = g->n[j+digits]; - } - return; - } -/* End OPT: 9 Jan 98 REC. */ - - for(j=0;jn[j+digits+1]) << cremain; - } - g->n[j] = ((g->n[j+digits]) >> remain ) | carry; - } - if (g->n[size-1] == 0) { - --size; - } - if(g->sign > 0) { - g->sign = size; - } - else { - g->sign = -size; - } - if (abs(g->sign) > g->capacity) { - CKRaise("gshiftright overflow"); - } -} - - -void extractbits(unsigned n, giant src, giant dest) { -/* dest becomes lowermost n bits of src. Equivalent to dest = src % 2^n */ - int digits = n >> GIANT_LOG2_BITS_PER_DIGIT; - int numbytes = digits * GIANT_BYTES_PER_DIGIT; - int bits = n & (GIANT_BITS_PER_DIGIT - 1); - - if (n <= 0) { - return; - } - if (dest->capacity * 8 * GIANT_BYTES_PER_DIGIT < n) { - CKRaise("extractbits - not enough room"); - } - if (digits >= abs(src->sign)) { - gtog(src,dest); - } - else { - memcpy((char *)(dest->n), (char *)(src->n), numbytes); - if (bits) { - dest->n[digits] = src->n[digits] & ((1<n[words-1] == 0) && (words > 0)) --words; - while((digits > 0) && (dest->n[digits-1] == 0)) { - --digits; - } - if(src->sign < 0) { - dest->sign = -digits; - } - else { - dest->sign = digits; - } - } - if (abs(dest->sign) > dest->capacity) { - CKRaise("extractbits overflow"); - } -} - -#define NEW_MERSENNE 0 - -/* - * New gmersennemod, 24 Dec 1997. This runs significantly slower than the - * original. - */ -#if NEW_MERSENNE - -void -gmersennemod( - int n, - giant g -) -/* g := g (mod 2^n - 1) */ -{ - int the_sign; - giant scratch3 = borrowGiant(g->capacity); - giant scratch4 = borrowGiant(1); - - if ((the_sign = gsign(g)) < 0) absg(g); - while (bitlen(g) > n) { - gtog(g,scratch3); - gshiftright(n,scratch3); - addg(scratch3,g); - gshiftleft(n,scratch3); - subg(scratch3,g); - } - if(isZero(g)) goto out; - int_to_giant(1,scratch3); - gshiftleft(n,scratch3); - int_to_giant(1,scratch4); - subg(scratch4,scratch3); - if(gcompg(g,scratch3) >= 0) subg(scratch3,g); - if (the_sign < 0) { - g->sign = -g->sign; - addg(scratch3,g); - } -out: - returnGiant(scratch3); - returnGiant(scratch4); -} - -#else /* NEW_MERSENNE */ - -void gmersennemod(int n, giant g) { -/* g becomes g mod ((2^n)-1) - 31 Jul 96 modified REC. - 17 Jan 97 modified REC. -*/ - unsigned bits = n & (GIANT_BITS_PER_DIGIT - 1); - unsigned digits = 1 + ((n-1) >> GIANT_LOG2_BITS_PER_DIGIT); - int isPositive = (g->sign > 0); - int j; - int b; - int size; - int foundzero; - giantDigit mask = (bits == 0) ? GIANT_DIGIT_MASK : (giantDigit)((1<> - GIANT_LOG2_BITS_PER_DIGIT; - giantDigit lastWord = 0; - giantDigit bits = 1; - - if(g->sign >= 0) return; - - /* - * Cons up ((2**n)-1), add to g. - */ - scratch1 = borrowGiant(numDigits + 1); - scratch1->sign = numDigits; - for(j=0; j<(int)(numDigits-1); j++) { - scratch1->n[j] = GIANT_DIGIT_MASK; - } - - /* - * Last word has lower (n & (GIANT_BITS_PER_DIGIT-1)) bits set. - */ - for(j=0; j < (int)(n & (GIANT_BITS_PER_DIGIT-1)); j++) { - lastWord |= bits; - bits <<= 1; - } - scratch1->n[numDigits-1] = lastWord; - addg(g, scratch1); /* One version. */ - gtog(scratch1, g); - returnGiant(scratch1); - return; - } - if(b == n) { - for(foundzero=0, j=0; jcapacity); - while ( ((unsigned)(g->sign) > digits) || - ( ((unsigned)(g->sign)==digits) && (g->n[digits-1] > mask))) { - extractbits(n, g, scratch1); - gshiftright(n, g); - addg(scratch1, g); - } - size = g->sign; - -/* Commence new negation routine - REC 17 Jan 1997. */ - if (!isPositive) { /* Mersenne negation is just bitwise complement. */ - for(j = digits-1; j >= size; j--) { - g->n[j] = GIANT_DIGIT_MASK; - } - for(j = size-1; j >= 0; j--) { - g->n[j] = ~g->n[j]; - } - g->n[digits-1] &= mask; - j = digits-1; - while((g->n[j] == 0) && (j > 0)) { - --j; - } - size = j+1; - } -/* End new negation routine. */ - - g->sign = size; - if (abs(g->sign) > g->capacity) { - CKRaise("gmersennemod overflow"); - } - if (size < (int)digits) { - goto bye; - } - if (g->n[size-1] != mask) { - goto bye; - } - mask = GIANT_DIGIT_MASK; - for(j=0; j<(size-1); j++) { - if (g->n[j] != mask) { - goto bye; - } - } - g->sign = 0; - bye: - returnGiant(scratch1); -} - -#endif /* NEW_MERSENNE */ - -void mulg(giant a, giant b) { /* b becomes a*b. */ - - int i; - int asize, bsize; - giantDigit *bptr = b->n; - giantDigit mult; - giant scratch1; - giantDigit carry; - giantDigit *scrPtr; - - - if (isZero(b)) { - return; - } - if (isZero(a)) { - gtog(a, b); - return; - } - if(a == b) { - grammarSquare(b); - return; - } - - bsize = abs(b->sign); - asize = abs(a->sign); - scratch1 = borrowGiant((asize+bsize)); - scrPtr = scratch1->n; - - for(i=0; in, - asize, - scrPtr); - /* handle MSD carry */ - scrPtr[asize] += carry; - } - } - bsize+=asize; - if(scratch1->n[bsize - 1] == 0) { - --bsize; - } - scratch1->sign = gsign(a) * gsign(b) * bsize; - if (abs(scratch1->sign) > scratch1->capacity) { - CKRaise("GiantGrammarMul overflow"); - } - gtog(scratch1,b); - returnGiant(scratch1); - - #if FEE_DEBUG - (void)bitlen(b); // Assertion.... - #endif /* FEE_DEBUG */ - PROF_INCR(numMulg); // for normal profiling - INCR_MULGS; // for ellipticMeasure -} - -void grammarSquare(giant a) { - /* - * For now, we're going to match the old implementation line for - * line by maintaining prod, carry, and temp as double precision - * giantDigits. There is probably a much better implementation.... - */ - giantDigit prodLo; - giantDigit prodHi; - giantDigit carryLo = 0; - giantDigit carryHi = 0; - giantDigit tempLo; - giantDigit tempHi; - unsigned int cur_term; - unsigned asize; - unsigned max; - giantDigit *ptr = a->n; - giantDigit *ptr1; - giantDigit *ptr2; - giant scratch; - - /* dmitch 11 Jan 1998 - special case for a == 0 */ - if(a->sign == 0) { - goto end; - } - /* end a == 0 case */ - asize = abs(a->sign); - max = asize * 2 - 1; - scratch = borrowGiant(2 * asize); - asize--; - - /* - * temp = *ptr; - * temp *= temp; - * scratch->n[0] = temp; - * carry = temp >> 16; - */ - giantMulDigits(*ptr, *ptr, &tempLo, &tempHi); - scratch->n[0] = tempLo; - carryLo = tempHi; - carryHi = 0; - - for (cur_term = 1; cur_term < max; cur_term++) { - ptr1 = ptr2 = ptr; - if (cur_term <= asize) { - ptr2 += cur_term; - } else { - ptr1 += cur_term - asize; - ptr2 += asize; - } - - /* - * prod = carry & 0xFFFF; - * carry >>= 16; - */ - prodLo = carryLo; - prodHi = 0; - carryLo = carryHi; - carryHi = 0; - while(ptr1 < ptr2) { - /* - * temp = *ptr1++ * *ptr2--; - */ - giantMulDigits(*ptr1++, *ptr2--, &tempLo, &tempHi); - - /* - * prod += (temp << 1) & 0xFFFF; - */ - giantAddDouble(&prodLo, &prodHi, (tempLo << 1)); - - /* - * carry += (temp >> 15); - * use bits from both product digits.. - */ - giantAddDouble(&carryLo, &carryHi, - (tempLo >> (GIANT_BITS_PER_DIGIT - 1))); - giantAddDouble(&carryLo, &carryHi, (tempHi << 1)); - - /* snag the msb from that last shift */ - carryHi += (tempHi >> (GIANT_BITS_PER_DIGIT - 1)); - } - if (ptr1 == ptr2) { - /* - * temp = *ptr1; - * temp *= temp; - */ - giantMulDigits(*ptr1, *ptr1, &tempLo, &tempHi); - - /* - * prod += temp & 0xFFFF; - */ - giantAddDouble(&prodLo, &prodHi, tempLo); - - /* - * carry += (temp >> 16); - */ - giantAddDouble(&carryLo, &carryHi, tempHi); - } - - /* - * carry += prod >> 16; - */ - giantAddDouble(&carryLo, &carryHi, prodHi); - - scratch->n[cur_term] = prodLo; - } - if (carryLo) { - scratch->n[cur_term] = carryLo; - scratch->sign = cur_term+1; - } else scratch->sign = cur_term; - - gtog(scratch,a); - returnGiant(scratch); -end: - PROF_INCR(numGsquare); -} - -/* - * Clear all of a giant's data fields, for secure erasure of sensitive data., - */ -void clearGiant(giant g) -{ - unsigned i; - - for(i=0; icapacity; i++) { - g->n[i] = 0; - } - g->sign = 0; -} - -#if ENGINE_127_BITS -/* - * only used by engineNSA127.c, which is obsolete as of 16 Jan 1997 - */ -int -scompg(int n, giant g) { - if((g->sign == 1) && (g->n[0] == n)) return(1); - return(0); -} - -#endif // ENGINE_127_BITS - -/* - */ - -/* - * Calculate the reciprocal of a demonimator used in divg_via_recip() and - * modg_via_recip(). - */ -void -make_recip(giant d, giant r) -/* r becomes the steady-state reciprocal - 2^(2b)/d, where b = bit-length of d-1. */ -{ - int b; - int giantSize = 4 * abs(d->sign); - giant tmp = borrowGiant(giantSize); - giant tmp2 = borrowGiant(giantSize); - - if (isZero(d) || (d->sign < 0)) - { - CKRaise("illegal argument to make_recip"); - } - int_to_giant(1, r); subg(r, d); b = bitlen(d); addg(r, d); - gshiftleft(b, r); gtog(r, tmp2); - while(1) { - gtog(r, tmp); - gsquare(tmp); - gshiftright(b, tmp); - mulg(d, tmp); - gshiftright(b, tmp); - addg(r, r); subg(tmp, r); - if(gcompg(r, tmp2) <= 0) break; - gtog(r, tmp2); - } - int_to_giant(1, tmp); - gshiftleft(2*b, tmp); - gtog(r, tmp2); mulg(d, tmp2); - subg(tmp2, tmp); - int_to_giant(1, tmp2); - while(tmp->sign < 0) { - subg(tmp2, r); - addg(d, tmp); - } - - returnGiant(tmp); - returnGiant(tmp2); - return; -} - -/* - * Optimized divg, when reciprocal of denominator is known. - */ -void -divg_via_recip(giant d, giant r, giant n) -/* n := n/d, where r is the precalculated - steady-state reciprocal of d. */ -{ - int s = 2*(bitlen(r)-1), sign = gsign(n); - int giantSize = (4 * abs(d->sign)) + abs(n->sign); - giant tmp = borrowGiant(giantSize); - giant tmp2 = borrowGiant(giantSize); - - if (isZero(d) || (d->sign < 0)) - { - CKRaise("illegal argument to divg_via_recip"); - } - n->sign = abs(n->sign); - int_to_giant(0, tmp2); - while(1) { - gtog(n, tmp); - mulg(r, tmp); - gshiftright(s, tmp); - addg(tmp, tmp2); - mulg(d, tmp); - subg(tmp, n); - if(gcompg(n,d) >= 0) { - subg(d,n); - iaddg(1, tmp2); - } - if(gcompg(n,d) < 0) break; - } - gtog(tmp2, n); - n->sign *= sign; - returnGiant(tmp); - returnGiant(tmp2); - return; -} - -/* - * Optimized modg, when reciprocal of denominator is known. - */ - -/* New version, 24 Dec 1997. */ - -void -modg_via_recip( - giant d, - giant r, - giant n -) -/* This is the fastest mod of the present collection. - n := n % d, where r is the precalculated - steady-state reciprocal of d. */ - -{ - int s = (bitlen(r)-1), sign = n->sign; - int giantSize = (4 * abs(d->sign)) + abs(n->sign); - giant tmp, tmp2; - - tmp = borrowGiant(giantSize); - tmp2 = borrowGiant(giantSize); - if (isZero(d) || (d->sign < 0)) - { - CKRaise("illegal argument to modg_via_recip"); - } - n->sign = abs(n->sign); - while (1) - { - gtog(n, tmp); - /* bug fix 13 Apr 1998 */ - if(s == 0) { - gshiftleft(1, tmp); - } - else { - gshiftright(s-1, tmp); - } - /* end fix */ - mulg(r, tmp); - gshiftright(s+1, tmp); - mulg(d, tmp); - subg(tmp, n); - if (gcompg(n,d) >= 0) - subg(d,n); - if (gcompg(n,d) < 0) - break; - } - if (sign >= 0) - goto done; - if (isZero(n)) - goto done; - negg(n); - addg(d,n); -done: - returnGiant(tmp); - returnGiant(tmp2); - return; -} - -/* - * Unoptimized, inefficient general modg, when reciprocal of denominator - * is not known. - */ -void -modg( - giant d, - giant n -) -{ - /* n becomes n%d. n is arbitrary, but the denominator d must be - * positive! */ - - /* - * 4/9/2001: seeing overflow on this recip. Alloc per - * d->capacity, not d->sign. - */ - //giant recip = borrowGiant(2 * abs(d->sign)); - giant recip = borrowGiant(2 * d->capacity); - - #if WARN_UNOPTIMIZE - dbgLog(("Warning: unoptimized modg!\n")); - #endif // WARN_UNOPTIMIZE - - make_recip(d, recip); - modg_via_recip(d, recip, n); - returnGiant(recip); -} - -/* - * Unoptimized, inefficient general divg, when reciprocal of denominator - * is not known. - */ -void -divg( - giant d, - giant n -) -{ - /* n becomes n/d. n is arbitrary, but the denominator d must be - * positive! - */ - - giant recip = borrowGiant(2 * abs(d->sign)); - - #if WARN_UNOPTIMIZE - dbgLog(("Warning: unoptimized divg!\n")); - #endif // WARN_UNOPTIMIZE - - make_recip(d, recip); - divg_via_recip(d, recip, n); - returnGiant(recip); -} diff --git a/OSX/include/security_cryptkit/giantIntegers.h b/OSX/include/security_cryptkit/giantIntegers.h deleted file mode 100644 index 2352a368..00000000 --- a/OSX/include/security_cryptkit/giantIntegers.h +++ /dev/null @@ -1,162 +0,0 @@ -/* Copyright (c) 1998,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * giantIntegers.h - large-integer arithmetic library. - * - * Revision History - * ---------------- - * 05 Oct 98 at Apple - * Default "unsigned int" giantDigit for __i386__ and __i486__ - * 08 May 97 at Apple - * Changed size of giantstruct.n to 1 for Mac build - * Created. - */ - -#ifndef _CK_NSGIANTINTS_H_ -#define _CK_NSGIANTINTS_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Size of giant digit. - */ -#if NeXT || __i386__ || __i486__ - -typedef unsigned int giantDigit; - -/* - * used to divide by GIANT_BITS_PER_DIGIT via shift - no easy way to get - * the compiler to calculate this. - */ -#define GIANT_LOG2_BITS_PER_DIGIT 5 - -#elif defined(macintosh) || defined(__ppc__) - -typedef unsigned int giantDigit; -#define GIANT_LOG2_BITS_PER_DIGIT 5 - -#else - -typedef unsigned short giantDigit; -#define GIANT_LOG2_BITS_PER_DIGIT 4 - -#endif - -/* platform-independent digit manipulation macros */ - -#define GIANT_BYTES_PER_DIGIT (sizeof(giantDigit)) -#define GIANT_BITS_PER_DIGIT (8 * GIANT_BYTES_PER_DIGIT) -#define GIANT_DIGIT_MASK ((giantDigit)~0) -#define BYTES_TO_GIANT_DIGITS(x) \ - ((x + GIANT_BYTES_PER_DIGIT - 1) / GIANT_BYTES_PER_DIGIT) - -#define MAX_DIGITS ((1<<18)+(1<<17)) - /* 2^(16*MAX_DIGITS)-1 will fit into a giant. */ - -/* - * The giant stack package is a local cache which allows us to avoid calls - * to malloc() for borrowGiant(). On a 90 Mhz Pentium, enabling the - * giant stack package shows about a 1.35 speedup factor over an identical - * CryptKit without the giant stacks enabled. - */ -#define GIANTS_VIA_STACK CRYPTKIT_GIANT_STACK_ENABLE - -typedef struct { - int sign; /* number of giantDigits = abs(sign) */ - unsigned capacity; /* largest possible number of giantDigits */ - giantDigit n[1]; /* n[0] is l.s. digit */ -} giantstruct; -typedef giantstruct *giant; - -#if GIANTS_VIA_STACK -/* - * For giant stack debug only - * Set default giant size (i.e., for newGiant(0) and borrowGiant(0)) - */ -void setGiantSize(unsigned numDigits); - -/* - * Initialize giant stacks, with up to specified max giant size. - */ -void initGiantStacks(unsigned maxDigits); - -/* - * Free giant stacks on shutdown. - */ -void freeGiantStacks(void); - -#endif /* GIANTS_VIA_STACK */ - -giant newGiant(unsigned numDigits); -giant copyGiant(giant x); -void freeGiant(giant x); - -giant borrowGiant(unsigned numDigits); /* get a temporary */ -void returnGiant(giant); /* return it */ -unsigned bitlen(giant n); /* Returns the bit-length n; - * e.g. n=7 returns 3. */ -int bitval(giant n, int pos); /* Returns the value of bit pos of n */ -int isZero(giant g); /* Returns whether g is zero */ -int isone(giant g); /* Returns whether g is 1 */ -void gtog(giant src, giant dest); /* Copies one giant to another */ -void int_to_giant(int n, giant g); /* Gives a giant an int value */ -int gcompg(giant a, giant b); /* Returns 1, 0, -1 as a>b, a=b, a> GIANT_BITS_PER_DIGIT); - *lowProduct = (giantDigit)dprod; -} - -/* - * Multiply a vector of giantDigits, candVector, by a single giantDigit, - * plierDigit, adding results into prodVector. Returns m.s. digit from - * final multiply; only candLength digits of *prodVector will be written. - */ -static inline giantDigit VectorMultiply( - giantDigit plierDigit, - giantDigit *candVector, - unsigned candLength, - giantDigit *prodVector) -{ - unsigned candDex; // index into multiplicandVector - giantDigit lastCarry = 0; - giantDigit prodLo; - giantDigit prodHi; - - for(candDex=0; candDex> GIANT_BITS_PER_DIGIT); */ - stw r8, 0(hiProduct) - - /* *lowProduct = (giantDigit)dprod; */ - stw r7, 0(lowProduct) - blr -} - -asm giantDigit VectorMultiply( - register giantDigit plierDigit, /* r3 */ - register giantDigit *candVector, /* r4 */ - register unsigned candLength, /* r5 */ - register giantDigit *prodVector) /* r6 */ -{ - register unsigned candDex; /* index into multiplicandVector */ - register giantDigit lastCarry; - register giantDigit prodLo; - register giantDigit prodHi; - register unsigned scr1; - register unsigned sumLo; - - fralloc - - /* giantDigit lastCarry = 0; */ - li lastCarry,0 - - - /* for(candDex=0; candDex scr1 */ - addi candVector,candVector,4 /* candVector++ */ - - mullw prodLo,scr1,plierDigit /* prodLo = low(*candVector * plierDigit) */ - mulhwu prodHi,scr1,plierDigit /* prodHi = high(*candVector * plierDigit) */ - - /* giantAddDouble(&prodLo, &prodHi, *prodVector); */ - lwz scr1,0(prodVector) /* *prodVector --> r9 */ - add sumLo,prodLo,scr1 /* prodLo + *prodVector --> sumLo */ - cmpl crf0,0,sumLo,prodLo /* sumLo < prodLo? */ - bc 12,0,_carry1 - cmpl crf0,0,sumLo,scr1 /* sumLo < *prodVector? */ - bc 4,0,_noCar1 -_carry1: - addi prodHi,prodHi,1 /* prodHi++ */ -_noCar1: - mr. prodLo,sumLo /* prodLo := sumLo */ - - /* giantAddDouble(&prodLo, &prodHi, lastCarry); */ - add sumLo,sumLo,lastCarry /* sumLo += lastCarry */ - cmpl crf0,0,sumLo,prodLo /* sumLo < prodLo? */ - bc 12,0,_carry2 - cmpl crf0,0,sumLo,lastCarry /* sumLo < lastCarry? */ - bc 4,0,_noCar2 -_carry2: - addi prodHi,prodHi,1 /* prodHi++ */ -_noCar2: - mr. prodLo,sumLo /* prodLo := sumLo */ - - /* *(prodVector++) = prodLo; */ - stw prodLo,0(prodVector) /* prodLo --> *prodVector */ - addi prodVector,prodVector,4 /* prodVector++ */ - - /* lastCarry = prodHi; */ - mr. lastCarry,prodHi - - /* } */ - addi candDex,candDex,1 /* candDex++ */ -_endLoop: - cmpl crf0,0,candDex,candLength /* candDex < candLength? */ - bc 12,0,_topLoop - - /* return lastCarry; */ - mr. r3,lastCarry /* return lastCarry in r3 */ - frfree - blr -} - -#endif // PPC_GIANT_PORT_INLINE diff --git a/OSX/include/security_cryptkit/giantPort_PPC.h b/OSX/include/security_cryptkit/giantPort_PPC.h deleted file mode 100644 index 44ebeb3b..00000000 --- a/OSX/include/security_cryptkit/giantPort_PPC.h +++ /dev/null @@ -1,119 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * giantPort_PPC.h - PPC-dependent giant definitions. - * - * Revision History - * ---------------- - * 10/06/98 ap - * Changed to compile with C++. - * 06 Apr 1998 at Apple - * Created. - */ - -#ifndef _CK_NSGIANT_PORT_PPC_H_ -#define _CK_NSGIANT_PORT_PPC_H_ - -#include "feeDebug.h" -#include "platform.h" -#include "giantIntegers.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/**** FIXME - implement asm giant digits! ****/ -/* - * 0 ==> use function declarations from this file and implementation - * in giantPort_PPC.c - * 1 ==> use static inline C function in giantPort_Generic.h - */ -/*@@@ HACK @@@ -#if defined NeXT -#define PPC_GIANT_PORT_INLINE 1 -#else -#define PPC_GIANT_PORT_INLINE 0 -#endif -*/ -#define PPC_GIANT_PORT_INLINE 1 - -#if PPC_GIANT_PORT_INLINE - -#include "giantPort_Generic.h" - -#else // PPC_GIANT_PORT_INLINE - -/* - * We'll be using the compiler's 64-bit long long for these routines. - * - * Mask for upper word. - */ -#define GIANT_UPPER_DIGIT_MASK (~(unsigned long long(GIANT_DIGIT_MASK))) - -/* - * Multiple-precision arithmetic routines/macros. C for now, eventually - * they'll be in assembly. - */ - -/* - * Add two digits, return sum. Carry bit returned as an out parameter. - * This should work any size giantDigits up to unsigned int. - */ -extern giantDigit giantAddDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *carry); /* RETURNED, 0 or 1 */ - -/* - * Add a single digit value to a double digit accumulator in place. - * Carry out of the MSD of the accumulator is not handled. - */ -void giantAddDouble( - giantDigit *accLow, /* IN/OUT */ - giantDigit *accHigh, /* IN/OUT */ - giantDigit val); - - -/* - * Subtract a - b, return difference. Borrow bit returned as an out parameter. - */ -giantDigit giantSubDigits( - giantDigit a, - giantDigit b, - giantDigit *borrow); /* RETURNED, 0 or 1 */ - - -/* - * Multiply two digits, return two digits. - */ -void giantMulDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *lowProduct, /* RETURNED, low digit */ - giantDigit *hiProduct); /* RETURNED, high digit */ - -/* - * Multiply a vector of giantDigits, candVector, by a single giantDigit, - * plierDigit, adding results into prodVector. Returns m.s. digit from - * final multiply; only candLength digits of *prodVector will be written. - */ -giantDigit VectorMultiply( - giantDigit plierDigit, - giantDigit *candVector, - unsigned candLength, - giantDigit *prodVector); - -#ifdef __cplusplus -} -#endif - -#endif /* !PPC_GIANT_PORT_INLINE */ - -#endif /*_CK_NSGIANT_PORT_PPC_H_*/ diff --git a/OSX/include/security_cryptkit/giantPort_PPC_Gnu.h b/OSX/include/security_cryptkit/giantPort_PPC_Gnu.h deleted file mode 100644 index 3676da99..00000000 --- a/OSX/include/security_cryptkit/giantPort_PPC_Gnu.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * giantPort_PPC_Gnu.h - giant definitions, PPC/GNU version. - */ - -#ifndef _CK_NSGIANT_PORT_PPC_GNU_H_ -#define _CK_NSGIANT_PORT_PPC_GNU_H_ - -#include "feeDebug.h" -#include "platform.h" -#include "giantIntegers.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* define this true to disable this module and use generic C versions instead */ -#define PPC_GIANT_PORT_INLINE 0 - -#if PPC_GIANT_PORT_INLINE - -#include "giantPort_Generic.h" - -#else // PPC_GIANT_PORT_INLINE - -/* - * Multiple-precision arithmetic routines/macros implemented in - * giantPort_PPC_Gnu.s - */ - -/* - * Add two digits, return sum. Carry bit returned as an out parameter. - */ -extern giantDigit giantAddDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *carry); /* RETURNED, 0 or 1 */ - -/* - * Add a single digit value to a double digit accumulator in place. - * Carry out of the MSD of the accumulator is not handled. - */ -void giantAddDouble( - giantDigit *accLow, /* IN/OUT */ - giantDigit *accHigh, /* IN/OUT */ - giantDigit val); - - -/* - * Subtract a - b, return difference. Borrow bit returned as an out parameter. - */ -giantDigit giantSubDigits( - giantDigit a, - giantDigit b, - giantDigit *borrow); /* RETURNED, 0 or 1 */ - - -/* - * Multiply two digits, return two digits. - */ -void giantMulDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *lowProduct, /* RETURNED, low digit */ - giantDigit *hiProduct); /* RETURNED, high digit */ - -/* - * Multiply a vector of giantDigits, candVector, by a single giantDigit, - * plierDigit, adding results into prodVector. Returns m.s. digit from - * final multiply; only candLength digits of *prodVector will be written. - */ -giantDigit VectorMultiply( - giantDigit plierDigit, - giantDigit *candVector, - unsigned candLength, - giantDigit *prodVector); - -#ifdef __cplusplus -} -#endif - -#endif /* !PPC_GIANT_PORT_INLINE */ - -#endif /*_CK_NSGIANT_PORT_PPC_GNU_H_*/ diff --git a/OSX/include/security_cryptkit/giantPort_PPC_Gnu.s b/OSX/include/security_cryptkit/giantPort_PPC_Gnu.s deleted file mode 100644 index 1319b53a..00000000 --- a/OSX/include/security_cryptkit/giantPort_PPC_Gnu.s +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright (c) 2001,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * As of 3/19/2001, using this module results in no change in runtime - * performance compared to using the inline C functions in - * giantPort_Generic.h. Examination of the compiled code shows that - * the GNU C compiler, when configured for -O2, generates almost - * exactly the same code as we have here. - * We'll leave this code in, to protect against changes in gcc, changes - * in CFLAGS, and to serve as an example for other PPC implementations. - */ - -#if defined(__ppc__) && defined(__MACH__) - -/********************************************* - -Add two digits, return sum. Carry bit returned as an out parameter. - -giantDigit giantAddDigits( - register giantDigit dig1, - register giantDigit dig2, - register giantDigit *carry) ...RETURNED, 0 or 1 -**********************************************/ - .text - .align 2 -.globl _giantAddDigits -_giantAddDigits: - /* - * dig1 : r3 - * dig2 : r4 - * carry : r5 - * sum : r6 - */ - - /* sum = dig1 + dig2 */ - add r6, r3, r4; - - /* if((sum < dig1) || (sum < dig2)) */ - cmplw cr0,r6,r3 - blt L1 - cmplw cr0,r6,r4 - bge L2 - -L1: - /* *carry = 1; */ - li r7,1 - stw r7, 0(r5) - b L3 - -L2: - /* else *carry = 0; */ - li r7,0 - stw r7, 0(r5) - -L3: - /* return sum in r3 */ - mr. r3,r6 - blr - -/********************************************* - -Add a single digit value to a double digit accumulator in place. -Carry out of the MSD of the accumulator is not handled. - -void giantAddDouble( - giantDigit *accLow, -- IN/OUT - giantDigit *accHigh, -- IN/OUT - giantDigit val); -**********************************************/ - - .align 2 -.globl _giantAddDouble -_giantAddDouble: - /* - * r3 : accLow - * r4 : accHi - * r5 : val - * r6 : sumLo - * r7 : *accLow - */ - - /* giantDigit sumLo = *accLow + val; */ - lwz r7,0(r3) - add r6,r7,r5 - - /* if((sumLo < *accLow) || (sumLo < val)) { */ - cmplw cr0,r6,r7 - blt L10 - cmplw cr0,r6,r5 - bge L11 - -L10: - /* (*accHigh)++; */ - lwz r7, 0(r4) - addi r7,r7,1 - stw r7, 0(r4) - -L11: - /* *accLow = sumLo; */ - stw r6,0(r3) - blr - -/***************************************************************************** - -Subtract a - b, return difference. Borrow bit returned as an out parameter. - -giantDigit giantSubDigits( - giantDigit a, - giantDigit b, - giantDigit *borrow) -- RETURNED, 0 or 1 - -******************************************************************************/ - - .align 2 -.globl _giantSubDigits -_giantSubDigits: - - /* a : r3 - b : r4 - borrow : r5 - diff : r6 */ - - /* giantDigit diff = a - b; */ - subf r6, r4, r3; - - /* if(a < b) */ - cmplw cr0,r3,r4 - bge L20 - - /* *borrow = 1; */ - li r7,1 - stw r7, 0(r5) - b L21 - -L20: - /* else *borrow = 0; */ - li r7,0 - stw r7, 0(r5) - -L21: - /* return diff in r3 */ - mr. r3,r6 - blr - -/***************************************************************************** - -Multiply two digits, return two digits. - -void giantMulDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *lowProduct, -- RETURNED, low digit - giantDigit *hiProduct) -- RETURNED, high digit - -******************************************************************************/ - - .align 2 -.globl _giantMulDigits -_giantMulDigits: - - /* r3 : dig1 - r4 : dig2 - r5 : lowProduct - r6 : hiProduct */ - - /* dprod = (unsigned long long)dig1 * (unsigned long long)dig2; */ - mullw r7, r3, r4 /* r7 = low(dig1 * dig2) */ - mulhwu r8, r3, r4 /* r8 - hi(dig1 * dig2) */ - - /* *hiProduct = (giantDigit)(dprod >> GIANT_BITS_PER_DIGIT); */ - stw r8, 0(r6) - - /* *lowProduct = (giantDigit)dprod; */ - stw r7, 0(r5) - blr - - -/***************************************************************************** - -Multiply a vector of giantDigits, candVector, by a single giantDigit, -plierDigit, adding results into prodVector. Returns m.s. digit from -final multiply; only candLength digits of *prodVector will be written. - -giantDigit VectorMultiply( - giantDigit plierDigit, - giantDigit *candVector, - unsigned candLength, - giantDigit *prodVector) - -******************************************************************************/ - -/* - * Register definitions - * Input paramters: - */ -#define plierDigit r3 -#define candVector r4 -#define candLength r5 -#define prodVector r6 - -/* - * PPC ABI specifies: - * r3..r10 for parameter passing - * r11, r12 volatile (caller saved, we can write) - * - * We'll use the remainder of the registers normally used for parameter passing - * and also the other volatile register for local variables. - */ -#define candDex r7 -#define lastCarry r8 -#define prodLo r9 -#define prodHi r10 -#define scr1 r11 -#define sumLo r12 - - .align 2 -.globl _VectorMultiply -_VectorMultiply: - - /* giantDigit lastCarry = 0; */ - li lastCarry,0 - - - /* for(candDex=0; candDex scr1 */ - addi candVector,candVector,4 /* candVector++ */ - - mullw prodLo,scr1,plierDigit /* prodLo = low(*candVector * plierDigit) */ - mulhwu prodHi,scr1,plierDigit /* prodHi = high(*candVector * plierDigit) */ - - /* giantAddDouble(&prodLo, &prodHi, *prodVector); */ - lwz scr1,0(prodVector) /* *prodVector --> r9 */ - add sumLo,prodLo,scr1 /* prodLo + *prodVector --> sumLo */ - cmplw cr0,sumLo,prodLo /* sumLo < prodLo? */ - blt L_carry1 - cmplw cr0,sumLo,scr1 /* sumLo < *prodVector? */ - bge L_noCar1 -L_carry1: - addi prodHi,prodHi,1 /* prodHi++ */ -L_noCar1: - mr. prodLo,sumLo /* prodLo := sumLo */ - - /* giantAddDouble(&prodLo, &prodHi, lastCarry); */ - add sumLo,sumLo,lastCarry /* sumLo += lastCarry */ - cmplw cr0,sumLo,prodLo /* sumLo < prodLo? */ - blt L_carry2 - cmplw cr0,sumLo,lastCarry /* sumLo < lastCarry? */ - bge L_noCar2 -L_carry2: - addi prodHi,prodHi,1 /* prodHi++ */ -L_noCar2: - mr. prodLo,sumLo /* prodLo := sumLo */ - - /* *(prodVector++) = prodLo; */ - stw prodLo,0(prodVector) /* prodLo --> *prodVector */ - addi prodVector,prodVector,4 /* prodVector++ */ - - /* lastCarry = prodHi; */ - mr. lastCarry,prodHi - - /* } */ - addi candDex,candDex,1 /* candDex++ */ -L_endLoop: - cmplw cr0,candDex,candLength /* candDex < candLength? */ - blt L_topLoop - - /* return lastCarry; */ - mr. r3,lastCarry /* return lastCarry in r3 */ - blr - -#endif /* defined(__ppc__) && defined(__MACH__) */ diff --git a/OSX/include/security_cryptkit/giantPort_i486.h b/OSX/include/security_cryptkit/giantPort_i486.h deleted file mode 100644 index b0e74f7b..00000000 --- a/OSX/include/security_cryptkit/giantPort_i486.h +++ /dev/null @@ -1,126 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * giantPorti486.h - OpenStep-dependent giant definitions. - * - * Revision History - * ---------------- - * 06 Apr 1998 at Apple - * Created. - */ - -#ifndef _CK_NSGIANT_PORT_I486_H_ -#define _CK_NSGIANT_PORT_I486_H_ - -#include "giantIntegers.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Add two digits, return sum. Carry bit returned as an out parameter. - */ -static inline giantDigit giantAddDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *carry) /* RETURNED, 0 or 1 */ -{ - giantDigit _sum; /* r/w %0 */ - asm volatile( - "movl %2, %0 /* _sum = dig1 */ \n" - "addl %3, %0 /* _sum += dig2 */ \n" - "jc .+9 \n" - "movl $0, %1 /* carry = 0 */ \n" - "jmp .+7 \n" - "movl $1, %1 /* carry = 1 */ \n" - : "=&r" (_sum), "=&r" (*carry) - : "r" (dig1), "r" (dig2)); - return _sum; -} - -/* - * Add a single digit value to a double digit accumulator in place. - * Carry out of the MSD of the accumulator is not handled. - */ -static inline void giantAddDouble( - giantDigit *accLow, /* IN/OUT */ - giantDigit *accHigh, /* IN/OUT */ - giantDigit val) -{ - asm volatile( - "addl %4, %0 /* accLow += val */ \n" - "jnc .+3 \n" - "incl %1 /* accHigh++ */ \n" - : "=&r" (*accLow), "=&r" (*accHigh) - : "0" (*accLow), "1" (*accHigh), "r" (val)); -} - -/* - * Subtract a - b, return difference. Borrow bit returned as an out parameter. - */ -static inline giantDigit giantSubDigits( - giantDigit a, - giantDigit b, - giantDigit *borrow) /* RETURNED, 0 or 1 */ -{ - giantDigit _diff; /* r/w %0 */ - asm volatile( - "movl %2, %0 /* _diff = a */ \n" - "subl %3, %0 /* _diff -= b */ \n" - "jc .+9 \n" - "movl $0, %1 /* borrow = 0 */ \n" - "jmp .+7 \n" - "movl $1, %1 /* borrow = 1 */ \n" - : "=&r" (_diff), "=&r" (*borrow) - : "r" (a), "r" (b)); - return _diff; -} - -/* - * Multiply two digits, return two digits. - */ -static inline void giantMulDigits( - giantDigit dig1, - giantDigit dig2, - giantDigit *lowProduct, // RETURNED, low digit - giantDigit *hiProduct) // RETURNED, high digit - -{ - asm volatile( - "movl %2, %%eax /* eax = dig1 */ \n" - "movl %3, %%edx /* edx = dig2 */ \n" - "mull %%edx /* eax *= dig2 */ \n" - : "=&a" (*lowProduct), "=&d" (*hiProduct) - : "r" (dig1), "r" (dig2) - : "%eax", "%edx" ); -} - -/* - * Multiply a vector of giantDigits, candVector, by a single giantDigit, - * plierDigit, adding results into prodVector. Returns m.s. digit from - * final multiply; only candLength digits of *prodVector will be written. - * - * This one's implemented in a .s file. - */ -extern giantDigit vectorMult_x86( - giantDigit plierDigit, - giantDigit *candVector, - unsigned candLength, - giantDigit *prodVector); - -#define VectorMultiply(pd, cv, cl, pv) vectorMult_x86(pd, cv, cl, pv) - - -#ifdef __cplusplus -} -#endif - -#endif _CK_NSGIANT_PORT_I486_H_ diff --git a/OSX/include/security_cryptkit/giantPort_i486.s b/OSX/include/security_cryptkit/giantPort_i486.s deleted file mode 100644 index 357b5cfc..00000000 --- a/OSX/include/security_cryptkit/giantPort_i486.s +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * giantPorti486.s - i486-specific assembly routines. - * - * Revision History - * ---------------- - * 17 Apr 1998 at Apple - * Created. - */ - -#if defined (i386) || defined(__i386__) -.text - -/* - * Multiply a vector a giantDigits, candVector, by a single giantDigit, - * plierDigit, adding results in prodVector. - * - * void VectorMultiply( - * giantDigit plierDigit, - * giantDigit *candVector, - * unsigned candLength, - * giantDigit *prodVector) - */ - -.align 2,0x90 -.globl _vectorMult_x86 - -/* - * Stack locations, relative to adjusted bp. - */ -#define LOCAL_SPACE 0x4 - -#define ARG_START (LOCAL_SPACE + 8) /* rtn ptr plus bp */ -#define ARG_PLIER_DIGIT (ARG_START + 0) -#define ARG_CAND_VECTOR (ARG_START + 4) /* cached in ecx */ -#define ARG_CAND_LENGTH (ARG_START + 8) -#define ARG_PROD_VECTOR (ARG_START + 12) /* cached in esi */ - -#define LOCAL_START (0) -#define LOC_CAND_DEX (LOCAL_START + 0) /* index into candVector */ - -/* - * ebx : lastCarry - * esi : prodVector - * ecx : candVector - */ -_vectorMult_x86: - - pushl %ebp - subl $LOCAL_SPACE,%esp - movl %esp,%ebp - pushl %edi - pushl %esi - pushl %ebx - - /* esp not used again 'til we pop these off stack */ - - /* prodVector = %esi */ - movl ARG_PROD_VECTOR(%ebp),%esi - - /* lastCarry = 0 */ - /* 0 --> candDex in 0xf0(%ebp) */ - xorl %ebx,%ebx - - /* candVector --> %ecx */ - movl ARG_CAND_VECTOR(%ebp),%ecx - - /* for(candDex=0; candDex 0 to start...*/ - cmpl %ebx,ARG_CAND_LENGTH(%ebp) - jbe _loopEnd - -_loopTop: - /* branch back to top of for loop */ - - /* *candVector--> %eax */ - movl (%ecx),%eax - - /* candVector++ */ - addl $0x04,%ecx - - /* plierDigit --> %edx */ - movl ARG_PLIER_DIGIT(%ebp),%edx - - /* eax = *candVector - * edx = plierDigit - * edx:eax := (plierDigit * *candVector) */ - mull %edx - - /* from here to end of loop: - prodLo : eax - prodHi : edx */ - - /* prodLo += *prodVector */ - addl (%esi),%eax - - /* add carry to hi digit */ - adc $0,%edx - - /* prodLo += lastCarry */ - addl %ebx,%eax - /* add carry to hi digit */ - adc $0,%edx - - /* *(prodVector++) = prodLo; */ - movl %eax,(%esi) - addl $0x04,%esi - - /* lastCarry = prodHi */ - movl %edx, %ebx - - /* candDex++ */ - incl LOC_CAND_DEX(%ebp) - - /* top of loop if candDex < candLength */ - movl ARG_CAND_LENGTH(%ebp),%eax - cmpl %eax,LOC_CAND_DEX(%ebp) - jb _loopTop - -_loopEnd: - /* out of for loop */ - /* *prodVector += lastCarry; */ -#if 0 - addl %ebx,(%esi) - - /* return carry from last addition */ - xorl %eax,%eax - adc $0,%eax -#else - /* return lastCarry */ - movl %ebx,%eax -#endif - popl %ebx - popl %esi - popl %edi - addl $LOCAL_SPACE,%esp - popl %ebp - ret -#endif /* i386 */ diff --git a/OSX/include/security_cryptkit/mutils.h b/OSX/include/security_cryptkit/mutils.h deleted file mode 100644 index 57023f74..00000000 --- a/OSX/include/security_cryptkit/mutils.h +++ /dev/null @@ -1,36 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * mutils.h - general private ObjC routine declarations - * - * Revision History - * ---------------- - * 2 Aug 96 at NeXT - * Broke out from Blaine Garst's original NSCryptors.m - */ - -#ifndef _CK_MUTILS_H_ -#define _CK_MUTILS_H_ - -#include -#include "giantIntegers.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern NSMutableData *data_with_giant(giant u); -extern void canonicalize_data(NSMutableData *data); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_MUTILS_H_*/ diff --git a/OSX/include/security_cryptkit/mutils.m b/OSX/include/security_cryptkit/mutils.m deleted file mode 100644 index 129c905c..00000000 --- a/OSX/include/security_cryptkit/mutils.m +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * mutils.m - general private ObjC routine declarations - * - * Revision History - * ---------------- - * 2 Aug 96 at NeXT - * Broke out from Blaine Garst's original NSCryptors.m - */ - -#import -#import "giantIntegers.h" -#import "ckutilities.h" -#import "mutils.h" -#import "feeFunctions.h" -#import - -#if defined(NeXT) && !defined(WIN32) - -/* - * Public, declared in NSCryptors.h - */ -NSString *NSPromptForPassPhrase(NSString *prompt) { - // useful for command line (/dev/tty) programs - char buffer[PHRASELEN]; - NSString *result; - - getpassword([prompt cString], buffer); - if (buffer[0] == 0) return nil; - result = [NSString stringWithCString:buffer]; - bzero(buffer, PHRASELEN); - return result; -} - - -#endif NeXT diff --git a/OSX/include/security_cryptkit/platform.c b/OSX/include/security_cryptkit/platform.c deleted file mode 100644 index fa6c1b2e..00000000 --- a/OSX/include/security_cryptkit/platform.c +++ /dev/null @@ -1,197 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * platform.c - platform-dependent C functions - * - * Revision History - * ---------------- - * 6 Sep 96 at NeXT - * Created. - */ - -#include "platform.h" -#include -#include "feeDebug.h" -#ifdef NeXT - -/* - * OpenStep.... - */ -void CKRaise(const char *reason) { - #if FEE_DEBUG - printf("CryptKit fatal error: %s\n", reason); - #endif - exit(1); -} - -#import "feeDebug.h" - -#if !defined(NeXT_PDO) && FEE_DEBUG - -/* - * Mach, private build. use quick microsecond-accurate system clock. - */ - -#include - -unsigned createRandomSeed() -{ - struct tsval tsp; - - (void)kern_timestamp(&tsp); - return tsp.low_val; -} - -#else - -/* - * OpenStep, normal case. - */ -#include -#include - -extern int getpid(); - -unsigned createRandomSeed(void) -{ - time_t curTime; - unsigned thisPid; - - time(&curTime); - thisPid = (unsigned)getpid(); - - return (unsigned)curTime ^ (unsigned)thisPid; -} - -#endif /* FEE_DEBUG */ - -#elif WIN32 - -/* - * OpenStep on Windows. - */ -#include /* for _getpid() */ - -void CKRaise(const char *reason) { - #if FEE_DEBUG - printf("CryptKit fatal error: %s\n", reason); - #endif - exit(1); -} - -extern void time(unsigned *tp); - -unsigned createRandomSeed() -{ - unsigned curTime; - unsigned thisPid; - - time(&curTime); - thisPid = _getpid(); - return (unsigned)curTime ^ (unsigned)thisPid; -} - - -#elif __MAC_BUILD__ - -/* - * Macintosh, all flavors. - */ -#include -#include - -void CKRaise(const char *reason) { - #if FEE_DEBUG - printf("CryptKit fatal error: %s\n", reason); - #endif - exit(1); -} - -/* for X, this isn't used except for testing when SecurityServer when - * Yarrow is not running. So let's strip it down so we don't have - * to link against CarbonCore. - */ -#define BARE_BONES_SEED 1 -#if BARE_BONES_SEED - -#include - -extern int getpid(); - -unsigned createRandomSeed() -{ - time_t curTime; - unsigned thisPid; - - time(&curTime); - thisPid = (unsigned)getpid(); - - return (unsigned)curTime ^ (unsigned)thisPid; -} - -#else /* BARE_BONES_SEED */ - -#include -#include - -// this is mighty pitiful anyway... -unsigned createRandomSeed() -{ - UnsignedWide curTime; - //unsigned ticks; /* use 16 bits */ - unsigned rtnHi; - unsigned rtnLo; - - /* FIXME - need a way to distinguish OS9x from Carbon. Carbon - * doesn't have LMGetTicks(). */ - - Microseconds(&curTime); /* low 16 bits are pretty good */ - - // Carbon hack - // rtnHi = LMGetTicks(); - rtnHi = 0x5a5aa5a5; - rtnLo = curTime.lo & 0xffff; - return (rtnHi ^ rtnLo); -} -#endif /* BARE_BONES_SEED */ - -#elif unix - -/* try for generic UNIX */ - -void CKRaise(const char *reason) { - #if FEE_DEBUG - printf("CryptKit fatal error: %s\n", reason); - #endif - exit(1); -} - -#include -#include - -extern int getpid(); - -unsigned createRandomSeed() -{ - time_t curTime; - unsigned thisPid; - - time(&curTime); - thisPid = (unsigned)getpid(); - - return (unsigned)curTime ^ (unsigned)thisPid; -} - - -#else - -#error platform-specific work needed in security_cryptkit/platform.c - -#endif diff --git a/OSX/include/security_cryptkit/platform.h b/OSX/include/security_cryptkit/platform.h deleted file mode 100644 index 7a9e9a99..00000000 --- a/OSX/include/security_cryptkit/platform.h +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved. - * - * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT - * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE - * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE - * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE, - * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL - * EXPOSE YOU TO LIABILITY. - *************************************************************************** - * - * platform.h - platform-dependent C functions - * - * Revision History - * ---------------- - * 6 Sep 96 at NeXT - * Created. - */ - -#ifndef _CK_PLATFORM_H_ -#define _CK_PLATFORM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -/* many ways to determin macintosh - different for 68k, PPC/OS9, X */ -#if defined(__POWERPC__) || defined(__CFM68K__) || defined(__APPLE__) - #undef __MAC_BUILD__ - #define __MAC_BUILD__ 1 -#endif - -/* - * Make sure endianness is defined... - */ -#if defined(__BIG_ENDIAN__) && defined(__LITTLE_ENDIAN__) -#error Hey! multiply defined endianness! -#endif -#if !defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__) - #if __MAC_BUILD__ - #define __BIG_ENDIAN__ 1 - #elif __i386__ || __i486__ - #define __LITTLE_ENDIAN__ 1 - #else - #error Platform dependent work needed - #endif -#endif /* endian */ - -#ifndef NeXT - #define bcopy(s, d, l) memmove(d, s, l) - #define bzero(s, l) memset(s, 0, l) - #define bcmp(s, d, l) memcmp(s, d, l) -#endif - -/* - * Other platform-dependent functions in platform.c. - */ - -extern void CKRaise(const char *reason); - -/* - * Come up with some kind of "really" random int with which to seed the - * random number generator. - */ -extern unsigned createRandomSeed(void); - -#ifdef __cplusplus -} -#endif - -#endif /*_CK_PLATFORM_H_*/ diff --git a/OSX/include/security_cryptkit/unixMakefile b/OSX/include/security_cryptkit/unixMakefile deleted file mode 100644 index b3a976a8..00000000 --- a/OSX/include/security_cryptkit/unixMakefile +++ /dev/null @@ -1,102 +0,0 @@ -# -# FEE library Makefile, generic UNIX version. -# -FEE_LIB=libFEE.a -# -CFILES=CipherFileDES.c CipherFileFEED.c ckDES.c ckMD5.c elliptic.c giantIntegers.c ckSHA1.c ckSHA1_priv.c byteRep.c curveParams.c enc64.c falloc.c feeCipherFile.c feeCipherFileAtom.c feeDES.c feeDigitalSignature.c feeECDSA.c feeFEED.c feeFEEDExp.c feeHash.c feePublicKey.c feeRandom.c platform.c ckutilities.c ellipticProj.c -# -SFILES=giantPort_PPC_Gnu.s -OFILES= $(CFILES:%.c=%.o) $(SFILES:%.s=%.o) -# -CFLAGS=-g -O -Wall -c -I.. -# -# set to platform-specific compiler (gcc, /bin/cc, etc.) -CC=cc -# -first all: $(FEE_LIB) -# -clean: - rm -f *.o *.a -# -$(FEE_LIB): $(OFILES) - rm -f $(FEE_LIB) - ar r ${FEE_LIB} $(OFILES) - ranlib ${FEE_LIB} -# -CipherFileDES.o: CipherFileDES.c - $(CC) $(CFLAGS) -o $@ CipherFileDES.c - -CipherFileFEED.o: CipherFileFEED.c - $(CC) $(CFLAGS) -o $@ CipherFileFEED.c - -DES.o: DES.c - $(CC) $(CFLAGS) -o $@ DES.c - -MD5.o: MD5.c - $(CC) $(CFLAGS) -o $@ MD5.c - -elliptic.o: elliptic.c - $(CC) $(CFLAGS) -o $@ elliptic.c - -giantIntegers.o: giantIntegers.c - $(CC) $(CFLAGS) -o $@ giantIntegers.c - -ckSHA1.o: ckSHA1.c - $(CC) $(CFLAGS) -o $@ ckSHA1.c - -ckSHA1_priv.o: ckSHA1_priv.c - $(CC) $(CFLAGS) -o $@ ckSHA1_priv.c - -byteRep.o: byteRep.c - $(CC) $(CFLAGS) -o $@ byteRep.c - -curveParams.o: curveParams.c - $(CC) $(CFLAGS) -o $@ curveParams.c - -enc64.o: enc64.c - $(CC) $(CFLAGS) -o $@ enc64.c - -falloc.o: falloc.c - $(CC) $(CFLAGS) -o $@ falloc.c - -feeCipherFile.o: feeCipherFile.c - $(CC) $(CFLAGS) -o $@ feeCipherFile.c - -feeCipherFileAtom.o: feeCipherFileAtom.c - $(CC) $(CFLAGS) -o $@ feeCipherFileAtom.c - -feeDES.o: feeDES.c - $(CC) $(CFLAGS) -o $@ feeDES.c - -feeDigitalSignature.o: feeDigitalSignature.c - $(CC) $(CFLAGS) -o $@ feeDigitalSignature.c - -feeECDSA.o: feeECDSA.c - $(CC) $(CFLAGS) -o $@ feeECDSA.c - -feeFEED.o: feeFEED.c - $(CC) $(CFLAGS) -o $@ feeFEED.c - -feeFEEDExp.o: feeFEEDExp.c - $(CC) $(CFLAGS) -o $@ feeFEEDExp.c - -feeHash.o: feeHash.c - $(CC) $(CFLAGS) -o $@ feeHash.c - -feePublicKey.o: feePublicKey.c - $(CC) $(CFLAGS) -o $@ feePublicKey.c - -feeRandom.o: feeRandom.c - $(CC) $(CFLAGS) -o $@ feeRandom.c - -platform.o: platform.c - $(CC) $(CFLAGS) -o $@ platform.c - -utilities.o: utilities.c - $(CC) $(CFLAGS) -o $@ utilities.c - -giantPort_PPC_Gnu.o: giantPort_PPC_Gnu.s - $(CC) $(CFLAGS) -o $@ giantPort_PPC_Gnu.s - -ellipticProj.o: ellipticProj.c - $(CC) $(CFLAGS) -o $@ ellipticProj.c diff --git a/OSX/include/security_filedb b/OSX/include/security_filedb new file mode 120000 index 00000000..99185cdc --- /dev/null +++ b/OSX/include/security_filedb @@ -0,0 +1 @@ +./libsecurity_filedb/lib \ No newline at end of file diff --git a/OSX/include/security_filedb/AppleDatabase.cpp b/OSX/include/security_filedb/AppleDatabase.cpp deleted file mode 100644 index ddad1a74..00000000 --- a/OSX/include/security_filedb/AppleDatabase.cpp +++ /dev/null @@ -1,2564 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003,2011-2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// AppleDatabase.cpp - Description t.b.d. -// -#include "AppleDatabase.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const char *kAppleDatabaseChanged = "com.apple.AppleDatabaseChanged"; - -/* Number of seconds after which we open/pread/close a db to check it's - version number even if we didn't get any notifications. Note that we always - check just after we take a write lock and whenever we get a notification - that any db on the system has changed. */ -static const CFTimeInterval kForceReReadTime = 15.0; - -/* Token on which we receive notifications and the pthread_once_t protecting - it's initialization. */ -pthread_once_t gCommonInitMutex = PTHREAD_ONCE_INIT; - -/* Global counter of how many notifications we have received and a lock to - protect the counter. */ -static int kSegmentSize = 4; -int32_t* gSegment = NULL; - -/* Registration routine for notifcations. Called inside a pthread_once(). */ -static void initCommon(void) -{ - // open the file - int segmentDescriptor = shm_open (kAppleDatabaseChanged, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO); - if (segmentDescriptor < 0) - { - return; - } - - // set the segment size - ftruncate (segmentDescriptor, kSegmentSize); - - // map it into memory - int32_t* tmp = (int32_t*) mmap (NULL, kSegmentSize, PROT_READ | PROT_WRITE, MAP_SHARED, segmentDescriptor, 0); - close (segmentDescriptor); - - if (tmp == (int32_t*) -1) // can't map the memory? - { - gSegment = NULL; - } - else - { - gSegment = tmp; - } -} - -// -// Table -// -Table::Table(const ReadSection &inTableSection) : - mMetaRecord(inTableSection[OffsetId]), - mTableSection(inTableSection), - mRecordsCount(inTableSection[OffsetRecordsCount]), - mFreeListHead(inTableSection[OffsetFreeListHead]), - mRecordNumbersCount(inTableSection[OffsetRecordNumbersCount]) -{ - // can't easily initialize indexes here, since meta record is incomplete - // until much later... see DbVersion::open() -} - -Table::~Table() -{ - for_each_map_delete(mIndexMap.begin(), mIndexMap.end()); -} - -void -Table::readIndexSection() -{ - uint32 indexSectionOffset = mTableSection.at(OffsetIndexesOffset); - - uint32 numIndexes = mTableSection.at(indexSectionOffset + AtomSize); - - for (uint32 i = 0; i < numIndexes; i++) { - uint32 indexOffset = mTableSection.at(indexSectionOffset + (i + 2) * AtomSize); - ReadSection indexSection(mTableSection.subsection(indexOffset)); - - auto_ptr index(new DbConstIndex(*this, indexSection)); - mIndexMap.insert(ConstIndexMap::value_type(index->indexId(), index.get())); - index.release(); - } -} - -Cursor * -Table::createCursor(const CSSM_QUERY *inQuery, const DbVersion &inDbVersion) const -{ - // if an index matches the query, return a cursor which uses the index - - ConstIndexMap::const_iterator it; - DbQueryKey *queryKey; - - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - if (it->second->matchesQuery(*inQuery, queryKey)) { - IndexCursor *cursor = new IndexCursor(queryKey, inDbVersion, *this, it->second); - return cursor; - } - - // otherwise, return a cursor that iterates over all table records - - return new LinearCursor(inQuery, inDbVersion, *this); -} - -const ReadSection -Table::getRecordSection(uint32 inRecordNumber) const -{ - if (inRecordNumber >= mRecordNumbersCount) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORD_UID); - - uint32 aRecordOffset = mTableSection[OffsetRecordNumbers + AtomSize - * inRecordNumber]; - - // Check if this RecordNumber has been deleted. - if (aRecordOffset & 1 || aRecordOffset == 0) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - - return MetaRecord::readSection(mTableSection, aRecordOffset); -} - -const RecordId -Table::getRecord(const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - Allocator &inAllocator) const -{ - const ReadSection aRecordSection = getRecordSection(inRecordId.mRecordNumber); - const RecordId aRecordId = MetaRecord::unpackRecordId(aRecordSection); - - // Make sure the RecordNumber matches that in the RecordId we just retrived. - if (aRecordId.mRecordNumber != inRecordId.mRecordNumber) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - if (aRecordId.mCreateVersion != inRecordId.mCreateVersion) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORD_UID); - - // XXX Figure out which value to pass for inQueryFlags (5th) argument - mMetaRecord.unpackRecord(aRecordSection, inAllocator, inoutAttributes, - inoutData, 0); - return aRecordId; -} - -uint32 -Table::popFreeList(uint32 &aFreeListHead) const -{ - assert(aFreeListHead | 1); - uint32 anOffset = aFreeListHead ^ 1; - uint32 aRecordNumber = (anOffset - OffsetRecordNumbers) / AtomSize; - aFreeListHead = mTableSection[anOffset]; - return aRecordNumber; -} - -const ReadSection -Table::getRecordsSection() const -{ - return mTableSection.subsection(mTableSection[OffsetRecords]); -} - -bool -Table::matchesTableId(Id inTableId) const -{ - Id anId = mMetaRecord.dataRecordType(); - if (inTableId == CSSM_DL_DB_RECORD_ANY) // All non schema tables. - return !(CSSM_DB_RECORDTYPE_SCHEMA_START <= anId - && anId < CSSM_DB_RECORDTYPE_SCHEMA_END); - - if (inTableId == CSSM_DL_DB_RECORD_ALL_KEYS) // All key tables. - return (anId == CSSM_DL_DB_RECORD_PUBLIC_KEY - || anId == CSSM_DL_DB_RECORD_PRIVATE_KEY - || anId == CSSM_DL_DB_RECORD_SYMMETRIC_KEY); - - return inTableId == anId; // Only if exact match. -} - - -// -// ModifiedTable -// -ModifiedTable::ModifiedTable(const Table *inTable) : - mTable(inTable), - mNewMetaRecord(nil), - mRecordNumberCount(inTable->recordNumberCount()), - mFreeListHead(inTable->freeListHead()), - mIsModified(false) -{ -} - -ModifiedTable::ModifiedTable(MetaRecord *inMetaRecord) : - mTable(nil), - mNewMetaRecord(inMetaRecord), - mRecordNumberCount(0), - mFreeListHead(0), - mIsModified(true) -{ -} - -ModifiedTable::~ModifiedTable() -{ - for_each_map_delete(mIndexMap.begin(), mIndexMap.end()); - for_each_map_delete(mInsertedMap.begin(), mInsertedMap.end()); - - delete mNewMetaRecord; -} - -void -ModifiedTable::deleteRecord(const RecordId &inRecordId) -{ - modifyTable(); - - uint32 aRecordNumber = inRecordId.mRecordNumber; - - // remove the record from all the indexes - MutableIndexMap::iterator it; - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - it->second->removeRecord(aRecordNumber); - - InsertedMap::iterator anIt = mInsertedMap.find(aRecordNumber); - if (anIt == mInsertedMap.end()) - { - // If we have no old table than this record can not exist yet. - if (!mTable) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - -#if RECORDVERSIONCHECK - const RecordId aRecordId = MetaRecord::unpackRecordId(mTable->getRecordSection(aRecordNumber)); - if (aRecordId.mRecordVersion != inRecordId.mRecordVersion) - CssmError::throwMe(CSSMERR_DL_RECORD_MODIFIED); -#endif - - // Schedule the record for deletion - if (!mDeletedSet.insert(aRecordNumber).second) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); // It was already deleted - } - else - { - const RecordId aRecordId = MetaRecord::unpackRecordId(*anIt->second); - if (aRecordId.mCreateVersion != inRecordId.mCreateVersion) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - -#if RECORDVERSIONCHECK - if (aRecordId.mRecordVersion != inRecordId.mRecordVersion) - CssmError::throwMe(CSSMERR_DL_RECORD_MODIFIED); -#endif - - // Remove the inserted (but uncommited) record. It should already be in mDeletedSet - // if it existed previously in mTable. - delete anIt->second; - mInsertedMap.erase(anIt); - } -} - -const RecordId -ModifiedTable::insertRecord(uint32 inVersionId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData) -{ - modifyTable(); - - auto_ptr aWriteSection(new WriteSection()); - getMetaRecord().packRecord(*aWriteSection, inAttributes, inData); - uint32 aRecordNumber = nextRecordNumber(); - - // add the record to all the indexes; this will throw if the new record - // violates a unique index - MutableIndexMap::iterator it; - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - it->second->insertRecord(aRecordNumber, *(aWriteSection.get())); - - // schedule the record for insertion - RecordId aRecordId(aRecordNumber, inVersionId); - MetaRecord::packRecordId(aRecordId, *aWriteSection); - mInsertedMap.insert(InsertedMap::value_type(aRecordNumber, aWriteSection.get())); - - aWriteSection.release(); - - return aRecordId; -} - -const RecordId -ModifiedTable::updateRecord(const RecordId &inRecordId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData, - CSSM_DB_MODIFY_MODE inModifyMode) -{ - modifyTable(); - - uint32 aRecordNumber = inRecordId.mRecordNumber; - InsertedMap::iterator anIt = mInsertedMap.find(aRecordNumber); - - // aReUpdate is true iff we are updating an already updated record. - bool aReUpdate = anIt != mInsertedMap.end(); - - // If we are not re-updating and there is no old table than this record does not exist yet. - if (!aReUpdate && !mTable) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - - const ReadSection &anOldDbRecord = aReUpdate ? *anIt->second : mTable->getRecordSection(aRecordNumber); - const RecordId aRecordId = MetaRecord::unpackRecordId(anOldDbRecord); - - // Did someone else delete the record we are trying to update. - if (aRecordId.mCreateVersion != inRecordId.mCreateVersion) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - -#if RECORDVERSIONCHECK - // Is the record we that our update is based on current? - if (aRecordId.mRecordVersion != inRecordId.mRecordVersion) - CssmError::throwMe(CSSMERR_DL_STALE_UNIQUE_RECORD); -#endif - - // Update the actual packed record. - auto_ptr aDbRecord(new WriteSection()); - getMetaRecord().updateRecord(anOldDbRecord, *aDbRecord, - CssmDbRecordAttributeData::overlay(inAttributes), inData, inModifyMode); - - - // Bump the RecordVersion of this record. - RecordId aNewRecordId(aRecordNumber, inRecordId.mCreateVersion, inRecordId.mRecordVersion + 1); - // Store the RecordVersion in the packed aDbRecord. - MetaRecord::packRecordId(aNewRecordId, *aDbRecord); - - if (!aReUpdate && !mDeletedSet.insert(aRecordNumber).second) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); // Record was already in mDeletedSet - - // remove the original record from all the indexes - MutableIndexMap::iterator it; - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - it->second->removeRecord(aRecordNumber); - - try - { - // Add the updated record to all the indexes; this will throw if the new record - // violates a unique index - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - it->second->insertRecord(aRecordNumber, *(aDbRecord.get())); - - if (aReUpdate) - { - // Get rid of anOldDbRecord from the inserted map and replace it - // with aDbRecord. - delete anIt->second; - anIt->second = aDbRecord.get(); - } - else - { - // First time though so let's just put the new value in the map. - mInsertedMap.insert(InsertedMap::value_type(aRecordNumber, aDbRecord.get())); - } - aDbRecord.release(); - } - catch(...) - { - // We only remove aRecordNumber from mDeletedSet if we added it above. - if (!aReUpdate) - mDeletedSet.erase(aRecordNumber); - - // The 2 operations below are an attempt to preserve the indices when - // an insert fails. - - // Remove the updated record from all the indexes - MutableIndexMap::iterator it; - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - it->second->removeRecord(aRecordNumber); - - // Add the original record back to all the indexes - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) - it->second->insertRecord(aRecordNumber, anOldDbRecord); - - throw; - } - - return aNewRecordId; -} - -const RecordId -ModifiedTable::getRecord(const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - Allocator &inAllocator) const -{ - if (mIsModified) - { - uint32 aRecordNumber = inRecordId.mRecordNumber; - InsertedMap::const_iterator anIt = mInsertedMap.find(aRecordNumber); - if (anIt != mInsertedMap.end()) - { - // We found the record in mInsertedMap so we use the inserted - // record. - const ReadSection &aRecordSection = *(anIt->second); - const RecordId aRecordId = MetaRecord::unpackRecordId(aRecordSection); - - // Make sure the RecordNumber matches that in the RecordId we just retrived. - if (aRecordId.mRecordNumber != aRecordNumber) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - if (aRecordId.mCreateVersion != inRecordId.mCreateVersion) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORD_UID); - - // XXX Figure out which value to pass for inQueryFlags (5th) argument - getMetaRecord().unpackRecord(aRecordSection, inAllocator, - inoutAttributes, inoutData, 0); - - return aRecordId; - } - else if (mDeletedSet.find(aRecordNumber) != mDeletedSet.end()) - { - // If aRecordNumber was not in mInsertedMap but it was in - // mDeletedSet then it was deleted but not yet commited. - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - } - } - - if (!mTable) - CssmError::throwMe(CSSMERR_DL_RECORD_NOT_FOUND); - - // Either this table wasn't modified yet or we didn't find aRecordNumber in - // mInsertedMap nor mDeletedSet so just ask mTable for it. - return mTable->getRecord(inRecordId, inoutAttributes, inoutData, - inAllocator); -} - -uint32 -ModifiedTable::nextRecordNumber() -{ - // If we still have unused free records in mTable get the next one. - if (mFreeListHead) - return mTable->popFreeList(mFreeListHead); - - // Bump up the mRecordNumberCount so we don't reuse the same one. - return mRecordNumberCount++; -} - -uint32 -ModifiedTable::recordNumberCount() const -{ - uint32 anOldMax = !mTable ? 0 : mTable->recordNumberCount() - 1; - uint32 anInsertedMax = mInsertedMap.empty() ? 0 : mInsertedMap.rbegin()->first; - - DeletedSet::reverse_iterator anIt = mDeletedSet.rbegin(); - DeletedSet::reverse_iterator anEnd = mDeletedSet.rend(); - for (; anIt != anEnd; anIt++) - { - if (*anIt != anOldMax || anOldMax <= anInsertedMax) - break; - anOldMax--; - } - - return max(anOldMax,anInsertedMax) + 1; -} - -const MetaRecord & -ModifiedTable::getMetaRecord() const -{ - return mNewMetaRecord ? *mNewMetaRecord : mTable->getMetaRecord(); -} - -// prepare to modify the table - -void -ModifiedTable::modifyTable() -{ - if (!mIsModified) { - createMutableIndexes(); - mIsModified = true; - } -} - -// create mutable indexes from the read-only indexes in the underlying table - -void -ModifiedTable::createMutableIndexes() -{ - if (mTable == NULL) - return; - - Table::ConstIndexMap::const_iterator it; - for (it = mTable->mIndexMap.begin(); it != mTable->mIndexMap.end(); it++) { - auto_ptr mutableIndex(new DbMutableIndex(*it->second)); - mIndexMap.insert(MutableIndexMap::value_type(it->first, mutableIndex.get())); - mutableIndex.release(); - } -} - -// find, and create if needed, an index with the given id - -DbMutableIndex & -ModifiedTable::findIndex(uint32 indexId, const MetaRecord &metaRecord, bool isUniqueIndex) -{ - MutableIndexMap::iterator it = mIndexMap.find(indexId); - - if (it == mIndexMap.end()) { - // create the new index - auto_ptr index(new DbMutableIndex(metaRecord, indexId, isUniqueIndex)); - it = mIndexMap.insert(MutableIndexMap::value_type(indexId, index.get())).first; - index.release(); - } - - return *it->second; -} - -uint32 -ModifiedTable::writeIndexSection(WriteSection &tableSection, uint32 offset) -{ - MutableIndexMap::iterator it; - - tableSection.put(Table::OffsetIndexesOffset, offset); - - // leave room for the size, to be written later - uint32 indexSectionOffset = offset; - offset += AtomSize; - - offset = tableSection.put(offset, (uint32)mIndexMap.size()); - - // leave room for the array of offsets to the indexes - uint32 indexOffsetOffset = offset; - offset += mIndexMap.size() * AtomSize; - - // write the indexes - for (it = mIndexMap.begin(); it != mIndexMap.end(); it++) { - indexOffsetOffset = tableSection.put(indexOffsetOffset, offset); - offset = it->second->writeIndex(tableSection, offset); - } - - // write the total index section size - tableSection.put(indexSectionOffset, offset - indexSectionOffset); - - return offset; -} - -uint32 -ModifiedTable::writeTable(AtomicTempFile &inAtomicTempFile, uint32 inSectionOffset) -{ - if (mTable && !mIsModified) { - // the table has not been modified, so we can just dump the old table - // section into the new database - - const ReadSection &tableSection = mTable->getTableSection(); - uint32 tableSize = tableSection.at(Table::OffsetSize); - - inAtomicTempFile.write(AtomicFile::FromStart, inSectionOffset, - tableSection.range(Range(0, tableSize)), tableSize); - - return inSectionOffset + tableSize; - } - - // We should have an old mTable or a mNewMetaRecord but not both. - assert(mTable != nil ^ mNewMetaRecord != nil); - const MetaRecord &aNewMetaRecord = getMetaRecord(); - - uint32 aRecordsCount = 0; - uint32 aRecordNumbersCount = recordNumberCount(); - uint32 aRecordsOffset = Table::OffsetRecordNumbers + AtomSize * aRecordNumbersCount; - WriteSection aTableSection(Allocator::standard(), aRecordsOffset); - aTableSection.size(aRecordsOffset); - aTableSection.put(Table::OffsetId, aNewMetaRecord.dataRecordType()); - aTableSection.put(Table::OffsetRecords, aRecordsOffset); - aTableSection.put(Table::OffsetRecordNumbersCount, aRecordNumbersCount); - - uint32 anOffset = inSectionOffset + aRecordsOffset; - - if (mTable) - { - // XXX Handle schema changes in the future. - assert(mNewMetaRecord == nil); - - // We have a modified old table so copy all non deleted records - // The code below is rather elaborate, but this is because it attempts - // to copy large ranges of non deleted records with single calls - // to AtomicFile::write() - uint32 anOldRecordsCount = mTable->getRecordsCount(); - ReadSection aRecordsSection = mTable->getRecordsSection(); - uint32 aReadOffset = 0; // Offset of current record - uint32 aWriteOffset = aRecordsOffset; // Offset for current write record - uint32 aBlockStart = aReadOffset; // Starting point for read - uint32 aBlockSize = 0; // Size of block to read - for (uint32 aRecord = 0; aRecord < anOldRecordsCount; aRecord++) - { - ReadSection aRecordSection = MetaRecord::readSection(aRecordsSection, aReadOffset); - uint32 aRecordNumber = MetaRecord::unpackRecordNumber(aRecordSection); - uint32 aRecordSize = aRecordSection.size(); - aReadOffset += aRecordSize; - if (mDeletedSet.find(aRecordNumber) == mDeletedSet.end()) - { - // This record has not been deleted. Register the offset - // at which it will be in the new file in aTableSection. - aTableSection.put(Table::OffsetRecordNumbers - + AtomSize * aRecordNumber, - aWriteOffset); - aWriteOffset += aRecordSize; - aBlockSize += aRecordSize; - aRecordsCount++; - // XXX update all indexes being created. - } - else - { - // The current record has been deleted. Copy all records up - // to but not including the current one to the new file. - if (aBlockSize > 0) - { - inAtomicTempFile.write(AtomicFile::FromStart, anOffset, - aRecordsSection.range(Range(aBlockStart, - aBlockSize)), - aBlockSize); - anOffset += aBlockSize; - } - - // Set the start of the next block to the start of the next - // record, and the size of the block to 0. - aBlockStart = aReadOffset; - aBlockSize = 0; - } // if (mDeletedSet..) - } // for (aRecord...) - - // Copy all records that have not yet been copied to the new file. - if (aBlockSize > 0) - { - inAtomicTempFile.write(AtomicFile::FromStart, anOffset, - aRecordsSection.range(Range(aBlockStart, - aBlockSize)), - aBlockSize); - anOffset += aBlockSize; - } - } // if (mTable) - - // Now add all inserted records to the table. - InsertedMap::const_iterator anIt = mInsertedMap.begin(); - InsertedMap::const_iterator anEnd = mInsertedMap.end(); - // Iterate over all inserted objects. - for (; anIt != anEnd; anIt++) - { - // Write out each inserted/modified record - const WriteSection &aRecord = *anIt->second; - uint32 aRecordNumber = anIt->first; - // Put offset relative to start of this table in recordNumber array. - aTableSection.put(Table::OffsetRecordNumbers + AtomSize * aRecordNumber, - anOffset - inSectionOffset); - inAtomicTempFile.write(AtomicFile::FromStart, anOffset, - aRecord.address(), aRecord.size()); - anOffset += aRecord.size(); - aRecordsCount++; - // XXX update all indexes being created. - } - - // Reconstruct the freelist (this is O(N) where N is the number of recordNumbers) - // We could implement it faster by using the old freelist and skipping the records - // that have been inserted. However building the freelist for the newly used - // recordNumbers (not in mTable) would look like the code below anyway (starting - // from mTable->recordNumberCount()). - // The first part of this would be O(M Log(N)) (where M is the old number of - // free records, and N is the number of newly inserted records) - // The second part would be O(N) where N is the currently max RecordNumber - // in use - the old max RecordNumber in use. - uint32 aFreeListHead = 0; // Link to previous free record - for (uint32 aRecordNumber = 0; aRecordNumber < aRecordNumbersCount; aRecordNumber++) - { - // Make the freelist a list of all records with 0 offset (non existing). - if (!aTableSection.at(Table::OffsetRecordNumbers + AtomSize * aRecordNumber)) - { - aTableSection.put(Table::OffsetRecordNumbers - + AtomSize * aRecordNumber, - aFreeListHead); - // Make aFreeListHead point to the previous free recordNumber slot in the table. - aFreeListHead = (Table::OffsetRecordNumbers + AtomSize * aRecordNumber) | 1; - } - } - aTableSection.put(Table::OffsetFreeListHead, aFreeListHead); - - anOffset -= inSectionOffset; - - // Write out indexes, which are part of the table section - - { - uint32 indexOffset = anOffset; - anOffset = writeIndexSection(aTableSection, anOffset); - inAtomicTempFile.write(AtomicFile::FromStart, inSectionOffset + indexOffset, - aTableSection.address() + indexOffset, anOffset - indexOffset); - } - - // Set the section size and recordCount. - aTableSection.put(Table::OffsetSize, anOffset); - aTableSection.put(Table::OffsetRecordsCount, aRecordsCount); - - // Write out aTableSection header. - inAtomicTempFile.write(AtomicFile::FromStart, inSectionOffset, - aTableSection.address(), aTableSection.size()); - - return anOffset + inSectionOffset; -} - - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-const-variable" - -// -// Metadata -// - -// Attribute definitions - -static const CSSM_DB_ATTRIBUTE_INFO RelationID = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "RelationID"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO RelationName = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "RelationName"}, - CSSM_DB_ATTRIBUTE_FORMAT_STRING -}; -static const CSSM_DB_ATTRIBUTE_INFO AttributeID = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "AttributeID"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO AttributeNameFormat = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "AttributeNameFormat"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO AttributeName = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "AttributeName"}, - CSSM_DB_ATTRIBUTE_FORMAT_STRING -}; -static const CSSM_DB_ATTRIBUTE_INFO AttributeNameID = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "AttributeNameID"}, - CSSM_DB_ATTRIBUTE_FORMAT_BLOB -}; -static const CSSM_DB_ATTRIBUTE_INFO AttributeFormat = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "AttributeFormat"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO IndexID = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "IndexID"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO IndexType = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "IndexType"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO IndexedDataLocation = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "IndexedDataLocation"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO ModuleID = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "ModuleID"}, - CSSM_DB_ATTRIBUTE_FORMAT_BLOB -}; -static const CSSM_DB_ATTRIBUTE_INFO AddinVersion = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "AddinVersion"}, - CSSM_DB_ATTRIBUTE_FORMAT_STRING -}; -static const CSSM_DB_ATTRIBUTE_INFO SSID = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "SSID"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; -static const CSSM_DB_ATTRIBUTE_INFO SubserviceType = -{ - CSSM_DB_ATTRIBUTE_NAME_AS_STRING, - {(char*) "SubserviceType"}, - CSSM_DB_ATTRIBUTE_FORMAT_UINT32 -}; - -#define ATTRIBUTE(type, name) \ - { CSSM_DB_ATTRIBUTE_NAME_AS_STRING, { (char*) #name }, CSSM_DB_ATTRIBUTE_FORMAT_ ## type } - -static const CSSM_DB_ATTRIBUTE_INFO AttrSchemaRelations[] = -{ - //RelationID, RelationName - ATTRIBUTE(UINT32, RelationID), - ATTRIBUTE(STRING, RelationName) -}; - -static const CSSM_DB_ATTRIBUTE_INFO AttrSchemaAttributes[] = -{ - //RelationID, AttributeID, - //AttributeNameFormat, AttributeName, AttributeNameID, - //AttributeFormat - ATTRIBUTE(UINT32, RelationID), - ATTRIBUTE(UINT32, AttributeID), - ATTRIBUTE(UINT32, AttributeNameFormat), - ATTRIBUTE(STRING, AttributeName), - ATTRIBUTE(BLOB, AttributeNameID), - ATTRIBUTE(UINT32, AttributeFormat) -}; - -static const CSSM_DB_ATTRIBUTE_INFO AttrSchemaIndexes[] = -{ - ATTRIBUTE(UINT32, RelationID), - ATTRIBUTE(UINT32, IndexID), - ATTRIBUTE(UINT32, AttributeID), - ATTRIBUTE(UINT32, IndexType), - ATTRIBUTE(UINT32, IndexedDataLocation) - //RelationID, IndexID, AttributeID, - //IndexType, IndexedDataLocation -}; - -static const CSSM_DB_ATTRIBUTE_INFO AttrSchemaParsingModule[] = -{ - ATTRIBUTE(UINT32, RelationID), - ATTRIBUTE(UINT32, AttributeID), - ATTRIBUTE(BLOB, ModuleID), - ATTRIBUTE(STRING, AddinVersion), - ATTRIBUTE(UINT32, SSID), - ATTRIBUTE(UINT32, SubserviceType) - //RelationID, AttributeID, - //ModuleID, AddinVersion, SSID, SubserviceType -}; - -#undef ATTRIBUTE -#pragma clang diagnostic pop - -// -// DbVersion -// -DbVersion::DbVersion(const AppleDatabase &db, const RefPointer &inAtomicBufferedFile) : - mDatabase(reinterpret_cast(NULL), 0), - mDb(db), - mBufferedFile(inAtomicBufferedFile) -{ - off_t aLength = mBufferedFile->length(); - off_t bytesRead = 0; - const uint8 *ptr = mBufferedFile->read(0, aLength, bytesRead); - mBufferedFile->close(); - mDatabase = ReadSection(ptr, (size_t)bytesRead); - open(); -} - -DbVersion::~DbVersion() -{ - try - { - for_each_map_delete(mTableMap.begin(), mTableMap.end()); - } - catch(...) {} -} - -void -DbVersion::open() -{ - try - { - // This is the oposite of DbModifier::commit() - mVersionId = mDatabase[mDatabase.size() - AtomSize]; - - const ReadSection aHeaderSection = mDatabase.subsection(HeaderOffset, - HeaderSize); - if (aHeaderSection.at(OffsetMagic) != HeaderMagic) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - // We currently only support one version. If we support additional - // file format versions in the future fix this. - uint32 aVersion = aHeaderSection.at(OffsetVersion); - if (aVersion != HeaderVersion) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - //const ReadSection anAuthSection = - // mDatabase.subsection(HeaderOffset + aHeaderSection.at(OffsetAuthOffset)); - // XXX Do something with anAuthSection. - - uint32 aSchemaOffset = aHeaderSection.at(OffsetSchemaOffset); - const ReadSection aSchemaSection = - mDatabase.subsection(HeaderOffset + aSchemaOffset); - - uint32 aSchemaSize = aSchemaSection[OffsetSchemaSize]; - // Make sure that the given range exists. - aSchemaSection.subsection(0, aSchemaSize); - uint32 aTableCount = aSchemaSection[OffsetTablesCount]; - - // Assert that the size of this section is big enough. - if (aSchemaSize < OffsetTables + AtomSize * aTableCount) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - for (uint32 aTableNumber = 0; aTableNumber < aTableCount; - aTableNumber++) - { - uint32 aTableOffset = aSchemaSection.at(OffsetTables + AtomSize - * aTableNumber); - // XXX Set the size boundary on aTableSection. - const ReadSection aTableSection = - aSchemaSection.subsection(aTableOffset); - auto_ptr aTable(new Table(aTableSection)); - Table::Id aTableId = aTable->getMetaRecord().dataRecordType(); - mTableMap.insert(TableMap::value_type(aTableId, aTable.get())); - aTable.release(); - } - - // Fill in the schema for the meta tables. - - findTable(mDb.schemaRelations.DataRecordType).getMetaRecord(). - setRecordAttributeInfo(mDb.schemaRelations); - findTable(mDb.schemaIndexes.DataRecordType).getMetaRecord(). - setRecordAttributeInfo(mDb.schemaIndexes); - findTable(mDb.schemaParsingModule.DataRecordType).getMetaRecord(). - setRecordAttributeInfo(mDb.schemaParsingModule); - - // OK, we have created all the tables in the tableMap. Now - // lets read the schema and proccess it accordingly. - // Iterate over all schema records. - Table &aTable = findTable(mDb.schemaAttributes.DataRecordType); - aTable.getMetaRecord().setRecordAttributeInfo(mDb.schemaAttributes); - uint32 aRecordsCount = aTable.getRecordsCount(); - ReadSection aRecordsSection = aTable.getRecordsSection(); - uint32 aReadOffset = 0; - const MetaRecord &aMetaRecord = aTable.getMetaRecord(); - - CSSM_DB_ATTRIBUTE_DATA aRelationIDData = - { - RelationID, - 0, - NULL - }; - CSSM_DB_ATTRIBUTE_DATA aAttributeIDData = - { - AttributeID, - 0, - NULL - }; - CSSM_DB_ATTRIBUTE_DATA aAttributeNameFormatData = - { - AttributeNameFormat, - 0, - NULL - }; - CSSM_DB_ATTRIBUTE_DATA aAttributeNameData = - { - AttributeName, - 0, - NULL - }; - CSSM_DB_ATTRIBUTE_DATA aAttributeNameIDData = - { - AttributeNameID, - 0, - NULL - }; - CSSM_DB_ATTRIBUTE_DATA aAttributeFormatData = - { - AttributeFormat, - 0, - NULL - }; - CSSM_DB_ATTRIBUTE_DATA aRecordAttributes[] = - { - aRelationIDData, - aAttributeIDData, - aAttributeNameFormatData, - aAttributeNameData, - aAttributeNameIDData, - aAttributeFormatData - }; - CSSM_DB_RECORD_ATTRIBUTE_DATA aRecordAttributeData = - { - aMetaRecord.dataRecordType(), - 0, - sizeof(aRecordAttributes) / sizeof(CSSM_DB_ATTRIBUTE_DATA), - aRecordAttributes - }; - CssmDbRecordAttributeData &aRecordData = CssmDbRecordAttributeData::overlay(aRecordAttributeData); - - TrackingAllocator recordAllocator(Allocator::standard()); - for (uint32 aRecord = 0; aRecord != aRecordsCount; aRecord++) - { - ReadSection aRecordSection = MetaRecord::readSection(aRecordsSection, aReadOffset); - uint32 aRecordSize = aRecordSection.size(); - aReadOffset += aRecordSize; - aMetaRecord.unpackRecord(aRecordSection, recordAllocator, - &aRecordAttributeData, NULL, 0); - // Create the attribute coresponding to this entry - if (aRecordData[0].size() != 1 || aRecordData[0].format() != CSSM_DB_ATTRIBUTE_FORMAT_UINT32) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - uint32 aRelationId = aRecordData[0]; - - // Skip the schema relations for the meta tables themselves. - // FIXME: this hard-wires the meta-table relation IDs to be - // within {CSSM_DB_RECORDTYPE_SCHEMA_START... - // CSSM_DB_RECORDTYPE_SCHEMA_END} (which is {0..4}). - // Bogus - the MDS schema relation IDs start at - // CSSM_DB_RELATIONID_MDS_START which is 0x40000000. - // Ref. Radar 2817921. - if (CSSM_DB_RECORDTYPE_SCHEMA_START <= aRelationId && aRelationId < CSSM_DB_RECORDTYPE_SCHEMA_END) - continue; - - // Get the MetaRecord corresponding to the specified RelationId - MetaRecord &aMetaRecord = findTable(aRelationId).getMetaRecord(); - - if (aRecordData[1].size() != 1 - || aRecordData[1].format() != CSSM_DB_ATTRIBUTE_FORMAT_UINT32 - || aRecordData[2].size() != 1 - || aRecordData[2].format() != CSSM_DB_ATTRIBUTE_FORMAT_UINT32 - || aRecordData[5].size() != 1 - || aRecordData[5].format() != CSSM_DB_ATTRIBUTE_FORMAT_UINT32) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - uint32 anAttributeId = aRecordData[1]; - uint32 anAttributeNameFormat = aRecordData[2]; - uint32 anAttributeFormat = aRecordData[5]; - auto_ptr aName; - const CssmData *aNameID = NULL; - - if (aRecordData[3].size() == 1) - { - if (aRecordData[3].format() != CSSM_DB_ATTRIBUTE_FORMAT_STRING) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - auto_ptr aName2(new string(static_cast(aRecordData[3]))); - aName = aName2; - } - - if (aRecordData[4].size() == 1) - { - if (aRecordData[4].format() != CSSM_DB_ATTRIBUTE_FORMAT_BLOB) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - // @@@ Invoking conversion operator to CssmData & on aRecordData[4] - // And taking address of result. - aNameID = &static_cast(aRecordData[4]); - } - - // Make sure that the attribute specified by anAttributeNameFormat is present. - switch (anAttributeNameFormat) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - if (aRecordData[3].size() != 1) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - break; - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - if (aRecordData[4].size() != 1) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - break; - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - break; - default: - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - // Create the attribute - aMetaRecord.createAttribute(aName.get(), aNameID, anAttributeId, anAttributeFormat); - } - - // initialize the indexes associated with each table - { - TableMap::iterator it; - for (it = mTableMap.begin(); it != mTableMap.end(); it++) - it->second->readIndexSection(); - } - } - catch(...) - { - for_each_map_delete(mTableMap.begin(), mTableMap.end()); - mTableMap.clear(); - throw; - } -} - -const RecordId -DbVersion::getRecord(Table::Id inTableId, const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA *inoutAttributes, - CssmData *inoutData, - Allocator &inAllocator) const -{ - return findTable(inTableId).getRecord(inRecordId, inoutAttributes, - inoutData, inAllocator); -} - -Cursor * -DbVersion::createCursor(const CSSM_QUERY *inQuery) const -{ - // XXX We should add support for these special query types - // By Creating a Cursor that iterates over multiple tables - if (!inQuery || inQuery->RecordType == CSSM_DL_DB_RECORD_ANY - || inQuery->RecordType == CSSM_DL_DB_RECORD_ALL_KEYS) - { - return new MultiCursor(inQuery, *this); - } - - return findTable(inQuery->RecordType).createCursor(inQuery, *this); -} - -bool DbVersion::hasTable(Table::Id inTableId) const -{ - TableMap::const_iterator it = mTableMap.find(inTableId); - return it != mTableMap.end(); -} - -const Table & -DbVersion::findTable(Table::Id inTableId) const -{ - TableMap::const_iterator it = mTableMap.find(inTableId); - if (it == mTableMap.end()) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - return *it->second; -} - -Table & -DbVersion::findTable(Table::Id inTableId) -{ - TableMap::iterator it = mTableMap.find(inTableId); - if (it == mTableMap.end()) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - return *it->second; -} - -// -// Cursor implemetation -// -Cursor::Cursor() -{ -} - -Cursor::Cursor(const DbVersion &inDbVersion) : mDbVersion(&inDbVersion) -{ -} - -Cursor::~Cursor() -{ -} - -bool -Cursor::next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR outAttributes, - CssmData *outData, - Allocator &inAllocator, - RecordId &recordId) -{ - return false; -} - -// -// LinearCursor implemetation -// -LinearCursor::LinearCursor(const CSSM_QUERY *inQuery, const DbVersion &inDbVersion, - const Table &inTable) : - Cursor(inDbVersion), - mRecordsCount(inTable.getRecordsCount()), - mRecord(0), - mRecordsSection(inTable.getRecordsSection()), - mReadOffset(0), - mMetaRecord(inTable.getMetaRecord()) -{ - if (inQuery) - { - mConjunctive = inQuery->Conjunctive; - mQueryFlags = inQuery->QueryFlags; - // XXX Do something with inQuery->QueryLimits? - uint32 aPredicatesCount = inQuery->NumSelectionPredicates; - mPredicates.resize(aPredicatesCount); - try - { - for (uint32 anIndex = 0; anIndex < aPredicatesCount; anIndex++) - { - CSSM_SELECTION_PREDICATE &aPredicate = inQuery->SelectionPredicate[anIndex]; - mPredicates[anIndex] = new SelectionPredicate(mMetaRecord, aPredicate); - } - } - catch(...) - { - for_each_delete(mPredicates.begin(), mPredicates.end()); - throw; - } - } -} - -LinearCursor::~LinearCursor() -{ - for_each_delete(mPredicates.begin(), mPredicates.end()); -} - -bool -LinearCursor::next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, Allocator &inAllocator, RecordId &recordId) -{ - while (mRecord++ < mRecordsCount) - { - ReadSection aRecordSection = MetaRecord::readSection(mRecordsSection, mReadOffset); - uint32 aRecordSize = aRecordSection.size(); - mReadOffset += aRecordSize; - - PredicateVector::const_iterator anIt = mPredicates.begin(); - PredicateVector::const_iterator anEnd = mPredicates.end(); - bool aMatch; - if (anIt == anEnd) - { - // If there are no predicates we have a match. - aMatch = true; - } - else if (mConjunctive == CSSM_DB_OR) - { - // If mConjunctive is OR, the first predicate that returns - // true indicates a match. Dropthough means no match - aMatch = false; - for (; anIt != anEnd; anIt++) - { - if ((*anIt)->evaluate(aRecordSection)) - { - aMatch = true; - break; - } - } - } - else if (mConjunctive == CSSM_DB_AND || mConjunctive == CSSM_DB_NONE) - { - // If mConjunctive is AND (or NONE), the first predicate that returns - // false indicates a mismatch. Dropthough means a match - aMatch = true; - for (; anIt != anEnd; anIt++) - { - if (!(*anIt)->evaluate(aRecordSection)) - { - aMatch = false; - break; - } - } - } - else - { - // XXX Should be CSSMERR_DL_INVALID_QUERY (or CSSMERR_DL_INVALID_CONJUNTIVE). - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_QUERY); - } - - if (aMatch) - { - // Get the actual record. - mMetaRecord.unpackRecord(aRecordSection, inAllocator, - inoutAttributes, inoutData, - mQueryFlags); - outTableId = mMetaRecord.dataRecordType(); - recordId = MetaRecord::unpackRecordId(aRecordSection); - return true; - } - } - - return false; -} - -// -// IndexCursor -// - -IndexCursor::IndexCursor(DbQueryKey *queryKey, const DbVersion &inDbVersion, - const Table &table, const DbConstIndex *index) : - Cursor(inDbVersion), mQueryKey(queryKey), mTable(table), mIndex(index) -{ - index->performQuery(*queryKey, mBegin, mEnd); -} - -IndexCursor::~IndexCursor() -{ - // the query key will be deleted automatically, since it's an auto_ptr -} - -bool -IndexCursor::next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR outAttributes, - CssmData *outData, - Allocator &inAllocator, RecordId &recordId) -{ - if (mBegin == mEnd) - return false; - - ReadSection rs = mIndex->getRecordSection(mBegin++); - const MetaRecord &metaRecord = mTable.getMetaRecord(); - - outTableId = metaRecord.dataRecordType(); - metaRecord.unpackRecord(rs, inAllocator, outAttributes, outData, 0); - - recordId = MetaRecord::unpackRecordId(rs); - return true; -} - -// -// MultiCursor -// -MultiCursor::MultiCursor(const CSSM_QUERY *inQuery, const DbVersion &inDbVersion) : - Cursor(inDbVersion), mTableIterator(inDbVersion.begin()) -{ - if (inQuery) - mQuery.reset(new CssmAutoQuery(*inQuery)); - else - { - mQuery.reset(new CssmAutoQuery()); - mQuery->recordType(CSSM_DL_DB_RECORD_ANY); - } -} - -MultiCursor::~MultiCursor() -{ -} - -bool -MultiCursor::next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, Allocator &inAllocator, RecordId &recordId) -{ - for (;;) - { - if (!mCursor.get()) - { - if (mTableIterator == mDbVersion->end()) - return false; - - const Table &aTable = *mTableIterator++; - if (!aTable.matchesTableId(mQuery->recordType())) - continue; - - mCursor.reset(aTable.createCursor(mQuery.get(), *mDbVersion)); - } - - if (mCursor->next(outTableId, inoutAttributes, inoutData, inAllocator, recordId)) - return true; - - mCursor.reset(NULL); - } -} - - -// -// DbModifier -// -DbModifier::DbModifier(AtomicFile &inAtomicFile, const AppleDatabase &db) : - Metadata(), - mDbVersion(), - mAtomicFile(inAtomicFile), - mDb(db) -{ -} - -DbModifier::~DbModifier() -{ - try - { - for_each_map_delete(mModifiedTableMap.begin(), mModifiedTableMap.end()); - // mAtomicTempFile will do automatic rollback on destruction. - } - catch(...) {} -} - -const RefPointer -DbModifier::getDbVersion(bool force) -{ - StLock _(mDbVersionLock); - - /* Initialize the shared memory file change mechanism */ - pthread_once(&gCommonInitMutex, initCommon); - - /* If we don't have a mDbVersion yet, or we are force to re-read the file - before a write transaction, or we have received any notifications after - the last time we read the file, or more than kForceReReadTime seconds - have passed since the last time we read the file, we open the file and - check if it has changed. */ - if (!mDbVersion || - force || - gSegment == NULL || - mNotifyCount != *gSegment || - CFAbsoluteTimeGetCurrent() > mDbLastRead + kForceReReadTime) - { - RefPointer atomicBufferedFile(mAtomicFile.read()); - off_t length = atomicBufferedFile->open(); - /* Record the number of notifications we've seen and when we last - opened the file. */ - if (gSegment != NULL) - { - mNotifyCount = *gSegment; - } - - mDbLastRead = CFAbsoluteTimeGetCurrent(); - - /* If we already have a mDbVersion, let's check if we can reuse it. */ - if (mDbVersion) - { - if (length < AtomSize) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - off_t bytesRead = 0; - const uint8 *ptr = atomicBufferedFile->read(length - AtomSize, - AtomSize, bytesRead); - ReadSection aVersionSection(ptr, (size_t)bytesRead); - uint32 aVersionId = aVersionSection[0]; - - /* If the version stamp hasn't changed the old mDbVersion is still - current. */ - if (aVersionId == mDbVersion->getVersionId()) - return mDbVersion; - } - - mDbVersion = new DbVersion(mDb, atomicBufferedFile); - } - - return mDbVersion; -} - -void -DbModifier::createDatabase(const CSSM_DBINFO &inDbInfo, - const CSSM_ACL_ENTRY_INPUT *inInitialAclEntry, - mode_t mode) -{ - // XXX This needs better locking. There is a possible race condition between - // two concurrent creators. Or a writer/creator or a close/create etc. - if (mAtomicTempFile || !mModifiedTableMap.empty()) - CssmError::throwMe(CSSMERR_DL_DATASTORE_ALREADY_EXISTS); - - mAtomicTempFile = mAtomicFile.create(mode); - // Set mVersionId to one since this is the first version of the database. - mVersionId = 1; - - // we need to create the meta tables first, because inserting tables - // (including the meta tables themselves) relies on them being there - createTable(new MetaRecord(mDb.schemaRelations)); - createTable(new MetaRecord(mDb.schemaAttributes)); - createTable(new MetaRecord(mDb.schemaIndexes)); - createTable(new MetaRecord(mDb.schemaParsingModule)); - - // now add the meta-tables' schema to the meta tables themselves - insertTableSchema(mDb.schemaRelations); - insertTableSchema(mDb.schemaAttributes); - insertTableSchema(mDb.schemaIndexes); - insertTableSchema(mDb.schemaParsingModule); - - if (inInitialAclEntry != NULL) - { - //createACL(*inInitialAclEntry); - } - - if (inDbInfo.NumberOfRecordTypes == 0) - return; - if (inDbInfo.RecordAttributeNames == NULL) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - if (inDbInfo.RecordIndexes == NULL) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORD_INDEX); - if (inDbInfo.DefaultParsingModules == NULL) - CssmError::throwMe(CSSMERR_DL_INVALID_PARSING_MODULE); - - for (uint32 anIndex = 0; anIndex < inDbInfo.NumberOfRecordTypes; anIndex++) - { - insertTable(CssmDbRecordAttributeInfo::overlay(inDbInfo.RecordAttributeNames[anIndex]), - &inDbInfo.RecordIndexes[anIndex], - &inDbInfo.DefaultParsingModules[anIndex]); - } -} - -void DbModifier::openDatabase() -{ - // No need to do anything on open if we are already writing the database. - if (!mAtomicTempFile) - getDbVersion(false); -} - -void DbModifier::closeDatabase() -{ - commit(); // XXX Requires write lock. - StLock _(mDbVersionLock); - mDbVersion = NULL; -} - -void DbModifier::deleteDatabase() -{ - bool isDirty = mAtomicTempFile; - rollback(); // XXX Requires write lock. - StLock _(mDbVersionLock); - - // Clean up mModifiedTableMap in case this object gets reused again for - // a new create. - for_each_map_delete(mModifiedTableMap.begin(), mModifiedTableMap.end()); - mModifiedTableMap.clear(); - - // If the database was dirty and we had no mDbVersion yet then rollback() - // would have deleted the db. - if (!isDirty || mDbVersion) - { - mDbVersion = NULL; - mAtomicFile.performDelete(); - } -} - -void -DbModifier::modifyDatabase() -{ - if (mAtomicTempFile) - return; - - try - { - mAtomicTempFile = mAtomicFile.write(); - // Now we are holding the write lock make sure we get the latest greatest version of the db. - // Also set mVersionId to one more that that of the old database. - mVersionId = getDbVersion(true)->getVersionId() + 1; - - // Never make a database with mVersionId 0 since it makes bad things happen to Jaguar and older systems - if (mVersionId == 0) - mVersionId = 1; - - // Remove all old modified tables - for_each_map_delete(mModifiedTableMap.begin(), mModifiedTableMap.end()); - mModifiedTableMap.clear(); - - // Setup the new tables - DbVersion::TableMap::const_iterator anIt = - mDbVersion->mTableMap.begin(); - DbVersion::TableMap::const_iterator anEnd = - mDbVersion->mTableMap.end(); - for (; anIt != anEnd; ++anIt) - { - auto_ptr aTable(new ModifiedTable(anIt->second)); - mModifiedTableMap.insert(ModifiedTableMap::value_type(anIt->first, - aTable.get())); - aTable.release(); - } - } - catch(...) - { - for_each_map_delete(mModifiedTableMap.begin(), mModifiedTableMap.end()); - mModifiedTableMap.clear(); - rollback(); - throw; - } -} - -void -DbModifier::deleteRecord(Table::Id inTableId, const RecordId &inRecordId) -{ - modifyDatabase(); - findTable(inTableId).deleteRecord(inRecordId); -} - -const RecordId -DbModifier::insertRecord(Table::Id inTableId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData) -{ - modifyDatabase(); - return findTable(inTableId).insertRecord(mVersionId, inAttributes, inData); -} - -const RecordId -DbModifier::updateRecord(Table::Id inTableId, const RecordId &inRecordId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData, - CSSM_DB_MODIFY_MODE inModifyMode) -{ - modifyDatabase(); - return findTable(inTableId).updateRecord(inRecordId, inAttributes, inData, inModifyMode); -} - -// Create a table associated with a given metarecord, and add the table -// to the database. - -ModifiedTable * -DbModifier::createTable(MetaRecord *inMetaRecord) -{ - auto_ptr aMetaRecord(inMetaRecord); - auto_ptr aModifiedTable(new ModifiedTable(inMetaRecord)); - // Now that aModifiedTable is fully constructed it owns inMetaRecord - aMetaRecord.release(); - - if (!mModifiedTableMap.insert - (ModifiedTableMap::value_type(inMetaRecord->dataRecordType(), - aModifiedTable.get())).second) - { - // XXX Should be CSSMERR_DL_DUPLICATE_RECORDTYPE. Since that - // doesn't exist we report that the metatable's unique index would - // no longer be valid - CssmError::throwMe(CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA); - } - - return aModifiedTable.release(); -} - -void -DbModifier::deleteTable(Table::Id inTableId) -{ - modifyDatabase(); - // Can't delete schema tables. - if (CSSM_DB_RECORDTYPE_SCHEMA_START <= inTableId - && inTableId < CSSM_DB_RECORDTYPE_SCHEMA_END) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - - // Find the ModifiedTable and delete it - ModifiedTableMap::iterator it = mModifiedTableMap.find(inTableId); - if (it == mModifiedTableMap.end()) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - - delete it->second; - mModifiedTableMap.erase(it); -} - -uint32 -DbModifier::writeAuthSection(uint32 inSectionOffset) -{ - WriteSection anAuthSection; - - // XXX Put real data into the authsection. - uint32 anOffset = anAuthSection.put(0, 0); - anAuthSection.size(anOffset); - - mAtomicTempFile->write(AtomicFile::FromStart, inSectionOffset, - anAuthSection.address(), anAuthSection.size()); - return inSectionOffset + anOffset; -} - -uint32 -DbModifier::writeSchemaSection(uint32 inSectionOffset) -{ - uint32 aTableCount = (uint32) mModifiedTableMap.size(); - WriteSection aTableSection(Allocator::standard(), - OffsetTables + AtomSize * aTableCount); - // Set aTableSection to the correct size. - aTableSection.size(OffsetTables + AtomSize * aTableCount); - aTableSection.put(OffsetTablesCount, aTableCount); - - uint32 anOffset = inSectionOffset + OffsetTables + AtomSize * aTableCount; - ModifiedTableMap::const_iterator anIt = mModifiedTableMap.begin(); - ModifiedTableMap::const_iterator anEnd = mModifiedTableMap.end(); - for (uint32 aTableNumber = 0; anIt != anEnd; anIt++, aTableNumber++) - { - // Put the offset to the current table relative to the start of - // this section into the tables array - aTableSection.put(OffsetTables + AtomSize * aTableNumber, - anOffset - inSectionOffset); - anOffset = anIt->second->writeTable(*mAtomicTempFile, anOffset); - } - - aTableSection.put(OffsetSchemaSize, anOffset - inSectionOffset); - mAtomicTempFile->write(AtomicFile::FromStart, inSectionOffset, - aTableSection.address(), aTableSection.size()); - - return anOffset; -} - -void -DbModifier::commit() -{ - if (!mAtomicTempFile) - return; - try - { - WriteSection aHeaderSection(Allocator::standard(), size_t(HeaderSize)); - // Set aHeaderSection to the correct size. - aHeaderSection.size(HeaderSize); - - // Start writing sections after the header - uint32 anOffset = HeaderOffset + HeaderSize; - - // Write auth section - aHeaderSection.put(OffsetAuthOffset, anOffset); - anOffset = writeAuthSection(anOffset); - // Write schema section - aHeaderSection.put(OffsetSchemaOffset, anOffset); - anOffset = writeSchemaSection(anOffset); - - // Write out the file header. - aHeaderSection.put(OffsetMagic, HeaderMagic); - aHeaderSection.put(OffsetVersion, HeaderVersion); - mAtomicTempFile->write(AtomicFile::FromStart, HeaderOffset, - aHeaderSection.address(), aHeaderSection.size()); - - // Write out the versionId. - WriteSection aVersionSection(Allocator::standard(), size_t(AtomSize)); - anOffset = aVersionSection.put(0, mVersionId); - aVersionSection.size(anOffset); - - mAtomicTempFile->write(AtomicFile::FromEnd, 0, - aVersionSection.address(), aVersionSection.size()); - - mAtomicTempFile->commit(); - mAtomicTempFile = NULL; - /* Initialize the shared memory file change mechanism */ - pthread_once(&gCommonInitMutex, initCommon); - - if (gSegment != NULL) - { - /* - PLEASE NOTE: - - The following operation is endian safe because we are not looking - for monotonic increase. I have tested every possible value of - *gSegment, and there is no value for which alternating - big and little endian increments will produce the original value. - */ - - OSAtomicIncrement32Barrier (gSegment); - } - } - catch(...) - { - rollback(); - throw; - } -} - -void -DbModifier::rollback() throw() -{ - // This will destroy the AtomicTempFile if we have one causing it to rollback. - mAtomicTempFile = NULL; -} - -const RecordId -DbModifier::getRecord(Table::Id inTableId, const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA *inoutAttributes, - CssmData *inoutData, Allocator &inAllocator) -{ - if (mAtomicTempFile) - { - // We are in the midst of changing the database. - return findTable(inTableId).getRecord(inRecordId, inoutAttributes, - inoutData, inAllocator); - } - else - { - return getDbVersion(false)->getRecord(inTableId, inRecordId, - inoutAttributes, inoutData, inAllocator); - } -} - -Cursor * -DbModifier::createCursor(const CSSM_QUERY *inQuery) -{ - if (mAtomicTempFile) - { - // We are modifying this database. - - // If we have a mDbVersion already then it's a snapshot of the database - // right before the modifications started. So return a cursor using - // that. - if (mDbVersion) - return mDbVersion->createCursor(inQuery); - - // This is a newly created but never commited database. Return a - // Cursor that will not return any matches. - return new Cursor(); - } - - // Get the latest and greatest version of the db and create the cursor - // on that. - return getDbVersion(false)->createCursor(inQuery); -} - -// Insert schema records for a new table into the metatables of the database. This gets -// called while a database is being created. - -void -DbModifier::insertTableSchema(const CssmDbRecordAttributeInfo &inInfo, - const CSSM_DB_RECORD_INDEX_INFO *inIndexInfo /* = NULL */) -{ - ModifiedTable &aTable = findTable(inInfo.DataRecordType); - const MetaRecord &aMetaRecord = aTable.getMetaRecord(); - - CssmAutoDbRecordAttributeData aRecordBuilder(5); // Set capacity to 5 so we don't need to grow - - // Create the entry for the SchemaRelations table. - aRecordBuilder.add(RelationID, inInfo.recordType()); - aRecordBuilder.add(RelationName, mDb.recordName(inInfo.recordType())); - - // Insert the record into the SchemaRelations ModifiedTable - findTable(mDb.schemaRelations.DataRecordType).insertRecord(mVersionId, - &aRecordBuilder, NULL); - - ModifiedTable &anAttributeTable = findTable(mDb.schemaAttributes.DataRecordType); - for (uint32 anIndex = 0; anIndex < inInfo.size(); anIndex++) - { - // Create an entry for the SchemaAttributes table. - aRecordBuilder.clear(); - aRecordBuilder.add(RelationID, inInfo.recordType()); - aRecordBuilder.add(AttributeNameFormat, inInfo.at(anIndex).nameFormat()); - - uint32 attributeId = aMetaRecord.metaAttribute(inInfo.at(anIndex)).attributeId(); - - switch (inInfo.at(anIndex).nameFormat()) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - aRecordBuilder.add(AttributeName, inInfo.at(anIndex).Label.AttributeName); - break; - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - aRecordBuilder.add(AttributeNameID, inInfo.at(anIndex).Label.AttributeOID); - break; - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - break; - default: - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - } - - aRecordBuilder.add(AttributeID, attributeId); - aRecordBuilder.add(AttributeFormat, inInfo.at(anIndex).format()); - - // Insert the record into the SchemaAttributes ModifiedTable - anAttributeTable.insertRecord(mVersionId, &aRecordBuilder, NULL); - } - - if (inIndexInfo != NULL) { - - if (inIndexInfo->DataRecordType != inInfo.DataRecordType && - inIndexInfo->NumberOfIndexes > 0) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - - ModifiedTable &indexMetaTable = findTable(mDb.schemaIndexes.DataRecordType); - uint32 aNumberOfIndexes = inIndexInfo->NumberOfIndexes; - - for (uint32 anIndex = 0; anIndex < aNumberOfIndexes; anIndex++) - { - const CssmDbIndexInfo &thisIndex = CssmDbIndexInfo::overlay(inIndexInfo->IndexInfo[anIndex]); - - // make sure the index is supported - if (thisIndex.dataLocation() != CSSM_DB_INDEX_ON_ATTRIBUTE) - CssmError::throwMe(CSSMERR_DL_INVALID_INDEX_INFO); - - // assign an index ID: the unique index is ID 0, all others are ID > 0 - uint32 indexId; - if (thisIndex.IndexType == CSSM_DB_INDEX_UNIQUE) - indexId = 0; - else - indexId = anIndex + 1; - - // figure out the attribute ID - uint32 attributeId = - aMetaRecord.metaAttribute(thisIndex.Info).attributeId(); - - // Create an entry for the SchemaIndexes table. - aRecordBuilder.clear(); - aRecordBuilder.add(RelationID, inInfo.DataRecordType); - aRecordBuilder.add(IndexID, indexId); - aRecordBuilder.add(AttributeID, attributeId); - aRecordBuilder.add(IndexType, thisIndex.IndexType); - aRecordBuilder.add(IndexedDataLocation, thisIndex.IndexedDataLocation); - - // Insert the record into the SchemaIndexes ModifiedTable - indexMetaTable.insertRecord(mVersionId, &aRecordBuilder, NULL); - - // update the table's index objects - DbMutableIndex &index = aTable.findIndex(indexId, aMetaRecord, indexId == 0); - index.appendAttribute(attributeId); - } - } -} - -// Insert a new table. The attribute info is required; the index and parsing module -// descriptions are optional. This version gets called during the creation of a -// database. - -void -DbModifier::insertTable(const CssmDbRecordAttributeInfo &inInfo, - const CSSM_DB_RECORD_INDEX_INFO *inIndexInfo /* = NULL */, - const CSSM_DB_PARSING_MODULE_INFO *inParsingModule /* = NULL */) -{ - modifyDatabase(); - createTable(new MetaRecord(inInfo)); - insertTableSchema(inInfo, inIndexInfo); -} - -// Insert a new table. This is the version that gets called when a table is added -// after a database has been created. - -void -DbModifier::insertTable(Table::Id inTableId, const string &inTableName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *inIndexInfo) -{ - modifyDatabase(); - ModifiedTable *aTable = createTable(new MetaRecord(inTableId, inNumberOfAttributes, inAttributeInfo)); - - CssmAutoDbRecordAttributeData aRecordBuilder(6); // Set capacity to 6 so we don't need to grow - - // Create the entry for the SchemaRelations table. - aRecordBuilder.add(RelationID, inTableId); - aRecordBuilder.add(RelationName, inTableName); - - // Insert the record into the SchemaRelations ModifiedTable - findTable(mDb.schemaRelations.DataRecordType).insertRecord(mVersionId, - &aRecordBuilder, NULL); - - ModifiedTable &anAttributeTable = findTable(mDb.schemaAttributes.DataRecordType); - for (uint32 anIndex = 0; anIndex < inNumberOfAttributes; anIndex++) - { - // Create an entry for the SchemaAttributes table. - aRecordBuilder.clear(); - aRecordBuilder.add(RelationID, inTableId); - // XXX What should this be? We set it to CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER for now - // since the AttributeID is always valid. - aRecordBuilder.add(AttributeNameFormat, uint32(CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER)); - aRecordBuilder.add(AttributeID, inAttributeInfo[anIndex].AttributeId); - if (inAttributeInfo[anIndex].AttributeName) - aRecordBuilder.add(AttributeName, inAttributeInfo[anIndex].AttributeName); - if (inAttributeInfo[anIndex].AttributeNameID.Length > 0) - aRecordBuilder.add(AttributeNameID, inAttributeInfo[anIndex].AttributeNameID); - aRecordBuilder.add(AttributeFormat, inAttributeInfo[anIndex].DataType); - - // Insert the record into the SchemaAttributes ModifiedTable - anAttributeTable.insertRecord(mVersionId, &aRecordBuilder, NULL); - } - - ModifiedTable &anIndexTable = findTable(mDb.schemaIndexes.DataRecordType); - for (uint32 anIndex = 0; anIndex < inNumberOfIndexes; anIndex++) - { - // Create an entry for the SchemaIndexes table. - aRecordBuilder.clear(); - aRecordBuilder.add(RelationID, inTableId); - aRecordBuilder.add(IndexID, inIndexInfo[anIndex].IndexId); - aRecordBuilder.add(AttributeID, inIndexInfo[anIndex].AttributeId); - aRecordBuilder.add(IndexType, inIndexInfo[anIndex].IndexType); - aRecordBuilder.add(IndexedDataLocation, inIndexInfo[anIndex].IndexedDataLocation); - - // Insert the record into the SchemaIndexes ModifiedTable - anIndexTable.insertRecord(mVersionId, &aRecordBuilder, NULL); - - // update the table's index objects - DbMutableIndex &index = aTable->findIndex(inIndexInfo[anIndex].IndexId, - aTable->getMetaRecord(), inIndexInfo[anIndex].IndexType == CSSM_DB_INDEX_UNIQUE); - index.appendAttribute(inIndexInfo[anIndex].AttributeId); - } -} - - - -bool DbModifier::hasTable(Table::Id inTableId) -{ - return getDbVersion(false)->hasTable(inTableId); -} - - - -ModifiedTable & -DbModifier::findTable(Table::Id inTableId) -{ - ModifiedTableMap::iterator it = mModifiedTableMap.find(inTableId); - if (it == mModifiedTableMap.end()) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - return *it->second; -} - - -// -// AppleDatabaseManager implementation -// - -AppleDatabaseManager::AppleDatabaseManager(const AppleDatabaseTableName *tableNames) - : DatabaseManager(), - mTableNames(tableNames) -{ - // make sure that a proper set of table ids and names has been provided - - if (!mTableNames) - CssmError::throwMe(CSSMERR_DL_INTERNAL_ERROR); - else { - uint32 i; - for (i = 0; mTableNames[i].mTableName; i++) {} - if (i < AppleDatabaseTableName::kNumRequiredTableNames) - CssmError::throwMe(CSSMERR_DL_INTERNAL_ERROR); - } -} - -Database * -AppleDatabaseManager::make(const DbName &inDbName) -{ - return new AppleDatabase(inDbName, mTableNames); -} - - -// -// AppleDbContext implementation -// - -/* This is the version 0 CSSM_APPLEDL_OPEN_PARAMETERS struct used up to 10.2.x. */ -extern "C" { - -typedef struct cssm_appledl_open_parameters_v0 -{ - uint32 length; /* Should be sizeof(CSSM_APPLEDL_OPEN_PARAMETERS_V0). */ - uint32 version; /* Should be 0. */ - CSSM_BOOL autoCommit; -} CSSM_APPLEDL_OPEN_PARAMETERS_V0; - -}; - -AppleDbContext::AppleDbContext(Database &inDatabase, - DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters) : - DbContext(inDatabase, inDatabaseSession, inAccessRequest, inAccessCred), - mAutoCommit(true), - mMode(0666) -{ - const CSSM_APPLEDL_OPEN_PARAMETERS *anOpenParameters = - reinterpret_cast(inOpenParameters); - - if (anOpenParameters) - { - switch (anOpenParameters->version) - { - case 1: - if (anOpenParameters->length < sizeof(CSSM_APPLEDL_OPEN_PARAMETERS)) - CssmError::throwMe(CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS); - - if (anOpenParameters->mask & kCSSM_APPLEDL_MASK_MODE) - mMode = anOpenParameters->mode; - /*DROPTHROUGH*/ - case 0: - if (anOpenParameters->length < sizeof(CSSM_APPLEDL_OPEN_PARAMETERS_V0)) - CssmError::throwMe(CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS); - - mAutoCommit = anOpenParameters->autoCommit == CSSM_FALSE ? false : true; - break; - - default: - CssmError::throwMe(CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS); - } - } -} - -AppleDbContext::~AppleDbContext() -{ -} - -// -// AppleDatabase implementation -// -AppleDatabase::AppleDatabase(const DbName &inDbName, const AppleDatabaseTableName *tableNames) : - Database(inDbName), - schemaRelations(tableNames[AppleDatabaseTableName::kSchemaInfo].mTableId, - sizeof(AttrSchemaRelations) / sizeof(CSSM_DB_ATTRIBUTE_INFO), - const_cast(AttrSchemaRelations)), - schemaAttributes(tableNames[AppleDatabaseTableName::kSchemaAttributes].mTableId, - sizeof(AttrSchemaAttributes) / sizeof(CSSM_DB_ATTRIBUTE_INFO), - const_cast(AttrSchemaAttributes)), - schemaIndexes(tableNames[AppleDatabaseTableName::kSchemaIndexes].mTableId, - sizeof(AttrSchemaIndexes) / sizeof(CSSM_DB_ATTRIBUTE_INFO), - const_cast(AttrSchemaIndexes)), - schemaParsingModule(tableNames[AppleDatabaseTableName::kSchemaParsingModule].mTableId, - sizeof(AttrSchemaParsingModule) / sizeof(CSSM_DB_ATTRIBUTE_INFO), - const_cast(AttrSchemaParsingModule)), - mAtomicFile(mDbName.dbName()), - mDbModifier(mAtomicFile, *this), - mTableNames(tableNames) -{ - /* temp check for X509Anchors access - this should removed before Leopard GM */ - if(!strcmp(inDbName.dbName(), "/System/Library/Keychains/X509Anchors")) { - Syslog::alert("Warning: accessing obsolete X509Anchors."); - } -} - -AppleDatabase::~AppleDatabase() -{ -} - -// Return the name of a record type. This uses a table that maps record types -// to record names. The table is provided when the database is created. - -const char *AppleDatabase::recordName(CSSM_DB_RECORDTYPE inRecordType) const -{ - if (inRecordType == CSSM_DL_DB_RECORD_ANY || inRecordType == CSSM_DL_DB_RECORD_ALL_KEYS) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORDTYPE); - - for (uint32 i = 0; mTableNames[i].mTableName; i++) - if (mTableNames[i].mTableId == inRecordType) - return mTableNames[i].mTableName; - - return ""; -} - -DbContext * -AppleDatabase::makeDbContext(DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters) -{ - return new AppleDbContext(*this, inDatabaseSession, inAccessRequest, - inAccessCred, inOpenParameters); -} - -void -AppleDatabase::dbCreate(DbContext &inDbContext, const CSSM_DBINFO &inDBInfo, - const CSSM_ACL_ENTRY_INPUT *inInitialAclEntry) -{ - AppleDbContext &context = safer_cast(inDbContext); - try - { - StLock _(mWriteLock); - mDbModifier.createDatabase(inDBInfo, inInitialAclEntry, context.mode()); - } - catch(...) - { - mDbModifier.rollback(); - throw; - } - if (context.autoCommit()) - mDbModifier.commit(); -} - -void -AppleDatabase::dbOpen(DbContext &inDbContext) -{ - mDbModifier.openDatabase(); -} - -void -AppleDatabase::dbClose() -{ - StLock _(mWriteLock); - mDbModifier.closeDatabase(); -} - -void -AppleDatabase::dbDelete(DatabaseSession &inDatabaseSession, - const AccessCredentials *inAccessCred) -{ - StLock _(mWriteLock); - // XXX Check callers credentials. - mDbModifier.deleteDatabase(); -} - -void -AppleDatabase::createRelation(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO &inIndexInfo) -{ - try - { - StLock _(mWriteLock); - // XXX Fix the refs here. - mDbModifier.insertTable(inRelationID, inRelationName, - inNumberOfAttributes, inAttributeInfo, - inNumberOfIndexes, &inIndexInfo); - } - catch(...) - { - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.rollback(); - throw; - } - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.commit(); -} - -void -AppleDatabase::destroyRelation(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRelationID) -{ - try - { - StLock _(mWriteLock); - mDbModifier.deleteTable(inRelationID); - } - catch(...) - { - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.rollback(); - throw; - } - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.commit(); -} - -void -AppleDatabase::authenticate(DbContext &inDbContext, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials &inAccessCred) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -void -AppleDatabase::getDbAcl(DbContext &inDbContext, - const CSSM_STRING *inSelectionTag, - uint32 &outNumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &outAclInfos) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -void -AppleDatabase::changeDbAcl(DbContext &inDbContext, - const AccessCredentials &inAccessCred, - const CSSM_ACL_EDIT &inAclEdit) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -void -AppleDatabase::getDbOwner(DbContext &inDbContext, - CSSM_ACL_OWNER_PROTOTYPE &outOwner) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -void -AppleDatabase::changeDbOwner(DbContext &inDbContext, - const AccessCredentials &inAccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &inNewOwner) -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -char * -AppleDatabase::getDbNameFromHandle(const DbContext &inDbContext) const -{ - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); -} - -CSSM_DB_UNIQUE_RECORD_PTR -AppleDatabase::dataInsert(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData) -{ - CSSM_DB_UNIQUE_RECORD_PTR anUniqueRecordPtr = NULL; - try - { - StLock _(mWriteLock); - const RecordId aRecordId = - mDbModifier.insertRecord(inRecordType, inAttributes, inData); - - anUniqueRecordPtr = createUniqueRecord(inDbContext, inRecordType, - aRecordId); - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.commit(); - } - catch(...) - { - if (anUniqueRecordPtr != NULL) - freeUniqueRecord(inDbContext, *anUniqueRecordPtr); - - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.rollback(); - throw; - } - - return anUniqueRecordPtr; -} - -void -AppleDatabase::dataDelete(DbContext &inDbContext, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecord) -{ - try - { - // syslog if it's the .Mac password - CSSM_DB_RECORD_ATTRIBUTE_DATA attrData; - // we have to do this in two phases -- the first to get the record type, and the second to actually read the attributes. Otherwise, we might get - // an exception. - memset(&attrData, 0, sizeof(attrData)); - dataGetFromUniqueRecordId(inDbContext, inUniqueRecord, &attrData, NULL); - - if (attrData.DataRecordType == CSSM_DL_DB_RECORD_GENERIC_PASSWORD) - { - CSSM_DB_ATTRIBUTE_DATA attributes; - - // setup some attributes and see if we are indeed the .Mac password - attributes.Info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - attributes.Info.Label.AttributeID = 'svce'; - attributes.Info.AttributeFormat = 0; - attributes.NumberOfValues = 1; - attributes.Value = NULL; - - attrData.NumberOfAttributes = 1; - attrData.AttributeData = &attributes; - - dataGetFromUniqueRecordId(inDbContext, inUniqueRecord, &attrData, NULL); - - // now check the results - std::string dataString((const char*) attrData.AttributeData[0].Value[0].Data, attrData.AttributeData[0].Value[0].Length); - if (dataString == "iTools") - { - syslog(LOG_WARNING, "Warning: Removed .Me password"); - } - - free(attrData.AttributeData[0].Value[0].Data); - free(attrData.AttributeData[0].Value); - } - - StLock _(mWriteLock); - Table::Id aTableId; - const RecordId aRecordId(parseUniqueRecord(inUniqueRecord, aTableId)); - mDbModifier.deleteRecord(aTableId, aRecordId); - } - catch(...) - { - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.rollback(); - throw; - } - - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.commit(); -} - -void -AppleDatabase::dataModify(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRecordType, - CSSM_DB_UNIQUE_RECORD &inoutUniqueRecord, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributesToBeModified, - const CssmData *inDataToBeModified, - CSSM_DB_MODIFY_MODE inModifyMode) -{ - try - { - StLock _(mWriteLock); - Table::Id aTableId; - const RecordId oldRecordId = parseUniqueRecord(inoutUniqueRecord, - aTableId); -#if 1 - if (inRecordType != aTableId) -#else - if (inRecordType != aTableId && - inRecordType != CSSM_DL_DB_RECORD_ANY && - !(inRecordType == CSSM_DL_DB_RECORD_ALL_KEYS && - (aTableId == CSSM_DL_DB_RECORD_PUBLIC_KEY || - aTableId == CSSM_DL_DB_RECORD_PRIVATE_KEY || - aTableId == CSSM_DL_DB_RECORD_SYMMETRIC_KEY))) -#endif - { - CssmError::throwMe(CSSMERR_DL_INVALID_RECORD_UID); - } - - const RecordId newRecordId = - mDbModifier.updateRecord(aTableId, - oldRecordId, - inAttributesToBeModified, - inDataToBeModified, - inModifyMode); - updateUniqueRecord(inDbContext, aTableId, newRecordId, - inoutUniqueRecord); - } - catch(...) - { - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.rollback(); - throw; - } - - if (safer_cast(inDbContext).autoCommit()) - mDbModifier.commit(); -} - -CSSM_HANDLE -AppleDatabase::dataGetFirst(DbContext &inDbContext, - const CssmQuery *inQuery, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord) -{ - // XXX: register Cursor with DbContext and have DbContext call - // dataAbortQuery for all outstanding Query objects on close. - auto_ptr aCursor(mDbModifier.createCursor(inQuery)); - Table::Id aTableId; - RecordId aRecordId; - - if (!aCursor->next(aTableId, inoutAttributes, inoutData, - inDbContext.mDatabaseSession, aRecordId)) - // return a NULL handle, and implicitly delete the cursor - return CSSM_INVALID_HANDLE; - - outUniqueRecord = createUniqueRecord(inDbContext, aTableId, aRecordId); - return aCursor.release()->handle(); // We didn't throw so keep the Cursor around. -} - -bool -AppleDatabase::dataGetNext(DbContext &inDbContext, - CSSM_HANDLE inResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord) -{ - auto_ptr aCursor(&HandleObject::find(inResultsHandle, CSSMERR_DL_INVALID_RESULTS_HANDLE)); - Table::Id aTableId; - RecordId aRecordId; - - if (!aCursor->next(aTableId, inoutAttributes, inoutData, inDbContext.mDatabaseSession, aRecordId)) - return false; - - outUniqueRecord = createUniqueRecord(inDbContext, aTableId, aRecordId); - - aCursor.release(); - return true; -} - -void -AppleDatabase::dataAbortQuery(DbContext &inDbContext, - CSSM_HANDLE inResultsHandle) -{ - delete &HandleObject::find(inResultsHandle, CSSMERR_DL_INVALID_RESULTS_HANDLE); -} - -void -AppleDatabase::dataGetFromUniqueRecordId(DbContext &inDbContext, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData) -{ - Table::Id aTableId; - const RecordId aRecordId(parseUniqueRecord(inUniqueRecord, aTableId)); - // XXX Change CDSA spec to use new RecordId returned by this function - mDbModifier.getRecord(aTableId, aRecordId, inoutAttributes, inoutData, - inDbContext.mDatabaseSession); -} - -void -AppleDatabase::freeUniqueRecord(DbContext &inDbContext, - CSSM_DB_UNIQUE_RECORD &inUniqueRecord) -{ - if (inUniqueRecord.RecordIdentifier.Length != 0 - && inUniqueRecord.RecordIdentifier.Data != NULL) - { - inUniqueRecord.RecordIdentifier.Length = 0; - inDbContext.mDatabaseSession.free(inUniqueRecord.RecordIdentifier.Data); - } - inDbContext.mDatabaseSession.free(&inUniqueRecord); -} - -void -AppleDatabase::updateUniqueRecord(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inTableId, - const RecordId &inRecordId, - CSSM_DB_UNIQUE_RECORD &inoutUniqueRecord) -{ - uint32 *aBuffer = reinterpret_cast(inoutUniqueRecord.RecordIdentifier.Data); - aBuffer[0] = inTableId; - aBuffer[1] = inRecordId.mRecordNumber; - aBuffer[2] = inRecordId.mCreateVersion; - aBuffer[3] = inRecordId.mRecordVersion; -} - -CSSM_DB_UNIQUE_RECORD_PTR -AppleDatabase::createUniqueRecord(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inTableId, - const RecordId &inRecordId) -{ - CSSM_DB_UNIQUE_RECORD_PTR aUniqueRecord = - inDbContext.mDatabaseSession.alloc(); - memset(aUniqueRecord, 0, sizeof(*aUniqueRecord)); - aUniqueRecord->RecordIdentifier.Length = sizeof(uint32) * 4; - try - { - aUniqueRecord->RecordIdentifier.Data = - inDbContext.mDatabaseSession.alloc(sizeof(uint32) * 4); - updateUniqueRecord(inDbContext, inTableId, inRecordId, *aUniqueRecord); - } - catch(...) - { - inDbContext.mDatabaseSession.free(aUniqueRecord); - throw; - } - - return aUniqueRecord; -} - -const RecordId -AppleDatabase::parseUniqueRecord(const CSSM_DB_UNIQUE_RECORD &inUniqueRecord, - CSSM_DB_RECORDTYPE &outTableId) -{ - if (inUniqueRecord.RecordIdentifier.Length != sizeof(uint32) * 4) - CssmError::throwMe(CSSMERR_DL_INVALID_RECORD_UID); - - uint32 *aBuffer = reinterpret_cast(inUniqueRecord.RecordIdentifier.Data); - outTableId = aBuffer[0]; - return RecordId(aBuffer[1], aBuffer[2], aBuffer[3]); -} - -void -AppleDatabase::passThrough(DbContext &dbContext, - uint32 passThroughId, - const void *inputParams, - void **outputParams) -{ - switch (passThroughId) - { - case CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT: - { - AppleDbContext &dbc = safer_cast(dbContext); - // Return the old state of the autoCommit flag if requested - if (outputParams) - *reinterpret_cast(outputParams) = dbc.autoCommit(); - dbc.autoCommit(inputParams ? CSSM_TRUE : CSSM_FALSE); - } - break; - - case CSSM_APPLEFILEDL_COMMIT: - mDbModifier.commit(); - break; - - case CSSM_APPLEFILEDL_ROLLBACK: - mDbModifier.rollback(); - break; - - case CSSM_APPLECSPDL_DB_RELATION_EXISTS: - { - CSSM_BOOL returnValue; - - CSSM_DB_RECORDTYPE recordType = *(CSSM_DB_RECORDTYPE*) inputParams; - if (recordType == CSSM_DL_DB_RECORD_ANY || recordType == CSSM_DL_DB_RECORD_ALL_KEYS) - { - returnValue = CSSM_TRUE; - } - else - { - returnValue = mDbModifier.hasTable(recordType); - } - - *(CSSM_BOOL*) outputParams = returnValue; - break; - } - - default: - CssmError::throwMe(CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED); - break; - } -} diff --git a/OSX/include/security_filedb/AppleDatabase.h b/OSX/include/security_filedb/AppleDatabase.h deleted file mode 100644 index c0e9dbd7..00000000 --- a/OSX/include/security_filedb/AppleDatabase.h +++ /dev/null @@ -1,666 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// AppleDatabase.h - Description t.b.d. -// -#ifndef _H_APPLEDATABASE -#define _H_APPLEDATABASE - -#include "MetaRecord.h" -#include "SelectionPredicate.h" -#include "DbIndex.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Security -{ - -// Abstract database Cursor class. -class Cursor; -class DbVersion; -class CssmAutoQuery; - -struct AppleDatabaseTableName -{ - uint32 mTableId; - const char *mTableName; - - // indices of meta-table entries in an array of table names - - enum { - kSchemaInfo = 0, - kSchemaAttributes, - kSchemaIndexes, - kSchemaParsingModule, - kNumRequiredTableNames - }; -}; - -// -// This is what the CDSA standard refers to as a Relation. We use -// the more conventional term Table. -// -class Table -{ - NOCOPY(Table) -public: - // Type used to refer to a table. - typedef CSSM_DB_RECORDTYPE Id; - - Table(const ReadSection &inTableSection); - ~Table(); - - // Return a newly created cursor satisfying inQuery on the receiving table - // The returned Cursor may or may not use indexes depending on their availability. - Cursor *createCursor(const CSSM_QUERY *inQuery, const DbVersion &inDbVersion) const; - - const ReadSection getRecordSection(uint32 inRecordNumber) const; - - const RecordId getRecord(const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - Allocator &inAllocator) const; - - // Return the number of recordNumbers in use by this table including empty slots. - uint32 recordNumberCount() const { return mRecordNumbersCount; } - uint32 freeListHead() const { return mFreeListHead; } - - // Return the record number corresponding to aFreeListHead and update - // aFreeListHead to point to the next availble recordNumber slot. - uint32 popFreeList(uint32 &aFreeListHead) const; - - MetaRecord &getMetaRecord() { return mMetaRecord; } - const MetaRecord &getMetaRecord() const { return mMetaRecord; } - - uint32 getRecordsCount() const { return mRecordsCount; } - const ReadSection getRecordsSection() const; - - const ReadSection &getTableSection() const { return mTableSection; } - - bool matchesTableId(Id inTableId) const; - - void readIndexSection(); - - enum - { - OffsetSize = AtomSize * 0, - OffsetId = AtomSize * 1, - OffsetRecordsCount = AtomSize * 2, - OffsetRecords = AtomSize * 3, - OffsetIndexesOffset = AtomSize * 4, - OffsetFreeListHead = AtomSize * 5, - OffsetRecordNumbersCount = AtomSize * 6, - OffsetRecordNumbers = AtomSize * 7 - }; -protected: - friend class ModifiedTable; - - MetaRecord mMetaRecord; - const ReadSection mTableSection; - - uint32 mRecordsCount; - uint32 mFreeListHead; - // Number of record numbers (including freelist slots) in this table. - uint32 mRecordNumbersCount; - - // all the table's indexes, mapped by index id - typedef map ConstIndexMap; - ConstIndexMap mIndexMap; -}; - -class ModifiedTable -{ - NOCOPY(ModifiedTable) -public: - ModifiedTable(const Table *inTable); - ModifiedTable(MetaRecord *inMetaRecord); // Take over ownership of inMetaRecord - ~ModifiedTable(); - - // Mark the record with inRecordId as deleted. - void deleteRecord(const RecordId &inRecordId); - const RecordId insertRecord(uint32 inVersionId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData); - const RecordId updateRecord(const RecordId &inRecordId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData, - CSSM_DB_MODIFY_MODE inModifyMode); - const RecordId getRecord(const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - Allocator &inAllocator) const; - - // Return the MetaRecord this table should use for writes. - const MetaRecord &getMetaRecord() const; - - // find, and create if needed, an index with the given id - DbMutableIndex &findIndex(uint32 indexId, const MetaRecord &metaRecord, bool isUniqueIndex); - - // Write this table to inOutputFile at inSectionOffset and return the new offset. - uint32 writeTable(AtomicTempFile &inAtomicTempFile, uint32 inSectionOffset); - -private: - // Return the next available record number for this table. - uint32 nextRecordNumber(); - - // Return the number of recordNumbers in use by this table including empty slots. - uint32 recordNumberCount() const; - - void modifyTable(); - void createMutableIndexes(); - uint32 writeIndexSection(WriteSection &tableSection, uint32 offset); - - // Optional, this is merly a reference, we do not own this object. - const Table *mTable; - - // Optional, New MetaRecord. This is only present if it is different from the - // MetaRecord of mTable or mTable is nil. - const MetaRecord *mNewMetaRecord; - - // Set of Records that have been deleted or modified. - typedef set DeletedSet; - DeletedSet mDeletedSet; - - // Set of Records that have been inserted or modified. - typedef map InsertedMap; - InsertedMap mInsertedMap; - - // Next lowest available RecordNumber - uint32 mRecordNumberCount; - // Head of the free list (if there is one) or 0 if either we have no - // mTable of the free list has been exhausted. - uint32 mFreeListHead; - - // has this table actually been modified? - bool mIsModified; - - typedef map MutableIndexMap; - MutableIndexMap mIndexMap; -}; - -// -// Read only snapshot of a database. -// -class Metadata -{ - NOCOPY(Metadata) -protected: - Metadata() {} - enum - { - HeaderOffset = 0, // Absolute offset of header. - OffsetMagic = AtomSize * 0, - OffsetVersion = AtomSize * 1, - OffsetAuthOffset = AtomSize * 2, - OffsetSchemaOffset = AtomSize * 3, - HeaderSize = AtomSize * 4, - - HeaderMagic = FOUR_CHAR_CODE('kych'), - HeaderVersion = 0x00010000 - }; - - enum - { - OffsetSchemaSize = AtomSize * 0, - OffsetTablesCount = AtomSize * 1, - OffsetTables = AtomSize * 2 - }; -}; - -// -// Read only representation of a database -// -class DbVersion : public Metadata, public RefCount -{ - NOCOPY(DbVersion) -public: - DbVersion(const class AppleDatabase &db, const RefPointer &inAtomicBufferedFile); - ~DbVersion(); - - uint32 getVersionId() const { return mVersionId; } - const RecordId getRecord(Table::Id inTableId, const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA *inoutAttributes, - CssmData *inoutData, Allocator &inAllocator) const; - Cursor *createCursor(const CSSM_QUERY *inQuery) const; -protected: - const Table &findTable(Table::Id inTableId) const; - Table &findTable(Table::Id inTableId); - -private: - void open(); // Part of constructor contract. - - ReadSection mDatabase; - uint32 mVersionId; - - friend class DbModifier; // XXX Fixme - typedef map TableMap; - TableMap mTableMap; - const class AppleDatabase &mDb; - RefPointer mBufferedFile; - -public: - typedef Table value_type; - typedef const Table &const_reference; - typedef const Table *const_pointer; - - // A const forward iterator. - class const_iterator - { - public: - const_iterator(const TableMap::const_iterator &it) : mIterator(it) {} - - // Use default copy consturctor and assignment operator. - //const_iterator(const const_iterator &it) : mIterator(it.mIterator) {} - //const_iterator &operator=(const const_iterator &it) { mIterator = it.mIterator; return *this; } - const_reference operator*() const { return *mIterator->second; } - const_iterator &operator++() { mIterator.operator++(); return *this; } - const_iterator operator++(int i) { return const_iterator(mIterator.operator++(i)); } - bool operator!=(const const_iterator &other) const { return mIterator != other.mIterator; } - bool operator==(const const_iterator &other) const { return mIterator == other.mIterator; } - - const_pointer operator->() const { return mIterator->second; } // Not really needed. - - private: - TableMap::const_iterator mIterator; - }; - - const_iterator begin() const { return const_iterator(mTableMap.begin()); } - const_iterator end() const { return const_iterator(mTableMap.end()); } - - bool hasTable(Table::Id inTableId) const; -}; - -// -// Cursor -// -class Cursor : public HandleObject -{ -public: - Cursor(); - Cursor(const DbVersion &inDbVersion); - virtual ~Cursor(); - virtual bool next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR outAttributes, - CssmData *outData, - Allocator &inAllocator, - RecordId &recordId); -protected: - const RefPointer mDbVersion; -}; - - -// -// LinearCursor -// -class LinearCursor : public Cursor -{ - NOCOPY(LinearCursor) -public: - LinearCursor(const CSSM_QUERY *inQuery, const DbVersion &inDbVersion, - const Table &inTable); - virtual ~LinearCursor(); - virtual bool next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR outAttributes, - CssmData *outData, - Allocator &inAllocator, - RecordId &recordId); - -private: - uint32 mRecordsCount; - uint32 mRecord; - const ReadSection mRecordsSection; - uint32 mReadOffset; - const MetaRecord &mMetaRecord; - - CSSM_DB_CONJUNCTIVE mConjunctive; - CSSM_QUERY_FLAGS mQueryFlags; // If CSSM_QUERY_RETURN_DATA is set return the raw key bits; - typedef vector PredicateVector; - - PredicateVector mPredicates; -}; - -// -// A cursor that uses an index. -// - -class IndexCursor : public Cursor -{ - NOCOPY(IndexCursor) -public: - IndexCursor(DbQueryKey *queryKey, const DbVersion &inDbVersion, - const Table &table, const DbConstIndex *index); - virtual ~IndexCursor(); - - virtual bool next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR outAttributes, - CssmData *outData, - Allocator &inAllocator, - RecordId &recordId); - -private: - auto_ptr mQueryKey; - const Table &mTable; - const DbConstIndex *mIndex; - - DbIndexIterator mBegin, mEnd; -}; - -// -// MultiCursor -// -class MultiCursor : public Cursor -{ - NOCOPY(MultiCursor) -public: - MultiCursor(const CSSM_QUERY *inQuery, const DbVersion &inDbVersion); - virtual ~MultiCursor(); - virtual bool next(Table::Id &outTableId, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR outAttributes, - CssmData *outData, - Allocator &inAllocator, - RecordId &recordId); -private: - auto_ptr mQuery; - - DbVersion::const_iterator mTableIterator; - auto_ptr mCursor; -}; - -// -// A DbModifier contains all pending changes to be made to a DB. -// It also contains a DbVersion representing the state of the Database before any such changes -// No read-style operations are supported by DbModifier. If a DbModifier exists for a -// particular Database and a client wishes to perform a query commit() must be called and -// the client should perform the new query on the current database version after the commit. -// Otherwise a client will not see changes made since the DbModifier was instanciated. -// -class DbModifier : public Metadata -{ - NOCOPY(DbModifier) -public: - DbModifier(AtomicFile &inAtomicFile, const class AppleDatabase &db); - ~DbModifier(); - - // Whole database affecting members. - void createDatabase(const CSSM_DBINFO &inDbInfo, - const CSSM_ACL_ENTRY_INPUT *inInitialAclEntry, - mode_t mode); - void openDatabase(); // This is optional right now. - void closeDatabase(); - void deleteDatabase(); - - void commit(); - void rollback() throw(); - - // Record changing members - void deleteRecord(Table::Id inTableId, const RecordId &inRecordId); - const RecordId insertRecord(Table::Id inTableId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData); - const RecordId updateRecord(Table::Id inTableId, const RecordId &inRecordId, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData, - CSSM_DB_MODIFY_MODE inModifyMode); - - // Schema changing members - void insertTable(Table::Id inTableId, const string &inTableName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *inIndexInfo); - void deleteTable(Table::Id inTableId); - - // Record reading members - const RecordId getRecord(Table::Id inTableId, const RecordId &inRecordId, - CSSM_DB_RECORD_ATTRIBUTE_DATA *inoutAttributes, - CssmData *inoutData, Allocator &inAllocator); - Cursor *createCursor(const CSSM_QUERY *inQuery); - - bool hasTable(Table::Id inTableid); - -protected: - void modifyDatabase(); - const RefPointer getDbVersion(bool force); - - ModifiedTable *createTable(MetaRecord *inMetaRecord); // Takes over ownership of inMetaRecord - - void insertTableSchema(const CssmDbRecordAttributeInfo &inInfo, - const CSSM_DB_RECORD_INDEX_INFO *inIndexInfo = NULL); - - void insertTable(const CssmDbRecordAttributeInfo &inInfo, - const CSSM_DB_RECORD_INDEX_INFO * inIndexInfo = NULL, - const CSSM_DB_PARSING_MODULE_INFO * inParsingModule = NULL); - - ModifiedTable &findTable(Table::Id inTableId); - - uint32 writeAuthSection(uint32 inSectionOffset); - uint32 writeSchemaSection(uint32 inSectionOffset); - -private: - - /* mDbVersion is the current DbVersion of this database before any changes - we are going to make. mNotifyCount holds the value of gNotifyCount at - the time mDbVersion was created. mDbLastRead is the time at which we - last checked if the file from which mDbVersion was read has changed. - mDbVersionLock protects the other 3 fields. */ - RefPointer mDbVersion; - int32_t mNotifyCount; - CFAbsoluteTime mDbLastRead; - Mutex mDbVersionLock; - - AtomicFile &mAtomicFile; - uint32 mVersionId; - RefPointer mAtomicTempFile; - - typedef map ModifiedTableMap; - ModifiedTableMap mModifiedTableMap; - - const class AppleDatabase &mDb; -}; - -// -// AppleDatabaseManager -// -class AppleDatabaseManager : public DatabaseManager -{ -public: - AppleDatabaseManager(const AppleDatabaseTableName *tableNames); - Database *make(const DbName &inDbName); - -protected: - const AppleDatabaseTableName *mTableNames; -}; - -// -// AppleDbContext -// -class AppleDbContext : public DbContext -{ -public: - AppleDbContext(Database &inDatabase, - DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters); - virtual ~AppleDbContext(); - bool autoCommit() const { return mAutoCommit; } - void autoCommit(bool on) { mAutoCommit = on; } - mode_t mode() const { return mMode; } - -private: - bool mAutoCommit; - mode_t mMode; -}; - -// -// AppleDatabase -// -class AppleDatabase : public Database -{ -public: - AppleDatabase(const DbName &inDbName, const AppleDatabaseTableName *tableNames); - virtual ~AppleDatabase(); - - virtual void - dbCreate(DbContext &inDbContext, const CSSM_DBINFO &inDBInfo, - const CSSM_ACL_ENTRY_INPUT *inInitialAclEntry); - - virtual void - dbOpen(DbContext &inDbContext); - - virtual void - dbClose(); - - virtual void - dbDelete(DatabaseSession &inDatabaseSession, - const AccessCredentials *inAccessCred); - - virtual void - createRelation(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO &inIndexInfo); - - virtual void - destroyRelation(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRelationID); - - virtual void - authenticate(DbContext &inDbContext, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials &inAccessCred); - - virtual void - getDbAcl(DbContext &inDbContext, - const CSSM_STRING *inSelectionTag, - uint32 &outNumberOfAclInfos, - CSSM_ACL_ENTRY_INFO_PTR &outAclInfos); - - virtual void - changeDbAcl(DbContext &inDbContext, - const AccessCredentials &inAccessCred, - const CSSM_ACL_EDIT &inAclEdit); - - virtual void - getDbOwner(DbContext &inDbContext, CSSM_ACL_OWNER_PROTOTYPE &outOwner); - - virtual void - changeDbOwner(DbContext &inDbContext, - const AccessCredentials &inAccessCred, - const CSSM_ACL_OWNER_PROTOTYPE &inNewOwner); - - virtual char * - getDbNameFromHandle(const DbContext &inDbContext) const; - - virtual CSSM_DB_UNIQUE_RECORD_PTR - dataInsert(DbContext &inDbContext, - CSSM_DB_RECORDTYPE RecordType, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData); - - virtual void - dataDelete(DbContext &inDbContext, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecordIdentifier); - - virtual void - dataModify(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inRecordType, - CSSM_DB_UNIQUE_RECORD &inoutUniqueRecordIdentifier, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributesToBeModified, - const CssmData *inDataToBeModified, - CSSM_DB_MODIFY_MODE inModifyMode); - - virtual CSSM_HANDLE - dataGetFirst(DbContext &inDbContext, - const CssmQuery *inQuery, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord); - - virtual bool - dataGetNext(DbContext &inDbContext, - CSSM_HANDLE inResultsHandle, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_DB_UNIQUE_RECORD_PTR &outUniqueRecord); - - virtual void - dataAbortQuery(DbContext &inDbContext, - CSSM_HANDLE inResultsHandle); - - virtual void - dataGetFromUniqueRecordId(DbContext &inDbContext, - const CSSM_DB_UNIQUE_RECORD &inUniqueRecord, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData); - - virtual void - freeUniqueRecord(DbContext &inDbContext, - CSSM_DB_UNIQUE_RECORD &inUniqueRecord); - - virtual void passThrough(DbContext &dbContext, - uint32 passThroughId, - const void *inputParams, - void **outputParams); - - // Subclasses must implement this method. - virtual DbContext *makeDbContext(DatabaseSession &inDatabaseSession, - CSSM_DB_ACCESS_TYPE inAccessRequest, - const AccessCredentials *inAccessCred, - const void *inOpenParameters); - - const CssmDbRecordAttributeInfo schemaRelations; - const CssmDbRecordAttributeInfo schemaAttributes; - const CssmDbRecordAttributeInfo schemaIndexes; - const CssmDbRecordAttributeInfo schemaParsingModule; - - const char *recordName(CSSM_DB_RECORDTYPE inRecordType) const; - -private: - static void - updateUniqueRecord(DbContext &inDbContext, - CSSM_DB_RECORDTYPE inTableId, - const RecordId &inRecordId, - CSSM_DB_UNIQUE_RECORD &inoutUniqueRecord); - - CSSM_DB_UNIQUE_RECORD_PTR - createUniqueRecord(DbContext &inDbContext, CSSM_DB_RECORDTYPE inTableId, - const RecordId &inRecordId); - const RecordId parseUniqueRecord(const CSSM_DB_UNIQUE_RECORD &inUniqueRecord, - CSSM_DB_RECORDTYPE &outTableId); - - Mutex mWriteLock; - AtomicFile mAtomicFile; - DbModifier mDbModifier; - const AppleDatabaseTableName *mTableNames; -}; - -} // end namespace Security - -#endif //_H_APPLEDATABASE diff --git a/OSX/include/security_filedb/AtomicFile.cpp b/OSX/include/security_filedb/AtomicFile.cpp deleted file mode 100644 index 68049c24..00000000 --- a/OSX/include/security_filedb/AtomicFile.cpp +++ /dev/null @@ -1,1262 +0,0 @@ -/* - * Copyright (c) 2000-2013 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define kAtomicFileMaxBlockSize INT_MAX - - -// -// AtomicFile.cpp -// -AtomicFile::AtomicFile(const std::string &inPath) : - mPath(inPath) -{ - pathSplit(inPath, mDir, mFile); - - if (mDir.length() == 0) - { - const char* buffer = getwd(NULL); - mDir = buffer; - free((void*) buffer); - } - - mDir += '/'; - - // determine if the path is on a local or a networked volume - struct statfs info; - int result = statfs(mDir.c_str(), &info); - if (result == -1) // error on opening? - { - mIsLocalFileSystem = false; // revert to the old ways if we can't tell what kind of system we have - } - else - { - mIsLocalFileSystem = (info.f_flags & MNT_LOCAL) != 0; - if (mIsLocalFileSystem) - { - // compute the name of the lock file for this file - CC_SHA1_CTX ctx; - CC_SHA1_Init(&ctx); - CC_SHA1_Update(&ctx, (const void*) mFile.c_str(), (CC_LONG)mFile.length()); - u_int8_t digest[CC_SHA1_DIGEST_LENGTH]; - CC_SHA1_Final(digest, &ctx); - - u_int32_t hash = (digest[0] << 24) | (digest[1] << 16) | (digest[2] << 8) | digest[3]; - - char buffer[256]; - sprintf(buffer, "%08X", hash); - mLockFilePath = mDir + ".fl" + buffer; - } - } -} - -AtomicFile::~AtomicFile() -{ -} - -// Aquire the write lock and remove the file. -void -AtomicFile::performDelete() -{ - AtomicLockedFile lock(*this); - if (::unlink(mPath.c_str()) != 0) - { - int error = errno; - secdebug("atomicfile", "unlink %s: %s", mPath.c_str(), strerror(error)); - if (error == ENOENT) - CssmError::throwMe(CSSMERR_DL_DATASTORE_DOESNOT_EXIST); - else - UnixError::throwMe(error); - } - - // unlink our lock file - ::unlink(mLockFilePath.c_str()); -} - -// Aquire the write lock and rename the file (and bump the version and stuff). -void -AtomicFile::rename(const std::string &inNewPath) -{ - const char *path = mPath.c_str(); - const char *newPath = inNewPath.c_str(); - - // @@@ lock the destination file too. - AtomicLockedFile lock(*this); - if (::rename(path, newPath) != 0) - { - int error = errno; - secdebug("atomicfile", "rename(%s, %s): %s", path, newPath, strerror(error)); - UnixError::throwMe(error); - } -} - -// Lock the file for writing and return a newly created AtomicTempFile. -RefPointer -AtomicFile::create(mode_t mode) -{ - const char *path = mPath.c_str(); - - // First make sure the directory to this file exists and is writable - mkpath(mDir); - - RefPointer lock(new AtomicLockedFile(*this)); - int fileRef = ropen(path, O_WRONLY|O_CREAT|O_EXCL, mode); - if (fileRef == -1) - { - int error = errno; - secdebug("atomicfile", "open %s: %s", path, strerror(error)); - - // Do the obvious error code translations here. - // @@@ Consider moving these up a level. - if (error == EACCES) - CssmError::throwMe(CSSM_ERRCODE_OS_ACCESS_DENIED); - else if (error == EEXIST) - CssmError::throwMe(CSSMERR_DL_DATASTORE_ALREADY_EXISTS); - else - UnixError::throwMe(error); - } - rclose(fileRef); - - try - { - // Now that we have created the lock and the new db file create a tempfile - // object. - RefPointer temp(new AtomicTempFile(*this, lock, mode)); - secdebug("atomicfile", "%p created %s", this, path); - return temp; - } - catch (...) - { - // Creating the temp file failed so remove the db file we just created too. - if (::unlink(path) == -1) - { - secdebug("atomicfile", "unlink %s: %s", path, strerror(errno)); - } - throw; - } -} - -// Lock the database file for writing and return a newly created AtomicTempFile. -// If the parent directory allows the write we're going to allow this. Previous -// versions checked for writability of the db file and that caused problems when -// setuid programs had made entries. As long as the db (keychain) file is readable -// this function can make the newer keychain file with the correct owner just by virtue -// of the copy that takes place. - -RefPointer -AtomicFile::write() -{ - - RefPointer lock(new AtomicLockedFile(*this)); - return new AtomicTempFile(*this, lock); -} - -// Return a bufferedFile containing current version of the file for reading. -RefPointer -AtomicFile::read() -{ - return new AtomicBufferedFile(mPath, mIsLocalFileSystem); -} - -mode_t -AtomicFile::mode() const -{ - const char *path = mPath.c_str(); - struct stat st; - if (::stat(path, &st) == -1) - { - int error = errno; - secdebug("atomicfile", "stat %s: %s", path, strerror(error)); - UnixError::throwMe(error); - } - return st.st_mode; -} - -// Split full into a dir and file component. -void -AtomicFile::pathSplit(const std::string &inFull, std::string &outDir, std::string &outFile) -{ - std::string::size_type slash, len = inFull.size(); - slash = inFull.rfind('/'); - if (slash == std::string::npos) - { - outDir = ""; - outFile = inFull; - } - else if (slash + 1 == len) - { - outDir = inFull; - outFile = ""; - } - else - { - outDir = inFull.substr(0, slash + 1); - outFile = inFull.substr(slash + 1, len); - } -} - -// -// Make sure the directory up to inDir exists inDir *must* end in a slash. -// -void -AtomicFile::mkpath(const std::string &inDir, mode_t mode) -{ - // see if the file already exists and is a directory - struct stat st; - int result = stat(inDir.c_str(), &st); - - if (result == 0) // file exists - { - if ((st.st_mode & S_IFDIR) == 0) - { - // whatever was there, it wasn't a directory. That's really bad, so complain - syslog(LOG_ALERT, "Needed a directory at %s, but the file that was there was not one.\n", inDir.c_str()); - UnixError::throwMe(ENOTDIR); - } - } - else - { - // the file did not exist, try to create it - result = mkpath_np(inDir.c_str(), 0777); // make the directory with umask - if (result != 0) - { - // mkpath_np does not set errno, you have to look at the result. - UnixError::throwMe(result); - } - } - - // Double check and see if we got what we hoped for - result = stat(inDir.c_str(), &st); - if (result != 0) - { - UnixError::throwMe(errno); - } - - if ((st.st_mode & S_IFDIR) == 0) - { - // we didn't create a dictionary? That's curious... - syslog(LOG_ALERT, "Failed to create a directory when we asked for one to be created at %s\n", inDir.c_str()); - UnixError::throwMe(ENOTDIR); - } -} - -int -AtomicFile::ropen(const char *const name, int flags, mode_t mode) -{ - bool isCreate = (flags & O_CREAT) != 0; - - /* - The purpose of checkForRead and checkForWrite is to mitigate - spamming of the log when a user has installed certain third - party software packages which create additional keychains. - Certain applications use a custom sandbox profile which do not - permit this and so the user gets a ton of spam in the log. - This turns into a serious performance problem. - - We handle this situation by checking two factors: - - 1: If the user is trying to create a file, we send the - request directly to open. This is the right thing - to do, as we don't want most applications creating - keychains unless they have been expressly authorized - to do so. - - The layers above this one only set O_CREAT when a file - doesn't exist, so the case where O_CREAT can be called - on an existing file is irrelevant. - - 2: If the user is trying to open the file for reading or - writing, we check with the sandbox mechanism to see if - the operation will be permitted (and tell it not to - log if it the operation will fail). - - If the operation is not permitted, we return -1 which - emulates the behavior of open. sandbox_check sets - errno properly, so the layers which call this function - will be able to act as though open had been called. - */ - - bool checkForRead = false; - bool checkForWrite = false; - - int fd, tries_left = 4 /* kNoResRetry */; - - if (!isCreate) - { - switch (flags & O_ACCMODE) - { - case O_RDONLY: - checkForRead = true; - break; - case O_WRONLY: - checkForWrite = true; - break; - case O_RDWR: - checkForRead = true; - checkForWrite = true; - break; - } - - if (checkForRead) - { - int result = sandbox_check(getpid(), "file-read-data", (sandbox_filter_type) (SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT), name); - if (result != 0) - { - return -1; - } - } - - if (checkForWrite) - { - int result = sandbox_check(getpid(), "file-write-data", (sandbox_filter_type) (SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT), name); - if (result != 0) - { - return -1; - } - } - } - - do - { - fd = ::open(name, flags, mode); - } while (fd < 0 && (errno == EINTR || (errno == ENFILE && --tries_left >= 0))); - - return fd; -} - -int -AtomicFile::rclose(int fd) -{ - int result; - do - { - result = ::close(fd); - } while(result && errno == EINTR); - - return result; -} - -// -// AtomicBufferedFile - This represents an instance of a file opened for reading. -// The file is read into memory and closed after this is done. -// The memory is released when this object is destroyed. -// -AtomicBufferedFile::AtomicBufferedFile(const std::string &inPath, bool isLocal) : - mPath(inPath), - mFileRef(-1), - mBuffer(NULL), - mLength(0), - mIsMapped(isLocal) -{ -} - -AtomicBufferedFile::~AtomicBufferedFile() -{ - if (mFileRef >= 0) - { - AtomicFile::rclose(mFileRef); - secdebug("atomicfile", "%p closed %s", this, mPath.c_str()); - } - - if (mBuffer) - { - secdebug("atomicfile", "%p free %s buffer %p", this, mPath.c_str(), mBuffer); - unloadBuffer(); - } -} - -// -// Open the file and return the length in bytes. -// -off_t -AtomicBufferedFile::open() -{ - const char *path = mPath.c_str(); - if (mFileRef >= 0) - { - secdebug("atomicfile", "open %s: already open, closing and reopening", path); - close(); - } - - mFileRef = AtomicFile::ropen(path, O_RDONLY, 0); - if (mFileRef == -1) - { - int error = errno; - secdebug("atomicfile", "open %s: %s", path, strerror(error)); - - // Do the obvious error code translations here. - // @@@ Consider moving these up a level. - if (error == ENOENT) - CssmError::throwMe(CSSMERR_DL_DATASTORE_DOESNOT_EXIST); - else if (error == EACCES) - CssmError::throwMe(CSSM_ERRCODE_OS_ACCESS_DENIED); - else - UnixError::throwMe(error); - } - - struct stat st; - int result = fstat(mFileRef, &st); - if (result == 0) - { - mLength = st.st_size; - } - else - { - int error = errno; - secdebug("atomicfile", "lseek(%s, END): %s", path, strerror(error)); - AtomicFile::rclose(mFileRef); - UnixError::throwMe(error); - } - - secdebug("atomicfile", "%p opened %s: %qd bytes", this, path, mLength); - - return mLength; -} - -// -// Unload the contents of the file. -// -void -AtomicBufferedFile::unloadBuffer() -{ - if (!mIsMapped) - { - delete [] mBuffer; - } - else - { - munmap(mBuffer, (size_t)mLength); - } -} - -// -// Load the contents of the file into memory. -// If we are on a local file system, we mmap the file. Otherwise, we -// read it all into memory -void -AtomicBufferedFile::loadBuffer() -{ - if (!mIsMapped) - { - // make a buffer big enough to hold the entire file - mBuffer = new uint8[mLength]; - lseek(mFileRef, 0, SEEK_SET); - ssize_t pos = 0; - - ssize_t bytesToRead = (ssize_t)mLength; - while (bytesToRead > 0) - { - ssize_t bytesRead = ::read(mFileRef, mBuffer + pos, bytesToRead); - if (bytesRead == -1) - { - if (errno != EINTR) - { - int error = errno; - secdebug("atomicfile", "lseek(%s, END): %s", mPath.c_str(), strerror(error)); - AtomicFile::rclose(mFileRef); - UnixError::throwMe(error); - } - } - else - { - bytesToRead -= bytesRead; - pos += bytesRead; - } - } - } - else - { - // mmap the buffer into place - mBuffer = (uint8*) mmap(NULL, (size_t)mLength, PROT_READ, MAP_PRIVATE, mFileRef, 0); - if (mBuffer == (uint8*) -1) - { - int error = errno; - secdebug("atomicfile", "lseek(%s, END): %s", mPath.c_str(), strerror(error)); - AtomicFile::rclose(mFileRef); - UnixError::throwMe(error); - } - } -} - - - -// -// Read the file starting at inOffset for inLength bytes into the buffer and return -// a pointer to it. On return outLength contain the actual number of bytes read, it -// will only ever be less than inLength if EOF was reached, and it will never be more -// than inLength. -// -const uint8 * -AtomicBufferedFile::read(off_t inOffset, off_t inLength, off_t &outLength) -{ - if (mFileRef < 0) - { - secdebug("atomicfile", "read %s: file yet not opened, opening", mPath.c_str()); - open(); - } - - off_t bytesLeft = inLength; - if (mBuffer) - { - secdebug("atomicfile", "%p free %s buffer %p", this, mPath.c_str(), mBuffer); - unloadBuffer(); - } - - loadBuffer(); - - secdebug("atomicfile", "%p allocated %s buffer %p size %qd", this, mPath.c_str(), mBuffer, bytesLeft); - - off_t maxEnd = inOffset + inLength; - if (maxEnd > mLength) - { - maxEnd = mLength; - } - - outLength = maxEnd - inOffset; - - return mBuffer + inOffset; -} - -void -AtomicBufferedFile::close() -{ - if (mFileRef < 0) - { - secdebug("atomicfile", "close %s: already closed", mPath.c_str()); - } - else - { - int result = AtomicFile::rclose(mFileRef); - mFileRef = -1; - if (result == -1) - { - int error = errno; - secdebug("atomicfile", "close %s: %s", mPath.c_str(), strerror(errno)); - UnixError::throwMe(error); - } - - secdebug("atomicfile", "%p closed %s", this, mPath.c_str()); - } -} - - -// -// AtomicTempFile - A temporary file to write changes to. -// -AtomicTempFile::AtomicTempFile(AtomicFile &inFile, const RefPointer &inLockedFile, mode_t mode) : - mFile(inFile), - mLockedFile(inLockedFile), - mCreating(true) -{ - create(mode); -} - -AtomicTempFile::AtomicTempFile(AtomicFile &inFile, const RefPointer &inLockedFile) : - mFile(inFile), - mLockedFile(inLockedFile), - mCreating(false) -{ - create(mFile.mode()); -} - -AtomicTempFile::~AtomicTempFile() -{ - // rollback if we didn't commit yet. - if (mFileRef >= 0) - rollback(); -} - -// -// Open the file and return the length in bytes. -// -void -AtomicTempFile::create(mode_t mode) -{ - // we now generate our temporary file name through sandbox API's. - - // put the dir into a canonical form - string dir = mFile.dir(); - int i = (int)dir.length() - 1; - - // walk backwards until we get to a non / character - while (i >= 0 && dir[i] == '/') - { - i -= 1; - } - - // point one beyond the string - i += 1; - - const char* temp = _amkrtemp((dir.substr(0, i) + "/" + mFile.file()).c_str()); - if (temp == NULL) - { - UnixError::throwMe(errno); - } - - mPath = temp; - free((void*) temp); - - const char *path = mPath.c_str(); - - mFileRef = AtomicFile::ropen(path, O_WRONLY|O_CREAT|O_TRUNC, mode); - if (mFileRef == -1) - { - int error = errno; - secdebug("atomicfile", "open %s: %s", path, strerror(error)); - - // Do the obvious error code translations here. - // @@@ Consider moving these up a level. - if (error == EACCES) - CssmError::throwMe(CSSM_ERRCODE_OS_ACCESS_DENIED); - else - UnixError::throwMe(error); - } - - // If we aren't creating the inital file, make sure we preserve - // the mode of the old file regardless of the current umask. - // If we are creating the inital file we respect the users - // current umask. - if (!mCreating) - { - if (::fchmod(mFileRef, mode)) - { - int error = errno; - secdebug("atomicfile", "fchmod %s: %s", path, strerror(error)); - UnixError::throwMe(error); - } - } - - secdebug("atomicfile", "%p created %s", this, path); -} - -void -AtomicTempFile::write(AtomicFile::OffsetType inOffsetType, off_t inOffset, const uint32 inData) -{ - uint32 aData = htonl(inData); - write(inOffsetType, inOffset, reinterpret_cast(&aData), sizeof(aData)); -} - -void -AtomicTempFile::write(AtomicFile::OffsetType inOffsetType, off_t inOffset, - const uint32 *inData, uint32 inCount) -{ -#ifdef HOST_LONG_IS_NETWORK_LONG - // Optimize this for the case where hl == nl - const uint32 *aBuffer = inData; -#else - auto_array aBuffer(inCount); - for (uint32 i = 0; i < inCount; i++) - aBuffer.get()[i] = htonl(inData[i]); -#endif - - write(inOffsetType, inOffset, reinterpret_cast(aBuffer.get()), - inCount * sizeof(*inData)); -} - -void -AtomicTempFile::write(AtomicFile::OffsetType inOffsetType, off_t inOffset, const uint8 *inData, size_t inLength) -{ - off_t pos; - if (inOffsetType == AtomicFile::FromEnd) - { - pos = ::lseek(mFileRef, 0, SEEK_END); - if (pos == -1) - { - int error = errno; - secdebug("atomicfile", "lseek(%s, %qd): %s", mPath.c_str(), inOffset, strerror(error)); - UnixError::throwMe(error); - } - } - else if (inOffsetType == AtomicFile::FromStart) - pos = inOffset; - else - CssmError::throwMe(CSSM_ERRCODE_INTERNAL_ERROR); - - off_t bytesLeft = inLength; - const uint8 *ptr = inData; - while (bytesLeft) - { - size_t toWrite = bytesLeft > kAtomicFileMaxBlockSize ? kAtomicFileMaxBlockSize : size_t(bytesLeft); - ssize_t bytesWritten = ::pwrite(mFileRef, ptr, toWrite, pos); - if (bytesWritten == -1) - { - int error = errno; - if (error == EINTR) - { - // We got interrupted by a signal, so try again. - secdebug("atomicfile", "write %s: interrupted, retrying", mPath.c_str()); - continue; - } - - secdebug("atomicfile", "write %s: %s", mPath.c_str(), strerror(error)); - UnixError::throwMe(error); - } - - // Write returning 0 is bad mmkay. - if (bytesWritten == 0) - { - secdebug("atomicfile", "write %s: 0 bytes written", mPath.c_str()); - CssmError::throwMe(CSSMERR_DL_INTERNAL_ERROR); - } - - secdebug("atomicfile", "%p wrote %s %ld bytes from %p", this, mPath.c_str(), bytesWritten, ptr); - - bytesLeft -= bytesWritten; - ptr += bytesWritten; - pos += bytesWritten; - } -} - -void -AtomicTempFile::fsync() -{ - if (mFileRef < 0) - { - secdebug("atomicfile", "fsync %s: already closed", mPath.c_str()); - } - else - { - int result; - do - { - result = ::fsync(mFileRef); - } while (result && errno == EINTR); - - if (result == -1) - { - int error = errno; - secdebug("atomicfile", "fsync %s: %s", mPath.c_str(), strerror(errno)); - UnixError::throwMe(error); - } - - secdebug("atomicfile", "%p fsynced %s", this, mPath.c_str()); - } -} - -void -AtomicTempFile::close() -{ - if (mFileRef < 0) - { - secdebug("atomicfile", "close %s: already closed", mPath.c_str()); - } - else - { - int result = AtomicFile::rclose(mFileRef); - mFileRef = -1; - if (result == -1) - { - int error = errno; - secdebug("atomicfile", "close %s: %s", mPath.c_str(), strerror(errno)); - UnixError::throwMe(error); - } - - secdebug("atomicfile", "%p closed %s", this, mPath.c_str()); - } -} - -// Commit the current create or write and close the write file. Note that a throw during the commit does an automatic rollback. -void -AtomicTempFile::commit() -{ - try - { - fsync(); - close(); - const char *oldPath = mPath.c_str(); - const char *newPath = mFile.path().c_str(); - - // - // Copy the security parameters of one file to another - // Adding this to guard against setuid utilities that are re-writing a user's keychain. We don't want to leave them root-owned. - // In order to not break backward compatability we'll make a best effort, but continue if these efforts fail. - // - // To clear something up - newPath is the name the keychain will become - which is the name of the file being replaced - // oldPath is the "temp filename". - - copyfile_state_t s; - s = copyfile_state_alloc(); - - if(copyfile(newPath, oldPath, s, COPYFILE_SECURITY | COPYFILE_NOFOLLOW) == -1) // Not fatal - secdebug("atomicfile", "copyfile (%s, %s): %s", oldPath, newPath, strerror(errno)); - - copyfile_state_free(s); - // END - - ::utimes(oldPath, NULL); - - if (::rename(oldPath, newPath) == -1) - { - int error = errno; - secdebug("atomicfile", "rename (%s, %s): %s", oldPath, newPath, strerror(errno)); - UnixError::throwMe(error); - } - - // Unlock the lockfile - mLockedFile = NULL; - - secdebug("atomicfile", "%p commited %s", this, oldPath); - } - catch (...) - { - rollback(); - throw; - } -} - -// Rollback the current create or write (happens automatically if commit() isn't called before the destructor is. -void -AtomicTempFile::rollback() throw() -{ - if (mFileRef >= 0) - { - AtomicFile::rclose(mFileRef); - mFileRef = -1; - } - - // @@@ Log errors if this fails. - const char *path = mPath.c_str(); - if (::unlink(path) == -1) - { - secdebug("atomicfile", "unlink %s: %s", path, strerror(errno)); - // rollback can't throw - } - - // @@@ Think about this. Depending on how we do locking we might not need this. - if (mCreating) - { - const char *path = mFile.path().c_str(); - if (::unlink(path) == -1) - { - secdebug("atomicfile", "unlink %s: %s", path, strerror(errno)); - // rollback can't throw - } - } -} - - -// -// An advisory write lock for inFile. -// -FileLocker::~FileLocker() -{ -} - - - -LocalFileLocker::LocalFileLocker(AtomicFile &inFile) : - mPath(inFile.lockFileName()) -{ -} - - -LocalFileLocker::~LocalFileLocker() -{ -} - - - -#ifndef NDEBUG -static double GetTime() -{ - struct timeval t; - gettimeofday(&t, NULL); - return ((double) t.tv_sec) + ((double) t.tv_usec) / 1000000.0; -} -#endif - - - -void -LocalFileLocker::lock(mode_t mode) -{ - struct stat st; - - do - { - // if the lock file doesn't exist, create it - mLockFile = open(mPath.c_str(), O_RDONLY | O_CREAT, mode); - - // if we can't open or create the file, something is wrong - if (mLockFile == -1) - { - UnixError::throwMe(errno); - } - - // try to get exclusive access to the file - IFDEBUG(double startTime = GetTime()); - int result = flock(mLockFile, LOCK_EX); - IFDEBUG(double endTime = GetTime()); - - IFDEBUG(secdebug("atomictime", "Waited %.4f milliseconds for file lock", (endTime - startTime) * 1000.0)); - - // errors at this point are bad - if (result == -1) - { - UnixError::throwMe(errno); - } - - // check and see if the file we have access to still exists. If not, another file shared our file lock - // due to a hash collision and has thrown our lock away -- that, or a user blew the lock file away himself. - - result = fstat(mLockFile, &st); - - // errors at this point are bad - if (result == -1) - { - UnixError::throwMe(errno); - } - - if (st.st_nlink == 0) // we've been unlinked! - { - close(mLockFile); - } - } while (st.st_nlink == 0); -} - - -void -LocalFileLocker::unlock() -{ - flock(mLockFile, LOCK_UN); - close(mLockFile); -} - - - -NetworkFileLocker::NetworkFileLocker(AtomicFile &inFile) : - mDir(inFile.dir()), - mPath(inFile.dir() + "lck~" + inFile.file()) -{ -} - -NetworkFileLocker::~NetworkFileLocker() -{ -} - -std::string -NetworkFileLocker::unique(mode_t mode) -{ - static const int randomPart = 16; - DevRandomGenerator randomGen; - std::string::size_type dirSize = mDir.size(); - std::string fullname(dirSize + randomPart + 2, '\0'); - fullname.replace(0, dirSize, mDir); - fullname[dirSize] = '~'; /* UNIQ_PREFIX */ - char buf[randomPart]; - struct stat filebuf; - int result, fd = -1; - - for (int retries = 0; retries < 10; ++retries) - { - /* Make a random filename. */ - randomGen.random(buf, randomPart); - for (int ix = 0; ix < randomPart; ++ix) - { - char ch = buf[ix] & 0x3f; - fullname[ix + dirSize + 1] = ch + - ( ch < 26 ? 'A' - : ch < 26 + 26 ? 'a' - 26 - : ch < 26 + 26 + 10 ? '0' - 26 - 26 - : ch == 26 + 26 + 10 ? '-' - 26 - 26 - 10 - : '_' - 26 - 26 - 11); - } - - result = lstat(fullname.c_str(), &filebuf); - if (result && errno == ENAMETOOLONG) - { - do - fullname.erase(fullname.end() - 1); - while((result = lstat(fullname.c_str(), &filebuf)) && errno == ENAMETOOLONG && fullname.size() > dirSize + 8); - } /* either it stopped being a problem or we ran out of filename */ - - if (result && errno == ENOENT) - { - fd = AtomicFile::ropen(fullname.c_str(), O_WRONLY|O_CREAT|O_EXCL, mode); - if (fd >= 0 || errno != EEXIST) - break; - } - } - - if (fd < 0) - { - int error = errno; - ::syslog(LOG_ERR, "Couldn't create temp file %s: %s", fullname.c_str(), strerror(error)); - secdebug("atomicfile", "Couldn't create temp file %s: %s", fullname.c_str(), strerror(error)); - UnixError::throwMe(error); - } - - /* @@@ Check for EINTR. */ - write(fd, "0", 1); /* pid 0, `works' across networks */ - - AtomicFile::rclose(fd); - - return fullname; -} - -/* Return 0 on success and 1 on failure if st is set to the result of stat(old) and -1 on failure if the stat(old) failed. */ -int -NetworkFileLocker::rlink(const char *const old, const char *const newn, struct stat &sto) -{ - int result = ::link(old,newn); - if (result) - { - int serrno = errno; - if (::lstat(old, &sto) == 0) - { - struct stat stn; - if (::lstat(newn, &stn) == 0 - && sto.st_dev == stn.st_dev - && sto.st_ino == stn.st_ino - && sto.st_uid == stn.st_uid - && sto.st_gid == stn.st_gid - && !S_ISLNK(sto.st_mode)) - { - /* Link failed but files are the same so the link really went ok. */ - return 0; - } - else - result = 1; - } - errno = serrno; /* Restore errno from link() */ - } - - return result; -} - -/* NFS-resistant rename() - * rename with fallback for systems that don't support it - * Note that this does not preserve the contents of the file. */ -int -NetworkFileLocker::myrename(const char *const old, const char *const newn) -{ - struct stat stbuf; - int fd = -1; - int ret; - - /* Try a real hardlink */ - ret = rlink(old, newn, stbuf); - if (ret > 0) - { - if (stbuf.st_nlink < 2 && (errno == EXDEV || errno == ENOTSUP)) - { - /* Hard link failed so just create a new file with O_EXCL instead. */ - fd = AtomicFile::ropen(newn, O_WRONLY|O_CREAT|O_EXCL, stbuf.st_mode); - if (fd >= 0) - ret = 0; - } - } - - /* We want the errno from the link or the ropen, not that of the unlink. */ - int serrno = errno; - - /* Unlink the temp file. */ - ::unlink(old); - if (fd > 0) - AtomicFile::rclose(fd); - - errno = serrno; - return ret; -} - -int -NetworkFileLocker::xcreat(const char *const name, mode_t mode, time_t &tim) -{ - std::string uniqueName = unique(mode); - const char *uniquePath = uniqueName.c_str(); - struct stat stbuf; /* return the filesystem time to the caller */ - stat(uniquePath, &stbuf); - tim = stbuf.st_mtime; - return myrename(uniquePath, name); -} - -void -NetworkFileLocker::lock(mode_t mode) -{ - const char *path = mPath.c_str(); - bool triedforce = false; - struct stat stbuf; - time_t t, locktimeout = 1024; /* DEFlocktimeout, 17 minutes. */ - bool doSyslog = false; - bool failed = false; - int retries = 0; - - while (!failed) - { - /* Don't syslog first time through. */ - if (doSyslog) - ::syslog(LOG_NOTICE, "Locking %s", path); - else - doSyslog = true; - - secdebug("atomicfile", "Locking %s", path); /* in order to cater for clock skew: get */ - if (!xcreat(path, mode, t)) /* time t from the filesystem */ - { - /* lock acquired, hurray! */ - break; - } - switch(errno) - { - case EEXIST: /* check if it's time for a lock override */ - if (!lstat(path, &stbuf) && stbuf.st_size <= 16 /* MAX_locksize */ && locktimeout - && !lstat(path, &stbuf) && locktimeout < t - stbuf.st_mtime) - /* stat() till unlink() should be atomic, but can't guarantee that. */ - { - if (triedforce) - { - /* Already tried, force lock override, not trying again */ - failed = true; - break; - } - else if (S_ISDIR(stbuf.st_mode) || ::unlink(path)) - { - triedforce=true; - ::syslog(LOG_ERR, "Forced unlock denied on %s", path); - secdebug("atomicfile", "Forced unlock denied on %s", path); - } - else - { - ::syslog(LOG_ERR, "Forcing lock on %s", path); - secdebug("atomicfile", "Forcing lock on %s", path); - sleep(16 /* DEFsuspend */); - break; - } - } - else - triedforce = false; /* legitimate iteration, clear flag */ - - /* Reset retry counter. */ - retries = 0; - usleep(250000); - break; - - case ENOSPC: /* no space left, treat it as a transient */ -#ifdef EDQUOT /* NFS failure */ - case EDQUOT: /* maybe it was a short term shortage? */ -#endif - case ENOENT: - case ENOTDIR: - case EIO: - /*case EACCES:*/ - if(++retries < (256 + 1)) /* nfsTRY number of times+1 to ignore spurious NFS errors */ - usleep(250000); - else - failed = true; - break; - -#ifdef ENAMETOOLONG - case ENAMETOOLONG: /* Filename is too long, shorten and retry */ - if (mPath.size() > mDir.size() + 8) - { - secdebug("atomicfile", "Truncating %s and retrying lock", path); - mPath.erase(mPath.end() - 1); - path = mPath.c_str(); - /* Reset retry counter. */ - retries = 0; - break; - } - /* DROPTHROUGH */ -#endif - default: - failed = true; - break; - } - } - - if (failed) - { - int error = errno; - ::syslog(LOG_ERR, "Lock failure on %s: %s", path, strerror(error)); - secdebug("atomicfile", "Lock failure on %s: %s", path, strerror(error)); - UnixError::throwMe(error); - } -} - -void -NetworkFileLocker::unlock() -{ - const char *path = mPath.c_str(); - if (::unlink(path) == -1) - { - secdebug("atomicfile", "unlink %s: %s", path, strerror(errno)); - // unlock can't throw - } -} - - - -AtomicLockedFile::AtomicLockedFile(AtomicFile &inFile) -{ - if (inFile.isOnLocalFileSystem()) - { - mFileLocker = new LocalFileLocker(inFile); - } - else - { - mFileLocker = new NetworkFileLocker(inFile); - } - - lock(); -} - - - -AtomicLockedFile::~AtomicLockedFile() -{ - unlock(); - delete mFileLocker; -} - - - -void -AtomicLockedFile::lock(mode_t mode) -{ - mFileLocker->lock(mode); -} - - - -void AtomicLockedFile::unlock() throw() -{ - mFileLocker->unlock(); -} - - - -#undef kAtomicFileMaxBlockSize diff --git a/OSX/include/security_filedb/AtomicFile.h b/OSX/include/security_filedb/AtomicFile.h deleted file mode 100644 index 65d8905a..00000000 --- a/OSX/include/security_filedb/AtomicFile.h +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (c) 2000-2001,2003,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// AtomicFile.h - Description t.b.d. -// -#ifndef _SECURITY_ATOMICFILE_H_ -#define _SECURITY_ATOMICFILE_H_ 1 - -#include -#include -#include -#include - -namespace Security -{ - -class AtomicBufferedFile; -class AtomicLockedFile; -class AtomicTempFile; - -class AtomicFile -{ -public: - AtomicFile(const std::string &inPath); - ~AtomicFile(); - - // Aquire the write lock and remove the file. - void performDelete(); - - // Aquire the write lock and rename the file. - void rename(const std::string &inNewPath); - - // Lock the file for writing and return a newly created AtomicTempFile. - RefPointer create(mode_t mode); - - // Lock the file for writing and return a newly created AtomicTempFile. - RefPointer write(); - - // Return a bufferedFile containing current version of the file for reading. - RefPointer read(); - - const string& path() const { return mPath; } - const string& dir() const { return mDir; } - const string& file() const { return mFile; } - const string& lockFileName() { return mLockFilePath; } - - mode_t mode() const; - bool isOnLocalFileSystem() {return mIsLocalFileSystem;} - - enum OffsetType - { - FromStart, - FromEnd // only works with offset of 0 - }; - - static void pathSplit(const std::string &inFull, std::string &outDir, std::string &outFile); - static void mkpath(const std::string &inDir, mode_t mode = 0777); - static int ropen(const char *const name, int flags, mode_t mode); - static int rclose(int fd); - -private: - bool mIsLocalFileSystem; - string mPath; - string mDir; - string mFile; - string mLockFilePath; -}; - - -// -// AtomicBufferedFile - This represents an instance of a file opened for reading. -// The file is read into memory and closed after this is done. -// The memory is released when this object is destroyed. -// -class AtomicBufferedFile : public RefCount -{ -public: - AtomicBufferedFile(const std::string &inPath, bool isLocalFileSystem); - ~AtomicBufferedFile(); - - // Open the file and return it's size. - off_t open(); - - // Read inLength bytes starting at inOffset. - const uint8 *read(off_t inOffset, off_t inLength, off_t &outLength); - - // Return the current mode bits of the file - mode_t mode(); - - // Close the file (this doesn't release the buffer). - void close(); - - // Return the length of the file. - off_t length() const { return mLength; } - -private: - void loadBuffer(); - void unloadBuffer(); - -private: - // Complete path to the file - string mPath; - - // File descriptor to the file or -1 if it's not currently open. - int mFileRef; - - // This is where the data from the file is read in to. - uint8 *mBuffer; - - // Length of file in bytes. - off_t mLength; - - // Is on a local file system - bool mIsMapped; -}; - - -// -// AtomicTempFile - A temporary file to write changes to. -// -class AtomicTempFile : public RefCount -{ -public: - // Start a write for a new file. - AtomicTempFile(AtomicFile &inFile, const RefPointer &inLockedFile, mode_t mode); - - // Start a write of an existing file. - AtomicTempFile(AtomicFile &inFile, const RefPointer &inLockedFile); - - ~AtomicTempFile(); - - // Commit the current create or write and close the write file. - void commit(); - - void write(AtomicFile::OffsetType inOffsetType, off_t inOffset, const uint32 *inData, uint32 inCount); - void write(AtomicFile::OffsetType inOffsetType, off_t inOffset, const uint8 *inData, size_t inLength); - void write(AtomicFile::OffsetType inOffsetType, off_t inOffset, const uint32 inData); - -private: - // Called by both constructors. - void create(mode_t mode); - - // Fsync the file - void fsync(); - - // Close the file - void close(); - - // Rollback the current create or write (happens automatically if commit() isn't called before the destructor is). - void rollback() throw(); - -private: - // Our AtomicFile object. - AtomicFile &mFile; - - RefPointer mLockedFile; - - // Complete path to the file - string mPath; - - // File descriptor to the file or -1 if it's not currently open. - int mFileRef; - - // If this is true we unlink both mPath and mFile.path() when we rollback. - bool mCreating; -}; - - -class FileLocker -{ -public: - virtual ~FileLocker(); - - virtual void lock(mode_t mode) = 0; - virtual void unlock() = 0; -}; - - - -class LocalFileLocker : public FileLocker -{ -public: - LocalFileLocker(AtomicFile &inFile); - virtual ~LocalFileLocker(); - - virtual void lock(mode_t mode); - virtual void unlock(); - -private: - int mLockFile; - string mPath; -}; - - - -class NetworkFileLocker : public FileLocker -{ -public: - NetworkFileLocker(AtomicFile &inFile); - virtual ~NetworkFileLocker(); - - virtual void lock(mode_t mode); - virtual void unlock(); - -private: - std::string unique(mode_t mode); - int rlink(const char *const old, const char *const newn, struct stat &sto); - int myrename(const char *const old, const char *const newn); - int xcreat(const char *const name, mode_t mode, time_t &tim); - - // The directory in which we create the lock - string mDir; - - // Complete path to the file - string mPath; -}; - - - -// The current lock being held. -class AtomicLockedFile : public RefCount -{ -public: - // Create a write lock for inFile. - AtomicLockedFile(AtomicFile &inFile); - - ~AtomicLockedFile(); - -private: - void lock(mode_t mode = (S_IRUSR|S_IRGRP|S_IROTH) /* === 0444 */); - void unlock() throw(); - -private: - FileLocker* mFileLocker; -}; - - -} // end namespace Security - - -#endif // _SECURITY_ATOMICFILE_H_ diff --git a/OSX/include/security_filedb/DbIndex.cpp b/OSX/include/security_filedb/DbIndex.cpp deleted file mode 100644 index 8c1d40e6..00000000 --- a/OSX/include/security_filedb/DbIndex.cpp +++ /dev/null @@ -1,476 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DbIndex.cpp -// - -#include "DbIndex.h" -#include "AppleDatabase.h" -#include - -DbQueryKey::DbQueryKey(const DbConstIndex &index) -: mIndex(index), - mTableSection(index.table().getTableSection()) -{ -} - -// Perform a less-than comparison between two keys. An offset of -// kUseQueryKeyOffset means to use the key provided as part of the -// query; otherwise, the key comes from the database. - -const uint32 DbKeyComparator::kUseQueryKeyOffset; - -bool -DbKeyComparator::operator () (uint32 offset1, uint32 offset2) const -{ - ReadSection rs1, rs2; - const ReadSection *key1, *key2; - - // get the read sections to compare - - if (offset1 == kUseQueryKeyOffset) - key1 = &mKey.mKeyData; - else { - rs1 = mKey.mTableSection.subsection(offset1); - key1 = &rs1; - } - - if (offset2 == kUseQueryKeyOffset) - key2 = &mKey.mKeyData; - else { - rs2 = mKey.mTableSection.subsection(offset2); - key2 = &rs2; - } - - // compare the values of the attributes in the keys - - uint32 valueOffset1 = sizeof(uint32), valueOffset2 = sizeof(uint32); - - for (uint32 i = 0; i < mKey.mNumKeyValues; i++) { - const MetaAttribute &metaAttribute = *mKey.mIndex.mAttributes[i]; - auto_ptr value1(metaAttribute.createValue(*key1, valueOffset1)); - auto_ptr value2(metaAttribute.createValue(*key2, valueOffset2)); - - if (metaAttribute.evaluate(value1.get(), value2.get(), CSSM_DB_LESS_THAN)) - return true; - - else if (metaAttribute.evaluate(value2.get(), value1.get(), CSSM_DB_LESS_THAN)) - return false; - } - - // if we are here, the keys are equal - - return false; -} - -// Comparison used when inserting an item into an index, but otherwise -// similar to the version above. - -bool -DbIndexKey::operator < (const DbIndexKey &other) const -{ - // compare the values of the attributes in the keys - - uint32 numAttributes = (uint32) mIndex.mAttributes.size(); - uint32 valueOffset1 = 0, valueOffset2 = 0; - - for (uint32 i = 0; i < numAttributes; i++) { - const MetaAttribute &metaAttribute = *mIndex.mAttributes[i]; - auto_ptr value1(metaAttribute.createValue(mKeySection.subsection(mKeyRange), - valueOffset1)); - auto_ptr value2(metaAttribute.createValue(other.mKeySection.subsection(other.mKeyRange), - valueOffset2)); - - if (metaAttribute.evaluate(value1.get(), value2.get(), CSSM_DB_LESS_THAN)) - return true; - - else if (metaAttribute.evaluate(value2.get(), value1.get(), CSSM_DB_LESS_THAN)) - return false; - } - - // if we are here, the keys are equal - - return false; -} - -DbIndex::DbIndex(const MetaRecord &metaRecord, uint32 indexId, bool isUniqueIndex) -: mMetaRecord(metaRecord), - mIndexId(indexId), - mIsUniqueIndex(isUniqueIndex) -{ -} - -// Append an attribute to the vector used to form index keys. - -void -DbIndex::appendAttribute(uint32 attributeId) -{ - CSSM_DB_ATTRIBUTE_INFO info; - info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - info.Label.AttributeID = attributeId; - - mAttributes.push_back(&(mMetaRecord.metaAttribute(info))); -} - -// Construct a new read-only index. - -DbConstIndex::DbConstIndex(const Table &table, uint32 indexId, bool isUniqueIndex) -: DbIndex(table.getMetaRecord(), indexId, isUniqueIndex), - mTable(table) -{ -} - -DbConstIndex::DbConstIndex(const Table &table, const ReadSection &indexSection) -: DbIndex(table.getMetaRecord(), indexSection.at(AtomSize), indexSection.at(2 * AtomSize)), - mTable(table) -{ - uint32 numAttributes = indexSection.at(3 * AtomSize); - - for (uint32 i = 0; i < numAttributes; i++) { - uint32 attributeId = indexSection.at((4 + i) * AtomSize); - appendAttribute(attributeId); - } - - uint32 offset = (4 + numAttributes) * AtomSize; - uint32 numRecords = indexSection.at(offset); - offset += AtomSize; - mKeyOffsetVector.overlay(numRecords, - reinterpret_cast(indexSection.range(Range(offset, numRecords * AtomSize)))); - - offset += numRecords * AtomSize; - mRecordNumberVector.overlay(numRecords, - reinterpret_cast(indexSection.range(Range(offset, numRecords * AtomSize)))); -} - -// Check to see if this index can be used to perform a given query, based on -// the attributes used in the query and their order. They must be a prefix -// of the index key attributes. If there is more than one attribute, all of the -// operators must be EQUAL and the conjunctive must be AND; this is needed to -// ensure that the results are a contiguous segment of the index. On success, -// the appropriate index key is generated from the query. - -bool -DbConstIndex::matchesQuery(const CSSM_QUERY &query, DbQueryKey *&queryKey) const -{ - uint32 numPredicates = query.NumSelectionPredicates; - - if (numPredicates == 0 || numPredicates > mAttributes.size()) - return false; - - // determine which index attributes are used in the query - - auto_array attributeUsed(mAttributes.size()); - for (uint32 i = 0; i < mAttributes.size(); attributeUsed[i++] = ~(uint32)0); - - for (uint32 i = 0, j; i < numPredicates; i++) { - const MetaAttribute &tableAttribute = - mMetaRecord.metaAttribute(query.SelectionPredicate[i].Attribute.Info); - - for (j = 0; j < mAttributes.size(); j++) { - if (tableAttribute.attributeId() == mAttributes[j]->attributeId()) { - if (attributeUsed[j] != ~(uint32)0) - // invalid query: attribute appears twice - CssmError::throwMe(CSSMERR_DL_INVALID_QUERY); - else { - // the jth index component is the ith predicate in the query - attributeUsed[j] = i; - break; - } - } - } - - if (j == mAttributes.size()) { - // the predicate attribute is not in the index, so return failure - return false; - } - } - - // check that the query predicates form a prefix of the index key, which means that - // the first N index components are the N query predicates in some order - - long lastIndex; - for (lastIndex = mAttributes.size() - 1; (lastIndex >= 0) && (attributeUsed[lastIndex] == ~(uint32)0); - lastIndex--); - - if (lastIndex != numPredicates - 1) - return false; - - // if there is more than one predicate, the conjunctive must be AND and all the - // operators must be EQUAL for the compound index to be useful - - CSSM_DB_OPERATOR op; - - if (numPredicates > 1) { - if (query.Conjunctive != CSSM_DB_AND) - return false; - - for (uint32 i = 0; i < numPredicates; i++) - if (query.SelectionPredicate[i].DbOperator != CSSM_DB_EQUAL) - return false; - - op = CSSM_DB_EQUAL; - } - - // for a single predicate, check the operator - - else { - op = query.SelectionPredicate[0].DbOperator; - if (op != CSSM_DB_EQUAL && op != CSSM_DB_LESS_THAN && op != CSSM_DB_GREATER_THAN) - return false; - } - - // ok, after all that, we can use this index, so generate an object used as a key - // for this query on this index - - queryKey = new DbQueryKey(*this); - queryKey->mNumKeyValues = numPredicates; - queryKey->mOp = op; - - uint32 keyLength = sizeof(uint32); - for (uint32 i = 0; i < numPredicates; i++) - mAttributes[i]->packValue(queryKey->mKeyData, keyLength, - *(query.SelectionPredicate[attributeUsed[i]].Attribute.Value)); - queryKey->mKeyData.put(0, keyLength - sizeof(uint32)); - queryKey->mKeyData.size(keyLength); - - return true; -} - -// Perform a query on an index, returning the iterators that bound the -// returned results. - -void -DbConstIndex::performQuery(const DbQueryKey &queryKey, - DbIndexIterator &begin, DbIndexIterator &end) const -{ - DbKeyComparator cmp(queryKey); - - switch (queryKey.mOp) { - - case CSSM_DB_EQUAL: - { - pair result; - result = equal_range(mKeyOffsetVector.begin(), mKeyOffsetVector.end(), - DbKeyComparator::kUseQueryKeyOffset, cmp); - begin = result.first; - end = result.second; - } - break; - - case CSSM_DB_LESS_THAN: - begin = mKeyOffsetVector.begin(); - end = lower_bound(begin, mKeyOffsetVector.end(), - DbKeyComparator::kUseQueryKeyOffset, cmp); - break; - - case CSSM_DB_GREATER_THAN: - end = mKeyOffsetVector.end(); - begin = lower_bound(mKeyOffsetVector.begin(), end, - DbKeyComparator::kUseQueryKeyOffset, cmp); - break; - - default: - CssmError::throwMe(CSSMERR_DL_INTERNAL_ERROR); - break; - } -} - -// Given an iterator as returned by performQuery(), return the read section for the record. - -ReadSection -DbConstIndex::getRecordSection(DbIndexIterator iter) const -{ - uint32 recordNumber = mRecordNumberVector[iter - mKeyOffsetVector.begin()]; - return mTable.getRecordSection(recordNumber); -} - -// Construct a mutable index from a read-only index. - -DbMutableIndex::DbMutableIndex(const DbConstIndex &index) -: DbIndex(index), - mIndexDataSize(0) -{ - // go through the const index and copy all the entries into the - // mutable index - - const ReadSection &tableSection = index.mTable.getTableSection(); - - size_t numRecords = index.mKeyOffsetVector.size(); - for (size_t i = 0; i < numRecords; i++) { - uint32 recordNumber = index.mRecordNumberVector.at(i); - uint32 keyOffset = index.mKeyOffsetVector.at(i); - uint32 keySize = tableSection.at(keyOffset); - DbIndexKey key(tableSection, Range(keyOffset + AtomSize, keySize), *this); - mMap.insert(IndexMap::value_type(key, recordNumber)); - } -} - -DbMutableIndex::DbMutableIndex(const MetaRecord &metaRecord, uint32 indexId, bool isUniqueIndex) -: DbIndex(metaRecord, indexId, isUniqueIndex), - mIndexDataSize(0) -{ -} - -DbMutableIndex::~DbMutableIndex() -{ -} - -// Remove all entries for a record from an index. This is not an ideal implementation, -// since it walks the entire index. In a perfect world, we'd generate all the record's -// keys and lookup matching entries, deleting only those with the correct record number. -// But this is not a perfect world. - -void -DbMutableIndex::removeRecord(uint32 recordNumber) -{ - IndexMap::iterator it, temp; - for (it = mMap.begin(); it != mMap.end(); ) { - temp = it; it++; - if (temp->second == recordNumber) - mMap.erase(temp); - } -} - -// Insert a record into an index. - -void -DbMutableIndex::insertRecord(uint32 recordNumber, const ReadSection &packedRecord) -{ - // The common case is that each indexed attribute has a single value in - // the record; detect and handle this separately since we can avoid an - // expensive recursive technique. - - size_t numAttributes = mAttributes.size(); - bool allSingleValued = true; - - for (size_t i = 0; i < numAttributes; i++) { - uint32 numValues = mAttributes[i]->getNumberOfValues(packedRecord); - if (numValues == 0) { - // record does not have value required by index; for a unique index, - // this is an error, otherwise just don't index the record - if (mIsUniqueIndex) - CssmError::throwMe(CSSMERR_DL_MISSING_VALUE); - else - return; - } - else if (numValues > 1) { - allSingleValued = false; - break; - } - } - - if (allSingleValued) - insertRecordSingle(recordNumber, packedRecord); - - else { - // recursively build all appropriate index keys, and add them to the map - WriteSection keyData; - insertRecordMulti(recordNumber, packedRecord, 0, keyData, 0); - } -} - -void -DbMutableIndex::insertRecordSingle(uint32 recordNumber, const ReadSection &packedRecord) -{ - // append the key values to the index data - uint32 offset = mIndexDataSize; - for (uint32 i = 0; i < mAttributes.size(); i++) - mAttributes[i]->copyValueBytes(0, packedRecord, mIndexData, mIndexDataSize); - mIndexData.size(mIndexDataSize); - - // make an index key - DbIndexKey key(mIndexData, Range(offset, mIndexDataSize - offset), *this); - - // if this is a unique index, check for a record with the same key - if (mIsUniqueIndex && (mMap.find(key) != mMap.end())) - // the key already exists, which is an error - CssmError::throwMe(CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA); - - // insert the item into the map - mMap.insert(IndexMap::value_type(key, recordNumber)); -} - -void -DbMutableIndex::insertRecordMulti(uint32 recordNumber, const ReadSection &packedRecord, - uint32 attributeIndex, WriteSection &keyData, uint32 keySize) -{ - const MetaAttribute &metaAttribute = *(mAttributes[attributeIndex]); - uint32 numValues = metaAttribute.getNumberOfValues(packedRecord); - - for (uint32 i = 0; i < numValues; i++) { - - uint32 newKeySize = keySize; - metaAttribute.copyValueBytes(i, packedRecord, keyData, newKeySize); - - if (attributeIndex + 1 == mAttributes.size()) { - uint32 offset = mIndexDataSize; - mIndexDataSize = mIndexData.put(mIndexDataSize, newKeySize, keyData.address()); - mIndexData.size(mIndexDataSize); - - DbIndexKey key(mIndexData, Range(offset, mIndexDataSize - offset), *this); - if (mIsUniqueIndex && (mMap.find(key) != mMap.end())) - CssmError::throwMe(CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA); - - mMap.insert(IndexMap::value_type(key, recordNumber)); - } - else - // otherwise, recurse with the rest of the attributes - insertRecordMulti(recordNumber, packedRecord, attributeIndex + 1, keyData, newKeySize); - } -} - -uint32 -DbMutableIndex::writeIndex(WriteSection &ws, uint32 offset) -{ - IndexMap::iterator it; - - // reserve space for the index size - uint32 sizeOffset = offset; - offset += AtomSize; - - offset = ws.put(offset, mIndexId); - offset = ws.put(offset, mIsUniqueIndex ? 1 : 0); - - offset = ws.put(offset, (uint32)mAttributes.size()); - for (uint32 i = 0; i < mAttributes.size(); i++) - offset = ws.put(offset, mAttributes[i]->attributeId()); - - offset = ws.put(offset, (uint32)mMap.size()); - - // reserve space for the array of offsets to key data - uint32 keyPtrOffset = offset; - offset += AtomSize * mMap.size(); - - // write the array of record numbers - for (it = mMap.begin(); it != mMap.end(); it++) { - offset = ws.put(offset, it->second); - } - - // write the key data - for (it = mMap.begin(); it != mMap.end(); it++) { - keyPtrOffset = ws.put(keyPtrOffset, offset); - offset = ws.put(offset, it->first.keySize()); - offset = ws.put(offset, it->first.keySize(), it->first.keyData()); - } - - // write the index size - ws.put(sizeOffset, offset - sizeOffset); - - return offset; -} diff --git a/OSX/include/security_filedb/DbIndex.h b/OSX/include/security_filedb/DbIndex.h deleted file mode 100644 index d178b26d..00000000 --- a/OSX/include/security_filedb/DbIndex.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DbIndex.h -// - -#ifndef _H_APPLEDL_DBINDEX -#define _H_APPLEDL_DBINDEX - -#include "MetaRecord.h" - -namespace Security -{ - -class Table; -class DbConstIndex; -class DbIndex; - -typedef constVector DbOffsetVector; - -typedef DbOffsetVector::const_iterator DbIndexIterator; - -// -// An object that represents a key being used as part of a query. -// - -class DbQueryKey -{ - friend class DbConstIndex; - friend class DbKeyComparator; - -public: - DbQueryKey(const DbConstIndex &index); - -private: - WriteSection mKeyData; - uint32 mNumKeyValues; - const DbConstIndex &mIndex; - const ReadSection &mTableSection; - CSSM_DB_OPERATOR mOp; -}; - -// -// An object which performs comparison between keys, either stored -// in a database or provided as part of a query. -// - -class DbKeyComparator -{ -public: - DbKeyComparator(const DbQueryKey &key) : mKey(key) {} - - bool operator () (uint32 keyOffset1, uint32 keyOffset2) const; - - // Pass this value as an argument to - // operator()(uint32,uint32) to compare against mKey. - static const uint32 kUseQueryKeyOffset = 0; - -private: - const DbQueryKey &mKey; -}; - -// -// A key as stored in an index. -// - -class DbIndexKey { -public: - DbIndexKey(const ReadSection &key, const Range &keyRange, const DbIndex &index) - : mKeySection(key), mKeyRange(keyRange), mIndex(index) {} - - bool operator < (const DbIndexKey &other) const; - - uint32 keySize() const { return mKeyRange.mSize; } - const uint8 *keyData() const { return mKeySection.range(mKeyRange); } - -private: - // the key data, expressed as a subsection of a read section - const ReadSection &mKeySection; - Range mKeyRange; - - // the index that knows how to interpret the key data - const DbIndex &mIndex; -}; - -// Base class containing stuff shared between const and mutable indexes. - -class DbIndex -{ - friend class DbIndexKey; - -public: - uint32 indexId() const { return mIndexId; } - - // append an attribute to the index key - void appendAttribute(uint32 attributeId); - -protected: - DbIndex(const MetaRecord &metaRecord, uint32 indexId, bool isUniqueIndex); - - // meta record for table associated with this index - const MetaRecord &mMetaRecord; - - // vector of indexed attributes - typedef vector AttributeVector; - AttributeVector mAttributes; - - uint32 mIndexId; - bool mIsUniqueIndex; -}; - -// Read-only index. - -class DbConstIndex : public DbIndex -{ - friend class DbMutableIndex; - friend class DbQueryKey; - friend class DbKeyComparator; - -public: - DbConstIndex(const Table &table, uint32 indexId, bool isUniqueIndex); - DbConstIndex(const Table &table, const ReadSection &indexSection); - - const Table &table() const { return mTable; } - - // check if this index can be used for a given query, and if so, generate - // the appropriate index key from the query - bool matchesQuery(const CSSM_QUERY &query, DbQueryKey *&queryKey) const; - - // perform a query on the index - void performQuery(const DbQueryKey &queryKey, - DbIndexIterator &begin, DbIndexIterator &end) const; - - // given an iterator as returned by performQuery(), return the read section for the record - ReadSection getRecordSection(DbIndexIterator iter) const; - -private: - // sorted vector of offsets to index key data - DbOffsetVector mKeyOffsetVector; - - // vector, in same order as key vector, of corresponding record numbers - DbOffsetVector mRecordNumberVector; - - const Table &mTable; -}; - -// A memory-resident index that can be modified, but not used for a query. - -class DbMutableIndex : public DbIndex -{ -public: - DbMutableIndex(const DbConstIndex &index); - DbMutableIndex(const MetaRecord &metaRecord, uint32 indexId, bool isUniqueIndex); - ~DbMutableIndex(); - - // insert a record into the index - void insertRecord(uint32 recordNumber, const ReadSection &packedRecord); - - // remove a record from the index - void removeRecord(uint32 recordNumber); - - // write the index - uint32 writeIndex(WriteSection &ws, uint32 offset); - -private: - // helper methods called by insertRecord() - void insertRecordSingle(uint32 recordOffset, const ReadSection &packedRecord); - void insertRecordMulti(uint32 recordOffset, const ReadSection &packedRecord, - uint32 attributeIndex, WriteSection &keyData, uint32 keySize); - - // a single write section which stores generated index key data - WriteSection mIndexData; - uint32 mIndexDataSize; - - // a map from index keys to record numbers - typedef multimap IndexMap; - IndexMap mMap; -}; - -} // end namespace Security - -#endif // _H_APPLEDL_DBINDEX diff --git a/OSX/include/security_filedb/DbQuery.cpp b/OSX/include/security_filedb/DbQuery.cpp deleted file mode 100644 index 90ed4ca5..00000000 --- a/OSX/include/security_filedb/DbQuery.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#ifdef __MWERKS__ -#define _CPP_DBQUERY -#endif -#include - -DbQuery::DbQuery () -{ -} - -DbQuery::~DbQuery () -{ -} diff --git a/OSX/include/security_filedb/DbQuery.h b/OSX/include/security_filedb/DbQuery.h deleted file mode 100644 index 6a7c38b4..00000000 --- a/OSX/include/security_filedb/DbQuery.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -#ifndef _DBQUERY_H_ -#define _DBQUERY_H_ 1 - -#include - -#ifdef _CPP_DBQUERY -# pragma export on -#endif - -namespace Security -{ - -class DbQuery: public HandleObject -{ - NOCOPY(DbQuery); -public: - DbQuery (); - virtual ~DbQuery (); -}; - -} // end namespace Security - -#ifdef _CPP_DBQUERY -# pragma export off -#endif - -#endif // _DBQUERY_H_ diff --git a/OSX/include/security_filedb/DbValue.cpp b/OSX/include/security_filedb/DbValue.cpp deleted file mode 100644 index f004fa34..00000000 --- a/OSX/include/security_filedb/DbValue.cpp +++ /dev/null @@ -1,555 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DbValue.cpp -// - -#include "DbValue.h" -#include - -// -// DbValue -// - -DbValue::~DbValue() -{ -} - -// -// UInt32Value -// - -UInt32Value::UInt32Value(const ReadSection &rs, uint32 &offset) -: BasicValue(rs.at(offset)) -{ - offset += size(); -} - -UInt32Value::UInt32Value(const CSSM_DATA &data) -{ - switch (data.Length) - { - case 1: - mValue = *reinterpret_cast(data.Data); - break; - case 2: - mValue = *reinterpret_cast(data.Data); - break; - case 4: - mValue = *reinterpret_cast(data.Data); - break; - default: - CssmError::throwMe(CSSMERR_DL_INVALID_VALUE); - } -} - -UInt32Value::~UInt32Value() -{ -} - -void -UInt32Value::pack(WriteSection &ws, uint32 &offset) const -{ - offset = ws.put(offset, mValue); -} - -// -// SInt32Value -// - -SInt32Value::SInt32Value(const ReadSection &rs, uint32 &offset) -: BasicValue(static_cast(rs.at(offset))) -{ - offset += size(); -} - -SInt32Value::SInt32Value(const CSSM_DATA &data) -{ - switch (data.Length) - { - case 1: - mValue = *reinterpret_cast(data.Data); - break; - case 2: - mValue = *reinterpret_cast(data.Data); - break; - case 4: - mValue = *reinterpret_cast(data.Data); - break; - default: - CssmError::throwMe(CSSMERR_DL_INVALID_VALUE); - } -} - -SInt32Value::~SInt32Value() -{ -} - -void -SInt32Value::pack(WriteSection &ws, uint32 &offset) const -{ - offset = ws.put(offset, static_cast(mValue)); -} - -// -// DoubleValue -// - -DoubleValue::DoubleValue(const ReadSection &rs, uint32 &offset) -{ - Range r(offset, (uint32)size()); - mValue = *reinterpret_cast(rs.range(r)); - offset += size(); -} - -DoubleValue::DoubleValue(const CSSM_DATA &data) -{ - switch (data.Length) - { - case 4: - mValue = *reinterpret_cast(data.Data); - break; - case 8: - mValue = *reinterpret_cast(data.Data); - break; - default: - CssmError::throwMe(CSSMERR_DL_INVALID_VALUE); - } -} - -DoubleValue::~DoubleValue() -{ -} - -void -DoubleValue::pack(WriteSection &ws, uint32 &offset) const -{ - offset = ws.put(offset, (uint32)size(), bytes()); -} - -// -// BlobValue -// - -BlobValue::BlobValue(const ReadSection &rs, uint32 &offset) -{ - Length = rs.at(offset); - Data = const_cast(rs.range(Range(offset + AtomSize, (uint32)Length))); - offset = ReadSection::align((uint32)(offset + Length + AtomSize)); -} - -BlobValue::BlobValue(const CSSM_DATA &data) -: CssmData(CssmData::overlay(data)) -{ -} - -BlobValue::~BlobValue() -{ -} - -void -BlobValue::pack(WriteSection &ws, uint32 &offset) const -{ - offset = ws.put(offset, (uint32)Length); - offset = ws.put(offset, (uint32)Length, Data); -} - -BlobValue::Comparator::~Comparator() -{ -} - -int -BlobValue::Comparator::operator () (const uint8 *ptr1, const uint8 *ptr2, uint32 length) -{ - return memcmp(ptr1, ptr2, length); -} - -bool -BlobValue::evaluate(const BlobValue &other, CSSM_DB_OPERATOR op) const -{ - return evaluate(*this, other, op, Comparator()); -} - -bool -BlobValue::evaluate(const CssmData &inData1, const CssmData &inData2, CSSM_DB_OPERATOR op, - Comparator compare) -{ - uint32 length1 = (uint32)inData1.Length, length2 = (uint32)inData2.Length; - const uint8 *data1 = inData1.Data; - const uint8 *data2 = inData2.Data; - - switch (op) { - - case CSSM_DB_CONTAINS_INITIAL_SUBSTRING: - if (length1 > length2) - return false; - length2 = length1; - goto DB_EQUAL; - - case CSSM_DB_CONTAINS_FINAL_SUBSTRING: - if (length1 > length2) - return false; - data2 += (length2 - length1); - length2 = length1; - // dropthrough... - - case CSSM_DB_EQUAL: - DB_EQUAL: - if (length1 != length2) - return false; - if (length1 == 0) - return true; - return compare(data1, data2, length1) == 0; - - case CSSM_DB_NOT_EQUAL: - if (length1 != length2) - return true; - if (length1 == 0) - return false; - return compare(data1, data2, length1) != 0; - - case CSSM_DB_LESS_THAN: - case CSSM_DB_GREATER_THAN: - { - uint32 length = min(length1, length2); - int result = (length == 0) ? 0 : compare(data1, data2, length); - - if (result < 0 || (result == 0 && length1 < length2)) - return op == CSSM_DB_LESS_THAN; - else if (result > 0 || (result == 0 && length1 > length2)) - return op == CSSM_DB_GREATER_THAN; - break; - } - - case CSSM_DB_CONTAINS: - if (length1 > length2) - return false; - if (length1 == 0) - return true; - // Both buffers are at least 1 byte long. - for (const uint8 *data = data2; data + length1 <= data2 + length2; data++) - if (compare(data1, data, length1) == 0) - return true; - break; - - default: - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_QUERY); - } - - return false; -} - -// -// TimeDateValue -// - -TimeDateValue::TimeDateValue(const ReadSection &rs, uint32 &offset) -{ - Length = kTimeDateSize; - Data = const_cast(rs.range(Range(offset, (uint32)Length))); - offset = ReadSection::align(offset + (uint32)Length); -} - -TimeDateValue::TimeDateValue(const CSSM_DATA &data) -: BlobValue(data) -{ - if (Length != kTimeDateSize || !isValidDate()) - CssmError::throwMe(CSSMERR_DL_INVALID_VALUE); -} - -TimeDateValue::~TimeDateValue() -{ -} - -void -TimeDateValue::pack(WriteSection &ws, uint32 &offset) const -{ - offset = ws.put(offset, (uint32)Length, Data); -} - -bool -TimeDateValue::isValidDate() const -{ - if (Length != kTimeDateSize || Data[kTimeDateSize - 1] != 0 || - Data[kTimeDateSize - 2] != 'Z') - return false; - - for (uint32 i = 0; i < kTimeDateSize - 2; i++) - if (!isdigit(Data[i])) - return false; - - uint32 month = rangeValue(4, 2); - if (month < 1 || month > 12) - return false; - - uint32 day = rangeValue(6, 2); - if (day < 1 || day > 31) - return false; - - uint32 hour = rangeValue(8, 2); - if (hour > 23) - return false; - - uint32 minute = rangeValue(10, 2); - if (minute > 59) - return false; - - uint32 second = rangeValue(12, 2); - if (second > 59) - return false; - - return true; -} - -uint32 -TimeDateValue::rangeValue(uint32 start, uint32 length) const -{ - uint32 value = 0; - for (uint32 i = 0; i < length; i++) - value = value * 10 + Data[start + i] - '0'; - return value; -} - -// -// StringValue -// - -StringValue::StringValue(const ReadSection &rs, uint32 &offset) -: BlobValue(rs, offset) -{ -} - -StringValue::StringValue(const CSSM_DATA &data) -: BlobValue(data) -{ -} - -StringValue::~StringValue() -{ -} - -int -StringValue::Comparator::operator () (const uint8 *ptr1, const uint8 *ptr2, uint32 length) -{ - return strncmp(reinterpret_cast(ptr1), - reinterpret_cast(ptr2), length); -} - -bool -StringValue::evaluate(const StringValue &other, CSSM_DB_OPERATOR op) const -{ - return BlobValue::evaluate(*this, other, op, StringValue::Comparator()); -} - -// -// BigNumValue -// - -BigNumValue::BigNumValue(const ReadSection &rs, uint32 &offset) -: BlobValue(rs, offset) -{ -} - -BigNumValue::BigNumValue(const CSSM_DATA &data) -: BlobValue(data) -{ - // remove trailing zero bytes - while (Length > 1 && Data[Length - 1] == 0) - Length--; - - // if the number is zero (positive or negative), make the length zero - if (Length == 1 && (Data[0] & ~kSignBit) == 0) - Length = 0; -} - -BigNumValue::~BigNumValue() -{ -} - -// Walk the contents of two equal-sized bignums, moving backward -// from the high-order bytes, and return the comparison result -// ala memcmp. - -int -BigNumValue::compare(const uint8 *a, const uint8 *b, int length) -{ - for (int diff, i = length - 1; i >= 1; i--) - if ((diff = a[i] - b[i])) - return diff; - - // for the last (i.e. first) byte, mask out the sign bit - return (a[0] & ~kSignBit) - (b[0] & ~kSignBit); -} - -// Compare two bignums, assuming they are in canonical form (i.e., -// no bytes containing trailing zeros. - -bool -BigNumValue::evaluate(const BigNumValue &other, CSSM_DB_OPERATOR op) const -{ - uint32 length1 = (uint32)Length, length2 = (uint32)other.Length; - uint8 sign1 = length1 ? (Data[0] & kSignBit) : 0; - uint8 sign2 = length2 ? (other.Data[0] & kSignBit) : 0; - - switch (op) - { - case CSSM_DB_EQUAL: - case CSSM_DB_NOT_EQUAL: - return BlobValue::evaluate(other, op); - - case CSSM_DB_LESS_THAN: - if (sign1 ^ sign2) - // different signs: return true iff left value is the negative one - return sign1; - else if (length1 != length2) - // in canonical form, shorter numbers have smaller absolute value - return sign1 ? (length1 > length2) : (length1 < length2); - else { - // same length, same sign... - int c = compare(Data, other.Data, length1); - return sign1 ? (c > 0) : (c < 0); - } - break; - - case CSSM_DB_GREATER_THAN: - if (sign1 ^ sign2) - return sign2; - else if (length1 != length2) - return sign1 ? (length1 < length2) : (length1 > length2); - else { - int c = compare(Data, other.Data, length1); - return sign1 ? (c < 0) : (c > 0); - } - break; - - case CSSM_DB_CONTAINS: - case CSSM_DB_CONTAINS_INITIAL_SUBSTRING: - case CSSM_DB_CONTAINS_FINAL_SUBSTRING: - default: - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_QUERY); - } -} - -// -// MultiUInt32Value -// - -MultiUInt32Value::MultiUInt32Value(const ReadSection &rs, uint32 &offset) -{ - // this is relatively expensive, since it copies the data from the - // read section to get the endianness correct - - mNumValues = rs.at(offset); - mValues = new uint32[mNumValues]; - - for (uint32 i = 0; i < mNumValues; i++) - mValues[i] = rs.at(offset + (i + 1) * AtomSize); - - offset = ReadSection::align(offset + (mNumValues + 1) * AtomSize); - mOwnsValues = true; -} - -MultiUInt32Value::MultiUInt32Value(const CSSM_DATA &data) -{ - if (data.Length & (sizeof(uint32) - 1)) - CssmError::throwMe(CSSMERR_DL_INVALID_VALUE); - - mNumValues = (uint32)(data.Length / sizeof(uint32)); - mValues = reinterpret_cast(data.Data); - mOwnsValues = false; -} - -MultiUInt32Value::~MultiUInt32Value() -{ - if (mOwnsValues) - delete [] mValues; -} - -void -MultiUInt32Value::pack(WriteSection &ws, uint32 &offset) const -{ - offset = ws.put(offset, mNumValues); - for (uint32 i = 0; i < mNumValues; i++) - offset = ws.put(offset, mValues[i]); -} - -static inline int -uint32cmp(const uint32 *a, const uint32 *b, uint32 length) -{ - return memcmp(a, b, length * sizeof(uint32)); -} - -bool -MultiUInt32Value::evaluate(const MultiUInt32Value &other, CSSM_DB_OPERATOR op) const -{ - uint32 length1 = mNumValues, length2 = other.mNumValues; - const uint32 *values1 = mValues; - const uint32 *values2 = other.mValues; - - switch (op) - { - case CSSM_DB_EQUAL: - if (length1 == length2) - return uint32cmp(values1, values2, length1) == 0; - break; - - case CSSM_DB_NOT_EQUAL: - if (length1 != length2 || uint32cmp(values1, values2, length1)) - return true; - break; - - case CSSM_DB_CONTAINS_INITIAL_SUBSTRING: - if (length1 <= length2) - return uint32cmp(values1, values2, length1) == 0; - break; - - case CSSM_DB_CONTAINS_FINAL_SUBSTRING: - if (length1 <= length2) - return uint32cmp(values1, values2 + (length2 - length1), length1) == 0; - break; - - case CSSM_DB_CONTAINS: - if (length1 <= length2) { - - if (length1 == 0) - return true; - - for (const uint32 *values = values2; values + length1 < values2 + length2; values++) - if (uint32cmp(values1, values, length1) == 0) - return true; - } - break; - - case CSSM_DB_LESS_THAN: - // this is not required by the spec, but is required to sort indexes over - // multi uint32 keys... - if (length1 < length2) - return true; - else if (length1 == length2) - return uint32cmp(values1, values2, length1) < 0; - break; - - default: - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_QUERY); - } - - return false; -} - - diff --git a/OSX/include/security_filedb/DbValue.h b/OSX/include/security_filedb/DbValue.h deleted file mode 100644 index 1d4fa103..00000000 --- a/OSX/include/security_filedb/DbValue.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// DbValue.h -// - -#ifndef _H_APPLEDL_DBVALUE -#define _H_APPLEDL_DBVALUE - -#include "ReadWriteSection.h" - -#include -#include -#include -#include -#include - -namespace Security -{ - -// -// DbValue -- A base class for all types of database values. -// -class DbValue -{ -public: - virtual ~DbValue(); -}; - -// A collection of subclasses of DbValue that work for simple -// data types, e.g. uint32, sint32, and double, that have -// the usual C comparison and sizeof operations. Defining this -// template saves typing below. - -template -class BasicValue : public DbValue -{ -public: - BasicValue() {} - BasicValue(T value) : mValue(value) {} - - bool evaluate(const BasicValue &other, CSSM_DB_OPERATOR op) const - { - switch (op) { - - case CSSM_DB_EQUAL: - return mValue == other.mValue; - - case CSSM_DB_NOT_EQUAL: - return mValue != other.mValue; - - case CSSM_DB_LESS_THAN: - return mValue < other.mValue; - - case CSSM_DB_GREATER_THAN: - return mValue > other.mValue; - - default: - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_QUERY); - return false; - } - } - - size_t size() const { return sizeof(T); } - size_t size(const ReadSection &rs, uint32 offset) const { return size(); } - const uint8 *bytes() const { return reinterpret_cast(&mValue); } - -protected: - T mValue; -}; - -// Actual useful subclasses of DbValue as instances of BasicValue. -// Note that all of these require a constructor of the form -// (const ReadSection &, uint32 &offset) that advances the offset -// to just after the value. - -class UInt32Value : public BasicValue -{ -public: - UInt32Value(const ReadSection &rs, uint32 &offset); - UInt32Value(const CSSM_DATA &data); - virtual ~UInt32Value(); - void pack(WriteSection &ws, uint32 &offset) const; -}; - -class SInt32Value : public BasicValue -{ -public: - SInt32Value(const ReadSection &rs, uint32 &offset); - SInt32Value(const CSSM_DATA &data); - virtual ~SInt32Value(); - void pack(WriteSection &ws, uint32 &offset) const; -}; - -class DoubleValue : public BasicValue -{ -public: - DoubleValue(const ReadSection &rs, uint32 &offset); - DoubleValue(const CSSM_DATA &data); - virtual ~DoubleValue(); - void pack(WriteSection &ws, uint32 &offset) const; -}; - -// Subclasses of Value for more complex types. - -class BlobValue : public DbValue, public CssmData -{ -public: - BlobValue() {} - BlobValue(const ReadSection &rs, uint32 &offset); - BlobValue(const CSSM_DATA &data); - virtual ~BlobValue(); - void pack(WriteSection &ws, uint32 &offset) const; - bool evaluate(const BlobValue &other, CSSM_DB_OPERATOR op) const; - - size_t size() const { return Length; } - const uint8 *bytes() const { return Data; } - -protected: - class Comparator { - public: - virtual ~Comparator(); - virtual int operator () (const uint8 *ptr1, const uint8 *ptr2, uint32 length); - }; - - static bool evaluate(const CssmData &data1, const CssmData &data2, CSSM_DB_OPERATOR op, - Comparator compare); -}; - -class TimeDateValue : public BlobValue -{ -public: - enum { kTimeDateSize = 16 }; - - TimeDateValue(const ReadSection &rs, uint32 &offset); - TimeDateValue(const CSSM_DATA &data); - virtual ~TimeDateValue(); - void pack(WriteSection &ws, uint32 &offset) const; - - bool isValidDate() const; - -private: - uint32 rangeValue(uint32 start, uint32 length) const; -}; - -class StringValue : public BlobValue -{ -public: - StringValue(const ReadSection &rs, uint32 &offset); - StringValue(const CSSM_DATA &data); - virtual ~StringValue(); - bool evaluate(const StringValue &other, CSSM_DB_OPERATOR op) const; - -private: - class Comparator : public BlobValue::Comparator { - public: - virtual int operator () (const uint8 *ptr1, const uint8 *ptr2, uint32 length); - }; - -}; - -class BigNumValue : public BlobValue -{ -public: - static const uint8 kSignBit = 0x80; - - BigNumValue(const ReadSection &rs, uint32 &offset); - BigNumValue(const CSSM_DATA &data); - virtual ~BigNumValue(); - bool evaluate(const BigNumValue &other, CSSM_DB_OPERATOR op) const; - -private: - static int compare(const uint8 *a, const uint8 *b, int length); -}; - -class MultiUInt32Value : public DbValue -{ -public: - MultiUInt32Value(const ReadSection &rs, uint32 &offset); - MultiUInt32Value(const CSSM_DATA &data); - virtual ~MultiUInt32Value(); - void pack(WriteSection &ws, uint32 &offset) const; - bool evaluate(const MultiUInt32Value &other, CSSM_DB_OPERATOR op) const; - - size_t size() const { return mNumValues * sizeof(uint32); } - const uint8 *bytes() const { return reinterpret_cast(mValues); } - -private: - uint32 mNumValues; - uint32 *mValues; - bool mOwnsValues; -}; - -} // end namespace Security - -#endif // _H_APPLEDL_DBVALUE - diff --git a/OSX/include/security_filedb/MetaAttribute.cpp b/OSX/include/security_filedb/MetaAttribute.cpp deleted file mode 100644 index 7a6214ae..00000000 --- a/OSX/include/security_filedb/MetaAttribute.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// MetaAttribute.cpp -// - -#include "MetaAttribute.h" -#include "MetaRecord.h" - -MetaAttribute::~MetaAttribute() -{ -} - -// Construct an instance of an appropriate subclass of MetaAttribute -// based on the given format. - -MetaAttribute * -MetaAttribute::create(Format format, uint32 attributeIndex, - uint32 attributeId) -{ - switch (format) - { - case CSSM_DB_ATTRIBUTE_FORMAT_STRING: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_SINT32: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_UINT32: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_REAL: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_BLOB: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32: - return new TypedMetaAttribute(format, attributeIndex, attributeId); - - case CSSM_DB_ATTRIBUTE_FORMAT_COMPLEX: - default: - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_FIELD_FORMAT); - } -} - -void -MetaAttribute::packNumberOfValues(WriteSection &ws, uint32 numValues, uint32 &valueOffset) const -{ - uint32 offset = MetaRecord::OffsetAttributeOffsets + mAttributeIndex * AtomSize; - - if (numValues == 0) { - // a zero offset means the attribute has no values - ws.put(offset, 0); - } - else if (numValues == 1) { - // setting the low bit of the offset means that there is exactly one value - ws.put(offset, valueOffset | 1); - } - else { - // write the offset, then write the number of values at that position - ws.put(offset, valueOffset); - valueOffset = ws.put(valueOffset, numValues); - } -} - -void -MetaAttribute::unpackNumberOfValues(const ReadSection &rs, uint32 &numValues, - uint32 &valueOffset) const -{ - uint32 offset = MetaRecord::OffsetAttributeOffsets + mAttributeIndex * AtomSize; - valueOffset = rs[offset]; - - if (valueOffset == 0) - // a zero offset means no values - numValues = 0; - else if (valueOffset & 1) { - // setting the LSB means exactly one value - valueOffset ^= 1; - numValues = 1; - } - else { - // otherwise, the number of values is at the offset, and the values follow - numValues = rs[valueOffset]; - valueOffset += AtomSize; - } -} - -void -MetaAttribute::packAttribute(WriteSection &ws, uint32 &valueOffset, uint32 numValues, - const CSSM_DATA *values) const -{ - packNumberOfValues(ws, numValues, valueOffset); - for (uint32 i = 0; i < numValues; i++) - packValue(ws, valueOffset, values[i]); -} - -void -MetaAttribute::unpackAttribute(const ReadSection &rs, Allocator &allocator, - uint32 &numValues, CSSM_DATA *&values) const -{ - uint32 valueOffset; - unpackNumberOfValues(rs, numValues, valueOffset); - - // Rough check for number of values; will be more like 10 or 20 - if (numValues > 1024) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - values = reinterpret_cast(allocator.malloc(numValues * sizeof(CSSM_DATA))); - - for (uint32 i = 0; i < numValues; i++) - unpackValue(rs, valueOffset, values[i], allocator); -} - -uint32 -MetaAttribute::getNumberOfValues(const ReadSection &rs) const -{ - uint32 numValues, valueOffset; - unpackNumberOfValues(rs, numValues, valueOffset); - return numValues; -} - -void -MetaAttribute::copyValueBytes(uint32 valueIndex, const ReadSection &rs, WriteSection &ws, - uint32 &writeOffset) const -{ - uint32 numValues, valueOffset; - unpackNumberOfValues(rs, numValues, valueOffset); - - // skip bytes before the desired value - for (uint32 i = 0; i < valueIndex; i++) - skipValue(rs, valueOffset); - - // copy the value bytes into the write section - copyValue(rs, valueOffset, ws, writeOffset); -} diff --git a/OSX/include/security_filedb/MetaAttribute.h b/OSX/include/security_filedb/MetaAttribute.h deleted file mode 100644 index 1456cd3a..00000000 --- a/OSX/include/security_filedb/MetaAttribute.h +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// MetaAttribute.h -// - -#ifndef _H_APPLEDL_METAATTRIBUTE -#define _H_APPLEDL_METAATTRIBUTE - -#include "DbValue.h" -#include - -namespace Security -{ - -// A base class for all meta attributes. - -class MetaAttribute -{ -public: - typedef CSSM_DB_ATTRIBUTE_FORMAT Format; - - virtual ~MetaAttribute(); - - // construct an appropriate subclass of MetaAttribute - static MetaAttribute *create(Format format, uint32 attributeIndex, - uint32 attributeId); - - Format attributeFormat() const { return mFormat; } - uint32 attributeIndex() const { return mAttributeIndex; } - uint32 attributeId() const { return mAttributeId; } - - void packAttribute(WriteSection &ws, uint32 &valueOffset, - uint32 numValues, const CSSM_DATA *values) const; - void unpackAttribute(const ReadSection &rs, Allocator &allocator, - uint32 &numValues, CSSM_DATA *&values) const; - - uint32 getNumberOfValues(const ReadSection &rs) const; - void copyValueBytes(uint32 valueIndex, const ReadSection &rs, WriteSection &ws, - uint32 &writeOffset) const; - - // interface required of all subclasses, implemented with templates below - virtual DbValue *createValue(const CSSM_DATA &data) const = 0; - virtual DbValue *createValue(const ReadSection &rs, uint32 &offset) const = 0; - virtual void packValue(WriteSection &ws, uint32 &offset, const CSSM_DATA &data) const = 0; - virtual void unpackValue(const ReadSection &rs, uint32 &offset, CSSM_DATA &data, - Allocator &allocator) const = 0; - virtual void skipValue(const ReadSection &rs, uint32 &offset) const = 0; - virtual void copyValue(const ReadSection &rs, uint32 &readOffset, WriteSection &ws, - uint32 &writeOffset) const = 0; - virtual bool evaluate(const DbValue *value, const ReadSection &rs, CSSM_DB_OPERATOR op) const = 0; - virtual bool evaluate(const DbValue *value1, const DbValue *value2, CSSM_DB_OPERATOR op) const = 0; - virtual uint32 parse(const CssmData &inData, CSSM_DATA_PTR &outValues) const = 0; - -protected: - MetaAttribute(Format format, uint32 attributeIndex, uint32 attributeId) - : mFormat(format), mAttributeIndex(attributeIndex), mAttributeId(attributeId) {} - - void packNumberOfValues(WriteSection &ws, uint32 numValues, uint32 &valueOffset) const; - void unpackNumberOfValues(const ReadSection &rs, uint32 &numValues, uint32 &valueOffset) const; - - Format mFormat; - uint32 mAttributeIndex; - uint32 mAttributeId; -}; - -// Template used to describe particular subclasses of MetaAttribute - -template -class TypedMetaAttribute : public MetaAttribute -{ -public: - TypedMetaAttribute(Format format, uint32 attributeIndex, uint32 attributeId) - : MetaAttribute(format, attributeIndex, attributeId) {} - - DbValue *createValue(const CSSM_DATA &data) const - { - return new T(data); - } - - DbValue *createValue(const ReadSection &rs, uint32 &offset) const - { - return new T(rs, offset); - } - - void packValue(WriteSection &ws, uint32 &offset, const CSSM_DATA &data) const - { - T value(data); - value.pack(ws, offset); - } - - void unpackValue(const ReadSection &rs, uint32 &offset, CSSM_DATA &data, Allocator &allocator) const - { - T value(rs, offset); - data.Length = value.size(); - - if (data.Length != 0) - { - data.Data = reinterpret_cast(allocator.malloc(data.Length)); - memcpy(data.Data, value.bytes(), data.Length); - } - else - { - data.Data = NULL; - } - } - - void skipValue(const ReadSection &rs, uint32 &offset) const - { - T value(rs, offset); - } - - void copyValue(const ReadSection &rs, uint32 &readOffset, WriteSection &ws, uint32 &writeOffset) const - { - T value(rs, readOffset); - value.pack(ws, writeOffset); - } - - bool evaluate(const DbValue *value, const ReadSection &rs, CSSM_DB_OPERATOR op) const - { - uint32 offset, numValues; - unpackNumberOfValues(rs, numValues, offset); - - /* If any of the values for this attribute match we have a - match. This is the same behaviour that indexes have. */ - for (uint32 ix = 0; ix < numValues; ++ix) - if (dynamic_cast(value)->evaluate(T(rs, offset), op)) - return true; - - return false; - } - - bool evaluate(const DbValue *value1, const DbValue *value2, CSSM_DB_OPERATOR op) const - { - return (dynamic_cast(value1))->evaluate(*dynamic_cast(value2), op); - } - - uint32 parse(const CssmData &inData, CSSM_DATA_PTR &outValues) const - { - return 0; - } -}; - -} // end namespace Security - -#endif // _H_APPLEDL_METAATTRIBUTE diff --git a/OSX/include/security_filedb/MetaRecord.cpp b/OSX/include/security_filedb/MetaRecord.cpp deleted file mode 100644 index 63be9447..00000000 --- a/OSX/include/security_filedb/MetaRecord.cpp +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// MetaRecord.cpp -// - -#include "MetaRecord.h" -#include -#include - - -MetaRecord::MetaRecord(CSSM_DB_RECORDTYPE inRecordType) : - mRecordType(inRecordType) -{ -} - -MetaRecord::MetaRecord(const CSSM_DB_RECORD_ATTRIBUTE_INFO &inInfo) -: mRecordType(inInfo.DataRecordType) -{ - try - { - setRecordAttributeInfo(inInfo); - } - catch (...) - { - for_each_delete(mAttributeVector.begin(), mAttributeVector.end()); - } -} - -MetaRecord::MetaRecord(CSSM_DB_RECORDTYPE inRelationID, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo) : - mRecordType(inRelationID) -{ - try { - for (uint32 anIndex = 0; anIndex < inNumberOfAttributes; anIndex++) - { - string aName; - if (inAttributeInfo[anIndex].AttributeName) - aName = string(inAttributeInfo[anIndex].AttributeName); - - const CssmData *aNameID = NULL; - if (inAttributeInfo[anIndex].AttributeNameID.Length > 0) - aNameID = &CssmData::overlay(inAttributeInfo[anIndex].AttributeNameID); - - uint32 aNumber = inAttributeInfo[anIndex].AttributeId; - createAttribute( - inAttributeInfo[anIndex].AttributeName ? &aName : NULL, - aNameID, aNumber, - inAttributeInfo[anIndex].DataType); - } - } - catch (...) - { - for_each_delete(mAttributeVector.begin(), mAttributeVector.end()); - } -} - -MetaRecord::~MetaRecord() -{ - // for_each_delete(mAttributeVector.begin(), mAttributeVector.end()); - AttributeVector::iterator it = mAttributeVector.begin(); - while (it != mAttributeVector.end()) - { - MetaAttribute* mat = *it++; - if (mat != NULL) - { - delete mat; - } - } -} - -void -MetaRecord::setRecordAttributeInfo(const CSSM_DB_RECORD_ATTRIBUTE_INFO &inInfo) -{ - for (uint32 anIndex = 0; anIndex < inInfo.NumberOfAttributes; anIndex++) - { - switch (inInfo.AttributeInfo[anIndex].AttributeNameFormat) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - { - string aName(inInfo.AttributeInfo[anIndex].Label.AttributeName); - createAttribute(&aName, nil, anIndex, - inInfo.AttributeInfo[anIndex].AttributeFormat); - break; - } - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - { - const CssmData &aNameID = CssmOid::overlay(inInfo.AttributeInfo[anIndex].Label.AttributeOID); - createAttribute(nil, &aNameID, anIndex, - inInfo.AttributeInfo[anIndex].AttributeFormat); - break; - } - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - { - uint32 aNumber = inInfo.AttributeInfo[anIndex].Label.AttributeID; - createAttribute(nil, nil, aNumber, - inInfo.AttributeInfo[anIndex].AttributeFormat); - break; - } - default: - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - break; - } - } -} - -void -MetaRecord::createAttribute(const string *inAttributeName, - const CssmOid *inAttributeOID, - uint32 inAttributeID, - CSSM_DB_ATTRIBUTE_FORMAT inAttributeFormat) -{ - // Index of new element is current size of vector - uint32 anAttributeIndex = (uint32)mAttributeVector.size(); - bool aInsertedAttributeName = false; - bool aInsertedAttributeOID = false; - bool aInsertedAttributeID = false; - - if (inAttributeName) - { - if (!mNameStringMap.insert(NameStringMap::value_type(*inAttributeName, anAttributeIndex)).second) - CssmError::throwMe(CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE); - aInsertedAttributeName = true; - } - try - { - if (inAttributeOID) - { - if (!mNameOIDMap.insert(NameOIDMap::value_type(*inAttributeOID, anAttributeIndex)).second) - CssmError::throwMe(CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE); - aInsertedAttributeOID = true; - } - - if (!mNameIntMap.insert(NameIntMap::value_type(inAttributeID, anAttributeIndex)).second) - CssmError::throwMe(CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE); - aInsertedAttributeID = true; - - // Note: this no longer throws INVALID_FIELD_NAME since the attribute will always have - // an attribute ID by which it is known - - mAttributeVector.push_back(MetaAttribute::create(inAttributeFormat, - anAttributeIndex, inAttributeID)); - } - catch(...) - { - if (aInsertedAttributeName) - mNameStringMap.erase(*inAttributeName); - if (aInsertedAttributeOID) - mNameOIDMap.erase(*inAttributeOID); - if (inAttributeID) - mNameIntMap.erase(inAttributeID); - - throw; - } -} - - -// Create a packed record from the given inputs. -void -MetaRecord::packRecord(WriteSection &inWriteSection, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData) const -{ - uint32 aDataSize; - if (inData) - aDataSize = (uint32)inData->Length; - else - aDataSize = 0; - - inWriteSection.put(OffsetDataSize, aDataSize); - uint32 anOffset = (uint32)(OffsetAttributeOffsets + AtomSize * mAttributeVector.size()); - if (aDataSize) - anOffset = inWriteSection.put(anOffset, aDataSize, inData->Data); - - vector aNumValues(mAttributeVector.size(), ~(uint32)0); - vector aValues(mAttributeVector.size()); - uint32 anIndex; - - if (inAttributes == NULL) - inWriteSection.put(OffsetSemanticInformation, 0); - else - { - inWriteSection.put(OffsetSemanticInformation, inAttributes->SemanticInformation); - - // Put the supplied attribute values into the list of attributes - // and values. - anIndex = inAttributes->NumberOfAttributes; - // Make sure that AttributeData is a valid array. - if (anIndex > 0) - Required(inAttributes->AttributeData); - - while (anIndex-- > 0) - { - CSSM_DB_ATTRIBUTE_DATA &anAttribute = inAttributes->AttributeData[anIndex]; - uint32 anAttributeIndex = attributeIndex(anAttribute.Info); - // Make sure that the caller specified the attribute values in the correct format. - if (anAttribute.Info.AttributeFormat != mAttributeVector[anAttributeIndex]->attributeFormat()) - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); - - // If this attribute was specified before, throw. - if (aNumValues[anAttributeIndex] != ~(uint32)0) - CssmError::throwMe(CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE); - - aNumValues[anAttributeIndex] = anAttribute.NumberOfValues; - aValues[anAttributeIndex] = anAttribute.Value; - } - } - - for (anIndex = 0; anIndex < mAttributeVector.size(); ++anIndex) - { - const MetaAttribute &aMetaAttribute = *mAttributeVector[anIndex]; - uint32 aNumberOfValues = aNumValues[anIndex]; - // Now call the parsingmodule for each attribute that - // wasn't explicitly specified and that has a parsingmodule. - if (aNumberOfValues == ~(uint32)0) - aNumberOfValues = aDataSize == 0 ? 0 : aMetaAttribute.parse(*inData, aValues[anIndex]); - - // XXX When do we throw CSSMERR_DL_MISSING_VALUE? Maybe if an - // attribute is part of a unique index. - - // Now we have a valuelist for this attribute. Let's encode it. - aMetaAttribute.packAttribute(inWriteSection, anOffset, aNumberOfValues, aValues[anIndex]); - } - - inWriteSection.put(OffsetRecordSize, anOffset); - inWriteSection.size(anOffset); -} - -inline void -MetaRecord::unpackAttribute(const ReadSection &inReadSection, - Allocator &inAllocator, - CSSM_DB_ATTRIBUTE_DATA &inoutAttribute) const -{ - const MetaAttribute &aMetaAttribute = metaAttribute(inoutAttribute.Info); - // XXX: See ISSUES on whether AttributeFormat should be an outputvalue or not. - inoutAttribute.Info.AttributeFormat = aMetaAttribute.attributeFormat(); - aMetaAttribute.unpackAttribute(inReadSection, inAllocator, - inoutAttribute.NumberOfValues, - inoutAttribute.Value); -} - -void -MetaRecord::unpackRecord(const ReadSection &inReadSection, - Allocator &inAllocator, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_QUERY_FLAGS inQueryFlags) const -{ - // XXX Use POD wrapper for inoutAttributes here. - TrackingAllocator anAllocator(inAllocator); - - try - { - if (inoutData) - { - // XXX Treat KEY records specially. - - // If inQueryFlags & CSSM_QUERY_RETURN_DATA is true return the raw - // key bits in the CSSM_KEY structure - Range aDataRange = dataRange(inReadSection); - inoutData->Length = aDataRange.mSize; - inoutData->Data = inReadSection.allocCopyRange(aDataRange, anAllocator); - } - - if (inoutAttributes) - { - inoutAttributes->DataRecordType = dataRecordType(); - inoutAttributes->SemanticInformation = semanticInformation(inReadSection); - uint32 anIndex = inoutAttributes->NumberOfAttributes; - - // Make sure that AttributeData is a valid array. - if (anIndex > 0 && inoutAttributes->AttributeData == NULL) - CssmError::throwMe(CSSM_ERRCODE_INVALID_POINTER); - - while (anIndex-- > 0) - { - unpackAttribute(inReadSection, anAllocator, - inoutAttributes->AttributeData[anIndex]); - } - } - } - catch (CssmError e) - { - if (e.osStatus() != CSSMERR_DL_DATABASE_CORRUPT) - { - // clear all pointers so that nothing dangles back to the user - if (inoutData) - { - inoutData->Data = NULL; - } - - if (inoutAttributes) - { - unsigned i; - for (i = 0; i < inoutAttributes->NumberOfAttributes; ++i) - { - CSSM_DB_ATTRIBUTE_DATA& data = inoutAttributes->AttributeData[i]; - - unsigned j; - for (j = 0; j < data.NumberOfValues; ++j) - { - data.Value[j].Data = NULL; - } - - data.Value = NULL; - - if (data.Info.AttributeNameFormat == CSSM_DB_ATTRIBUTE_NAME_AS_STRING) - { - data.Info.Label.AttributeName = NULL; - } - } - } - } - - throw; - } - catch (...) - { - // clear all pointers so that nothing dangles back to the user - if (inoutData) - { - inoutData->Data = NULL; - } - - if (inoutAttributes) - { - unsigned i; - for (i = 0; i < inoutAttributes->NumberOfAttributes; ++i) - { - CSSM_DB_ATTRIBUTE_DATA& data = inoutAttributes->AttributeData[i]; - - unsigned j; - for (j = 0; j < data.NumberOfValues; ++j) - { - data.Value[j].Data = NULL; - } - - data.Value = NULL; - - if (data.Info.AttributeNameFormat == CSSM_DB_ATTRIBUTE_NAME_AS_STRING) - { - data.Info.Label.AttributeName = NULL; - } - } - } - - throw; - } - - - // Don't free anything the trackingAllocator allocated when it is destructed. - anAllocator.commit(); -} - -// Return the index (0 though NumAttributes - 1) of the attribute -// represented by inAttributeInfo - -#ifndef NDEBUG -#define LOG_NAME_AS_STRING_FAIL -#endif -uint32 -MetaRecord::attributeIndex(const CSSM_DB_ATTRIBUTE_INFO &inAttributeInfo) const -{ - uint32 anIndex; - switch (inAttributeInfo.AttributeNameFormat) - { - case CSSM_DB_ATTRIBUTE_NAME_AS_STRING: - { - string aName(inAttributeInfo.Label.AttributeName); - assert(aName.size() < 500); // MDS leak debug - NameStringMap::const_iterator it = mNameStringMap.find(aName); - if (it == mNameStringMap.end()) { - #ifdef LOG_NAME_AS_STRING_FAIL - printf("NAME_AS_STRING failure; attrName %s\n", - inAttributeInfo.Label.AttributeName); - for(it = mNameStringMap.begin(); - it != mNameStringMap.end(); - it++) { - printf("name %s val %d\n", it->first.c_str(), it->second); - } - #endif - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - } - anIndex = it->second; - break; - } - case CSSM_DB_ATTRIBUTE_NAME_AS_OID: - { - const CssmOid &aName = CssmOid::overlay(inAttributeInfo.Label.AttributeOID); - NameOIDMap::const_iterator it = mNameOIDMap.find(aName); - if (it == mNameOIDMap.end()) - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - anIndex = it->second; - break; - } - case CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER: - { - uint32 aName = inAttributeInfo.Label.AttributeID; - NameIntMap::const_iterator it = mNameIntMap.find(aName); - if (it == mNameIntMap.end()) - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - anIndex = it->second; - break; - } - default: - CssmError::throwMe(CSSMERR_DL_INVALID_FIELD_NAME); - break; - } - - return anIndex; -} - -const MetaAttribute & -MetaRecord::metaAttribute(const CSSM_DB_ATTRIBUTE_INFO &inAttributeInfo) const -{ - return *mAttributeVector[attributeIndex(inAttributeInfo)]; -} - -// Create a packed record from the given inputs and the old packed record inReadSection. -void -MetaRecord::updateRecord(const ReadSection &inReadSection, - WriteSection &inWriteSection, - const CssmDbRecordAttributeData *inAttributes, - const CssmData *inData, - CSSM_DB_MODIFY_MODE inModifyMode) const -{ - TrackingAllocator anAllocator(Allocator::standard()); - - // modify the opaque data associated with the record - - uint32 aDataSize; - const uint8 *aDataData = NULL; - - if (inData) - { - // prepare to write new data - aDataSize = (uint32)inData->Length; - aDataData = inData->Data; - } - else - { - // prepare to copy old data - Range aDataRange = dataRange(inReadSection); - aDataSize = aDataRange.mSize; - if (aDataSize) - aDataData = inReadSection.range(aDataRange); - } - - // compute the data offset; this will keep a running total of the record size - uint32 anOffset = (uint32)(OffsetAttributeOffsets + AtomSize * mAttributeVector.size()); - - // write the appropriate data to the new record - inWriteSection.put(OffsetDataSize, aDataSize); - if (aDataSize) - anOffset = inWriteSection.put(anOffset, aDataSize, aDataData); - - // unpack the old attributes since some of them may need to be preserved - - auto_array attributeData(mAttributeVector.size()); - - for (size_t anAttributeIndex = mAttributeVector.size(); anAttributeIndex-- > 0; ) - { - // unpack the old attribute data for this attribute index - const MetaAttribute &attribute = *mAttributeVector[anAttributeIndex]; - attribute.unpackAttribute(inReadSection, anAllocator, - attributeData[anAttributeIndex].NumberOfValues, - attributeData[anAttributeIndex].Value); - } - - // retrieve the currrent semantic information - - uint32 oldSemanticInformation = semanticInformation(inReadSection); - - // process each input attribute as necessary, based on the modification mode - - if (inAttributes == NULL) - { - // make sure the modification mode is NONE, otherwise it's an - // error accordining to the spec - if (inModifyMode != CSSM_DB_MODIFY_ATTRIBUTE_NONE) - CssmError::throwMe(CSSMERR_DL_INVALID_MODIFY_MODE); - } - - else { - - // modify the semantic information - - uint32 inSemanticInformation = inAttributes ? inAttributes->SemanticInformation : 0; - - if (inModifyMode == CSSM_DB_MODIFY_ATTRIBUTE_ADD) - oldSemanticInformation |= inSemanticInformation; - - else if (inModifyMode == CSSM_DB_MODIFY_ATTRIBUTE_DELETE) - oldSemanticInformation &= ~inSemanticInformation; - - else if (inModifyMode == CSSM_DB_MODIFY_ATTRIBUTE_REPLACE) - oldSemanticInformation = inSemanticInformation; - - uint32 anIndex = inAttributes->NumberOfAttributes; - if (anIndex > 0) - Required(inAttributes->AttributeData); - - // modify the attributes - - while (anIndex-- > 0) { - - const CssmDbAttributeData &anAttribute = inAttributes->at(anIndex); - uint32 anAttributeIndex = attributeIndex(anAttribute.info()); - if (anAttribute.format() != mAttributeVector[anAttributeIndex]->attributeFormat()) - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); - - CssmDbAttributeData &oldAttribute = attributeData[anAttributeIndex]; - - // if the modify mode is ADD, merge new values with pre-existing values - - if (inModifyMode == CSSM_DB_MODIFY_ATTRIBUTE_ADD) - oldAttribute.add(anAttribute, anAllocator); - - // if the modify mode is DELETE, remove the indicated values, or remove - // all values if none are specified - - else if (inModifyMode == CSSM_DB_MODIFY_ATTRIBUTE_DELETE) - { - if (anAttribute.size() == 0) - oldAttribute.deleteValues(anAllocator); - else - oldAttribute.deleteValues(anAttribute, anAllocator); - } - - // if the modify mode is REPLACE, then replace the specified values, or - // delete all values if no values are specified - - else if (inModifyMode == CSSM_DB_MODIFY_ATTRIBUTE_REPLACE) - { - oldAttribute.deleteValues(anAllocator); - if (anAttribute.size() > 0) - oldAttribute.add(anAttribute, anAllocator); - else - // The spec says "all values are deleted or the the value is replaced - // with the default" but doesn't say which. We could call the parsing - // module for the attribute here...if they were implemented! But instead - // we choose "all values are deleted" and leave it at that. - ; - } - } - } - - // write the resulting attributes into the new record - - inWriteSection.put(OffsetSemanticInformation, oldSemanticInformation); - - for (uint32 anIndex = 0; anIndex < mAttributeVector.size(); ++anIndex) - { - const MetaAttribute &metaAttribute = *mAttributeVector[anIndex]; - metaAttribute.packAttribute(inWriteSection, anOffset, - attributeData[anIndex].NumberOfValues, - attributeData[anIndex].Value); - } - - inWriteSection.put(OffsetRecordSize, anOffset); - inWriteSection.size(anOffset); -} - diff --git a/OSX/include/security_filedb/MetaRecord.h b/OSX/include/security_filedb/MetaRecord.h deleted file mode 100644 index f119772d..00000000 --- a/OSX/include/security_filedb/MetaRecord.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// MetaRecord.h -// - -#ifndef _H_APPLEDL_METARECORD -#define _H_APPLEDL_METARECORD - -#include "MetaAttribute.h" - -namespace Security -{ - -// -// Part of the Unique record identifier needed to identify the actual record. -// -class RecordId -{ -public: - RecordId() : mRecordNumber(~(uint32)0), mCreateVersion(~(uint32)0), mRecordVersion(~(uint32)0) {} - RecordId(uint32 inRecordNumber, uint32 inCreateVersion, uint32 inRecordVersion = 0) - : mRecordNumber(inRecordNumber), - mCreateVersion(inCreateVersion), - mRecordVersion(inRecordVersion) {} - bool operator <(const RecordId &inRecordId) const - { - return (mRecordNumber < inRecordId.mRecordNumber - || (mRecordNumber == inRecordId.mRecordNumber - && (mCreateVersion < inRecordId.mCreateVersion - || (mCreateVersion == inRecordId.mCreateVersion - && mRecordVersion < inRecordId.mRecordVersion)))); - } - uint32 mRecordNumber; - uint32 mCreateVersion; - uint32 mRecordVersion; -}; - -// -// Meta (or Schema) representation of an a Record. Used for packing and unpacking objects. -// - -class MetaRecord -{ - NOCOPY(MetaRecord) - -public: - MetaRecord(CSSM_DB_RECORDTYPE inRecordType); - MetaRecord(const CSSM_DB_RECORD_ATTRIBUTE_INFO &inInfo); - MetaRecord(CSSM_DB_RECORDTYPE inRelationID, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *inAttributeInfo); - ~MetaRecord(); - - void setRecordAttributeInfo(const CSSM_DB_RECORD_ATTRIBUTE_INFO &inInfo); - - void createAttribute(const string *inAttributeName, - const CssmOid *inAttributeOID, - uint32 inAttributeID, - CSSM_DB_ATTRIBUTE_FORMAT inAttributeFormat); - - // Create a packed record from the given inputs. - void packRecord(WriteSection &inWriteSection, - const CSSM_DB_RECORD_ATTRIBUTE_DATA *inAttributes, - const CssmData *inData) const; - - // Unpack a record from the given inputs and return the RecordId of the record. - void unpackRecord(const ReadSection &inReadSection, - Allocator &inAllocator, - CSSM_DB_RECORD_ATTRIBUTE_DATA_PTR inoutAttributes, - CssmData *inoutData, - CSSM_QUERY_FLAGS inQueryFlags) const; - - const MetaAttribute &metaAttribute(const CSSM_DB_ATTRIBUTE_INFO &inAttributeInfo) const; - - void updateRecord(const ReadSection &inReadSection, - WriteSection &inWriteSection, - const CssmDbRecordAttributeData *inAttributes, - const CssmData *inData, - CSSM_DB_MODIFY_MODE inModifyMode) const; - - CSSM_DB_RECORDTYPE dataRecordType() const { return mRecordType; } - - Range dataRange(const ReadSection &inReadSection) const - { - return Range((uint32)(OffsetAttributeOffsets + mAttributeVector.size() * AtomSize), - inReadSection[OffsetDataSize]); - } - - // Currently this is not a real attribute. We should probably fix this. - uint32 semanticInformation(const ReadSection &inReadSection) const - { - return inReadSection[OffsetSemanticInformation]; - } - - // Return the ReadSection for record at offset - static const ReadSection readSection(const ReadSection &inTableSection, uint32 inOffset) - { - return inTableSection.subsection(inOffset, - inTableSection[inOffset + OffsetRecordSize]); - } - - // Set the RecordId of the record in inWriteSection - static void packRecordId(const RecordId &inRecordId, - WriteSection &inWriteSection) - { - inWriteSection.put(OffsetRecordNumber, inRecordId.mRecordNumber); - inWriteSection.put(OffsetCreateVersion, inRecordId.mCreateVersion); - inWriteSection.put(OffsetRecordVersion, inRecordId.mRecordVersion); - } - - // Return the RecordId for the record inRecordSection - static const uint32 unpackRecordNumber(const ReadSection &inRecordSection) - { - return inRecordSection[OffsetRecordNumber]; - } - - // Return the RecordId for the record inRecordSection - static const RecordId unpackRecordId(const ReadSection &inRecordSection) - { - return RecordId(inRecordSection[OffsetRecordNumber], - inRecordSection[OffsetCreateVersion], - inRecordSection[OffsetRecordVersion]); - } - -private: - // Return the index (0 though NumAttributes - 1) of the attribute - // represented by inAttributeInfo - uint32 attributeIndex(const CSSM_DB_ATTRIBUTE_INFO &inAttributeInfo) const; - - void unpackAttribute(const ReadSection &inReadSection, Allocator &inAllocator, - CSSM_DB_ATTRIBUTE_DATA &inoutAttribute) const; - - friend class MetaAttribute; - enum - { - OffsetRecordSize = AtomSize * 0, - OffsetRecordNumber = AtomSize * 1, - OffsetCreateVersion = AtomSize * 2, - OffsetRecordVersion = AtomSize * 3, - OffsetDataSize = AtomSize * 4, - OffsetSemanticInformation = AtomSize * 5, - OffsetAttributeOffsets = AtomSize * 6 - }; - - CSSM_DB_RECORDTYPE mRecordType; - typedef std::map NameStringMap; - typedef std::map, uint32> NameOIDMap; - typedef std::map NameIntMap; - typedef std::vector AttributeVector; - NameStringMap mNameStringMap; - NameOIDMap mNameOIDMap; - NameIntMap mNameIntMap; - AttributeVector mAttributeVector; -}; - -} // end namespace Security - -#endif // _H_APPLEDL_METARECORD - diff --git a/OSX/include/security_filedb/OverUnderflowCheck.h b/OSX/include/security_filedb/OverUnderflowCheck.h deleted file mode 100644 index 7224ac77..00000000 --- a/OSX/include/security_filedb/OverUnderflowCheck.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef __OVERUNDERFLOWCHECK__ -#define __OVERUNDERFLOWCHECK__ - -inline uint32 CheckUInt32Add(uint32 a, uint32 b) -{ - uint32 c = a + b; - if (c < a) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - return c; -} - - - -inline uint32 CheckUInt32Subtract(uint32 a, uint32 b) -{ - if (a < b) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - return a - b; -} - - - -inline uint32 CheckUInt32Multiply(uint32 a, uint32 b) -{ - uint32 c = a * b; - uint64 cc = ((uint64) a) * ((uint64) b); - if (c != cc) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - return c; -} - - - -inline uint64 Check64BitAdd(uint64 a, uint64 b) -{ - uint64 c = a + b; - if (c < a) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - return c; -} - - - -inline uint64 Check64BitSubtract(uint64 a, uint64 b) -{ - if (a < b) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - return a - b; -} - - - -inline uint64 Check64BitMultiply(uint64 a, uint64 b) -{ - if (a != 0) - { - uint64 max = (uint64) -1; - uint64 limit = max / a; - if (b > limit) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - } - - return a * b; -} - - - -#endif diff --git a/OSX/include/security_filedb/ReadWriteSection.cpp b/OSX/include/security_filedb/ReadWriteSection.cpp deleted file mode 100644 index 9fe1b489..00000000 --- a/OSX/include/security_filedb/ReadWriteSection.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "ReadWriteSection.h" - -uint32 WriteSection::put(uint32 inOffset, uint32 inValue) -{ - uint32 aLength = CheckUInt32Add(inOffset, sizeof(inValue)); - if (aLength > mCapacity) - grow(aLength); - - if (mAddress == NULL) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - *reinterpret_cast(mAddress + inOffset) = htonl(inValue); - return aLength; -} - - - -uint32 WriteSection::put(uint32 inOffset, uint32 inLength, const uint8 *inData) -{ - // if we are being asked to put 0 bytes, just return - if (inLength == 0 || inData == NULL) - { - return inOffset; - } - - uint32 aLength = CheckUInt32Add(inOffset, inLength); - - // Round up to nearest multiple of 4 bytes, to pad with zeros - uint32 aNewOffset = align(aLength); - if (aNewOffset > mCapacity) - grow(aNewOffset); - - if (mAddress == NULL) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - memcpy(mAddress + inOffset, inData, inLength); - - for (uint32 anOffset = aLength; anOffset < aNewOffset; anOffset++) - mAddress[anOffset] = 0; - - return aNewOffset; -} - - - -void WriteSection::grow(size_t inNewCapacity) -{ - size_t n = CheckUInt32Multiply((uint32)mCapacity, 2); - size_t aNewCapacity = max(n, inNewCapacity); - mAddress = reinterpret_cast(mAllocator.realloc(mAddress, aNewCapacity)); - - if (mAddress == NULL) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - memset(mAddress + mCapacity, 0, aNewCapacity - mCapacity); - mCapacity = aNewCapacity; -} diff --git a/OSX/include/security_filedb/ReadWriteSection.h b/OSX/include/security_filedb/ReadWriteSection.h deleted file mode 100644 index f77e8c4c..00000000 --- a/OSX/include/security_filedb/ReadWriteSection.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// ReadWriteSection.h -// - -#ifndef _H_APPLEDL_READWRITESECTION -#define _H_APPLEDL_READWRITESECTION - -#include -#include -#include -#include -#include -#include "OverUnderflowCheck.h" - -namespace Security -{ - -// -// Atom -- An Atom is a 32-bit unsigned integer value that is always internally -// represented using network byte order. -// -typedef Endian Atom; - -enum { - AtomSize = sizeof(uint32) // XXX Why not just use sizeof(Atom)? -}; - -// -// Class representing a range (or subrange of a buffer). -// -class Range -{ -public: - Range(uint32 inOffset, uint32 inSize) : mOffset(inOffset), mSize(inSize) {} - uint32 mOffset; - uint32 mSize; -}; - -// -// Class representing a packed record. All the accessors on this class are const since the -// underlying data is read-only -// -// XXX Should be replaced by Atom::Vector -class ReadSection -{ -protected: - ReadSection(uint8 *inAddress, size_t inLength) : mAddress(inAddress), mLength(inLength) - { - if (mAddress == NULL) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } -public: - ReadSection() : mAddress(NULL), mLength(0) {} - ReadSection(const uint8 *inAddress, size_t inLength) : - mAddress(const_cast(inAddress)), mLength(inLength) {} - - uint32 size() const { return (uint32)mLength; } - - uint32 at(uint32 inOffset) const - { - if (inOffset > mLength) - { - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - } - - return ntohl(*reinterpret_cast(mAddress + inOffset)); - } - - uint32 operator[](uint32 inOffset) const - { - return at(inOffset); - } - - // Return a subsection from inOffset to end of section. - ReadSection subsection(uint32 inOffset) const - { - if (inOffset > mLength) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - return ReadSection(mAddress + inOffset, mLength - inOffset); - } - - // Return a subsection from inOffset of inLength bytes. - ReadSection subsection(uint32 inOffset, uint32 inLength) const - { - if (CheckUInt32Add(inOffset, inLength) > mLength) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - return ReadSection(mAddress + inOffset, inLength); - } - - ReadSection subsection(const Range &inRange) const - { - return subsection(inRange.mOffset, inRange.mSize); - } - - const uint8 *range(const Range &inRange) const - { - if (CheckUInt32Add(inRange.mOffset, inRange.mSize) > mLength) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - return mAddress + inRange.mOffset; - } - - uint8 *allocCopyRange(const Range &inRange, Allocator &inAllocator) const - { - uint8 *aData; - if (inRange.mSize == 0) - aData = NULL; - else - { - if (CheckUInt32Add(inRange.mOffset, inRange.mSize) > mLength) - CssmError::throwMe(CSSMERR_DL_DATABASE_CORRUPT); - - aData = reinterpret_cast(inAllocator.malloc(inRange.mSize)); - memcpy(aData, mAddress + inRange.mOffset, inRange.mSize); - } - - return aData; - } - - static uint32 align(uint32 offset) { return (CheckUInt32Subtract(CheckUInt32Add(offset, AtomSize), 1)) & ~(AtomSize - 1); } - -protected: - uint8 *mAddress; - size_t mLength; -}; - -// -// Class representing a packed record (or buffer) used for writing. -// -class WriteSection : public ReadSection -{ -public: - static const size_t DefaultCapacity = 64; - - WriteSection(Allocator &inAllocator, size_t inCapacity) : - ReadSection(reinterpret_cast(inAllocator.malloc(inCapacity)), 0), - mAllocator(inAllocator), - mCapacity(inCapacity) - { - if (mCapacity > 0) - memset(mAddress, 0, mCapacity); - } - - WriteSection(Allocator &inAllocator = Allocator::standard()) : - ReadSection(reinterpret_cast(inAllocator.malloc(DefaultCapacity)), 0), - mAllocator(inAllocator), - mCapacity(DefaultCapacity) - { - } - - WriteSection(const WriteSection &ws, int length) : - ReadSection(reinterpret_cast(ws.mAllocator.malloc(length)), length), - mAllocator(ws.mAllocator), - mCapacity(length) - { - memcpy(mAddress, ws.mAddress, length); - } - - ~WriteSection() { mAllocator.free(mAddress); } - -private: - void grow(size_t inNewCapacity); - -public: -#if BUG_GCC - uint32 size() const { return ReadSection::size(); } -#else - // XXX This should work but egcs-2.95.2 doesn't like it. - using ReadSection::size; -#endif - - void size(uint32 inLength) { mLength = inLength; } - uint32 put(uint32 inOffset, uint32 inValue); - uint32 put(uint32 inOffset, uint32 inLength, const uint8 *inData); - - const uint8 *address() const { return mAddress; } - uint8 *release() - { - uint8 *anAddress = mAddress; - mAddress = NULL; - mCapacity = 0; - return anAddress; - } - -private: - Allocator &mAllocator; - size_t mCapacity; -}; - -} // end namespace Security - -#endif // _H_APPLEDL_READWRITESECTION diff --git a/OSX/include/security_filedb/SelectionPredicate.cpp b/OSX/include/security_filedb/SelectionPredicate.cpp deleted file mode 100644 index fe9efaf0..00000000 --- a/OSX/include/security_filedb/SelectionPredicate.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// SelectionPredicate.cpp -// - -#include "SelectionPredicate.h" - -SelectionPredicate::SelectionPredicate(const MetaRecord &inMetaRecord, - const CSSM_SELECTION_PREDICATE &inPredicate) -: mMetaAttribute(inMetaRecord.metaAttribute(inPredicate.Attribute.Info)), - mDbOperator(inPredicate.DbOperator) -{ - // Make sure that the caller specified the attribute values in the correct format. - if (inPredicate.Attribute.Info.AttributeFormat != mMetaAttribute.attributeFormat()) - CssmError::throwMe(CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT); - - // XXX See ISSUES - if (inPredicate.Attribute.NumberOfValues != 1) - CssmError::throwMe(CSSMERR_DL_UNSUPPORTED_QUERY); - - mData = inPredicate.Attribute.Value[0]; - mValue = mMetaAttribute.createValue(mData); -} - -SelectionPredicate::~SelectionPredicate() -{ - delete mValue; -} - -bool -SelectionPredicate::evaluate(const ReadSection &rs) const -{ - return mMetaAttribute.evaluate(mValue, rs, mDbOperator); -} diff --git a/OSX/include/security_filedb/SelectionPredicate.h b/OSX/include/security_filedb/SelectionPredicate.h deleted file mode 100644 index a0a14c2a..00000000 --- a/OSX/include/security_filedb/SelectionPredicate.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. - * - * The contents of this file constitute Original Code as defined in and are - * subject to the Apple Public Source License Version 1.2 (the 'License'). - * You may not use this file except in compliance with the License. Please obtain - * a copy of the License at http://www.apple.com/publicsource and read it before - * using this file. - * - * This Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS - * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT - * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR - * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the - * specific language governing rights and limitations under the License. - */ - - -// -// SelectionPredicate.h -// - -#ifndef _H_APPLEDL_SELECTIONPREDICATE -#define _H_APPLEDL_SELECTIONPREDICATE - -#include "MetaRecord.h" -#include - -namespace Security -{ - -class SelectionPredicate -{ - NOCOPY(SelectionPredicate) - -public: - SelectionPredicate(const MetaRecord &inMetaRecord, - const CSSM_SELECTION_PREDICATE &inPredicate); - ~SelectionPredicate(); - - bool evaluate(const ReadSection &inReadSection) const; - -private: - const MetaAttribute &mMetaAttribute; - CSSM_DB_OPERATOR mDbOperator; - CssmDataContainer mData; - DbValue *mValue; -}; - -} // end namespace Security - -#endif // _H_APPLEDL_SELECTIONPREDICATE diff --git a/OSX/include/security_keychain b/OSX/include/security_keychain new file mode 120000 index 00000000..aac53b6d --- /dev/null +++ b/OSX/include/security_keychain @@ -0,0 +1 @@ +./libsecurity_keychain/lib \ No newline at end of file diff --git a/OSX/include/security_keychain/ACL.cpp b/OSX/include/security_keychain/ACL.cpp deleted file mode 100644 index 9b655a69..00000000 --- a/OSX/include/security_keychain/ACL.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// ACL.cpp -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -using namespace KeychainCore; -using namespace DataWalkers; - - -// -// The default form of a prompt selector -// -const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR ACL::defaultSelector = { - CSSM_ACL_KEYCHAIN_PROMPT_CURRENT_VERSION, 0 -}; - - -// -// ACL static constants -// -const CSSM_ACL_HANDLE ACL::ownerHandle; - - -// -// Create an ACL object from the result of a CSSM ACL query -// -ACL::ACL(Access &acc, const AclEntryInfo &info, Allocator &alloc) - : allocator(alloc), access(acc), mState(unchanged), mSubjectForm(NULL), mMutex(Mutex::recursive) -{ - // parse the subject - parse(info.proto().subject()); - - // fill in AclEntryInfo layer information - const AclEntryPrototype &proto = info.proto(); - mAuthorizations = proto.authorization(); - mDelegate = proto.delegate(); - mEntryTag = proto.s_tag(); - - // take CSSM entry handle from info layer - mCssmHandle = info.handle(); -} - -ACL::ACL(Access &acc, const AclOwnerPrototype &owner, Allocator &alloc) - : allocator(alloc), access(acc), mState(unchanged), mSubjectForm(NULL), mMutex(Mutex::recursive) -{ - // parse subject - parse(owner.subject()); - - // for an owner "entry", the next-layer information is fixed (and fake) - mAuthorizations.insert(CSSM_ACL_AUTHORIZATION_CHANGE_ACL); - mDelegate = owner.delegate(); - mEntryTag[0] = '\0'; - - // use fixed (fake) entry handle - mCssmHandle = ownerHandle; -} - - -// -// Create a new ACL that authorizes anyone to do anything. -// This constructor produces a "pure" ANY ACL, without descriptor or selector. -// To generate a "standard" form of ANY, use the appListForm constructor below, -// then change its form to allowAnyForm. -// -ACL::ACL(Access &acc, Allocator &alloc) - : allocator(alloc), access(acc), mSubjectForm(NULL), mMutex(Mutex::recursive) -{ - mState = inserted; // new - mForm = allowAllForm; // everybody - mAuthorizations.insert(CSSM_ACL_AUTHORIZATION_ANY); // anything - mDelegate = false; - - //mPromptDescription stays empty - mPromptSelector = defaultSelector; - - // randomize the CSSM handle - UniformRandomBlobs().random(mCssmHandle); -} - - -// -// Create a new ACL in standard form. -// As created, it authorizes all activities. -// -ACL::ACL(Access &acc, string description, const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR &promptSelector, - Allocator &alloc) - : allocator(alloc), access(acc), mSubjectForm(NULL), mMutex(Mutex::recursive) -{ - mState = inserted; // new - mForm = appListForm; - mAuthorizations.insert(CSSM_ACL_AUTHORIZATION_ANY); // anything - mDelegate = false; - - mPromptDescription = description; - mPromptSelector = promptSelector; - - // randomize the CSSM handle - UniformRandomBlobs().random(mCssmHandle); -} - - -// -// Destroy an ACL -// -ACL::~ACL() -{ - // release subject form (if any) - chunkFree(mSubjectForm, allocator); -} - - -// -// Does this ACL authorize a particular right? -// -bool ACL::authorizes(AclAuthorization right) -{ - StLock_(mMutex); - return mAuthorizations.find(right) != mAuthorizations.end() - || mAuthorizations.find(CSSM_ACL_AUTHORIZATION_ANY) != mAuthorizations.end() - || mAuthorizations.empty(); -} - - -// -// Add an application to the trusted-app list of this ACL. -// Will fail unless this is a standard "simple" form ACL. -// -void ACL::addApplication(TrustedApplication *app) -{ - StLock_(mMutex); - switch (mForm) { - case appListForm: // simple... - mAppList.push_back(app); - modify(); - break; - case allowAllForm: // hmm... - if (!mPromptDescription.empty()) { - // verbose "any" form (has description, "any" override) - mAppList.push_back(app); - modify(); - break; - } - // pure "any" form without description. Cannot convert to appListForm - default: - MacOSError::throwMe(errSecACLNotSimple); - } -} - - -// -// Mark an ACL as modified. -// -void ACL::modify() -{ - StLock_(mMutex); - if (mState == unchanged) { - secdebug("SecAccess", "ACL %p marked modified", this); - mState = modified; - } -} - - -// -// Mark an ACL as "removed" -// Removed ACLs have no valid contents (they are invalid on their face). -// When "updated" to the originating item, they will cause the corresponding -// ACL entry to be deleted. Otherwise, they are irrelevant. -// Note: Removing an ACL does not actually remove it from its Access's map. -// -void ACL::remove() -{ - StLock_(mMutex); - mAppList.clear(); - mForm = invalidForm; - mState = deleted; -} - - -// -// Produce CSSM-layer form (ACL prototype) copies of our content. -// Note that the result is chunk-allocated, and becomes owned by the caller. -// -void ACL::copyAclEntry(AclEntryPrototype &proto, Allocator &alloc) -{ - StLock_(mMutex); - proto.clearPod(); // preset - - // carefully copy the subject - makeSubject(); - assert(mSubjectForm); - proto = AclEntryPrototype(*mSubjectForm, mDelegate); // shares subject - ChunkCopyWalker w(alloc); - walk(w, proto.subject()); // copy subject in-place - - // the rest of a prototype - proto.tag(mEntryTag); - AuthorizationGroup tags(mAuthorizations, allocator); - proto.authorization() = tags; -} - -void ACL::copyAclOwner(AclOwnerPrototype &proto, Allocator &alloc) -{ - StLock_(mMutex); - proto.clearPod(); - - makeSubject(); - assert(mSubjectForm); - proto = AclOwnerPrototype(*mSubjectForm, mDelegate); // shares subject - ChunkCopyWalker w(alloc); - walk(w, proto.subject()); // copy subject in-place -} - - -// -// (Re)place this ACL's setting into the AclBearer specified. -// If update, assume this is an update operation and the ACL was -// originally derived from this object; specifically, assume the -// CSSM handle is valid. If not update, assume this is a different -// object that has no related ACL entry (yet). -// -void ACL::setAccess(AclBearer &target, bool update, - const AccessCredentials *cred) -{ - StLock_(mMutex); - // determine what action we need to perform - State action = state(); - if (!update) - action = (action == deleted) ? unchanged : inserted; - - // the owner acl (pseudo) "entry" is a special case - if (isOwner()) { - switch (action) { - case unchanged: - secdebug("SecAccess", "ACL %p owner unchanged", this); - return; - case inserted: // means modify the initial owner - case modified: - { - secdebug("SecAccess", "ACL %p owner modified", this); - makeSubject(); - assert(mSubjectForm); - AclOwnerPrototype proto(*mSubjectForm, mDelegate); - target.changeOwner(proto, cred); - return; - } - default: - assert(false); - return; - } - } - - // simple cases - switch (action) { - case unchanged: // ignore - secdebug("SecAccess", "ACL %p handle 0x%lx unchanged", this, entryHandle()); - return; - case deleted: // delete - secdebug("SecAccess", "ACL %p handle 0x%lx deleted", this, entryHandle()); - target.deleteAcl(entryHandle(), cred); - return; - default: - break; - } - - // build the byzantine data structures that CSSM loves so much - makeSubject(); - assert(mSubjectForm); - AclEntryPrototype proto(*mSubjectForm, mDelegate); - proto.tag(mEntryTag); - AutoAuthorizationGroup tags(mAuthorizations, allocator); - proto.authorization() = tags; - AclEntryInput input(proto); - switch (action) { - case inserted: // insert - secdebug("SecAccess", "ACL %p inserted", this); - target.addAcl(input, cred); - break; - case modified: // update - secdebug("SecAccess", "ACL %p handle 0x%lx modified", this, entryHandle()); - target.changeAcl(entryHandle(), input, cred); - break; - default: - assert(false); - } -} - - -// -// Parse an AclEntryPrototype (presumably from a CSSM "Get" ACL operation -// into internal form. -// -void ACL::parse(const TypedList &subject) -{ - StLock_(mMutex); - try { - switch (subject.type()) { - case CSSM_ACL_SUBJECT_TYPE_ANY: - // subsume an "any" as a standard form - mForm = allowAllForm; - return; - case CSSM_ACL_SUBJECT_TYPE_KEYCHAIN_PROMPT: - // pure keychain prompt - interpret as applist form with no apps - parsePrompt(subject); - mForm = appListForm; - return; - case CSSM_ACL_SUBJECT_TYPE_THRESHOLD: - { - // app-list format: THRESHOLD(1, n): sign(1), ..., sign(n), PROMPT - if (subject[1] != 1) - throw ParseError(); - uint32 count = subject[2]; - - // parse final (PROMPT) element - TypedList &end = subject[count + 2]; // last choice - if (end.type() != CSSM_ACL_SUBJECT_TYPE_KEYCHAIN_PROMPT) - throw ParseError(); // not PROMPT at end - parsePrompt(end); - - // check for leading ANY - TypedList &first = subject[3]; - if (first.type() == CSSM_ACL_SUBJECT_TYPE_ANY) { - mForm = allowAllForm; - return; - } - - // parse other (code signing) elements - for (uint32 n = 0; n < count - 1; n++) - mAppList.push_back(new TrustedApplication(TypedList(subject[n + 3].list()))); - } - mForm = appListForm; - return; - default: - mForm = customForm; - mSubjectForm = chunkCopy(&subject); - return; - } - } catch (const ParseError &) { - secdebug("SecAccess", "acl compile failed; marking custom"); - mForm = customForm; - mSubjectForm = chunkCopy(&subject); - mAppList.clear(); - } -} - -void ACL::parsePrompt(const TypedList &subject) -{ - StLock_(mMutex); - assert(subject.length() == 3); - mPromptSelector = - *subject[1].data().interpretedAs(CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE); - mPromptDescription = subject[2].toString(); -} - - -// -// Take this ACL and produce its meaning as a CSSM ACL subject in mSubjectForm -// -void ACL::makeSubject() -{ - StLock_(mMutex); - switch (form()) { - case allowAllForm: - chunkFree(mSubjectForm, allocator); // release previous - if (mPromptDescription.empty()) { - // no description -> pure ANY - mSubjectForm = new(allocator) TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_ANY); - } else { - // have description -> threshold(1 of 2) of { ANY, PROMPT } - mSubjectForm = new(allocator) TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_THRESHOLD, - new(allocator) ListElement(1), - new(allocator) ListElement(2)); - *mSubjectForm += new(allocator) ListElement(TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_ANY)); - TypedList prompt(allocator, CSSM_ACL_SUBJECT_TYPE_KEYCHAIN_PROMPT, - new(allocator) ListElement(allocator, CssmData::wrap(mPromptSelector)), - new(allocator) ListElement(allocator, mPromptDescription)); - *mSubjectForm += new(allocator) ListElement(prompt); - } - return; - case appListForm: { - // threshold(1 of n+1) of { app1, ..., appn, PROMPT } - chunkFree(mSubjectForm, allocator); // release previous - uint32 appCount = (uint32)mAppList.size(); - mSubjectForm = new(allocator) TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_THRESHOLD, - new(allocator) ListElement(1), - new(allocator) ListElement(appCount + 1)); - for (uint32 n = 0; n < appCount; n++) - *mSubjectForm += - new(allocator) ListElement(mAppList[n]->makeSubject(allocator)); - TypedList prompt(allocator, CSSM_ACL_SUBJECT_TYPE_KEYCHAIN_PROMPT, - new(allocator) ListElement(allocator, CssmData::wrap(mPromptSelector)), - new(allocator) ListElement(allocator, mPromptDescription)); - *mSubjectForm += new(allocator) ListElement(prompt); - } - return; - case customForm: - assert(mSubjectForm); // already set; keep it - return; - default: - assert(false); // unexpected - } -} diff --git a/OSX/include/security_keychain/ACL.h b/OSX/include/security_keychain/ACL.h deleted file mode 100644 index 5ad2a2df..00000000 --- a/OSX/include/security_keychain/ACL.h +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// ACL.h - ACL control wrappers -// -#ifndef _SECURITY_ACL_H_ -#define _SECURITY_ACL_H_ - -#include -#include -#include -#include -#include -#include "SecCFTypes.h" - -#include - -namespace Security { -namespace KeychainCore { - -using CssmClient::AclBearer; - -class Access; -class TrustedApplication; - - -// -// An ACL Entry for an Access object -// -class ACL : public SecCFObject { - NOCOPY(ACL) -public: - SECCFFUNCTIONS(ACL, SecACLRef, errSecInvalidItemRef, gTypes().ACL) - - // create from CSSM layer ACL entry - ACL(Access &acc, const AclEntryInfo &info, - Allocator &alloc = Allocator::standard()); - // create from CSSM layer owner prototype - ACL(Access &acc, const AclOwnerPrototype &owner, - Allocator &alloc = Allocator::standard()); - // create an "any" ACL - ACL(Access &acc, Allocator &alloc = Allocator::standard()); - // create from "standard form" arguments (with empty application list) - ACL(Access &acc, string description, const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR &promptSelector, - Allocator &alloc = Allocator::standard()); - virtual ~ACL(); - - Allocator &allocator; - - enum State { - unchanged, // unchanged from source - inserted, // new - modified, // was changed (replace) - deleted // was deleted (now invalid) - }; - State state() const { return mState; } - - enum Form { - invalidForm, // invalid - customForm, // not a recognized format (but valid) - allowAllForm, // indiscriminate - appListForm // list of apps + prompt confirm - }; - Form form() const { return mForm; } - void form(Form f) { mForm = f; } - - Access &access; // we belong to this Access - -public: - AclAuthorizationSet &authorizations() { return mAuthorizations; } - bool authorizes(AclAuthorization right); - void setAuthorization(CSSM_ACL_AUTHORIZATION_TAG auth) - { mAuthorizations.clear(); mAuthorizations.insert(auth); } - - typedef vector< SecPointer > ApplicationList; - ApplicationList &applications() - { assert(form() == appListForm); return mAppList; } - void addApplication(TrustedApplication *app); - - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR &promptSelector() { return mPromptSelector; } - string &promptDescription() { return mPromptDescription; } - - CSSM_ACL_HANDLE entryHandle() const { return mCssmHandle; } - - static const CSSM_ACL_HANDLE ownerHandle = 0xff0e2743; // pseudo-handle for owner ACL - bool isOwner() const { return mCssmHandle == ownerHandle; } - void makeOwner() { mCssmHandle = ownerHandle; } - - void modify(); // mark modified (update on commit) - void remove(); // mark removed (delete on commit) - - // produce chunk copies of CSSM forms; caller takes ownership - void copyAclEntry(AclEntryPrototype &proto, Allocator &alloc = Allocator::standard()); - void copyAclOwner(AclOwnerPrototype &proto, Allocator &alloc = Allocator::standard()); - -public: - void setAccess(AclBearer &target, bool update = false, - const AccessCredentials *cred = NULL); - -public: - struct ParseError { }; - -public: - static const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR defaultSelector; - -private: - void parse(const TypedList &subject); - void parsePrompt(const TypedList &subject); - void makeSubject(); - void clearSubjects(Form newForm); - -private: - State mState; // change state - Form mForm; // format type - - // AclEntryPrototype fields (minus subject, which is virtually constructed) - CSSM_ACL_HANDLE mCssmHandle; // CSSM entry handle (for updates) - string mEntryTag; // CSSM entry tag (64 bytes or so, they say) - bool mDelegate; // CSSM delegate flag - AclAuthorizationSet mAuthorizations; // rights for this ACL entry - - // composite AclEntryPrototype (constructed when needed) - TypedList *mSubjectForm; - - // following values valid only if form() == appListForm - ApplicationList mAppList; // list of trusted applications - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR mPromptSelector; // selector field of PROMPT subject - string mPromptDescription; // description field of PROMPT subject - Mutex mMutex; -}; - - -} // end namespace KeychainCore -} // end namespace Security - -#endif // !_SECURITY_ACL_H_ diff --git a/OSX/include/security_keychain/Access.cpp b/OSX/include/security_keychain/Access.cpp deleted file mode 100644 index d510cd98..00000000 --- a/OSX/include/security_keychain/Access.cpp +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Access.cpp -// -#include -#include -#include "SecBridge.h" -#include -#include -#include -#include -#include -using namespace KeychainCore; -using namespace CssmClient; - - -// -// Access static constants -// -const CSSM_ACL_HANDLE Access::ownerHandle; - - -// -// Create a completely open Access (anyone can do anything) -// Note that this means anyone can *change* the ACL at will, too. -// These ACL entries contain no descriptor names. -// -Access::Access() : mMutex(Mutex::recursive) -{ - SecPointer owner = new ACL(*this); - owner->setAuthorization(CSSM_ACL_AUTHORIZATION_CHANGE_ACL); - addOwner(owner); - - SecPointer any = new ACL(*this); - add(any); -} - - -// -// Create a default Access object. -// This construct an Access with "default form", whatever that happens to be -// in this release. -// -Access::Access(const string &descriptor, const ACL::ApplicationList &trusted) : mMutex(Mutex::recursive) -{ - makeStandard(descriptor, trusted); -} - -Access::Access(const string &descriptor) : mMutex(Mutex::recursive) -{ - ACL::ApplicationList trusted; - trusted.push_back(new TrustedApplication); - makeStandard(descriptor, trusted); -} - -Access::Access(const string &descriptor, const ACL::ApplicationList &trusted, - const AclAuthorizationSet &limitedRights, const AclAuthorizationSet &freeRights) : mMutex(Mutex::recursive) -{ - makeStandard(descriptor, trusted, limitedRights, freeRights); -} - -void Access::makeStandard(const string &descriptor, const ACL::ApplicationList &trusted, - const AclAuthorizationSet &limitedRights, const AclAuthorizationSet &freeRights) -{ - StLock_(mMutex); - - // owner "entry" - SecPointer owner = new ACL(*this, descriptor, ACL::defaultSelector); - owner->setAuthorization(CSSM_ACL_AUTHORIZATION_CHANGE_ACL); - addOwner(owner); - - // unlimited entry - SecPointer unlimited = new ACL(*this, descriptor, ACL::defaultSelector); - if (freeRights.empty()) { - unlimited->authorizations().clear(); - unlimited->authorizations().insert(CSSM_ACL_AUTHORIZATION_ENCRYPT); - } else - unlimited->authorizations() = freeRights; - unlimited->form(ACL::allowAllForm); - add(unlimited); - - // limited entry - SecPointer limited = new ACL(*this, descriptor, ACL::defaultSelector); - if (limitedRights.empty()) { - limited->authorizations().clear(); - limited->authorizations().insert(CSSM_ACL_AUTHORIZATION_DECRYPT); - limited->authorizations().insert(CSSM_ACL_AUTHORIZATION_SIGN); - limited->authorizations().insert(CSSM_ACL_AUTHORIZATION_MAC); - limited->authorizations().insert(CSSM_ACL_AUTHORIZATION_DERIVE); - limited->authorizations().insert(CSSM_ACL_AUTHORIZATION_EXPORT_CLEAR); - limited->authorizations().insert(CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED); - } else - limited->authorizations() = limitedRights; - limited->applications() = trusted; - add(limited); -} - - -// -// Create an Access object whose initial value is taken -// from a CSSM ACL bearing object. -// -Access::Access(AclBearer &source) : mMutex(Mutex::recursive) -{ - // retrieve and set - AutoAclOwnerPrototype owner; - source.getOwner(owner); - AutoAclEntryInfoList acls; - source.getAcl(acls); - compile(*owner, acls.count(), acls.entries()); -} - - -// -// Create an Access object from CSSM-layer access controls -// -Access::Access(const CSSM_ACL_OWNER_PROTOTYPE &owner, - uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls) : mMutex(Mutex::recursive) -{ - compile(owner, aclCount, acls); -} - - -Access::~Access() -{ -} - - -// Convert a SecPointer to a SecACLRef. -static SecACLRef -convert(const SecPointer &acl) -{ - return *acl; -} - -// -// Return all ACL components in a newly-made CFArray. -// -CFArrayRef Access::copySecACLs() const -{ - return makeCFArray(convert, mAcls); -} - -CFArrayRef Access::copySecACLs(CSSM_ACL_AUTHORIZATION_TAG action) const -{ - list choices; - for (Map::const_iterator it = mAcls.begin(); it != mAcls.end(); it++) - if (it->second->authorizes(action)) - choices.push_back(it->second); - return choices.empty() ? NULL : makeCFArray(convert, choices); -} - - -// -// Enter the complete access configuration into a AclBearer. -// If update, skip any part marked unchanged. (If not update, skip -// any part marked deleted.) -// -void Access::setAccess(AclBearer &target, bool update /* = false */) -{ - StLock_(mMutex); - AclFactory factory; - editAccess(target, update, factory.promptCred()); -} - -void Access::setAccess(AclBearer &target, Maker &maker) -{ - StLock_(mMutex); - if (maker.makerType() == Maker::kStandardMakerType) - { - // remove initial-setup ACL - target.deleteAcl(Maker::creationEntryTag, maker.cred()); - - // insert our own ACL entries - editAccess(target, false, maker.cred()); - } -} - -void Access::editAccess(AclBearer &target, bool update, const AccessCredentials *cred) -{ - StLock_(mMutex); - assert(mAcls[ownerHandle]); // have owner - - // apply all non-owner ACLs first - for (Map::iterator it = mAcls.begin(); it != mAcls.end(); it++) - if (!it->second->isOwner()) - it->second->setAccess(target, update, cred); - - // finally, apply owner - mAcls[ownerHandle]->setAccess(target, update, cred); -} - - -// -// A convenience function to add one application to a standard ("simple") form -// ACL entry. This will only work if -// -- there is exactly one ACL entry authorizing the right -// -- that entry is in simple form -// -void Access::addApplicationToRight(AclAuthorization right, TrustedApplication *app) -{ - StLock_(mMutex); - vector acls; - findAclsForRight(right, acls); - if (acls.size() != 1) - MacOSError::throwMe(errSecACLNotSimple); // let's not guess here... - (*acls.begin())->addApplication(app); -} - - -// -// Yield new (copied) CSSM level owner and acls values, presumably -// for use at CSSM layer operations. -// Caller is responsible for releasing the beasties when done. -// -void Access::copyOwnerAndAcl(CSSM_ACL_OWNER_PROTOTYPE * &ownerResult, - uint32 &aclCount, CSSM_ACL_ENTRY_INFO * &aclsResult) -{ - StLock_(mMutex); - Allocator& alloc = Allocator::standard(); - unsigned long count = mAcls.size() - 1; // one will be owner, others are acls - AclOwnerPrototype owner; - CssmAutoPtr acls = new(alloc) AclEntryInfo[count]; - AclEntryInfo *aclp = acls; // -> next unfilled acl element - for (Map::const_iterator it = mAcls.begin(); it != mAcls.end(); it++) { - SecPointer acl = it->second; - if (acl->isOwner()) { - acl->copyAclOwner(owner, alloc); - } else { - aclp->handle() = acl->entryHandle(); - acl->copyAclEntry(*aclp, alloc); - ++aclp; - } - } - assert((aclp - acls) == count); // all ACL elements filled - - // commit output - ownerResult = new(alloc) AclOwnerPrototype(owner); - aclCount = (uint32)count; - aclsResult = acls.release(); -} - - -// -// Retrieve the description from a randomly chosen ACL within this Access. -// In the conventional case where all ACLs have the same descriptor, this -// is deterministic. But you have been warned. -// -string Access::promptDescription() const -{ - for (Map::const_iterator it = mAcls.begin(); it != mAcls.end(); it++) { - ACL *acl = it->second; - switch (acl->form()) { - case ACL::allowAllForm: - case ACL::appListForm: - { - string descr = acl->promptDescription(); - if (!descr.empty()) - return descr; - } - default: - break; - } - } - // couldn't find suitable ACL (no description anywhere) - CssmError::throwMe(errSecACLNotSimple); -} - - -// -// Add a new ACL to the resident set. The ACL must have been -// newly made for this Access. -// -void Access::add(ACL *newAcl) -{ - StLock_(mMutex); - if (&newAcl->access != this) - MacOSError::throwMe(errSecParam); - assert(!mAcls[newAcl->entryHandle()]); - mAcls[newAcl->entryHandle()] = newAcl; -} - - -// -// Add the owner ACL to the resident set. The ACL must have been -// newly made for this Access. -// Since an Access must have exactly one owner ACL, this call -// should only be made (exactly once) for a newly created Access. -// -void Access::addOwner(ACL *newAcl) -{ - StLock_(mMutex); - newAcl->makeOwner(); - assert(mAcls.find(ownerHandle) == mAcls.end()); // no owner yet - add(newAcl); -} - - -// -// Compile a set of ACL entries and owner into internal form. -// -void Access::compile(const CSSM_ACL_OWNER_PROTOTYPE &owner, - uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls) -{ - StLock_(mMutex); - // add owner acl - mAcls[ownerHandle] = new ACL(*this, AclOwnerPrototype::overlay(owner)); - - // add acl entries - const AclEntryInfo *acl = AclEntryInfo::overlay(acls); - for (uint32 n = 0; n < aclCount; n++) { - secdebug("SecAccess", "%p compiling entry %ld", this, acl[n].handle()); - mAcls[acl[n].handle()] = new ACL(*this, acl[n]); - } - secdebug("SecAccess", "%p %ld entries compiled", this, mAcls.size()); -} - - -// -// Creation helper objects -// -const char Access::Maker::creationEntryTag[] = "___setup___"; - -Access::Maker::Maker(Allocator &alloc, MakerType makerType) - : allocator(alloc), mKey(alloc), mCreds(allocator), mMakerType(makerType) -{ - if (makerType == kStandardMakerType) - { - // generate random key - mKey.malloc(keySize); - UniformRandomBlobs().random(mKey.get()); - - // create entry info for resource creation - mInput = AclEntryPrototype(TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_PASSWORD, - new(allocator) ListElement(mKey.get()))); - mInput.proto().tag(creationEntryTag); - - // create credential sample for access - mCreds += TypedList(allocator, CSSM_SAMPLE_TYPE_PASSWORD, new(allocator) ListElement(mKey.get())); - } - else - { - // just make it an CSSM_ACL_SUBJECT_TYPE_ANY list - mInput = AclEntryPrototype(TypedList(allocator, CSSM_ACL_SUBJECT_TYPE_ANY)); - } -} - -void Access::Maker::initialOwner(ResourceControlContext &ctx, const AccessCredentials *creds) -{ - //@@@ make up ctx.entry-info - ctx.input() = mInput; - ctx.credentials(creds); -} - -const AccessCredentials *Access::Maker::cred() -{ - return &mCreds; -} diff --git a/OSX/include/security_keychain/Access.h b/OSX/include/security_keychain/Access.h deleted file mode 100644 index ec562dd8..00000000 --- a/OSX/include/security_keychain/Access.h +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Access.h - Access control wrappers -// -#ifndef _SECURITY_ACCESS_H_ -#define _SECURITY_ACCESS_H_ - -#include -#include -#include -#include -#include -#include -#include - -namespace Security { -namespace KeychainCore { - -using CssmClient::AclBearer; - - -class Access : public SecCFObject { - NOCOPY(Access) -public: - SECCFFUNCTIONS(Access, SecAccessRef, errSecInvalidItemRef, gTypes().Access) - - class Maker { - NOCOPY(Maker) - static const size_t keySize = 16; // number of (random) bytes - friend class Access; - public: - enum MakerType {kStandardMakerType, kAnyMakerType}; - - Maker(Allocator &alloc = Allocator::standard(), MakerType makerType = kStandardMakerType); - - void initialOwner(ResourceControlContext &ctx, const AccessCredentials *creds = NULL); - const AccessCredentials *cred(); - - TrackingAllocator allocator; - - static const char creationEntryTag[]; - - MakerType makerType() {return mMakerType;} - - private: - CssmAutoData mKey; - AclEntryInput mInput; - AutoCredentials mCreds; - MakerType mMakerType; - }; - -public: - // make default forms - Access(const string &description); - Access(const string &description, const ACL::ApplicationList &trusted); - Access(const string &description, const ACL::ApplicationList &trusted, - const AclAuthorizationSet &limitedRights, const AclAuthorizationSet &freeRights); - - // make a completely open Access (anyone can do anything) - Access(); - - // retrieve from an existing AclBearer - Access(AclBearer &source); - - // make from CSSM layer information (presumably retrieved by caller) - Access(const CSSM_ACL_OWNER_PROTOTYPE &owner, - uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls); - virtual ~Access(); - -public: - CFArrayRef copySecACLs() const; - CFArrayRef copySecACLs(CSSM_ACL_AUTHORIZATION_TAG action) const; - - void add(ACL *newAcl); - void addOwner(ACL *newOwnerAcl); - - void setAccess(AclBearer &target, bool update = false); - void setAccess(AclBearer &target, Maker &maker); - - template - void findAclsForRight(AclAuthorization right, Container &cont) - { - cont.clear(); - for (Map::const_iterator it = mAcls.begin(); it != mAcls.end(); it++) - if (it->second->authorizes(right)) - cont.push_back(it->second); - } - - std::string promptDescription() const; // from any one of the ACLs contained - - void addApplicationToRight(AclAuthorization right, TrustedApplication *app); - - void copyOwnerAndAcl(CSSM_ACL_OWNER_PROTOTYPE * &owner, - uint32 &aclCount, CSSM_ACL_ENTRY_INFO * &acls); - -protected: - void makeStandard(const string &description, const ACL::ApplicationList &trusted, - const AclAuthorizationSet &limitedRights = AclAuthorizationSet(), - const AclAuthorizationSet &freeRights = AclAuthorizationSet()); - void compile(const CSSM_ACL_OWNER_PROTOTYPE &owner, - uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls); - - void editAccess(AclBearer &target, bool update, const AccessCredentials *cred); - -private: - static const CSSM_ACL_HANDLE ownerHandle = ACL::ownerHandle; - typedef map > Map; - - Map mAcls; // set of ACL entries - Mutex mMutex; -}; - - -} // end namespace KeychainCore -} // end namespace Security - -#endif // !_SECURITY_ACCESS_H_ diff --git a/OSX/include/security_keychain/AppleBaselineEscrowCertificates.h b/OSX/include/security_keychain/AppleBaselineEscrowCertificates.h deleted file mode 100644 index 56a9b6cf..00000000 --- a/OSX/include/security_keychain/AppleBaselineEscrowCertificates.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#ifndef sec_AppleBaselineEscrowCertificates_h -#define sec_AppleBaselineEscrowCertificates_h - -struct RootRecord -{ - size_t _length; - UInt8* _bytes; -}; - -/* ========================================================================== - Production Escrow Certificates - ========================================================================== */ - - -static const UInt8 kBaseLineEscrowRootGM[] = { - 0x30,0x82,0x03,0xd0,0x30,0x82,0x02,0xb8,0xa0,0x03,0x02,0x01,0x02,0x02,0x01,0x64, - 0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0b,0x05,0x00,0x30, - 0x79,0x31,0x0c,0x30,0x0a,0x06,0x03,0x55,0x04,0x05,0x13,0x03,0x31,0x30,0x30,0x31, - 0x0b,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11, - 0x06,0x03,0x55,0x04,0x0a,0x13,0x0a,0x41,0x70,0x70,0x6c,0x65,0x20,0x49,0x6e,0x63, - 0x2e,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0b,0x13,0x1d,0x41,0x70,0x70,0x6c, - 0x65,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20, - 0x41,0x75,0x74,0x68,0x6f,0x72,0x69,0x74,0x79,0x31,0x1f,0x30,0x1d,0x06,0x03,0x55, - 0x04,0x03,0x13,0x16,0x45,0x73,0x63,0x72,0x6f,0x77,0x20,0x53,0x65,0x72,0x76,0x69, - 0x63,0x65,0x20,0x52,0x6f,0x6f,0x74,0x20,0x43,0x41,0x30,0x1e,0x17,0x0d,0x31,0x33, - 0x30,0x38,0x30,0x32,0x32,0x33,0x32,0x34,0x34,0x34,0x5a,0x17,0x0d,0x32,0x33,0x30, - 0x38,0x30,0x32,0x32,0x33,0x32,0x34,0x34,0x34,0x5a,0x30,0x79,0x31,0x0c,0x30,0x0a, - 0x06,0x03,0x55,0x04,0x05,0x13,0x03,0x31,0x30,0x30,0x31,0x0b,0x30,0x09,0x06,0x03, - 0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x0a, - 0x13,0x0a,0x41,0x70,0x70,0x6c,0x65,0x20,0x49,0x6e,0x63,0x2e,0x31,0x26,0x30,0x24, - 0x06,0x03,0x55,0x04,0x0b,0x13,0x1d,0x41,0x70,0x70,0x6c,0x65,0x20,0x43,0x65,0x72, - 0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41,0x75,0x74,0x68,0x6f, - 0x72,0x69,0x74,0x79,0x31,0x1f,0x30,0x1d,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x45, - 0x73,0x63,0x72,0x6f,0x77,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x20,0x52,0x6f, - 0x6f,0x74,0x20,0x43,0x41,0x30,0x82,0x01,0x22,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48, - 0x86,0xf7,0x0d,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01,0x0f,0x00,0x30,0x82,0x01, - 0x0a,0x02,0x82,0x01,0x01,0x00,0xd0,0xa3,0xf4,0x56,0x7d,0x3f,0x46,0x31,0xd2,0x56, - 0xa0,0xdf,0x42,0xa0,0x29,0x83,0x1e,0xb9,0x82,0xb5,0xa5,0xff,0x3e,0xde,0xb5,0x0f, - 0x4a,0x8a,0x28,0x60,0xcf,0x75,0xb4,0xa0,0x70,0x7c,0xf5,0xe2,0x94,0xf3,0x22,0x02, - 0xc8,0x81,0xce,0x34,0xc7,0x66,0x6a,0x18,0xaa,0xb4,0xfd,0x6d,0xb0,0x0b,0xdd,0x4a, - 0xdd,0xcf,0xe0,0x08,0x1b,0x1c,0xa6,0xdb,0xba,0xb2,0xc1,0xa4,0x10,0x5f,0x35,0x4f, - 0x8b,0x8b,0x7a,0xa3,0xdb,0x3c,0xf6,0x54,0x95,0x42,0xad,0x2a,0x3b,0xfe,0x06,0x8c, - 0xe1,0x92,0xf1,0x60,0x97,0x58,0x1b,0xd9,0x8f,0xbe,0xfb,0x46,0x4c,0x29,0x5c,0x1c, - 0xf0,0x20,0xb6,0x2b,0xa5,0x12,0x09,0x9b,0x28,0x41,0x34,0x97,0x9f,0xf3,0x88,0x4b, - 0x69,0x72,0xea,0x3a,0x27,0xb0,0x50,0x1d,0x88,0x29,0x0d,0xbb,0xed,0x04,0xa2,0x11, - 0xcf,0x0c,0x5b,0x65,0x61,0x35,0xbd,0xf2,0x0d,0xfc,0xe2,0xb9,0x20,0xd3,0xb7,0x03, - 0x70,0x39,0xd5,0xe0,0x86,0x7c,0x04,0xcc,0xc9,0xa1,0x85,0xb4,0x9b,0xbc,0x88,0x4e, - 0xd7,0xad,0x5c,0xff,0x2c,0x0d,0x80,0x8e,0x51,0x39,0x20,0x8b,0xaf,0x1e,0x46,0x95, - 0xfa,0x0d,0x1b,0xd2,0xbf,0x80,0xe0,0x9f,0x6d,0x4a,0xf5,0x31,0x67,0x18,0x11,0xa5, - 0x63,0x27,0x08,0xee,0xd9,0x07,0x29,0xd0,0xd4,0x36,0x91,0x5b,0xfb,0x4a,0x0b,0x07, - 0xd1,0x0d,0x79,0x16,0x6e,0x16,0x02,0x23,0x80,0xc6,0x15,0x07,0x6d,0xa0,0x06,0xb6, - 0x45,0x90,0xb0,0xae,0xa4,0xad,0x0e,0x75,0x04,0x2b,0x2b,0x78,0xf1,0x57,0x84,0x23, - 0x87,0x24,0xec,0x58,0xc4,0xf1,0x02,0x03,0x01,0x00,0x01,0xa3,0x63,0x30,0x61,0x30, - 0x0f,0x06,0x03,0x55,0x1d,0x13,0x01,0x01,0xff,0x04,0x05,0x30,0x03,0x01,0x01,0xff, - 0x30,0x0e,0x06,0x03,0x55,0x1d,0x0f,0x01,0x01,0xff,0x04,0x04,0x03,0x02,0x01,0x06, - 0x30,0x1d,0x06,0x03,0x55,0x1d,0x0e,0x04,0x16,0x04,0x14,0xfd,0x78,0x96,0x53,0x80, - 0xd6,0xf6,0xdc,0xa6,0xc3,0x59,0x06,0x38,0xed,0x79,0x3e,0x8f,0x50,0x1b,0x50,0x30, - 0x1f,0x06,0x03,0x55,0x1d,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0xfd,0x78,0x96,0x53, - 0x80,0xd6,0xf6,0xdc,0xa6,0xc3,0x59,0x06,0x38,0xed,0x79,0x3e,0x8f,0x50,0x1b,0x50, - 0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0b,0x05,0x00,0x03, - 0x82,0x01,0x01,0x00,0x71,0x15,0xca,0x87,0xd0,0x2d,0xb5,0x18,0xd5,0x35,0x7a,0xcd, - 0xdf,0x62,0x28,0xf0,0x0b,0x63,0x4d,0x4e,0x02,0xba,0x3d,0xb8,0xb4,0x37,0xea,0xb0, - 0x93,0x93,0xab,0x1c,0xfd,0x9f,0xe8,0x72,0xbf,0xf3,0xdb,0xe6,0xad,0x16,0xfe,0x71, - 0x61,0xa8,0x5a,0xd0,0x58,0x0f,0x65,0x7a,0x57,0x7a,0xe0,0x34,0x80,0x8e,0xbb,0x41, - 0x01,0xe7,0xb0,0x3b,0xf7,0x2b,0x3a,0x6d,0x44,0x2a,0x3a,0x04,0x52,0xfa,0x2b,0x7b, - 0x3b,0x21,0xdd,0x0c,0x70,0x3d,0xfb,0x45,0xc6,0x79,0x68,0x62,0xe2,0x89,0xb8,0x25, - 0xee,0x63,0x76,0x02,0xb2,0x22,0xe9,0x53,0x85,0x68,0x3e,0x75,0xb6,0x0b,0x65,0xe9, - 0x1c,0xba,0x84,0x93,0xb0,0x8a,0xef,0xb5,0x1a,0x12,0xe4,0x8f,0xae,0xd5,0x5c,0xa1, - 0x05,0x4a,0x01,0xbc,0x6f,0xf9,0x58,0x5e,0xf7,0x04,0x61,0xee,0xf5,0xc6,0xa0,0x1b, - 0x44,0x2e,0x5a,0x3a,0x59,0xa1,0xb3,0xb0,0xf4,0xb6,0xcb,0xe0,0x6c,0x2b,0x59,0x8a, - 0xfb,0x6a,0xe0,0xa2,0x57,0x09,0x79,0xc1,0xdd,0xfb,0x84,0x86,0xeb,0x66,0x29,0x73, - 0xae,0xbf,0x58,0xae,0x47,0x4d,0x48,0x37,0xd6,0xb1,0x8c,0x5f,0x26,0x5f,0xb5,0x26, - 0x07,0x0b,0x85,0xb7,0x36,0x37,0x14,0xcf,0x5e,0x55,0xa5,0x3c,0xf3,0x1e,0x79,0x50, - 0xbb,0x85,0x3b,0xb2,0x94,0x68,0xb0,0x25,0x4f,0x75,0xec,0xf0,0xf9,0xc0,0x5a,0x2d, - 0xe5,0xed,0x67,0xcd,0x88,0x55,0xa0,0x42,0xde,0x78,0xbc,0xfe,0x30,0xb1,0x62,0x2d, - 0xe1,0xfd,0xec,0x75,0x03,0xa6,0x1f,0x7c,0xc4,0x3a,0x4a,0x59,0xfe,0x77,0xc3,0x99, - 0x96,0x87,0x44,0xc3, -}; - -static const UInt8 kBaseLinePCSEscrowRootGM[] = { - 0x30,0x82,0x03,0xD8,0x30,0x82,0x02,0xC0,0xA0,0x03,0x02,0x01,0x02,0x02,0x01,0x64, - 0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x30, - 0x7D,0x31,0x0C,0x30,0x0A,0x06,0x03,0x55,0x04,0x05,0x13,0x03,0x31,0x30,0x30,0x31, - 0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11, - 0x06,0x03,0x55,0x04,0x0A,0x13,0x0A,0x41,0x70,0x70,0x6C,0x65,0x20,0x49,0x6E,0x63, - 0x2E,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,0x13,0x1D,0x41,0x70,0x70,0x6C, - 0x65,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20, - 0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x31,0x23,0x30,0x21,0x06,0x03,0x55, - 0x04,0x03,0x13,0x1A,0x45,0x66,0x66,0x61,0x63,0x65,0x61,0x62,0x6C,0x65,0x20,0x53, - 0x65,0x72,0x76,0x69,0x63,0x65,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x1E, - 0x17,0x0D,0x31,0x34,0x30,0x37,0x32,0x38,0x32,0x31,0x30,0x33,0x35,0x32,0x5A,0x17, - 0x0D,0x32,0x34,0x30,0x37,0x32,0x38,0x32,0x31,0x30,0x33,0x35,0x32,0x5A,0x30,0x7D, - 0x31,0x0C,0x30,0x0A,0x06,0x03,0x55,0x04,0x05,0x13,0x03,0x31,0x30,0x30,0x31,0x0B, - 0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11,0x06, - 0x03,0x55,0x04,0x0A,0x13,0x0A,0x41,0x70,0x70,0x6C,0x65,0x20,0x49,0x6E,0x63,0x2E, - 0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,0x13,0x1D,0x41,0x70,0x70,0x6C,0x65, - 0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41, - 0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x31,0x23,0x30,0x21,0x06,0x03,0x55,0x04, - 0x03,0x13,0x1A,0x45,0x66,0x66,0x61,0x63,0x65,0x61,0x62,0x6C,0x65,0x20,0x53,0x65, - 0x72,0x76,0x69,0x63,0x65,0x20,0x52,0x6F,0x6F,0x74,0x20,0x43,0x41,0x30,0x82,0x01, - 0x22,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00, - 0x03,0x82,0x01,0x0F,0x00,0x30,0x82,0x01,0x0A,0x02,0x82,0x01,0x01,0x00,0xC0,0x55, - 0xCC,0x74,0xCF,0x49,0xE9,0xEC,0x9A,0x76,0x17,0x30,0x12,0x40,0x7D,0xC1,0x69,0x98, - 0x97,0x2C,0xA7,0xC0,0xD6,0xF4,0x9A,0x1D,0xC2,0x46,0x75,0xB6,0xAD,0x81,0xE2,0x2F, - 0x65,0xF1,0xAF,0xF6,0xBA,0xBD,0xC1,0x44,0x37,0x93,0xB8,0x92,0x2A,0x83,0xCC,0xE3, - 0x6F,0xFD,0x95,0xAA,0x86,0xAE,0x4D,0x62,0x98,0xBC,0xE6,0x90,0x40,0x5B,0x5A,0x2E, - 0x65,0x0C,0xFF,0x07,0xB9,0x79,0xC4,0x2E,0x2E,0x72,0x80,0xE3,0xB9,0x98,0x08,0xE9, - 0x3B,0x79,0x3B,0x46,0x99,0xD7,0xB9,0xDF,0x1F,0xC4,0x0D,0x49,0xB9,0x78,0x39,0xAF, - 0x7F,0xF5,0xDC,0x9C,0xEE,0xC1,0xB0,0x90,0x70,0x97,0xD6,0xE7,0x49,0x0C,0x11,0x19, - 0xE9,0xDD,0xEA,0x38,0x30,0xB9,0x1D,0xF4,0xD7,0xFF,0xBB,0xFC,0x6B,0x49,0xFC,0x69, - 0xE8,0x05,0x8E,0x96,0x14,0x87,0x62,0xD6,0x82,0x2F,0xA2,0x97,0xB5,0x4A,0x80,0x46, - 0x43,0xF5,0xF2,0x1B,0x94,0xBF,0xFE,0x48,0x8B,0x7F,0x4D,0xD6,0x3D,0x3E,0x64,0xBE, - 0x09,0x7C,0x9E,0x24,0x80,0xDE,0xAB,0xC9,0x17,0x91,0xAC,0x60,0x06,0x98,0x9C,0xCB, - 0xAD,0x04,0x41,0x1F,0x7F,0xE5,0xC2,0x08,0xD5,0x80,0xD7,0x63,0xF1,0x5C,0x60,0xA2, - 0xE5,0xAD,0x5F,0x6E,0xBC,0x3A,0xC4,0x9F,0x4D,0xE4,0x65,0xA3,0xF2,0x18,0x0B,0x1A, - 0x2D,0xB4,0x64,0x3D,0x53,0x5A,0x14,0xF6,0x26,0x92,0x13,0x23,0x83,0x33,0xBE,0xE0, - 0xA4,0x43,0xFC,0x79,0xA0,0x91,0xFB,0x1C,0x17,0xF0,0x87,0xE5,0x8C,0x68,0xF2,0xCF, - 0xAE,0x3B,0xC5,0xD5,0xD2,0x58,0x8E,0xFB,0x29,0x53,0xFE,0x9E,0xDE,0x4F,0x02,0x03, - 0x01,0x00,0x01,0xA3,0x63,0x30,0x61,0x30,0x0F,0x06,0x03,0x55,0x1D,0x13,0x01,0x01, - 0xFF,0x04,0x05,0x30,0x03,0x01,0x01,0xFF,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01, - 0x01,0xFF,0x04,0x04,0x03,0x02,0x01,0x06,0x30,0x1D,0x06,0x03,0x55,0x1D,0x0E,0x04, - 0x16,0x04,0x14,0x64,0x0B,0xE4,0x72,0x73,0x5C,0x54,0xB2,0x58,0x59,0xAE,0x42,0xDF, - 0x2B,0xB7,0xBA,0xB9,0xEB,0x86,0xAE,0x30,0x1F,0x06,0x03,0x55,0x1D,0x23,0x04,0x18, - 0x30,0x16,0x80,0x14,0x64,0x0B,0xE4,0x72,0x73,0x5C,0x54,0xB2,0x58,0x59,0xAE,0x42, - 0xDF,0x2B,0xB7,0xBA,0xB9,0xEB,0x86,0xAE,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86, - 0xF7,0x0D,0x01,0x01,0x0B,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x79,0xF4,0x22,0xC9, - 0x6C,0x25,0x64,0x2D,0x8E,0x91,0x53,0x7B,0xFB,0xA7,0xD2,0x0C,0xAD,0xDC,0xA9,0x83, - 0x90,0x75,0x16,0x98,0xC1,0x2C,0xFE,0x7C,0x16,0xCE,0x2A,0xA0,0xB8,0x8A,0xF6,0xDB, - 0x3E,0x2D,0x6C,0x5D,0x61,0x41,0x10,0xBB,0x02,0xBA,0x51,0x5B,0x42,0x62,0x18,0x9F, - 0xC4,0x25,0xF3,0x24,0xCC,0x1D,0xD2,0xFF,0x47,0xB2,0x14,0x9E,0x6A,0x31,0xA3,0xA7, - 0xB1,0x0C,0x7E,0x55,0xCE,0xC4,0x9E,0xA6,0x0A,0x06,0x9B,0x50,0x40,0x04,0x13,0xA0, - 0xC7,0x4D,0x37,0xD9,0x85,0xCF,0xB2,0xD9,0x16,0x38,0x4B,0xA3,0xA5,0x3E,0xDC,0x06, - 0x0D,0xE0,0xB1,0x13,0x7C,0x8B,0x79,0x1F,0x67,0xD8,0xBA,0xB4,0x58,0x9C,0x84,0x18, - 0xE4,0xED,0x22,0x17,0x41,0xA9,0x3B,0x88,0xD5,0x55,0x54,0x5F,0x33,0x4D,0xE2,0xBD, - 0xBE,0x66,0x46,0x59,0xC0,0x60,0xC5,0xB2,0x7A,0xF6,0xCA,0xCD,0xB9,0x2D,0xBD,0x50, - 0xB3,0xD6,0x18,0xD5,0x1F,0xFA,0x42,0x30,0x4C,0x10,0xFB,0x12,0xA9,0x9A,0x0E,0x39, - 0xFA,0x77,0xB6,0x82,0x53,0xF3,0x35,0x74,0xB5,0x10,0x5A,0x22,0xAE,0x17,0x25,0xD1, - 0x09,0xB9,0x71,0x08,0xA1,0xFA,0x2D,0xB9,0xEA,0x8C,0xC5,0xAC,0x31,0x6C,0x45,0x46, - 0x2E,0x11,0x2D,0x75,0x07,0x88,0x39,0xA3,0x14,0x08,0xA6,0xBF,0x7B,0x2C,0x26,0xAE, - 0x28,0xE9,0x1D,0x6C,0xFF,0xAC,0x99,0x53,0x44,0x91,0x26,0x2E,0x82,0x1A,0x11,0x66, - 0xB5,0x9C,0xEF,0x9E,0xC1,0x52,0x8F,0xCE,0x12,0xF3,0x88,0x86,0x06,0xF0,0xE8,0x62, - 0x69,0x12,0x04,0x6D,0x2B,0x75,0x83,0xE1,0x12,0xFC,0x3E,0xF1, -}; - - -static struct RootRecord kBaseLineEscrowRootRecord = {sizeof(kBaseLineEscrowRootGM), (UInt8*)kBaseLineEscrowRootGM}; -static struct RootRecord* kBaseLineEscrowRoots[] = {&kBaseLineEscrowRootRecord}; -static const int kNumberOfBaseLineEscrowRoots = (int)(sizeof(kBaseLineEscrowRoots)/sizeof(kBaseLineEscrowRoots[0])); - -static struct RootRecord kBaseLinePCSEscrowRootRecord = {sizeof(kBaseLinePCSEscrowRootGM), (UInt8*)kBaseLinePCSEscrowRootGM}; -static struct RootRecord* kBaseLinePCSEscrowRoots[] = {&kBaseLinePCSEscrowRootRecord}; -static const int kNumberOfBaseLinePCSEscrowRoots = (int)(sizeof(kBaseLinePCSEscrowRoots)/sizeof(kBaseLinePCSEscrowRoots[0])); - -#endif diff --git a/OSX/include/security_keychain/CCallbackMgr.cp b/OSX/include/security_keychain/CCallbackMgr.cp deleted file mode 100644 index 66741f9f..00000000 --- a/OSX/include/security_keychain/CCallbackMgr.cp +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - File: CCallbackMgr.cp - - Contains: Code that communicates with processes that install a callback - with the Keychain Manager to receive keychain events. - -*/ - -#include "CCallbackMgr.h" - -#include -#include - -#include "Globals.h" -#include -#include -#include -#include - -using namespace KeychainCore; -using namespace CssmClient; -using namespace SecurityServer; - -#pragma mark ÑÑÑÑ CallbackInfo ÑÑÑÑ - -CallbackInfo::CallbackInfo() : mCallback(NULL),mEventMask(0),mContext(NULL) -{ -} - -CallbackInfo::CallbackInfo(SecKeychainCallback inCallbackFunction, - SecKeychainEventMask inEventMask, void *inContext) - : mCallback(inCallbackFunction), mEventMask(inEventMask), mContext(inContext) -{ -} - -CallbackInfo::~CallbackInfo() -{ -} - -bool CallbackInfo::operator==(const CallbackInfo& other) const -{ - return mCallback==other.mCallback; -} - -bool CallbackInfo::operator!=(const CallbackInfo& other) const -{ - return !(*this==other); -} - - -#pragma mark ÑÑÑÑ CCallbackMgr ÑÑÑÑ - - -class CallbackMaker -{ -protected: - RefPointer mCallbackManager; - -public: - CallbackMaker(); - CCallbackMgr& instance() {return *mCallbackManager;} -}; - - -CallbackMaker::CallbackMaker() -{ - CCallbackMgr* manager = new CCallbackMgr(); - mCallbackManager = manager; -} - - - -ModuleNexus gCallbackMaker; - -CCallbackMgr::CCallbackMgr() : EventListener (kNotificationDomainDatabase, kNotificationAllEvents) -{ - EventListener::FinishedInitialization(this); -} - -CCallbackMgr::~CCallbackMgr() -{ -} - -CCallbackMgr& CCallbackMgr::Instance() -{ - return gCallbackMaker().instance(); -} - -void CCallbackMgr::AddCallback( SecKeychainCallback inCallbackFunction, - SecKeychainEventMask inEventMask, - void* inContext) - -{ - CallbackInfo info( inCallbackFunction, inEventMask, inContext ); - CallbackInfo existingInfo; - - - CallbackInfoListIterator ix = find( CCallbackMgr::Instance().mEventCallbacks.begin(), - CCallbackMgr::Instance().mEventCallbacks.end(), info ); - - // make sure it is not already there - if ( ix!=CCallbackMgr::Instance().mEventCallbacks.end() ) - { - // It's already there. This could mean that the old process died unexpectedly, - // so we need to validate the process ID of the existing callback. - // On Mac OS X this list is per process so this is always a duplicate - MacOSError::throwMe(errSecDuplicateCallback); - } - - CCallbackMgr::Instance().mEventCallbacks.push_back(info); -} - - -class Predicate -{ - SecKeychainCallback mCallbackFunction; -public: - Predicate(SecKeychainCallback inCallbackFunction) : mCallbackFunction(inCallbackFunction) {} - bool operator()(const CallbackInfo &cbInfo) { return cbInfo.mCallback == mCallbackFunction; } -}; - -void CCallbackMgr::RemoveCallback(SecKeychainCallback inCallbackFunction) -{ - size_t oldSize = CCallbackMgr::Instance().mEventCallbacks.size(); - Predicate predicate(inCallbackFunction); - CCallbackMgr::Instance().mEventCallbacks.remove_if(predicate); - - if (oldSize == CCallbackMgr::Instance().mEventCallbacks.size()) - MacOSError::throwMe(errSecInvalidCallback); -} - -void CCallbackMgr::AlertClients(const list &eventCallbacks, - SecKeychainEvent inEvent, - pid_t inPid, - const Keychain &inKeychain, - const Item &inItem) -{ - secdebug("kcnotify", "dispatch event %ld pid %d keychain %p item %p", - (unsigned long)inEvent, inPid, &inKeychain, !!inItem ? &*inItem : NULL); - - // Iterate through callbacks, looking for those registered for inEvent - const SecKeychainEventMask theMask = 1U << inEvent; - - for (ConstCallbackInfoListIterator ix = eventCallbacks.begin(); ix != eventCallbacks.end(); ++ix) - { - if (!(ix->mEventMask & theMask)) - continue; - - SecKeychainCallbackInfo cbInfo; - cbInfo.version = 0; // @@@ kKeychainAPIVersion; - cbInfo.item = inItem ? inItem->handle() : 0; - cbInfo.keychain = inKeychain ? inKeychain->handle() : 0; - cbInfo.pid = inPid; - - ix->mCallback(inEvent, &cbInfo, ix->mContext); - if (cbInfo.item) CFRelease(cbInfo.item); - if (cbInfo.keychain) CFRelease(cbInfo.keychain); - } -} - - - -void CCallbackMgr::consume (SecurityServer::NotificationDomain domain, SecurityServer::NotificationEvent whichEvent, const CssmData &data) -{ - NameValueDictionary dictionary (data); - - // Decode from userInfo the event type, 'keychain' CFDict, and 'item' CFDict - SecKeychainEvent thisEvent = whichEvent; - - pid_t thisPid; - const NameValuePair* pidRef = dictionary.FindByName(PID_KEY); - if (pidRef == 0) - { - thisPid = 0; - } - else - { - thisPid = n2h(*reinterpret_cast(pidRef->Value().data ())); - } - - Keychain thisKeychain; - Item thisItem; - list eventCallbacks; - { - // Lock the global API lock before doing stuff with StorageManager. - // make sure we have a database identifier - if (dictionary.FindByName (SSUID_KEY) != 0) - { - StLock_(*globals().storageManager.getStorageManagerMutex()); - DLDbIdentifier dbid = NameValueDictionary::MakeDLDbIdentifierFromNameValueDictionary(dictionary); - thisKeychain = globals().storageManager.keychain(dbid); - } - - const NameValuePair* item = dictionary.FindByName(ITEM_KEY); - - if (item && thisKeychain) - { - PrimaryKey pk(item->Value()); - thisItem = thisKeychain->item(pk); - } - - // Deal with events that we care about ourselves first. - if (thisEvent == kSecDeleteEvent && thisKeychain.get() && thisItem.get()) - thisKeychain->didDeleteItem(thisItem.get()); - else if (thisEvent == kSecKeychainListChangedEvent) - globals().storageManager.forceUserSearchListReread(); - - eventCallbacks = CCallbackMgr::Instance().mEventCallbacks; - // We can safely release the global API lock now since thisKeychain and thisItem - // are CFRetained and will be until they go out of scope. - } - - // Notify our process of this event. - CCallbackMgr::AlertClients(eventCallbacks, thisEvent, thisPid, thisKeychain, thisItem); -} diff --git a/OSX/include/security_keychain/CCallbackMgr.h b/OSX/include/security_keychain/CCallbackMgr.h deleted file mode 100644 index 52ea8d11..00000000 --- a/OSX/include/security_keychain/CCallbackMgr.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 1998-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * CCallbackMgr.h -- Code that communicates with processes that install a callback - * with the Keychain Manager to receive keychain events. - */ -#ifndef _SECURITY_CCALLBACKMGR_H_ -#define _SECURITY_CCALLBACKMGR_H_ - -#include -#include -#include -#include -#include -#include -#include "KCEventNotifier.h" - -namespace Security -{ - -namespace KeychainCore -{ - -class CallbackInfo; -class CCallbackMgr; - -class CallbackInfo -{ -public: - ~CallbackInfo(); - CallbackInfo(); - CallbackInfo(SecKeychainCallback inCallbackFunction,SecKeychainEventMask inEventMask,void *inContext); - - bool operator ==(const CallbackInfo& other) const; - bool operator !=(const CallbackInfo& other) const; - - SecKeychainCallback mCallback; - SecKeychainEventMask mEventMask; - void *mContext; -}; - -// typedefs -typedef CallbackInfo *CallbackInfoPtr; -typedef CallbackInfo const *ConstCallbackInfoPtr; - -typedef list::iterator CallbackInfoListIterator; -typedef list::const_iterator ConstCallbackInfoListIterator; - - -class CCallbackMgr : public SecurityServer::EventListener -{ -public: - CCallbackMgr(); - ~CCallbackMgr(); - - static CCallbackMgr& Instance(); - - static void AddCallback( SecKeychainCallback inCallbackFunction, SecKeychainEventMask inEventMask, void* inContext); - - static void RemoveCallback( SecKeychainCallback inCallbackFunction ); - //static void RemoveCallbackUPP(KCCallbackUPP inCallbackFunction); - static bool HasCallbacks() - { return CCallbackMgr::Instance().mEventCallbacks.size() > 0; }; - -private: - - void consume (SecurityServer::NotificationDomain domain, SecurityServer::NotificationEvent whichEvent, - const CssmData &data); - - static void AlertClients(const list &eventCallbacks, SecKeychainEvent inEvent, pid_t inPid, - const Keychain& inKeychain, const Item &inItem); - - list mEventCallbacks; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_CCALLBACKMGR_H_ diff --git a/OSX/include/security_keychain/Certificate.cpp b/OSX/include/security_keychain/Certificate.cpp deleted file mode 100644 index 1b625a49..00000000 --- a/OSX/include/security_keychain/Certificate.cpp +++ /dev/null @@ -1,1471 +0,0 @@ -/* - * Copyright (c) 2002-2007,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Certificate.cpp -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace KeychainCore; - -CL -Certificate::clForType(CSSM_CERT_TYPE type) -{ - return CL(gGuidAppleX509CL); -} - -Certificate::Certificate(const CSSM_DATA &data, CSSM_CERT_TYPE type, CSSM_CERT_ENCODING encoding) : - ItemImpl(CSSM_DL_DB_RECORD_X509_CERTIFICATE, reinterpret_cast(NULL), UInt32(data.Length), reinterpret_cast(data.Data)), - mHaveTypeAndEncoding(true), - mPopulated(false), - mType(type), - mEncoding(encoding), - mCL(clForType(type)), - mCertHandle(0), - mV1SubjectPublicKeyCStructValue(NULL), - mV1SubjectNameCStructValue(NULL), - mV1IssuerNameCStructValue(NULL), - mSha1Hash(NULL), - mEncodingVerified(false) -{ - if (data.Length == 0 || data.Data == NULL) - MacOSError::throwMe(errSecParam); -} - -// db item constructor -Certificate::Certificate(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) : - ItemImpl(keychain, primaryKey, uniqueId), - mHaveTypeAndEncoding(false), - mPopulated(false), - mCL(NULL), - mCertHandle(0), - mV1SubjectPublicKeyCStructValue(NULL), - mV1SubjectNameCStructValue(NULL), - mV1IssuerNameCStructValue(NULL), - mSha1Hash(NULL), - mEncodingVerified(false) -{ -} - - - -Certificate* Certificate::make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) -{ - Certificate* c = new Certificate(keychain, primaryKey, uniqueId); - keychain->addItem(primaryKey, c); - return c; -} - - - -Certificate* Certificate::make(const Keychain &keychain, const PrimaryKey &primaryKey) -{ - Certificate* c = new Certificate(keychain, primaryKey); - keychain->addItem(primaryKey, c); - return c; -} - - - - -// PrimaryKey item constructor -Certificate::Certificate(const Keychain &keychain, const PrimaryKey &primaryKey) : - ItemImpl(keychain, primaryKey), - mHaveTypeAndEncoding(false), - mPopulated(false), - mCL(NULL), - mCertHandle(0), - mV1SubjectPublicKeyCStructValue(NULL), - mV1SubjectNameCStructValue(NULL), - mV1IssuerNameCStructValue(NULL), - mSha1Hash(NULL), - mEncodingVerified(false) -{ - // @@@ In this case we don't know the type... -} - -Certificate::Certificate(Certificate &certificate) : - ItemImpl(certificate), - mHaveTypeAndEncoding(certificate.mHaveTypeAndEncoding), - mPopulated(false /* certificate.mPopulated */), - mType(certificate.mType), - mEncoding(certificate.mEncoding), - mCL(certificate.mCL), - mCertHandle(0), - mV1SubjectPublicKeyCStructValue(NULL), - mV1SubjectNameCStructValue(NULL), - mV1IssuerNameCStructValue(NULL), - mSha1Hash(NULL), - mEncodingVerified(false) -{ -} - -Certificate::~Certificate() -try -{ - if (mV1SubjectPublicKeyCStructValue) - releaseFieldValue(CSSMOID_X509V1SubjectPublicKeyCStruct, mV1SubjectPublicKeyCStructValue); - - if (mCertHandle && mCL) - CSSM_CL_CertAbortCache(mCL->handle(), mCertHandle); - - if (mV1SubjectNameCStructValue) - releaseFieldValue(CSSMOID_X509V1SubjectNameCStruct, mV1SubjectNameCStructValue); - - if (mV1IssuerNameCStructValue) - releaseFieldValue(CSSMOID_X509V1IssuerNameCStruct, mV1IssuerNameCStructValue); - - if (mSha1Hash) - CFRelease(mSha1Hash); -} -catch (...) -{ -} - -CSSM_HANDLE -Certificate::certHandle() -{ - StLock_(mMutex); - const CSSM_DATA *cert = &data(); - if (!mCertHandle) - { - if (CSSM_RETURN retval = CSSM_CL_CertCache(clHandle(), cert, &mCertHandle)) - CssmError::throwMe(retval); - } - - return mCertHandle; -} - -/* Return a zero terminated list of CSSM_DATA_PTR's with the values of the field specified by field. Caller must call releaseFieldValues to free the storage allocated by this call. */ -CSSM_DATA_PTR * -Certificate::copyFieldValues(const CSSM_OID &field) -{ - StLock_(mMutex); - CSSM_CL_HANDLE clh = clHandle(); - CSSM_DATA_PTR fieldValue, *fieldValues; - CSSM_HANDLE resultsHandle = 0; - uint32 numberOfFields = 0; - CSSM_RETURN result; - - result = CSSM_CL_CertGetFirstCachedFieldValue(clh, certHandle(), &field, &resultsHandle, &numberOfFields, &fieldValue); - if (result) - { - if (result == CSSMERR_CL_NO_FIELD_VALUES) - return NULL; - - CssmError::throwMe(result); - } - - fieldValues = new CSSM_DATA_PTR[numberOfFields + 1]; - fieldValues[0] = fieldValue; - fieldValues[numberOfFields] = NULL; - - for (uint32 value = 1; value < numberOfFields; ++value) - { - CSSM_RETURN cresult = CSSM_CL_CertGetNextCachedFieldValue(clh, resultsHandle, &fieldValues[value]); - if (cresult) - { - fieldValues[value] = NULL; - result = cresult; - break; // No point in continuing really. - } - } - - CSSM_CL_CertAbortQuery(clh, resultsHandle); - - if (result) - { - releaseFieldValues(field, fieldValues); - CssmError::throwMe(result); - } - - return fieldValues; -} - -void -Certificate::releaseFieldValues(const CSSM_OID &field, CSSM_DATA_PTR *fieldValues) -{ - StLock_(mMutex); - if (fieldValues) - { - CSSM_CL_HANDLE clh = clHandle(); - - for (int ix = 0; fieldValues[ix]; ++ix) - CSSM_CL_FreeFieldValue(clh, &field, fieldValues[ix]); - - delete[] fieldValues; - } -} - -void -Certificate::addParsedAttribute(const CSSM_DB_ATTRIBUTE_INFO &info, const CSSM_OID &field) -{ - StLock_(mMutex); - CSSM_DATA_PTR *fieldValues = copyFieldValues(field); - if (fieldValues) - { - CssmDbAttributeData &anAttr = mDbAttributes->add(info); - for (int ix = 0; fieldValues[ix]; ++ix) - anAttr.add(*fieldValues[ix], *mDbAttributes); - - releaseFieldValues(field, fieldValues); - } -} - -void -Certificate::addSubjectKeyIdentifier() -{ - StLock_(mMutex); - const CSSM_DB_ATTRIBUTE_INFO &info = Schema::attributeInfo(kSecSubjectKeyIdentifierItemAttr); - const CSSM_OID &field = CSSMOID_SubjectKeyIdentifier; - - CSSM_DATA_PTR *fieldValues = copyFieldValues(field); - if (fieldValues) - { - CssmDbAttributeData &anAttr = mDbAttributes->add(info); - for (int ix = 0; fieldValues[ix]; ++ix) - { - const CSSM_X509_EXTENSION *extension = reinterpret_cast(fieldValues[ix]->Data); - if (extension == NULL || fieldValues[ix]->Length != sizeof(CSSM_X509_EXTENSION)) - { - assert(extension != NULL && fieldValues[ix]->Length == sizeof(CSSM_X509_EXTENSION)); - continue; - } - const CE_SubjectKeyID *skid = reinterpret_cast(extension->value.parsedValue); - if (skid == NULL) - { - assert(skid != NULL); - continue; - } - anAttr.add(*skid, *mDbAttributes); - } - - releaseFieldValues(field, fieldValues); - } -} - -/* Return a CSSM_DATA_PTR with the value of the first field specified by field. Caller must call releaseFieldValue to free the storage allocated by this call. */ -CSSM_DATA_PTR -Certificate::copyFirstFieldValue(const CSSM_OID &field) -{ - StLock_(mMutex); - CSSM_CL_HANDLE clh = clHandle(); - CSSM_DATA_PTR fieldValue; - CSSM_HANDLE resultsHandle = 0; - uint32 numberOfFields = 0; - CSSM_RETURN result; - - result = CSSM_CL_CertGetFirstCachedFieldValue(clh, certHandle(), &field, &resultsHandle, &numberOfFields, &fieldValue); - if (result) - { - if (result == CSSMERR_CL_NO_FIELD_VALUES) - return NULL; - - CssmError::throwMe(result); - } - - result = CSSM_CL_CertAbortQuery(clh, resultsHandle); - - if (result) - { - releaseFieldValue(field, fieldValue); - CssmError::throwMe(result); - } - - return fieldValue; -} - -void -Certificate::releaseFieldValue(const CSSM_OID &field, CSSM_DATA_PTR fieldValue) -{ - StLock_(mMutex); - if (fieldValue) - { - CSSM_CL_HANDLE clh = clHandle(); - CSSM_CL_FreeFieldValue(clh, &field, fieldValue); - } -} - - - -/* - This method computes the keyIdentifier for the public key in the cert as - described below: - - The keyIdentifier is composed of the 160-bit SHA-1 hash of the - value of the BIT STRING subjectPublicKey (excluding the tag, - length, and number of unused bits). -*/ -const CssmData & -Certificate::publicKeyHash() -{ - StLock_(mMutex); - if (mPublicKeyHash.Length) - return mPublicKeyHash; - - CSSM_DATA_PTR keyPtr = copyFirstFieldValue(CSSMOID_CSSMKeyStruct); - if (keyPtr && keyPtr->Data) - { - CssmClient::CSP csp(gGuidAppleCSP); - CssmClient::PassThrough passThrough(csp); - CSSM_KEY *key = reinterpret_cast(keyPtr->Data); - void *outData; - CssmData *cssmData; - - /* Given a CSSM_KEY_PTR in any format, obtain the SHA-1 hash of the - * associated key blob. - * Key is specified in CSSM_CSP_CreatePassThroughContext. - * Hash is allocated by the CSP, in the App's memory, and returned - * in *outData. */ - passThrough.key(key); - passThrough(CSSM_APPLECSP_KEYDIGEST, NULL, &outData); - cssmData = reinterpret_cast(outData); - - assert(cssmData->Length <= sizeof(mPublicKeyHashBytes)); - mPublicKeyHash.Data = mPublicKeyHashBytes; - mPublicKeyHash.Length = cssmData->Length; - memcpy(mPublicKeyHash.Data, cssmData->Data, cssmData->Length); - csp.allocator().free(cssmData->Data); - csp.allocator().free(cssmData); - } - - releaseFieldValue(CSSMOID_CSSMKeyStruct, keyPtr); - - return mPublicKeyHash; -} - -const CssmData & -Certificate::subjectKeyIdentifier() -{ - StLock_(mMutex); - if (mSubjectKeyID.Length) - return mSubjectKeyID; - - CSSM_DATA_PTR fieldValue = copyFirstFieldValue(CSSMOID_SubjectKeyIdentifier); - if (fieldValue && fieldValue->Data && fieldValue->Length == sizeof(CSSM_X509_EXTENSION)) - { - const CSSM_X509_EXTENSION *extension = reinterpret_cast(fieldValue->Data); - const CE_SubjectKeyID *skid = reinterpret_cast(extension->value.parsedValue); // CSSM_DATA - - if (skid->Length <= sizeof(mSubjectKeyIDBytes)) - { - mSubjectKeyID.Data = mSubjectKeyIDBytes; - mSubjectKeyID.Length = skid->Length; - memcpy(mSubjectKeyID.Data, skid->Data, skid->Length); - } - else - mSubjectKeyID.Length = 0; - } - - releaseFieldValue(CSSMOID_SubjectKeyIdentifier, fieldValue); - - return mSubjectKeyID; -} - - -/* - * Given an CSSM_X509_NAME, Find the first (or last) name/value pair with - * a printable value which matches the specified OID (e.g., CSSMOID_CommonName). - * Returns the CFString-style encoding associated with name component's BER tag. - * Returns NULL if none found. - */ -static const CSSM_DATA * -findPrintableField( - const CSSM_X509_NAME &x509Name, - const CSSM_OID *tvpType, // NULL means "any printable field" - bool lastInstance, // false means return first instance - CFStringBuiltInEncodings *encoding) // RETURNED -{ - const CSSM_DATA *result = NULL; - for(uint32 rdnDex=0; rdnDexnumberOfPairs; tvpDex++) { - const CSSM_X509_TYPE_VALUE_PAIR *tvpPtr = - &rdnPtr->AttributeTypeAndValue[tvpDex]; - - /* type/value pair: match caller's specified type? */ - if(tvpType != NULL && tvpType->Data != NULL) { - if(tvpPtr->type.Length != tvpType->Length) { - continue; - } - if(memcmp(tvpPtr->type.Data, tvpType->Data, tvpType->Length)) { - /* If we don't have a match but the requested OID is CSSMOID_UserID, - * look for a matching X.500 UserID OID: (0.9.2342.19200300.100.1.1) */ - const char cssm_userid_oid[] = { 0x09,0x49,0x86,0x49,0x1f,0x12,0x8c,0xe4,0x81,0x81 }; - const char x500_userid_oid[] = { 0x09,0x92,0x26,0x89,0x93,0xF2,0x2C,0x64,0x01,0x01 }; - if(!(tvpType->Length == sizeof(cssm_userid_oid) && - !memcmp(tvpPtr->type.Data, x500_userid_oid, sizeof(x500_userid_oid)) && - !memcmp(tvpType->Data, cssm_userid_oid, sizeof(cssm_userid_oid)))) { - continue; - } - } - } - - /* printable? */ - switch(tvpPtr->valueType) { - case BER_TAG_PRINTABLE_STRING: - case BER_TAG_IA5_STRING: - *encoding = kCFStringEncodingASCII; - result = &tvpPtr->value; - break; - case BER_TAG_PKIX_UTF8_STRING: - case BER_TAG_GENERAL_STRING: - case BER_TAG_PKIX_UNIVERSAL_STRING: - *encoding = kCFStringEncodingUTF8; - result = &tvpPtr->value; - break; - case BER_TAG_T61_STRING: - case BER_TAG_VIDEOTEX_STRING: - case BER_TAG_ISO646_STRING: - *encoding = kCFStringEncodingISOLatin1; - result = &tvpPtr->value; - break; - case BER_TAG_PKIX_BMP_STRING: - *encoding = kCFStringEncodingUnicode; - result = &tvpPtr->value; - break; - default: - /* not printable */ - break; - } - /* if we found a result and we want the first instance, return it now. */ - if(result && !lastInstance) { - return result; - } - - } /* for each pair */ - } /* for each RDN */ - - /* result is NULL if no printable component was found */ - return result; -} - -/* - * Infer printable label for a given CSSM_X509_NAME. Returns NULL - * if no appropriate printable name found. Returns the CFString-style - * encoding associated with name component's BER tag. Also optionally - * returns Description component and its encoding if present and the - * returned name component was one we explicitly requested. - */ -static const CSSM_DATA *inferLabelFromX509Name( - const CSSM_X509_NAME *x509Name, - CFStringBuiltInEncodings *encoding, // RETURNED - const CSSM_DATA **description, // optionally RETURNED - CFStringBuiltInEncodings *descrEncoding) // RETURNED if description != NULL -{ - const CSSM_DATA *printValue; - if(description != NULL) { - *description = findPrintableField(*x509Name, &CSSMOID_Description, false, descrEncoding); - } - /* - * Search order (take the first one found with a printable - * value): - * -- common name - * -- Organizational Unit - * -- Organization - * -- email address - * -- field of any kind - */ - printValue = findPrintableField(*x509Name, &CSSMOID_CommonName, true, encoding); - if(printValue != NULL) { - return printValue; - } - printValue = findPrintableField(*x509Name, &CSSMOID_OrganizationalUnitName, false, encoding); - if(printValue != NULL) { - return printValue; - } - printValue = findPrintableField(*x509Name, &CSSMOID_OrganizationName, false, encoding); - if(printValue != NULL) { - return printValue; - } - printValue = findPrintableField(*x509Name, &CSSMOID_EmailAddress, false, encoding); - if(printValue != NULL) { - return printValue; - } - /* if we didn't get one of the above names, don't append description */ - if(description != NULL) { - *description = NULL; - } - /* take anything */ - return findPrintableField(*x509Name, NULL, false, encoding); -} - -/* - * Infer printable label for a given an CSSM_X509_NAME. Returns NULL - * if no appropriate printable name found. - */ -const CSSM_DATA *SecInferLabelFromX509Name( - const CSSM_X509_NAME *x509Name) -{ - /* callees of this routine don't care about the encoding */ - CFStringBuiltInEncodings encoding = kCFStringEncodingASCII; - return inferLabelFromX509Name(x509Name, &encoding, NULL, &encoding); -} - - -void -Certificate::inferLabel(bool addLabel, CFStringRef *rtnString) -{ - StLock_(mMutex); - // Set PrintName and optionally the Alias attribute for this certificate, based on the - // X509 SubjectAltName and SubjectName. - const CSSM_DATA *printName = NULL; - const CSSM_DATA *description = NULL; - std::vector emailAddresses; - CSSM_DATA puntData; - CssmAutoData printPlusDescr(Allocator::standard()); - CssmData printPlusDescData; - CFStringBuiltInEncodings printEncoding = kCFStringEncodingUTF8; - CFStringBuiltInEncodings descrEncoding = kCFStringEncodingUTF8; - - // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them - const CSSM_OID &sanOid = CSSMOID_SubjectAltName; - CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid); - const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct; - CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid); - - getNames(sanValues, snValue, GNT_RFC822Name, emailAddresses); - - if (snValue && snValue->Data) - { - const CSSM_X509_NAME &x509Name = *(const CSSM_X509_NAME *)snValue->Data; - printName = inferLabelFromX509Name(&x509Name, &printEncoding, - &description, &descrEncoding); - if (printName) - { - /* Don't ever use "Thawte Freemail Member" as the label for a cert. Instead force - a fall back on the email address. */ - const char tfm[] = "Thawte Freemail Member"; - if ( (printName->Length == sizeof(tfm) - 1) && - !memcmp(printName->Data, tfm, sizeof(tfm) - 1)) { - printName = NULL; - } - } - } - - /* Do a check to see if a '\0' was at the end of printName and strip it. */ - CssmData cleanedUpPrintName; - if((printName != NULL) && - (printName->Length != 0) && - (printEncoding != kCFStringEncodingISOLatin1) && - (printEncoding != kCFStringEncodingUnicode) && - (printName->Data[printName->Length - 1] == '\0')) { - cleanedUpPrintName.Data = printName->Data; - cleanedUpPrintName.Length = printName->Length - 1; - printName = &cleanedUpPrintName; - } - - if((printName != NULL) && (description != NULL) && (description->Length != 0)) - { - /* - * Munge Print Name (which in this case is the CommonName) and Description - * together with the Description in parentheses. We convert from whatever - * format Print Name and Description are in to UTF8 here. - */ - CFRef combo(CFStringCreateMutable(NULL, 0)); - CFRef cfPrint(CFStringCreateWithBytes(NULL, printName->Data, - (CFIndex)printName->Length, printEncoding, true)); - CssmData cleanedUpDescr(description->Data, description->Length); - if ((cleanedUpDescr.Data[cleanedUpDescr.Length - 1] == '\0') && - (descrEncoding != kCFStringEncodingISOLatin1) && - (descrEncoding != kCFStringEncodingUnicode)) { - cleanedUpDescr.Length--; - } - CFRef cfDesc(CFStringCreateWithBytes(NULL, cleanedUpDescr.Data, - (CFIndex)cleanedUpDescr.Length, descrEncoding, true)); - CFStringAppend(combo, cfPrint); - CFStringAppendCString(combo, " (", kCFStringEncodingASCII); - CFStringAppend(combo, cfDesc); - CFStringAppendCString(combo, ")", kCFStringEncodingASCII); - CFRef comboData(CFStringCreateExternalRepresentation(NULL, combo, - kCFStringEncodingUTF8, 0)); - printPlusDescr.copy(CFDataGetBytePtr(comboData), CFDataGetLength(comboData)); - printPlusDescData = printPlusDescr; - printName = &printPlusDescData; - printEncoding = kCFStringEncodingUTF8; - } - - if (printName == NULL) - { - /* If the we couldn't find a label use the emailAddress instead. */ - if (!emailAddresses.empty()) - printName = &emailAddresses[0]; - else - { - /* punt! */ - puntData.Data = (uint8 *)"X509 Certificate"; - puntData.Length = 16; - printName = &puntData; - } - printEncoding = kCFStringEncodingUTF8; - } - - /* If we couldn't find an email address just use the printName which might be the url or something else useful. */ - if (emailAddresses.empty()) - emailAddresses.push_back(CssmData::overlay(*printName)); - - /* What do we do with the inferred label - return it or add it mDbAttributes? */ - if (addLabel) - { - mDbAttributes->add(Schema::kX509CertificatePrintName, *printName); - CssmDbAttributeData &attrData = mDbAttributes->add(Schema::kX509CertificateAlias); - - /* Add the email addresses to attrData and normalize them. */ - uint32 ix = 0; - for (std::vector::const_iterator it = emailAddresses.begin(); it != emailAddresses.end(); ++it, ++ix) - { - /* Add the email address using the allocator from mDbAttributes. */ - attrData.add(*it, *mDbAttributes); - /* Normalize the emailAddresses in place since attrData already copied it. */ - normalizeEmailAddress(attrData.Value[ix]); - } - } - - if (rtnString) - { - CFStringBuiltInEncodings testEncoding = printEncoding; - if(testEncoding == kCFStringEncodingISOLatin1) { - // try UTF-8 first - testEncoding = kCFStringEncodingUTF8; - } - *rtnString = CFStringCreateWithBytes(NULL, printName->Data, - (CFIndex)printName->Length, testEncoding, true); - if(*rtnString == NULL && printEncoding == kCFStringEncodingISOLatin1) { - // string cannot be represented in UTF-8, fall back to ISO Latin 1 - *rtnString = CFStringCreateWithBytes(NULL, printName->Data, - (CFIndex)printName->Length, printEncoding, true); - } - } - - // Clean up - if (snValue) - releaseFieldValue(snOid, snValue); - if (sanValues) - releaseFieldValues(sanOid, sanValues); -} - -void -Certificate::populateAttributes() -{ - StLock_(mMutex); - if (mPopulated) - return; - - addParsedAttribute(Schema::attributeInfo(kSecSubjectItemAttr), CSSMOID_X509V1SubjectName); - addParsedAttribute(Schema::attributeInfo(kSecIssuerItemAttr), CSSMOID_X509V1IssuerName); - addParsedAttribute(Schema::attributeInfo(kSecSerialNumberItemAttr), CSSMOID_X509V1SerialNumber); - - addSubjectKeyIdentifier(); - - if(!mHaveTypeAndEncoding) - MacOSError::throwMe(errSecDataNotAvailable); // @@@ Or some other error. - - // Adjust mType based on the actual version of the cert. - CSSM_DATA_PTR versionPtr = copyFirstFieldValue(CSSMOID_X509V1Version); - if (versionPtr && versionPtr->Data && versionPtr->Length == sizeof(uint32)) - { - mType = CSSM_CERT_X_509v1 + (*reinterpret_cast(versionPtr->Data)); - } - else - mType = CSSM_CERT_X_509v1; - - releaseFieldValue(CSSMOID_X509V1Version, versionPtr); - - mDbAttributes->add(Schema::attributeInfo(kSecCertTypeItemAttr), mType); - mDbAttributes->add(Schema::attributeInfo(kSecCertEncodingItemAttr), mEncoding); - mDbAttributes->add(Schema::attributeInfo(kSecPublicKeyHashItemAttr), publicKeyHash()); - inferLabel(true); - - mPopulated = true; -} - -bool -Certificate::verifyEncoding(CSSM_DATA_PTR data) -{ - bool verified = false; - CSSM_SIZE verifiedLength = 0; - { - StLock_(mMutex); - if (!data || !data->Data || !data->Length) { - mEncodingVerified = false; - return false; - } - verified = mEncodingVerified; - if (verified) { - return true; - } - - // Note: the Certificate class supports X509v1 through X509v3 certs, - // with CSSM_CERT_ENCODING_BER or CSSM_CERT_ENCODING_DER encoding. - // Any other types/encodings would need additional verification code here. - - if (mHaveTypeAndEncoding) { - if (mType < CSSM_CERT_X_509v1 || mType > CSSM_CERT_X_509v3) { - secdebug("Certificate", "verifyEncoding: certificate has custom type (%d)", (int)mType); - } - if (mEncoding < CSSM_CERT_ENCODING_BER || mEncoding > CSSM_CERT_ENCODING_DER) { - secdebug("Certificate", "verifyEncoding: certificate has custom encoding (%d)", (int)mEncoding); - } - } - - // attempt to decode the top-level ASN.1 sequence - const DERItem der = { (DERByte *)data->Data, (DERSize)data->Length }; - DERDecodedInfo derInfo; - // sanity check the first byte to avoid decoding a non-DER blob - if ((DERByte)0x30 != *(der.data)) { - return false; - } - DERReturn drtn = DERDecodeItem(&der, &derInfo); - if (drtn == DR_Success) { - CSSM_SIZE tagLength = (CSSM_SIZE)((uintptr_t)derInfo.content.data - (uintptr_t)der.data); - CSSM_SIZE derLength = (CSSM_SIZE)derInfo.content.length + tagLength; - if (derLength != data->Length) { - secdebug("Certificate", "Certificate DER length is %d, but data length is %d", - (int)derLength, (int)data->Length); - // will adjust data size if DER length is positive, but smaller than actual length - if ((derLength > 0) && (derLength < data->Length)) { - verifiedLength = derLength; - secdebug("Certificate", "Will adjust certificate data length to %d", - (int)derLength); - } - else { - secdebug("Certificate", "Certificate encoding invalid (DER length is %d)", - (int)derLength); - return false; - } - } - verified = mEncodingVerified = true; - } - else { - // failure to decode provided data as DER sequence - secdebug("Certificate", "Certificate not in DER encoding (error %d)", - (int)drtn); - return false; - } - } - - if (verifiedLength > 0) { - // setData acquires the mMutex lock, so we call it while not holding the lock - setData((UInt32)verifiedLength, data->Data); - secdebug("Certificate", "Adjusted certificate data length to %d", - (int)verifiedLength); - } - - return verified; -} - -const CssmData & -Certificate::data() -{ - CssmDataContainer *data = NULL; - bool hasKeychain = false; - bool verified = false; - { - StLock_(mMutex); - data = mData.get(); - hasKeychain = (mKeychain != NULL); - verified = mEncodingVerified; - } - - // If data has been set but not yet verified, verify it now. - if (!verified && data) { - // verifyEncoding might modify mData, so refresh the data container - verified = verifyEncoding(data); - { - StLock_(mMutex); - data = mData.get(); - } - } - - // If data isn't set at this point, try to read it from the db record - if (!data && hasKeychain) - { - // Make sure mUniqueId is set. - dbUniqueRecord(); - CssmDataContainer _data; - { - StLock_(mMutex); - mData = NULL; - /* new data allocated by CSPDL, implicitly freed by CssmDataContainer */ - mUniqueId->get(NULL, &_data); - } - /* this saves a copy to be freed at destruction and to be passed to caller */ - setData((UInt32)_data.length(), _data.data()); - // verifyEncoding might modify mData, so refresh the data container - verified = verifyEncoding(&_data); - { - StLock_(mMutex); - data = mData.get(); - } - } - - // If the data hasn't been set we can't return it. - if (!data) - MacOSError::throwMe(errSecDataNotAvailable); - - return *data; -} - -CFHashCode Certificate::hash() -{ - (void)data(); // ensure that mData is set up - return ItemImpl::hash(); -} - -CSSM_CERT_TYPE -Certificate::type() -{ - StLock_(mMutex); - if (!mHaveTypeAndEncoding) - { - SecKeychainAttribute attr; - attr.tag = kSecCertTypeItemAttr; - attr.data = &mType; - attr.length = sizeof(mType); - getAttribute(attr, NULL); - } - - return mType; -} - -CSSM_CERT_ENCODING -Certificate::encoding() -{ - StLock_(mMutex); - if (!mHaveTypeAndEncoding) - { - SecKeychainAttribute attr; - attr.tag = kSecCertEncodingItemAttr; - attr.data = &mEncoding; - attr.length = sizeof(mEncoding); - getAttribute(attr, NULL); - } - - return mEncoding; -} - -const CSSM_X509_ALGORITHM_IDENTIFIER_PTR -Certificate::algorithmID() -{ - StLock_(mMutex); - if (!mV1SubjectPublicKeyCStructValue) - mV1SubjectPublicKeyCStructValue = copyFirstFieldValue(CSSMOID_X509V1SubjectPublicKeyCStruct); - - CSSM_X509_SUBJECT_PUBLIC_KEY_INFO *info = (CSSM_X509_SUBJECT_PUBLIC_KEY_INFO *)mV1SubjectPublicKeyCStructValue->Data; - CSSM_X509_ALGORITHM_IDENTIFIER *algid = &info->algorithm; - return algid; -} - -CFDataRef -Certificate::sha1Hash() -{ - StLock_(mMutex); - if (!mSha1Hash) { - SecCertificateRef certRef = handle(false); - CFAllocatorRef allocRef = (certRef) ? CFGetAllocator(certRef) : NULL; - CSSM_DATA certData = data(); - if (certData.Length == 0 || !certData.Data) { - MacOSError::throwMe(errSecDataNotAvailable); - } - const UInt8 *dataPtr = (const UInt8 *)certData.Data; - CFIndex dataLen = (CFIndex)certData.Length; - CFMutableDataRef digest = CFDataCreateMutable(allocRef, CC_SHA1_DIGEST_LENGTH); - CFDataSetLength(digest, CC_SHA1_DIGEST_LENGTH); - CCDigest(kCCDigestSHA1, dataPtr, dataLen, CFDataGetMutableBytePtr(digest)); - mSha1Hash = digest; - } - return mSha1Hash; /* object is owned by our instance; caller should NOT release it */ -} - -CFStringRef -Certificate::commonName() -{ - StLock_(mMutex); - return distinguishedName(&CSSMOID_X509V1SubjectNameCStruct, &CSSMOID_CommonName); -} - -CFStringRef -Certificate::distinguishedName(const CSSM_OID *sourceOid, const CSSM_OID *componentOid) -{ - StLock_(mMutex); - CFStringRef rtnString = NULL; - CSSM_DATA_PTR fieldValue = copyFirstFieldValue(*sourceOid); - CSSM_X509_NAME_PTR x509Name = (CSSM_X509_NAME_PTR)fieldValue->Data; - const CSSM_DATA *printValue = NULL; - CFStringBuiltInEncodings encoding; - - if (fieldValue && fieldValue->Data) - printValue = findPrintableField(*x509Name, componentOid, true, &encoding); - - if (printValue) - rtnString = CFStringCreateWithBytes(NULL, printValue->Data, - CFIndex(printValue->Length), encoding, true); - - releaseFieldValue(*sourceOid, fieldValue); - - return rtnString; -} - - -/* - * Return a CFString containing the first email addresses for this certificate, based on the - * X509 SubjectAltName and SubjectName. - */ -CFStringRef -Certificate::copyFirstEmailAddress() -{ - StLock_(mMutex); - CFStringRef rtnString; - - const CSSM_OID &sanOid = CSSMOID_SubjectAltName; - CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid); - const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct; - CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid); - std::vector emailAddresses; - - getNames(sanValues, snValue, GNT_RFC822Name, emailAddresses); - if (emailAddresses.empty()) - rtnString = NULL; - else - { - /* Encoding is kCFStringEncodingUTF8 since the string is either - PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */ - rtnString = CFStringCreateWithBytes(NULL, emailAddresses[0].Data, - (CFIndex)emailAddresses[0].Length, kCFStringEncodingUTF8, true); - } - - // Clean up - if (snValue) - releaseFieldValue(snOid, snValue); - if (sanValues) - releaseFieldValues(sanOid, sanValues); - - return rtnString; -} - -/* - * Return a CFArray containing the DNS hostnames for this certificate, based on the - * X509 SubjectAltName and SubjectName. - */ -CFArrayRef -Certificate::copyDNSNames() -{ - StLock_(mMutex); - CFMutableArrayRef array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - std::vector dnsNames; - - // Find the SubjectAltName fields, if any, and extract the GNT_DNSName entries from all of them - const CSSM_OID &sanOid = CSSMOID_SubjectAltName; - CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid); - - const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct; - CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid); - - getNames(sanValues, snValue, GNT_DNSName, dnsNames); - - for (std::vector::const_iterator it = dnsNames.begin(); it != dnsNames.end(); ++it) - { - /* Encoding is kCFStringEncodingUTF8 since the string is either - PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */ - CFStringRef string = CFStringCreateWithBytes(NULL, it->Data, static_cast(it->Length), kCFStringEncodingUTF8, true); - /* Be prepared for improperly formatted (non-UTF8) strings! */ - if (!string) continue; - CFArrayAppendValue(array, string); - CFRelease(string); - } - - // Clean up - if (snValue) - releaseFieldValue(snOid, snValue); - if (sanValues) - releaseFieldValues(sanOid, sanValues); - - return array; -} - -/* - * Return a CFArray containing the email addresses for this certificate, based on the - * X509 SubjectAltName and SubjectName. - */ -CFArrayRef -Certificate::copyEmailAddresses() -{ - StLock_(mMutex); - CFMutableArrayRef array = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - std::vector emailAddresses; - - // Find the SubjectAltName fields, if any, and extract all the GNT_RFC822Name entries from all of them - const CSSM_OID &sanOid = CSSMOID_SubjectAltName; - CSSM_DATA_PTR *sanValues = copyFieldValues(sanOid); - - const CSSM_OID &snOid = CSSMOID_X509V1SubjectNameCStruct; - CSSM_DATA_PTR snValue = copyFirstFieldValue(snOid); - - getNames(sanValues, snValue, GNT_RFC822Name, emailAddresses); - - for (std::vector::const_iterator it = emailAddresses.begin(); it != emailAddresses.end(); ++it) - { - /* Encoding is kCFStringEncodingUTF8 since the string is either - PRINTABLE_STRING, IA5_STRING, T61_STRING or PKIX_UTF8_STRING. */ - CFStringRef string = CFStringCreateWithBytes(NULL, it->Data, static_cast(it->Length), kCFStringEncodingUTF8, true); - /* Be prepared for improperly formatted (non-UTF8) strings! */ - if (!string) continue; - CFArrayAppendValue(array, string); - CFRelease(string); - } - - // Clean up - if (snValue) - releaseFieldValue(snOid, snValue); - if (sanValues) - releaseFieldValues(sanOid, sanValues); - - return array; -} - -const CSSM_X509_NAME_PTR -Certificate::subjectName() -{ - StLock_(mMutex); - if (!mV1SubjectNameCStructValue) - if ((mV1SubjectNameCStructValue = copyFirstFieldValue(CSSMOID_X509V1SubjectNameCStruct)) == NULL) - return NULL; - - return (const CSSM_X509_NAME_PTR)mV1SubjectNameCStructValue->Data; -} - -const CSSM_X509_NAME_PTR -Certificate::issuerName() -{ - StLock_(mMutex); - if (!mV1IssuerNameCStructValue) - if ((mV1IssuerNameCStructValue = copyFirstFieldValue(CSSMOID_X509V1IssuerNameCStruct)) == NULL) - return NULL; - - return (const CSSM_X509_NAME_PTR)mV1IssuerNameCStructValue->Data; -} - -CSSM_CL_HANDLE -Certificate::clHandle() -{ - StLock_(mMutex); - if (!mCL) - mCL = clForType(type()); - - return mCL->handle(); -} - -bool -Certificate::operator < (Certificate &other) -{ - // Certificates in different keychains are considered equal if data is equal - // Note that the Identity '<' operator relies on this assumption. - return data() < other.data(); -} - -bool -Certificate::operator == (Certificate &other) -{ - // Certificates in different keychains are considered equal if data is equal - // Note that the Identity '==' operator relies on this assumption. - return data() == other.data(); -} - -void -Certificate::update() -{ - ItemImpl::update(); -} - -Item -Certificate::copyTo(const Keychain &keychain, Access *newAccess) -{ - StLock_(mMutex); - /* Certs can't have access controls. */ - if (newAccess) - MacOSError::throwMe(errSecNoAccessForItem); - - Item item(new Certificate(data(), type(), encoding())); - keychain->add(item); - return item; -} - -void -Certificate::didModify() -{ -} - -PrimaryKey -Certificate::add(Keychain &keychain) -{ - StLock_(mMutex); - // If we already have a Keychain we can't be added. - if (mKeychain) - MacOSError::throwMe(errSecDuplicateItem); - - populateAttributes(); - - CSSM_DB_RECORDTYPE recordType = mDbAttributes->recordType(); - - Db db(keychain->database()); - // add the item to the (regular) db - try - { - mUniqueId = db->insert(recordType, mDbAttributes.get(), mData.get()); - } - catch (const CssmError &e) - { - if (e.osStatus() != CSSMERR_DL_INVALID_RECORDTYPE) - throw; - - // Create the cert relation and try again. - db->createRelation(CSSM_DL_DB_RECORD_X509_CERTIFICATE, - "CSSM_DL_DB_RECORD_X509_CERTIFICATE", - Schema::X509CertificateSchemaAttributeCount, - Schema::X509CertificateSchemaAttributeList, - Schema::X509CertificateSchemaIndexCount, - Schema::X509CertificateSchemaIndexList); - keychain->keychainSchema()->didCreateRelation( - CSSM_DL_DB_RECORD_X509_CERTIFICATE, - "CSSM_DL_DB_RECORD_X509_CERTIFICATE", - Schema::X509CertificateSchemaAttributeCount, - Schema::X509CertificateSchemaAttributeList, - Schema::X509CertificateSchemaIndexCount, - Schema::X509CertificateSchemaIndexList); - - mUniqueId = db->insert(recordType, mDbAttributes.get(), mData.get()); - } - - mPrimaryKey = keychain->makePrimaryKey(recordType, mUniqueId); - mKeychain = keychain; - - return mPrimaryKey; -} - -SecPointer -Certificate::publicKey() -{ - StLock_(mMutex); - SecPointer keyItem; - // Return a CSSM_DATA_PTR with the value of the first field specified by field. - // Caller must call releaseFieldValue to free the storage allocated by this call. - // call OSStatus SecKeyGetCSSMKey(SecKeyRef key, const CSSM_KEY **cssmKey); to retrieve - - CSSM_DATA_PTR keyPtr = copyFirstFieldValue(CSSMOID_CSSMKeyStruct); - if (keyPtr && keyPtr->Data) - { - CssmClient::CSP csp(gGuidAppleCSP); - CssmKey *cssmKey = reinterpret_cast(keyPtr->Data); - CssmClient::Key key(csp, *cssmKey); - keyItem = new KeyItem(key); - // Clear out KeyData since KeyItem() takes over ownership of the key, and we don't want it getting released. - cssmKey->KeyData.Data = NULL; - cssmKey->KeyData.Length = 0; - } - - releaseFieldValue(CSSMOID_CSSMKeyStruct, keyPtr); - - return keyItem; -} - -// This function "borrowed" from the X509 CL, which is (currently) linked into -// the Security.framework as a built-in plugin. -extern "C" bool getField_normRDN_NSS ( - const CSSM_DATA &derName, - uint32 &numFields, // RETURNED (if successful, 0 or 1) - CssmOwnedData &fieldValue); // RETURNED - -KCCursor -Certificate::cursorForIssuerAndSN(const StorageManager::KeychainList &keychains, const CssmData &issuer, const CssmData &serialNumber) -{ - CssmAutoData fieldValue(Allocator::standard(Allocator::normal)); - uint32 numFields; - - // We need to decode issuer, normalize it, then re-encode it - if (!getField_normRDN_NSS(issuer, numFields, fieldValue)) - MacOSError::throwMe(errSecDataNotAvailable); - - // Code basically copied from SecKeychainSearchCreateFromAttributes and SecKeychainSearchCopyNext: - KCCursor cursor(keychains, kSecCertificateItemClass, NULL); - cursor->conjunctive(CSSM_DB_AND); - cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateIssuer, fieldValue.get()); - cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateSerialNumber, serialNumber); - - return cursor; -} - -KCCursor -Certificate::cursorForIssuerAndSN_CF(const StorageManager::KeychainList &keychains, CFDataRef issuer, CFDataRef serialNumber) -{ - // This assumes a normalized issuer - CSSM_DATA issuerCSSM, serialNumberCSSM; - - issuerCSSM.Length = CFDataGetLength(issuer); - issuerCSSM.Data = const_cast(CFDataGetBytePtr(issuer)); - - serialNumberCSSM.Length = CFDataGetLength(serialNumber); - serialNumberCSSM.Data = const_cast(CFDataGetBytePtr(serialNumber)); - - // Code basically copied from SecKeychainSearchCreateFromAttributes and SecKeychainSearchCopyNext: - KCCursor cursor(keychains, kSecCertificateItemClass, NULL); - cursor->conjunctive(CSSM_DB_AND); - cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateIssuer, issuerCSSM); - cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateSerialNumber, serialNumberCSSM); - - return cursor; -} - -KCCursor -Certificate::cursorForSubjectKeyID(const StorageManager::KeychainList &keychains, const CssmData &subjectKeyID) -{ - KCCursor cursor(keychains, kSecCertificateItemClass, NULL); - cursor->conjunctive(CSSM_DB_AND); - cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateSubjectKeyIdentifier, subjectKeyID); - - return cursor; -} - -KCCursor -Certificate::cursorForEmail(const StorageManager::KeychainList &keychains, const char *emailAddress) -{ - KCCursor cursor(keychains, kSecCertificateItemClass, NULL); - if (emailAddress) - { - cursor->conjunctive(CSSM_DB_AND); - CssmSelectionPredicate &pred = cursor->add(CSSM_DB_EQUAL, Schema::kX509CertificateAlias, emailAddress); - /* Normalize the emailAddresses in place since cursor already copied it. */ - normalizeEmailAddress(pred.Attribute.Value[0]); - } - - return cursor; -} - -SecPointer -Certificate::findInKeychain(const StorageManager::KeychainList &keychains) -{ - StLock_(mMutex); - const CSSM_OID &issuerOid = CSSMOID_X509V1IssuerName; - CSSM_DATA_PTR issuerPtr = copyFirstFieldValue(issuerOid); - CssmData issuer(issuerPtr->Data, issuerPtr->Length); - - const CSSM_OID &serialOid = CSSMOID_X509V1SerialNumber; - CSSM_DATA_PTR serialPtr = copyFirstFieldValue(serialOid); - CssmData serial(serialPtr->Data, serialPtr->Length); - - SecPointer foundCert = NULL; - try { - foundCert = findByIssuerAndSN(keychains, issuer, serial); - } catch (...) { - foundCert = NULL; - } - - releaseFieldValue(issuerOid, issuerPtr); - releaseFieldValue(serialOid, serialPtr); - - return foundCert; -} - -SecPointer -Certificate::findByIssuerAndSN(const StorageManager::KeychainList &keychains, const CssmData &issuer, const CssmData &serialNumber) -{ - Item item; - if (!cursorForIssuerAndSN(keychains, issuer, serialNumber)->next(item)) - CssmError::throwMe(errSecItemNotFound); - - return static_cast(&*item); -} - -SecPointer -Certificate::findBySubjectKeyID(const StorageManager::KeychainList &keychains, const CssmData &subjectKeyID) -{ - Item item; - if (!cursorForSubjectKeyID(keychains, subjectKeyID)->next(item)) - CssmError::throwMe(errSecItemNotFound); - - return static_cast(&*item); -} - -SecPointer -Certificate::findByEmail(const StorageManager::KeychainList &keychains, const char *emailAddress) -{ - Item item; - if (!cursorForEmail(keychains, emailAddress)->next(item)) - CssmError::throwMe(errSecItemNotFound); - - return static_cast(&*item); -} - -/* Normalize emailAddresses in place. */ -void -Certificate::normalizeEmailAddress(CSSM_DATA &emailAddress) -{ - /* Do a check to see if a '\0' was at the end of emailAddress and strip it. */ - if (emailAddress.Length && emailAddress.Data[emailAddress.Length - 1] == '\0') - emailAddress.Length--; - bool foundAt = false; - for (uint32 ix = 0; ix < emailAddress.Length; ++ix) - { - uint8 ch = emailAddress.Data[ix]; - if (foundAt) - { - if ('A' <= ch && ch <= 'Z') - emailAddress.Data[ix] = ch + 'a' - 'A'; - } - else if (ch == '@') - foundAt = true; - } -} - -void -Certificate::getNames(CSSM_DATA_PTR *sanValues, CSSM_DATA_PTR snValue, CE_GeneralNameType generalNameType, std::vector &names) -{ - // Get the DNS host names or RFC822 email addresses for this certificate (depending on generalNameType), - // within the X509 SubjectAltName and SubjectName. - - // Find the SubjectAltName fields, if any, and extract the nameType entries from all of them - if (sanValues) - { - for (CSSM_DATA_PTR *sanIx = sanValues; *sanIx; ++sanIx) - { - CSSM_DATA_PTR sanValue = *sanIx; - if (sanValue && sanValue->Data) - { - CSSM_X509_EXTENSION *cssmExt = (CSSM_X509_EXTENSION *)sanValue->Data; - CE_GeneralNames *parsedValue = (CE_GeneralNames *)cssmExt->value.parsedValue; - - /* Grab all the values that are of the specified name type. */ - for (uint32 i = 0; i < parsedValue->numNames; ++i) - { - if (parsedValue->generalName[i].nameType == generalNameType) - { - if (parsedValue->generalName[i].berEncoded) // can't handle this - continue; - - names.push_back(CssmData::overlay(parsedValue->generalName[i].name)); - } - } - } - } - } - - if (names.empty() && snValue && snValue->Data) - { - const CSSM_X509_NAME &x509Name = *(const CSSM_X509_NAME *)snValue->Data; - for (uint32 rdnDex = 0; rdnDex < x509Name.numberOfRDNs; rdnDex++) - { - const CSSM_X509_RDN *rdnPtr = - &x509Name.RelativeDistinguishedName[rdnDex]; - for (uint32 tvpDex = 0; tvpDex < rdnPtr->numberOfPairs; tvpDex++) - { - const CSSM_X509_TYPE_VALUE_PAIR *tvpPtr = - &rdnPtr->AttributeTypeAndValue[tvpDex]; - - /* type/value pair: match caller's specified type */ - if (GNT_RFC822Name == generalNameType) { - if (((tvpPtr->type.Length != CSSMOID_EmailAddress.Length) || - memcmp(tvpPtr->type.Data, CSSMOID_EmailAddress.Data, CSSMOID_EmailAddress.Length))) { - continue; - } - } - if (GNT_DNSName == generalNameType) { - if (((tvpPtr->type.Length != CSSMOID_CommonName.Length) || - memcmp(tvpPtr->type.Data, CSSMOID_CommonName.Data, CSSMOID_CommonName.Length))) { - continue; - } - } - - /* printable? */ - switch (tvpPtr->valueType) - { - case BER_TAG_PRINTABLE_STRING: - case BER_TAG_IA5_STRING: - case BER_TAG_T61_STRING: - case BER_TAG_PKIX_UTF8_STRING: - /* success */ - names.push_back(CssmData::overlay(tvpPtr->value)); - break; - default: - break; - } - } /* for each pair */ - } /* for each RDN */ - } -} - -void Certificate::willRead() -{ - populateAttributes(); -} - -Boolean Certificate::isSelfSigned() -{ - StLock_(mMutex); - CSSM_DATA_PTR issuer = NULL; - CSSM_DATA_PTR subject = NULL; - OSStatus ortn = errSecSuccess; - Boolean brtn = false; - - issuer = copyFirstFieldValue(CSSMOID_X509V1IssuerNameStd); - subject = copyFirstFieldValue(CSSMOID_X509V1SubjectNameStd); - if((issuer == NULL) || (subject == NULL)) { - ortn = errSecParam; - } - else if((issuer->Length == subject->Length) && - !memcmp(issuer->Data, subject->Data, issuer->Length)) { - brtn = true; - } - if(brtn) { - /* names match: verify signature */ - CSSM_RETURN crtn; - CSSM_DATA certData = data(); - crtn = CSSM_CL_CertVerify(clHandle(), 0, - &certData, &certData, NULL, 0); - if(crtn) { - brtn = false; - } - } - if(issuer) { - releaseFieldValue(CSSMOID_X509V1IssuerNameStd, issuer); - } - if(subject) { - releaseFieldValue(CSSMOID_X509V1SubjectNameStd, subject); - } - if(ortn) { - MacOSError::throwMe(ortn); - } - return brtn; -} diff --git a/OSX/include/security_keychain/Certificate.h b/OSX/include/security_keychain/Certificate.h deleted file mode 100644 index 867cd480..00000000 --- a/OSX/include/security_keychain/Certificate.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2002-2007,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Certificate.h - Certificate objects -// -#ifndef _SECURITY_CERTIFICATE_H_ -#define _SECURITY_CERTIFICATE_H_ - -#include - -#include -// @@@ This should not be here. -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class KeyItem; - -class Certificate : public ItemImpl -{ - NOCOPY(Certificate) -public: - SECCFFUNCTIONS(Certificate, SecCertificateRef, errSecInvalidItemRef, gTypes().Certificate) - - static CL clForType(CSSM_CERT_TYPE type); - - // new item constructor - Certificate(const CSSM_DATA &data, CSSM_CERT_TYPE type, CSSM_CERT_ENCODING encoding); - -private: - // db item constructor - Certificate(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - - // PrimaryKey item constructor - Certificate(const Keychain &keychain, const PrimaryKey &primaryKey); - -public: - static Certificate* make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - static Certificate* make(const Keychain &keychain, const PrimaryKey &primaryKey); - - Certificate(Certificate &certificate); - virtual ~Certificate(); - - virtual void update(); - virtual Item copyTo(const Keychain &keychain, Access *newAccess = NULL); - virtual void didModify(); // Forget any attributes and data we just wrote to the db - - const CssmData &data(); - CSSM_CERT_TYPE type(); - CSSM_CERT_ENCODING encoding(); - CFDataRef sha1Hash(); - CFStringRef commonName(); - CFStringRef distinguishedName(const CSSM_OID *sourceOid, const CSSM_OID *componentOid); - CFStringRef copyFirstEmailAddress(); - CFArrayRef copyEmailAddresses(); - CFArrayRef copyDNSNames(); - const CSSM_X509_NAME_PTR subjectName(); - const CSSM_X509_NAME_PTR issuerName(); - const CSSM_X509_ALGORITHM_IDENTIFIER_PTR algorithmID(); - CSSM_CL_HANDLE clHandle(); - void inferLabel(bool addLabel, CFStringRef *rtnString = NULL); - SecPointer publicKey(); - const CssmData &publicKeyHash(); - const CssmData &subjectKeyIdentifier(); - - static KCCursor cursorForIssuerAndSN(const StorageManager::KeychainList &keychains, const CssmData &issuer, const CssmData &serialNumber); - static KCCursor cursorForSubjectKeyID(const StorageManager::KeychainList &keychains, const CssmData &subjectKeyID); - static KCCursor cursorForEmail(const StorageManager::KeychainList &keychains, const char *emailAddress); - static KCCursor cursorForIssuerAndSN_CF(const StorageManager::KeychainList &keychains, CFDataRef issuer, CFDataRef serialNumber); - - SecPointer findInKeychain(const StorageManager::KeychainList &keychains); - static SecPointer findByIssuerAndSN(const StorageManager::KeychainList &keychains, const CssmData &issuer, const CssmData &serialNumber); - static SecPointer findBySubjectKeyID(const StorageManager::KeychainList &keychains, const CssmData &subjectKeyID); - static SecPointer findByEmail(const StorageManager::KeychainList &keychains, const char *emailAddress); - - static void normalizeEmailAddress(CSSM_DATA &emailAddress); - static void getNames(CSSM_DATA_PTR *sanValues, CSSM_DATA_PTR snValue, CE_GeneralNameType generalNameType, std::vector &names); - - bool operator < (Certificate &other); - bool operator == (Certificate &other); - - virtual CFHashCode hash(); - -public: - CSSM_DATA_PTR copyFirstFieldValue(const CSSM_OID &field); - void releaseFieldValue(const CSSM_OID &field, CSSM_DATA_PTR fieldValue); - - CSSM_DATA_PTR *copyFieldValues(const CSSM_OID &field); - void releaseFieldValues(const CSSM_OID &field, CSSM_DATA_PTR *fieldValues); - Boolean isSelfSigned(); - -protected: - virtual void willRead(); - virtual PrimaryKey add(Keychain &keychain); - CSSM_HANDLE certHandle(); - - void addParsedAttribute(const CSSM_DB_ATTRIBUTE_INFO &info, const CSSM_OID &field); - - void addSubjectKeyIdentifier(); - void populateAttributes(); - bool verifyEncoding(CSSM_DATA_PTR data); - -private: - bool mHaveTypeAndEncoding; - bool mPopulated; - CSSM_CERT_TYPE mType; - CSSM_CERT_ENCODING mEncoding; - CssmClient::CL mCL; - CSSM_HANDLE mCertHandle; - CssmData mPublicKeyHash; - uint8 mPublicKeyHashBytes[20]; - CssmData mSubjectKeyID; - uint8 mSubjectKeyIDBytes[20]; - CSSM_DATA_PTR mV1SubjectPublicKeyCStructValue; // Hack to prevent algorithmID() from leaking. - CSSM_DATA_PTR mV1SubjectNameCStructValue; - CSSM_DATA_PTR mV1IssuerNameCStructValue; - CFDataRef mSha1Hash; - bool mEncodingVerified; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_CERTIFICATE_H_ diff --git a/OSX/include/security_keychain/CertificateRequest.cpp b/OSX/include/security_keychain/CertificateRequest.cpp deleted file mode 100644 index 76c1808c..00000000 --- a/OSX/include/security_keychain/CertificateRequest.cpp +++ /dev/null @@ -1,858 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// CertificateRequest.cpp -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* one top-level prefs file for all of .mac cert requests */ -#define DOT_MAC_REQ_PREFS "com.apple.security.certreq" - -/* - * Within that dictionary is a set of per-policy dictionaries; the key in the - * top-level prefs for these dictionaries is the raw policy OID data encoded - * as an ASCII string. - * - * Within one per-policy dictionary exists a number of per-user dictionaries, - * with the username key as a string. Note that this user name, the one passed to the - * .mac server, does NOT have to have any relation to the current Unix user name; one - * Unix user can have multiple .mac accounts. - * - * - * Within the per-policy, per user dictionary are these two values, both stored - * as raw data (CFData) blobs. - */ -#define DOT_MAC_REF_ID_KEY "refId" -#define DOT_MAC_CERT_KEY "certificate" - -/* Domain for .mac cert requests */ -#define DOT_MAC_DOMAIN_KEY "domain" -#define DOT_MAC_DOMAIN "mac.com" - -/* Hosts for .mac cert requests */ -#define DOT_MAC_MGMT_HOST "certmgmt" -#define DOT_MAC_INFO_HOST "certinfo" - -/* - * Compare two CSSM_DATAs (or two CSSM_OIDs), return true if identical. - */ -static -bool nssCompareCssmData( - const CSSM_DATA *data1, - const CSSM_DATA *data2) -{ - if((data1 == NULL) || (data1->Data == NULL) || - (data2 == NULL) || (data2->Data == NULL) || - (data1->Length != data2->Length)) { - return false; - } - if(data1->Length != data2->Length) { - return false; - } - if(memcmp(data1->Data, data2->Data, data1->Length) == 0) { - return true; - } - else { - return false; - } -} - -/* any nonzero value means true */ -static bool attrBoolValue( - const SecCertificateRequestAttribute *attr) -{ - if((attr->value.Data != NULL) && - (attr->value.Length != 0) && - (attr->value.Data[0] != 0)) { - return true; - } - else { - return false; - } -} - -static void tokenizeName( - const CSSM_DATA *inName, /* required */ - CSSM_DATA *outName, /* required */ - CSSM_DATA *outDomain) /* optional */ -{ - if (!inName || !outName) return; - CSSM_SIZE idx = 0; - CSSM_SIZE stopIdx = inName->Length; - uint8 *p = inName->Data; - *outName = *inName; - if (outDomain) { - outDomain->Length = idx; - outDomain->Data = p; - } - if (!p) return; - while (idx < stopIdx) { - if (*p++ == '@') { - outName->Length = idx; - if (outDomain) { - outDomain->Length = inName->Length - (idx + 1); - outDomain->Data = p; - } - break; - } - idx++; - } -} - -using namespace KeychainCore; - -CertificateRequest::CertificateRequest(const CSSM_OID &policy, - CSSM_CERT_TYPE certificateType, - CSSM_TP_AUTHORITY_REQUEST_TYPE requestType, - SecKeyRef privateKeyItemRef, - SecKeyRef publicKeyItemRef, - const SecCertificateRequestAttributeList *attributeList, - bool isNew /* = true */) - : mAlloc(Allocator::standard()), - mTP(gGuidAppleDotMacTP), - mCL(gGuidAppleX509CL), - mPolicy(mAlloc, policy.Data, policy.Length), - mCertType(certificateType), - mReqType(requestType), - mPrivKey(NULL), - mPubKey(NULL), - mEstTime(0), - mRefId(mAlloc), - mCertState(isNew ? CRS_New : CRS_Reconstructed), - mCertData(mAlloc), - mUserName(mAlloc), - mPassword(mAlloc), - mHostName(mAlloc), - mDomain(mAlloc), - mDoRenew(false), - mIsAsync(false), - mMutex(Mutex::recursive) -{ - StLock_(mMutex); - certReqDbg("CertificateRequest construct"); - - /* Validate policy OID. */ - if(!(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_IDENTITY, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_EMAIL_SIGN, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_SHARED_SERVICES, &policy))) { - certReqDbg("CertificateRequest(): unknown policy oid"); - MacOSError::throwMe(errSecParam); - } - if(privateKeyItemRef) { - mPrivKey = privateKeyItemRef; - CFRetain(mPrivKey); - } - if(publicKeyItemRef) { - mPubKey = publicKeyItemRef; - CFRetain(mPubKey); - } - - /* parse attr array */ - if(attributeList == NULL) { - return; - } - - bool doPendingRequest = false; - for(unsigned dex=0; dexcount; dex++) { - const SecCertificateRequestAttribute *attr = &attributeList->attr[dex]; - - if((attr->oid.Data == NULL) || (attr->value.Data == NULL)) { - MacOSError::throwMe(errSecParam); - } - if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_VALUE_USERNAME, &attr->oid)) { - CSSM_DATA userName = { 0, NULL }; - CSSM_DATA domainName = { 0, NULL }; - tokenizeName(&attr->value, &userName, &domainName); - if (!domainName.Length || !domainName.Data) { - domainName.Length = strlen(DOT_MAC_DOMAIN); - domainName.Data = (uint8*) DOT_MAC_DOMAIN; - } - mUserName.copy(userName); - mDomain.copy(domainName); - } - else if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_VALUE_PASSWORD, &attr->oid)) { - mPassword.copy(attr->value); - } - else if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_VALUE_HOSTNAME, &attr->oid)) { - mHostName.copy(attr->value); - } - else if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_VALUE_RENEW, &attr->oid)) { - /* - * any nonzero value means true - * FIXME: this is deprecated, Treadstone doesn't allow this. Reject this - * request? Ignore? - */ - mDoRenew = attrBoolValue(attr); - } - else if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_VALUE_ASYNC, &attr->oid)) { - /* any nonzero value means true */ - mIsAsync = attrBoolValue(attr); - } - else if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_VALUE_IS_PENDING, &attr->oid)) { - /* any nonzero value means true */ - doPendingRequest = attrBoolValue(attr); - } - - else { - certReqDbg("CertificateRequest(): unknown name/value oid"); - MacOSError::throwMe(errSecParam); - } - } - if(mCertState == CRS_Reconstructed) { - /* see if we have a refId or maybe even a cert in prefs */ - retrieveResults(); - if(mCertData.data() != NULL) { - mCertState = CRS_HaveCert; - } - else if(mRefId.data() != NULL) { - mCertState = CRS_HaveRefId; - } - else if(doPendingRequest) { - /* ask the server if there's a request pending */ - postPendingRequest(); - /* NOT REACHED - that always throws */ - } - else { - certReqDbg("CertificateRequest(): nothing in prefs"); - /* Nothing found in prefs; nothing to go by */ - MacOSError::throwMe(errSecItemNotFound); - } - } -} - -CertificateRequest::~CertificateRequest() throw() -{ - StLock_(mMutex); - certReqDbg("CertificateRequest destruct"); - - if(mPrivKey) { - CFRelease(mPrivKey); - } - if(mPubKey) { - CFRelease(mPubKey); - } -} - -#pragma mark ----- cert request submit ----- - -void CertificateRequest::submit( - sint32 *estimatedTime) -{ - StLock_(mMutex); - CSSM_DATA &policy = mPolicy.get(); - if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_IDENTITY, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_EMAIL_SIGN, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_SHARED_SERVICES, &policy)) { - return submitDotMac(estimatedTime); - } - else { - /* shouldn't be here, we already validated policy in constructor */ - assert(0); - certReqDbg("CertificateRequest::submit(): bad policy"); - MacOSError::throwMe(errSecParam); - } -} - -void CertificateRequest::submitDotMac( - sint32 *estimatedTime) -{ - StLock_(mMutex); - CSSM_RETURN crtn; - CSSM_TP_AUTHORITY_ID tpAuthority; - CSSM_TP_AUTHORITY_ID *tpAuthPtr = NULL; - CSSM_NET_ADDRESS tpNetAddrs; - CSSM_APPLE_DOTMAC_TP_CERT_REQUEST certReq; - CSSM_TP_REQUEST_SET reqSet; - CSSM_CSP_HANDLE cspHand = 0; - CSSM_X509_TYPE_VALUE_PAIR tvp; - CSSM_TP_CALLERAUTH_CONTEXT callerAuth; - CSSM_FIELD policyField; - CSSM_DATA refId = {0, NULL}; - const CSSM_KEY *privKey; - const CSSM_KEY *pubKey; - OSStatus ortn; - - if(mCertState != CRS_New) { - certReqDbg("CertificateRequest: can only submit a new request"); - MacOSError::throwMe(errSecParam); - } - if((mUserName.data() == NULL) || (mPassword.data() == NULL)) { - certReqDbg("CertificateRequest: user name and password required"); - MacOSError::throwMe(errSecParam); - } - - /* get keys and CSP handle in CSSM terms */ - if((mPrivKey == NULL) || (mPubKey == NULL)) { - certReqDbg("CertificateRequest: pub and priv keys required"); - MacOSError::throwMe(errSecParam); - } - ortn = SecKeyGetCSSMKey(mPrivKey, &privKey); - if(ortn) { - MacOSError::throwMe(ortn); - } - ortn = SecKeyGetCSSMKey(mPubKey, &pubKey); - if(ortn) { - MacOSError::throwMe(ortn); - } - ortn = SecKeyGetCSPHandle(mPrivKey, &cspHand); - if(ortn) { - MacOSError::throwMe(ortn); - } - - /* - * CSSM_X509_TYPE_VALUE_PAIR_PTR - one pair for now. - * Caller passes in user name like "johnsmith"; in the CSR, - * we write "johnsmith@mac.com". - */ - tvp.type = CSSMOID_CommonName; - tvp.valueType = BER_TAG_PKIX_UTF8_STRING; - CssmAutoData fullUserName(mAlloc); - size_t nameLen = mUserName.length(); - size_t domainLen = mDomain.length(); - fullUserName.malloc(nameLen + 1 + domainLen); - tvp.value = fullUserName.get(); - memmove(tvp.value.Data, mUserName.data(), nameLen); - memmove(tvp.value.Data + nameLen, "@", 1); - memmove(tvp.value.Data + nameLen + 1, mDomain.data(), domainLen); - - /* Fill in the CSSM_APPLE_DOTMAC_TP_CERT_REQUEST */ - memset(&certReq, 0, sizeof(certReq)); - certReq.version = CSSM_DOT_MAC_TP_REQ_VERSION; - certReq.cspHand = cspHand; - certReq.clHand = mCL->handle(); - certReq.numTypeValuePairs = 1; - certReq.typeValuePairs = &tvp; - certReq.publicKey = const_cast(pubKey); - certReq.privateKey = const_cast(privKey); - certReq.userName = mUserName.get(); - certReq.password = mPassword.get(); - if(mDoRenew) { - certReq.flags |= CSSM_DOTMAC_TP_SIGN_RENEW; - } - /* we don't deal with CSR here, input or output */ - - /* now the rest of the args for CSSM_TP_SubmitCredRequest() */ - reqSet.Requests = &certReq; - reqSet.NumberOfRequests = 1; - policyField.FieldOid = mPolicy; - policyField.FieldValue.Data = NULL; - policyField.FieldValue.Length = 0; - memset(&callerAuth, 0, sizeof(callerAuth)); - callerAuth.Policy.NumberOfPolicyIds = 1; - callerAuth.Policy.PolicyIds = &policyField; - ortn = SecKeyGetCredentials(mPrivKey, - CSSM_ACL_AUTHORIZATION_SIGN, - kSecCredentialTypeDefault, - const_cast(&callerAuth.CallerCredentials)); - if(ortn) { - certReqDbg("CertificateRequest: SecKeyGetCredentials error"); - MacOSError::throwMe(ortn); - } - - CssmAutoData hostName(mAlloc); - tpAuthority.AuthorityCert = NULL; - tpAuthority.AuthorityLocation = &tpNetAddrs; - tpNetAddrs.AddressType = CSSM_ADDR_NAME; - if(mHostName.data() != NULL) { - tpNetAddrs.Address = mHostName.get(); - } else { - unsigned hostLen = strlen(DOT_MAC_MGMT_HOST); - hostName.malloc(hostLen + 1 + domainLen); - tpNetAddrs.Address = hostName.get(); - memmove(tpNetAddrs.Address.Data, DOT_MAC_MGMT_HOST, hostLen); - memmove(tpNetAddrs.Address.Data + hostLen, ".", 1); - memmove(tpNetAddrs.Address.Data + hostLen + 1, mDomain.data(), domainLen); - } - tpAuthPtr = &tpAuthority; - - /* go */ - crtn = CSSM_TP_SubmitCredRequest(mTP->handle(), - tpAuthPtr, - CSSM_TP_AUTHORITY_REQUEST_CERTISSUE, - &reqSet, - &callerAuth, - &mEstTime, - &refId); // CSSM_DATA_PTR ReferenceIdentifier - - /* handle return, store results */ - switch(crtn) { - case CSSM_OK: - /* refID is a cert, we have to store it in prefs for later retrieval. */ - certReqDbg("submitDotMac: full success, storing cert"); - if(!mIsAsync) { - /* store in prefs if not running in async mode */ - ortn = storeResults(NULL, &refId); - if(ortn) { - crtn = ortn; - } - } - /* but keep a local copy too */ - mCertData.copy(refId); - mCertState = CRS_HaveCert; - if(estimatedTime) { - /* it's ready right now */ - *estimatedTime = 0; - } - break; - - case CSSMERR_APPLE_DOTMAC_REQ_QUEUED: - /* refID is the blob we use in CSSM_TP_RetrieveCredResult() */ - certReqDbg("submitDotMac: queued, storing refId"); - mRefId.copy(refId); - /* return success - this crtn is not visible at API */ - crtn = CSSM_OK; - if(!mIsAsync) { - /* store in prefs if not running in async mode */ - ortn = storeResults(&refId, NULL); - if(ortn) { - crtn = ortn; - } - } - mCertState = CRS_HaveRefId; - if(estimatedTime) { - *estimatedTime = mEstTime; - } - break; - - case CSSMERR_APPLE_DOTMAC_REQ_REDIRECT: - /* refID is a URL, caller obtains via getReturnData() */ - certReqDbg("submitDotMac: redirect"); - mRefId.copy(refId); - mCertState = CRS_HaveOtherData; - break; - - default: - /* all others are fatal errors, thrown below */ - break; - } - if(refId.Data) { - /* mallocd on our behalf by TP */ - free(refId.Data); - } - if(crtn) { - CssmError::throwMe(crtn); - } -} - -#pragma mark ----- cert request get result ----- - -void CertificateRequest::getResult( - sint32 *estimatedTime, // optional - CssmData &certData) -{ - StLock_(mMutex); - CSSM_DATA &policy = mPolicy.get(); - if(nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_IDENTITY, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_EMAIL_SIGN, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_EMAIL_ENCRYPT, &policy) || - nssCompareCssmData(&CSSMOID_DOTMAC_CERT_REQ_SHARED_SERVICES, &policy)) { - return getResultDotMac(estimatedTime, certData); - } - else { - /* shouldn't be here, we already validated policy in constructor */ - assert(0); - certReqDbg("CertificateRequest::getResult(): bad policy"); - MacOSError::throwMe(errSecParam); - } -} - -void CertificateRequest::getResultDotMac( - sint32 *estimatedTime, // optional - CssmData &certData) -{ - StLock_(mMutex); - switch(mCertState) { - case CRS_HaveCert: - /* trivial case, we already have what caller is looking for */ - certReqDbg("getResultDotMac: have the cert right now"); - assert(mCertData.data() != NULL); - certData = mCertData.get(); - if(estimatedTime) { - *estimatedTime = 0; - } - break; - case CRS_HaveRefId: - { - /* ping the server */ - certReqDbg("getResultDotMac: CRS_HaveRefId; polling server"); - assert(mRefId.data() != NULL); - CSSM_BOOL ConfirmationRequired; - CSSM_TP_RESULT_SET_PTR resultSet = NULL; - CSSM_RETURN crtn; - - crtn = CSSM_TP_RetrieveCredResult(mTP->handle(), - &mRefId.get(), - NULL, // CallerAuthCredentials - &mEstTime, - &ConfirmationRequired, - &resultSet); - switch(crtn) { - case CSSM_OK: - break; - case CSSMERR_TP_CERT_NOT_VALID_YET: - /* - * By convention, this means "not ready yet". - * The dot mac server does not have a way of telling us the - * estimated time on a straight lookup like this (we only get - * an estimated completion time on the initial request), so we - * fake it. - */ - certReqDbg("getResultDotMac: polled server, not ready yet"); - if(estimatedTime) { - *estimatedTime = (mEstTime) ? mEstTime : 1; - } - MacOSError::throwMe(CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING); - default: - certReqDbg("CSSM_TP_RetrieveCredResult error"); - CssmError::throwMe(crtn); - } - if(resultSet == NULL) { - certReqDbg("***CSSM_TP_RetrieveCredResult OK, but no result set"); - MacOSError::throwMe(errSecInternalComponent); - } - if(resultSet->NumberOfResults != 1) { - certReqDbg("***CSSM_TP_RetrieveCredResult OK, NumberOfResults (%lu)", - (unsigned long)resultSet->NumberOfResults); - MacOSError::throwMe(errSecInternalComponent); - } - if(resultSet->Results == NULL) { - certReqDbg("***CSSM_TP_RetrieveCredResult OK, but empty result set"); - MacOSError::throwMe(errSecInternalComponent); - } - certReqDbg("getResultDotMac: polled server, SUCCESS"); - CSSM_DATA_PTR result = (CSSM_DATA_PTR)resultSet->Results; - if(result->Data == NULL) { - certReqDbg("***CSSM_TP_RetrieveCredResult OK, but empty result"); - MacOSError::throwMe(errSecInternalComponent); - } - mCertData.copy(*result); - certData = mCertData.get(); - mCertState = CRS_HaveCert; - if(estimatedTime) { - *estimatedTime = 0; - } - - /* - * Free the stuff allocated on our behalf by TP. - * FIXME - are we sure CssmClient is using alloc, free, etc.? - */ - free(result->Data); - free(result); - free(resultSet); - break; - } - default: - /* what do we do with this? */ - certReqDbg("CertificateRequest::getResultDotMac(): bad state"); - MacOSError::throwMe(errSecInternalComponent); - } - - /* - * One more thing: once we pass a cert back to caller, we erase - * the record of this transaction from prefs. - */ - assert(mCertData.data() != NULL); - assert(mCertData.data() == certData.Data); - removeResults(); -} - -/* - * Obtain policy/error specific return data blob. We own the data, it's - * not copied. - */ -void CertificateRequest::getReturnData( - CssmData &rtnData) -{ - StLock_(mMutex); - rtnData = mRefId.get(); -} - -#pragma mark ----- preferences support ----- - -/* Current user as CFString, for use as key in per-policy dictionary */ -CFStringRef CertificateRequest::createUserKey() -{ - StLock_(mMutex); - return CFStringCreateWithBytes(NULL, (UInt8 *)mUserName.data(), mUserName.length(), - kCFStringEncodingUTF8, false); -} - -#define MAX_OID_LEN 2048 // way big... */ - -/* current policy as CFString, for use as key in prefs dictionary */ -CFStringRef CertificateRequest::createPolicyKey() -{ - StLock_(mMutex); - char oidstr[MAX_OID_LEN]; - unsigned char *inp = (unsigned char *)mPolicy.data(); - char *outp = oidstr; - CFIndex len = mPolicy.length(); - for(CFIndex dex=0; dex_(mMutex); - assert(mPolicy.data() != NULL); - assert(mUserName.data() != NULL); - assert(mDomain.data() != NULL); - - bool deleteEntry = ((refId == NULL) && (certData == NULL)); - - /* get a mutable copy of the existing prefs, or a fresh empty one */ - MutableDictionary *prefsDict = MutableDictionary::CreateMutableDictionary(DOT_MAC_REQ_PREFS, Dictionary::US_User); - if (prefsDict == NULL) - { - prefsDict = new MutableDictionary(); - } - - /* get a mutable copy of the dictionary for this policy, or a fresh empty one */ - CFStringRef policyKey = createPolicyKey(); - MutableDictionary *policyDict = prefsDict->copyMutableDictValue(policyKey); - - CFStringRef userKey = createUserKey(); - if(deleteEntry) { - /* remove user dictionary from this policy dictionary */ - policyDict->removeValue(userKey); - } - else { - /* get a mutable copy of the dictionary for this user, or a fresh empty one */ - MutableDictionary *userDict = policyDict->copyMutableDictValue(userKey); - - CFStringRef domainKey = CFStringCreateWithBytes(NULL, (UInt8 *)mDomain.data(), mDomain.length(), kCFStringEncodingUTF8, false); - userDict->setValue(CFSTR(DOT_MAC_DOMAIN_KEY), domainKey); - CFRelease(domainKey); - - /* write refId and/or cert --> user dictionary */ - if(refId) { - userDict->setDataValue(CFSTR(DOT_MAC_REF_ID_KEY), refId->Data, refId->Length); - } - if(certData) { - userDict->setDataValue(CFSTR(DOT_MAC_CERT_KEY), certData->Data, certData->Length); - } - - /* new user dictionary --> policy dictionary */ - policyDict->setValue(userKey, userDict->dict()); - delete userDict; - } - CFRelease(userKey); - - /* new policy dictionary to prefs dictionary, or nuke it */ - if(policyDict->count() == 0) { - prefsDict->removeValue(policyKey); - } - else { - prefsDict->setValue(policyKey, policyDict->dict()); - } - CFRelease(policyKey); - delete policyDict; - - /* prefs --> disk */ - OSStatus ortn = errSecSuccess; - if(!prefsDict->writePlistToPrefs(DOT_MAC_REQ_PREFS, Dictionary::US_User)) { - certReqDbg("storeResults: error writing prefs to disk"); - ortn = errSecIO; - } - delete prefsDict; - return ortn; -} - -/* - * Attempt to fetch mCertData or mRefId from preferences. - */ -void CertificateRequest::retrieveResults() -{ - StLock_(mMutex); - assert(mPolicy.data() != NULL); - assert(mUserName.data() != NULL); - - /* get the .mac cert prefs as a dictionary */ - Dictionary *pd = Dictionary::CreateDictionary(DOT_MAC_REQ_PREFS, Dictionary::US_User); - if (pd == NULL) - { - certReqDbg("retrieveResults: no prefs found"); - return; - } - - auto_ptr prefsDict(pd); - - /* get dictionary for current policy */ - CFStringRef policyKey = createPolicyKey(); - Dictionary *policyDict = prefsDict->copyDictValue(policyKey); - CFRelease(policyKey); - if(policyDict != NULL) { - /* dictionary for user */ - CFStringRef userKey = createUserKey(); - Dictionary *userDict = policyDict->copyDictValue(userKey); - if(userDict != NULL) { - /* is there a cert in there? */ - CFDataRef val = userDict->getDataValue(CFSTR(DOT_MAC_CERT_KEY)); - if(val) { - mCertData.copy(CFDataGetBytePtr(val), CFDataGetLength(val)); - } - - /* how about refId? */ - val = userDict->getDataValue(CFSTR(DOT_MAC_REF_ID_KEY)); - if(val) { - mRefId.copy(CFDataGetBytePtr(val), CFDataGetLength(val)); - } - delete userDict; - } - CFRelease(userKey); - delete policyDict; - } -} - -/* - * Remove all trace of current policy/user. Called when we successfully transferred - * the cert back to caller. - */ -void CertificateRequest::removeResults() -{ - StLock_(mMutex); - assert(mPolicy.data() != NULL); - assert(mUserName.data() != NULL); - storeResults(NULL, NULL); -} - -/* - * Have the TP ping the server to see of there's a request pending for the current - * user. Always throws: either - * CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING -- request pending - * CSSMERR_APPLE_DOTMAC_NO_REQ_PENDING -- no request pending - * errSecParam -- no user, no password - * other gross errors, e.g. errSecIO for server connection failure - * - * The distinguishing features about this TP request are: - * - * policy OID = CSSMOID_DOTMAC_CERT_REQ_{IDENTITY,EMAIL_SIGN,EMAIL_ENCRYPT,SHARED_SERVICES} - * CSSM_TP_AUTHORITY_REQUEST_TYPE = CSSM_TP_AUTHORITY_REQUEST_CERTLOOKUP - * CSSM_APPLE_DOTMAC_TP_CERT_REQUEST.flags = CSSM_DOTMAC_TP_IS_REQ_PENDING - * must have userName and password - * hostname optional as usual - */ -void CertificateRequest::postPendingRequest() -{ - StLock_(mMutex); - CSSM_RETURN crtn; - CSSM_TP_AUTHORITY_ID tpAuthority; - CSSM_TP_AUTHORITY_ID *tpAuthPtr = NULL; - CSSM_NET_ADDRESS tpNetAddrs; - CSSM_APPLE_DOTMAC_TP_CERT_REQUEST certReq; - CSSM_TP_REQUEST_SET reqSet; - CSSM_TP_CALLERAUTH_CONTEXT callerAuth; - CSSM_FIELD policyField; - CSSM_DATA refId = {0, NULL}; - - assert(mCertState == CRS_Reconstructed); - if((mUserName.data() == NULL) || (mPassword.data() == NULL)) { - certReqDbg("postPendingRequest: user name and password required"); - MacOSError::throwMe(errSecParam); - } - - /* Fill in the CSSM_APPLE_DOTMAC_TP_CERT_REQUEST */ - memset(&certReq, 0, sizeof(certReq)); - certReq.version = CSSM_DOT_MAC_TP_REQ_VERSION; - certReq.userName = mUserName.get(); - certReq.password = mPassword.get(); - certReq.flags = CSSM_DOTMAC_TP_IS_REQ_PENDING; - - /* now the rest of the args for CSSM_TP_SubmitCredRequest() */ - reqSet.Requests = &certReq; - reqSet.NumberOfRequests = 1; - /* - * This OID actually doesn't matter - right? This RPC doesn't know about - * which request we seek... - */ - policyField.FieldOid = mPolicy; - policyField.FieldValue.Data = NULL; - policyField.FieldValue.Length = 0; - memset(&callerAuth, 0, sizeof(callerAuth)); - callerAuth.Policy.NumberOfPolicyIds = 1; - callerAuth.Policy.PolicyIds = &policyField; - /* no other creds here */ - - if(mHostName.data() != NULL) { - tpAuthority.AuthorityCert = NULL; - tpAuthority.AuthorityLocation = &tpNetAddrs; - tpNetAddrs.AddressType = CSSM_ADDR_NAME; - tpNetAddrs.Address = mHostName.get(); - tpAuthPtr = &tpAuthority; - } - - /* go */ - crtn = CSSM_TP_SubmitCredRequest(mTP->handle(), - tpAuthPtr, - CSSM_TP_AUTHORITY_REQUEST_CERTLOOKUP, - &reqSet, - &callerAuth, - &mEstTime, - &refId); // CSSM_DATA_PTR ReferenceIdentifier - - if(refId.Data) { - /* shouldn't be any but just in case.... */ - free(refId.Data); - } - switch(crtn) { - case CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING: - certReqDbg("postPendingRequest: REQ_IS_PENDING"); - break; - case CSSMERR_APPLE_DOTMAC_NO_REQ_PENDING: - certReqDbg("postPendingRequest: NO_REQ_PENDING"); - break; - case CSSM_OK: - /* should never happen */ - certReqDbg("postPendingRequest: unexpected success!"); - crtn = errSecInternalComponent; - break; - default: - certReqDbg("postPendingRequest: unexpected rtn %lu", (unsigned long)crtn); - break; - } - CssmError::throwMe(crtn); -} - diff --git a/OSX/include/security_keychain/CertificateRequest.h b/OSX/include/security_keychain/CertificateRequest.h deleted file mode 100644 index fcecb54c..00000000 --- a/OSX/include/security_keychain/CertificateRequest.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// CertificateRequest.h -// -#ifndef _SECURITY_CERTIFICATEREQUEST_H_ -#define _SECURITY_CERTIFICATEREQUEST_H_ - -#include -#include -#include "SecCFTypes.h" -#include -#include -#include -#include -#include -#include - -#define certReqDbg(args...) secdebug("certReq", ## args) - -namespace Security -{ - -namespace KeychainCore -{ - -class CertificateRequest : public SecCFObject -{ - NOCOPY(CertificateRequest) -public: - SECCFFUNCTIONS(CertificateRequest, SecCertificateRequestRef, errSecInvalidItemRef, gTypes().CertificateRequest) - - CertificateRequest(const CSSM_OID &policy, - CSSM_CERT_TYPE certificateType, - CSSM_TP_AUTHORITY_REQUEST_TYPE requestType, - SecKeyRef privateKeyItemRef, // optional - SecKeyRef publicKeyItemRef, // optional - const SecCertificateRequestAttributeList *attributeList, - /* - * true when called from SecCertificateRequestCreate, cooking up a new - * request from scratch - * false when called from SecCertificateFindRequest, recomnstructing - * a request in progress - */ - bool isNew = true); - - virtual ~CertificateRequest() throw(); - - void submit( - sint32 *estimatedTime); - void getResult( - sint32 *estimatedTime, // optional - CssmData &certData); - - /* - * Obtain policy/error specific return data blob. We own the data, it's - * not copied. - */ - void getReturnData( - CssmData &rtnData); - - CSSM_CERT_TYPE certType() { return mCertType; } - CSSM_TP_AUTHORITY_REQUEST_TYPE reqType() { return mReqType; } - -private: - void submitDotMac( - sint32 *estimatedTime); - void getResultDotMac( - sint32 *estimatedTime, // optional - CssmData &certData); - void postPendingRequest(); - - /* preferences support */ - CFStringRef createUserKey(); - CFStringRef createPolicyKey(); - CFDictionaryRef getPolicyDictionary( - CFDictionaryRef prefsDict); - CFDictionaryRef getUserDictionary( - CFDictionaryRef policyDict); - - /* - * Preferences storage and retrieval. - * Both assume valid mPolicy and mUserName. storeResults stores the - * specified data; retrieveResults retrieves whatever is found in the - * prefs dictionary and restores to mRefId or mCert as appropriate. - */ - OSStatus storeResults( - const CSSM_DATA *refId, // optional, for queued requests - const CSSM_DATA *certDat); // optional, for immediate completion - void retrieveResults(); - void removeResults(); - - typedef enum { - CRS_New = 0, // created via SecCertificateRequestCreate - CRS_Reconstructed, // created via SecCertificateFindRequest - CRS_HaveCert, // completed request one way or another, have a good cert - CRS_HaveRefId, // submitted request, have RefId for later retrieval - CRS_HaveOtherData // submitted request, have other data in mRefId - } CertReqState; - - Allocator &mAlloc; - CssmClient::TP mTP; - CssmClient::CL mCL; - CssmAutoData mPolicy; /* i.e., "CssmAutoOid" */ - CSSM_CERT_TYPE mCertType; - CSSM_TP_AUTHORITY_REQUEST_TYPE mReqType; - SecKeyRef mPrivKey; - SecKeyRef mPubKey; - sint32 mEstTime; - CssmAutoData mRefId; /* returned from SubmitCredRequest() */ - CertReqState mCertState; - CssmAutoData mCertData; - - /* - * The incoming SecCertificateRequestAttributeList oid/value pairs - * map to these: - */ - CssmAutoData mUserName; - CssmAutoData mPassword; /* optional (lookup doesn't use it) */ - CssmAutoData mHostName; /* optional */ - CssmAutoData mDomain; /* optional */ - bool mDoRenew; - bool mIsAsync; /* true means no persistent state - * stored in user prefs; default - * is false */ - Mutex mMutex; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_CERTIFICATEREQUEST_H_ diff --git a/OSX/include/security_keychain/CertificateValues.cpp b/OSX/include/security_keychain/CertificateValues.cpp deleted file mode 100644 index 4025c9f6..00000000 --- a/OSX/include/security_keychain/CertificateValues.cpp +++ /dev/null @@ -1,610 +0,0 @@ -/* - * Copyright (c) 2002-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// CertificateValues.cpp -// -#include -#include -#include -#include -#include -#include "SecCertificateOIDs.h" -#include "CertificateValues.h" -#include "SecCertificateP.h" -#include "SecCertificatePrivP.h" -#include -#include "SecCertificateP.h" - -/* FIXME including SecCertificateInternalP.h here produces errors; investigate */ -extern "C" CFDataRef SecCertificateCopyIssuerSequenceP(SecCertificateRefP certificate); -extern "C" CFDataRef SecCertificateCopySubjectSequenceP(SecCertificateRefP certificate); - -extern "C" void appendPropertyP(CFMutableArrayRef properties, CFStringRef propertyType, CFStringRef label, CFTypeRef value); - -extern const CFStringRef __nonnull kSecPropertyKeyType; -extern const CFStringRef __nonnull kSecPropertyKeyLabel; -extern const CFStringRef __nonnull kSecPropertyKeyLocalizedLabel; -extern const CFStringRef __nonnull kSecPropertyKeyValue; - -extern const CFStringRef __nonnull kSecPropertyTypeData; -extern const CFStringRef __nonnull kSecPropertyTypeString; -extern const CFStringRef __nonnull kSecPropertyTypeURL; -extern const CFStringRef __nonnull kSecPropertyTypeDate; - -CFStringRef kSecPropertyTypeArray = CFSTR("array"); -CFStringRef kSecPropertyTypeNumber = CFSTR("number"); - - -#pragma mark ---------- CertificateValues Implementation ---------- - -using namespace KeychainCore; - -void addFieldValues(const void *key, const void *value, void *context); -void addPropertyToFieldValues(const void *value, void *context); -void filterFieldValues(const void *key, const void *value, void *context); -void validateKeys(const void *value, void *context); - -CFDictionaryRef CertificateValues::mOIDRemap = NULL; - -typedef struct FieldValueFilterContext -{ - CFMutableDictionaryRef filteredValues; - CFArrayRef filterKeys; -} FieldValueFilterContext; - -CertificateValues::CertificateValues(SecCertificateRef certificateRef) : mCertificateRef(certificateRef), - mCertificateData(NULL) -{ - if (mCertificateRef) - CFRetain(mCertificateRef); -} - -CertificateValues::~CertificateValues() throw() -{ - if (mCertificateData) - CFRelease(mCertificateData); - if (mCertificateRef) - CFRelease(mCertificateRef); -} - -CFDictionaryRef CertificateValues::copyFieldValues(CFArrayRef keys, CFErrorRef *error) -{ - if (keys) - { - if (CFGetTypeID(keys)!=CFArrayGetTypeID()) - return NULL; - CFRange range = CFRangeMake(0, CFArrayGetCount((CFArrayRef)keys)); - bool failed = false; - CFArrayApplyFunction(keys, range, validateKeys, &failed); - if (failed) - return NULL; - } - - if (mCertificateData) - { - CFRelease(mCertificateData); - mCertificateData = NULL; - } - if (!mCertificateData) - { - mCertificateData = SecCertificateCopyData(mCertificateRef); // OK to call, no big lock - if (!mCertificateData) - { - if (error) { - *error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, errSecInvalidCertificateRef, NULL); - } - return NULL; - } - } - - SecCertificateRefP certificateP = SecCertificateCreateWithDataP(kCFAllocatorDefault, mCertificateData); - if (!certificateP) - { - if (error) - *error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, errSecInvalidCertificateGroup, NULL); - return NULL; - } - - CFMutableDictionaryRef fieldValues=CFDictionaryCreateMutable(kCFAllocatorDefault, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - - // Return an array of CFStringRefs representing the common names in the certificates subject if any - CFArrayRef commonNames=SecCertificateCopyCommonNamesP(certificateP); - if (commonNames) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeArray, CFSTR("CN"), commonNames); - CFDictionaryAddValue(fieldValues, kSecOIDCommonName, (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(commonNames); - CFRelease(additionalValues); - } - - // These can exist in the subject alt name or in the subject - CFArrayRef dnsNames=SecCertificateCopyDNSNamesP(certificateP); - if (dnsNames) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeArray, CFSTR("DNS"), dnsNames); - CFDictionaryAddValue(fieldValues, CFSTR("DNSNAMES"), (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(dnsNames); - CFRelease(additionalValues); - } - - CFArrayRef ipAddresses=SecCertificateCopyIPAddressesP(certificateP); - if (ipAddresses) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeArray, CFSTR("IP"), dnsNames); - CFDictionaryAddValue(fieldValues, CFSTR("IPADDRESSES"), (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(ipAddresses); - CFRelease(additionalValues); - } - - // These can exist in the subject alt name or in the subject - CFArrayRef emailAddrs=SecCertificateCopyRFC822NamesP(certificateP); - if (emailAddrs) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeArray, CFSTR("DNS"), dnsNames); - CFDictionaryAddValue(fieldValues, kSecOIDEmailAddress, (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(emailAddrs); - CFRelease(additionalValues); - } - - CFAbsoluteTime notBefore = SecCertificateNotValidBeforeP(certificateP); - CFNumberRef notBeforeRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, ¬Before); - if (notBeforeRef) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeNumber, CFSTR("Not Valid Before"), notBeforeRef); - CFDictionaryAddValue(fieldValues, kSecOIDX509V1ValidityNotBefore, (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(notBeforeRef); - CFRelease(additionalValues); - } - - CFAbsoluteTime notAfter = SecCertificateNotValidAfterP(certificateP); - CFNumberRef notAfterRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, ¬After); - if (notAfterRef) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeNumber, CFSTR("Not Valid After"), notAfterRef); - CFDictionaryAddValue(fieldValues, kSecOIDX509V1ValidityNotAfter, (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(notAfterRef); - CFRelease(additionalValues); - } - - SecKeyUsage keyUsage=SecCertificateGetKeyUsageP(certificateP); - CFNumberRef ku = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &keyUsage); - if (ku) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeNumber, CFSTR("Key Usage"), ku); - CFDictionaryAddValue(fieldValues, kSecOIDKeyUsage, (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(ku); - CFRelease(additionalValues); - } - - CFArrayRef ekus = SecCertificateCopyExtendedKeyUsageP(certificateP); - if (ekus) - { - CFMutableArrayRef additionalValues = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - appendPropertyP(additionalValues, kSecPropertyTypeArray, CFSTR("Extended Key Usage"), ekus); - CFDictionaryAddValue(fieldValues, kSecOIDExtendedKeyUsage, (CFTypeRef)CFArrayGetValueAtIndex(additionalValues, 0)); - CFRelease(ekus); - CFRelease(additionalValues); - } - - // Add all values from properties dictionary - CFArrayRef properties = SecCertificateCopyPropertiesP(certificateP); - if (properties) - { - CFRange range = CFRangeMake(0, CFArrayGetCount((CFArrayRef)properties)); - CFArrayApplyFunction(properties, range, addPropertyToFieldValues, fieldValues); - // CFDictionaryApplyFunction(properties, addFieldValues, fieldValues); - CFRelease(properties); - } - - CFAbsoluteTime verifyTime = CFAbsoluteTimeGetCurrent(); - CFMutableArrayRef summaryProperties = - SecCertificateCopySummaryPropertiesP(certificateP, verifyTime); - if (summaryProperties) - { - CFRange range = CFRangeMake(0, CFArrayGetCount((CFArrayRef)summaryProperties)); - CFArrayApplyFunction(summaryProperties, range, addPropertyToFieldValues, fieldValues); -// CFDictionaryApplyFunction(summaryProperties, addFieldValues, fieldValues); -// CFDictionaryAddValue(fieldValues, CFSTR("summaryProperties"), summaryProperties); - CFRelease(summaryProperties); - } - - if (certificateP) - CFRelease(certificateP); - - if (keys==NULL) - return (CFDictionaryRef)fieldValues; - - // Otherwise, we need to filter - CFMutableDictionaryRef filteredFieldValues=CFDictionaryCreateMutable(kCFAllocatorDefault, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - - FieldValueFilterContext fvcontext; - fvcontext.filteredValues = filteredFieldValues; - fvcontext.filterKeys = keys; - - CFDictionaryApplyFunction(fieldValues, filterFieldValues, &fvcontext); - - CFRelease(fieldValues); - return (CFDictionaryRef)filteredFieldValues; -} - -void validateKeys(const void *value, void *context) -{ - if (value == NULL || (CFGetTypeID(value)!=CFStringGetTypeID())) - if (context) - *(bool *)context = true; -} - -void filterFieldValues(const void *key, const void *value, void *context) -{ - // each element of keys is a CFStringRef with an OID, e.g. - // const CFStringRef kSecOIDTitle = CFSTR("2.5.4.12"); - - CFTypeRef fieldKey = (CFTypeRef)key; - if (fieldKey == NULL || (CFGetTypeID(fieldKey)!=CFStringGetTypeID()) || context==NULL) - return; - - FieldValueFilterContext *fvcontext = (FieldValueFilterContext *)context; - - CFRange range = CFRangeMake(0, CFArrayGetCount(fvcontext->filterKeys)); - CFIndex idx = CFArrayGetFirstIndexOfValue(fvcontext->filterKeys, range, fieldKey); - if (idx != kCFNotFound) - CFDictionaryAddValue(fvcontext->filteredValues, fieldKey, value); -} - -void addFieldValues(const void *key, const void *value, void *context) -{ - CFMutableDictionaryRef fieldValues = (CFMutableDictionaryRef)context; - CFDictionaryAddValue(fieldValues, key, value); -} - -void addPropertyToFieldValues(const void *value, void *context) -{ - CFMutableDictionaryRef fieldValues = (CFMutableDictionaryRef)context; - if (CFGetTypeID(value)==CFDictionaryGetTypeID()) - { - CFStringRef label = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)value, kSecPropertyKeyLabel); -#if 0 - CFStringRef typeD = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)value, kSecPropertyKeyType); - CFTypeRef valueD = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)value, kSecPropertyKeyValue); -#endif - CFStringRef key = CertificateValues::remapLabelToKey(label); - if (key) - CFDictionaryAddValue(fieldValues, key, value); - } -} - -CFStringRef CertificateValues::remapLabelToKey(CFStringRef label) -{ - if (!label) - return NULL; - - if (!mOIDRemap) - { - CFTypeRef keys[] = - { - CFSTR("Subject Name"), - CFSTR("Normalized Subject Name"), - CFSTR("Issuer Name"), - CFSTR("Normalized Subject Name"), - CFSTR("Version"), - CFSTR("Serial Number"), - CFSTR("Signature Algorithm"), - CFSTR("Subject Unique ID"), - CFSTR("Issuer Unique ID"), - CFSTR("Public Key Algorithm"), - CFSTR("Public Key Data"), - CFSTR("Signature"), - CFSTR("Not Valid Before"), - CFSTR("Not Valid After"), - CFSTR("Expires") - }; - - CFTypeRef values[] = - { - kSecOIDX509V1SubjectName, - kSecOIDX509V1SubjectNameStd, - kSecOIDX509V1IssuerName, - kSecOIDX509V1IssuerNameStd, - kSecOIDX509V1Version, - kSecOIDX509V1SerialNumber, - kSecOIDX509V1SignatureAlgorithm, // or CSSMOID_X509V1SignatureAlgorithmTBS? - kSecOIDX509V1CertificateSubjectUniqueId, - kSecOIDX509V1CertificateIssuerUniqueId, - kSecOIDX509V1SubjectPublicKeyAlgorithm, - kSecOIDX509V1SubjectPublicKey, - kSecOIDX509V1Signature, - kSecOIDX509V1ValidityNotBefore, - kSecOIDX509V1ValidityNotAfter, - kSecOIDInvalidityDate - }; - - mOIDRemap = CFDictionaryCreate(NULL, keys, values, - (sizeof(keys) / sizeof(*keys)), &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); - } - - CFTypeRef result = (CFTypeRef)CFDictionaryGetValue(mOIDRemap, label); - - return result?(CFStringRef)result:label; -} - -CFDataRef CertificateValues::copySerialNumber(CFErrorRef *error) -{ - CFDataRef result = NULL; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - - if (certificateP) - { - result = SecCertificateCopySerialNumberP(certificateP); - CFRelease(certificateP); - } - return result; -} - -CFDataRef CertificateValues::copyNormalizedIssuerContent(CFErrorRef *error) -{ - CFDataRef result = NULL; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateCopyNormalizedIssuerSequenceP(certificateP); - CFRelease(certificateP); - } - return result; -} - -CFDataRef CertificateValues::copyNormalizedSubjectContent(CFErrorRef *error) -{ - CFDataRef result = NULL; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateCopyNormalizedSubjectSequenceP(certificateP); - CFRelease(certificateP); - } - return result; -} - -CFDataRef CertificateValues::copyIssuerSequence(CFErrorRef *error) -{ - CFDataRef result = NULL; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateCopyIssuerSequenceP(certificateP); - CFRelease(certificateP); - } - return result; -} - -CFDataRef CertificateValues::copySubjectSequence(CFErrorRef *error) -{ - CFDataRef result = NULL; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateCopySubjectSequenceP(certificateP); - CFRelease(certificateP); - } - return result; -} - -bool CertificateValues::isValid(CFAbsoluteTime verifyTime, CFErrorRef *error) -{ - bool result = NULL; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateIsValidP(certificateP, verifyTime); - CFRelease(certificateP); - } - return result; -} - -CFAbsoluteTime CertificateValues::notValidBefore(CFErrorRef *error) -{ - CFAbsoluteTime result = 0; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateNotValidBeforeP(certificateP); - CFRelease(certificateP); - } - return result; -} - -CFAbsoluteTime CertificateValues::notValidAfter(CFErrorRef *error) -{ - CFAbsoluteTime result = 0; - SecCertificateRefP certificateP = getSecCertificateRefP(error); - if (certificateP) - { - result = SecCertificateNotValidAfterP(certificateP); - CFRelease(certificateP); - } - return result; -} - -SecCertificateRefP CertificateValues::getSecCertificateRefP(CFErrorRef *error) -{ - // SecCertificateCopyData returns an object created with CFDataCreate, so we - // own it and must release it - - if (mCertificateData) - { - CFRelease(mCertificateData); - mCertificateData = NULL; - } - - mCertificateData = SecCertificateCopyData(mCertificateRef); // OK to call, no big lock - if (!mCertificateData && error) - { - *error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, errSecInvalidCertificateRef, NULL); - return NULL; - } - - SecCertificateRefP certificateP = SecCertificateCreateWithDataP(kCFAllocatorDefault, mCertificateData); - if (!certificateP && error) - { - *error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, errSecInvalidCertificateGroup, NULL); - return NULL; - } - - return certificateP; -} - -#pragma mark ---------- OID Constants ---------- - -const CFStringRef kSecOIDADC_CERT_POLICY = CFSTR("1.2.840.113635.100.5.3"); -const CFStringRef kSecOIDAPPLE_CERT_POLICY = CFSTR("1.2.840.113635.100.5.1"); -const CFStringRef kSecOIDAPPLE_EKU_CODE_SIGNING = CFSTR("1.2.840.113635.100.4.1"); -const CFStringRef kSecOIDAPPLE_EKU_CODE_SIGNING_DEV = CFSTR("1.2.840.113635.100.4.1.1"); -const CFStringRef kSecOIDAPPLE_EKU_ICHAT_ENCRYPTION = CFSTR("1.2.840.113635.100.4.3"); -const CFStringRef kSecOIDAPPLE_EKU_ICHAT_SIGNING = CFSTR("1.2.840.113635.100.4.2"); -const CFStringRef kSecOIDAPPLE_EKU_RESOURCE_SIGNING = CFSTR("1.2.840.113635.100.4.1.4"); -const CFStringRef kSecOIDAPPLE_EKU_SYSTEM_IDENTITY = CFSTR("1.2.840.113635.100.4.4"); -const CFStringRef kSecOIDAPPLE_EXTENSION = CFSTR("1.2.840.113635.100.6"); -const CFStringRef kSecOIDAPPLE_EXTENSION_ADC_APPLE_SIGNING = CFSTR("1.2.840.113635.100.6.1.2.0.0"); -const CFStringRef kSecOIDAPPLE_EXTENSION_ADC_DEV_SIGNING = CFSTR("1.2.840.113635.100.6.1.2.0"); -const CFStringRef kSecOIDAPPLE_EXTENSION_APPLE_SIGNING = CFSTR("1.2.840.113635.100.6.1.1"); -const CFStringRef kSecOIDAPPLE_EXTENSION_CODE_SIGNING = CFSTR("1.2.840.113635.100.6.1"); -const CFStringRef kSecOIDAPPLE_EXTENSION_INTERMEDIATE_MARKER = CFSTR("1.2.840.113635.100.6.2"); -const CFStringRef kSecOIDAPPLE_EXTENSION_WWDR_INTERMEDIATE = CFSTR("1.2.840.113635.100.6.2.1"); -const CFStringRef kSecOIDAPPLE_EXTENSION_ITMS_INTERMEDIATE = CFSTR("1.2.840.113635.100.6.2.2"); -const CFStringRef kSecOIDAPPLE_EXTENSION_AAI_INTERMEDIATE = CFSTR("1.2.840.113635.100.6.2.3"); -const CFStringRef kSecOIDAPPLE_EXTENSION_APPLEID_INTERMEDIATE = CFSTR("1.2.840.113635.100.6.2.7"); -const CFStringRef kSecOIDAuthorityInfoAccess = CFSTR("1.3.6.1.5.5.7.1.1"); -const CFStringRef kSecOIDAuthorityKeyIdentifier = CFSTR("2.5.29.35"); -const CFStringRef kSecOIDBasicConstraints = CFSTR("2.5.29.19"); -const CFStringRef kSecOIDBiometricInfo = CFSTR("1.3.6.1.5.5.7.1.2"); -const CFStringRef kSecOIDCSSMKeyStruct = CFSTR("2.16.840.1.113741.2.1.1.1.20"); -const CFStringRef kSecOIDCertIssuer = CFSTR("2.5.29.29"); -const CFStringRef kSecOIDCertificatePolicies = CFSTR("2.5.29.32"); -const CFStringRef kSecOIDClientAuth = CFSTR("1.3.6.1.5.5.7.3.2"); -const CFStringRef kSecOIDCollectiveStateProvinceName = CFSTR("2.5.4.8.1"); -const CFStringRef kSecOIDCollectiveStreetAddress = CFSTR("2.5.4.9.1"); -const CFStringRef kSecOIDCommonName = CFSTR("2.5.4.3"); -const CFStringRef kSecOIDCountryName = CFSTR("2.5.4.6"); -const CFStringRef kSecOIDCrlDistributionPoints = CFSTR("2.5.29.31"); -const CFStringRef kSecOIDCrlNumber = CFSTR("2.5.29.20"); -const CFStringRef kSecOIDCrlReason = CFSTR("2.5.29.21"); -const CFStringRef kSecOIDDOTMAC_CERT_EMAIL_ENCRYPT = CFSTR("1.2.840.113635.100.3.2.3"); -const CFStringRef kSecOIDDOTMAC_CERT_EMAIL_SIGN = CFSTR("1.2.840.113635.100.3.2.2"); -const CFStringRef kSecOIDDOTMAC_CERT_EXTENSION = CFSTR("1.2.840.113635.100.3.2"); -const CFStringRef kSecOIDDOTMAC_CERT_IDENTITY = CFSTR("1.2.840.113635.100.3.2.1"); -const CFStringRef kSecOIDDOTMAC_CERT_POLICY = CFSTR("1.2.840.113635.100.5.2"); -const CFStringRef kSecOIDDeltaCrlIndicator = CFSTR("2.5.29.27"); -const CFStringRef kSecOIDDescription = CFSTR("2.5.4.13"); -const CFStringRef kSecOIDEKU_IPSec = CFSTR("1.3.6.1.5.5.8.2.2"); -const CFStringRef kSecOIDEmailAddress = CFSTR("1.2.840.113549.1.9.1"); -const CFStringRef kSecOIDEmailProtection = CFSTR("1.3.6.1.5.5.7.3.4"); -const CFStringRef kSecOIDExtendedKeyUsage = CFSTR("2.5.29.37"); -const CFStringRef kSecOIDExtendedKeyUsageAny = CFSTR("2.5.29.37.0"); -const CFStringRef kSecOIDExtendedUseCodeSigning = CFSTR("1.3.6.1.5.5.7.3.3"); -const CFStringRef kSecOIDGivenName = CFSTR("2.5.4.42"); -const CFStringRef kSecOIDHoldInstructionCode = CFSTR("2.5.29.23"); -const CFStringRef kSecOIDInvalidityDate = CFSTR("2.5.29.24"); -const CFStringRef kSecOIDIssuerAltName = CFSTR("2.5.29.18"); -const CFStringRef kSecOIDIssuingDistributionPoint = CFSTR("2.5.29.28"); -const CFStringRef kSecOIDIssuingDistributionPoints = CFSTR("2.5.29.28"); -const CFStringRef kSecOIDKERBv5_PKINIT_KP_CLIENT_AUTH = CFSTR("1.3.6.1.5.2.3.4"); -const CFStringRef kSecOIDKERBv5_PKINIT_KP_KDC = CFSTR("1.3.6.1.5.2.3.5"); -const CFStringRef kSecOIDKeyUsage = CFSTR("2.5.29.15"); -const CFStringRef kSecOIDLocalityName = CFSTR("2.5.4.7"); -const CFStringRef kSecOIDMS_NTPrincipalName = CFSTR("1.3.6.1.4.1.311.20.2.3"); -const CFStringRef kSecOIDMicrosoftSGC = CFSTR("1.3.6.1.4.1.311.10.3.3"); -const CFStringRef kSecOIDNameConstraints = CFSTR("2.5.29.30"); -const CFStringRef kSecOIDNetscapeCertSequence = CFSTR("2.16.840.1.113730.2.5"); -const CFStringRef kSecOIDNetscapeCertType = CFSTR("2.16.840.1.113730.1.1"); -const CFStringRef kSecOIDNetscapeSGC = CFSTR("2.16.840.1.113730.4.1"); -const CFStringRef kSecOIDOCSPSigning = CFSTR("1.3.6.1.5.5.7.3.9"); -const CFStringRef kSecOIDOrganizationName = CFSTR("2.5.4.10"); -const CFStringRef kSecOIDOrganizationalUnitName = CFSTR("2.5.4.11"); -const CFStringRef kSecOIDPolicyConstraints = CFSTR("2.5.29.36"); -const CFStringRef kSecOIDPolicyMappings = CFSTR("2.5.29.33"); -const CFStringRef kSecOIDPrivateKeyUsagePeriod = CFSTR("2.5.29.16"); -const CFStringRef kSecOIDQC_Statements = CFSTR("1.3.6.1.5.5.7.1.3"); -const CFStringRef kSecOIDSerialNumber = CFSTR("2.5.4.5"); -const CFStringRef kSecOIDServerAuth = CFSTR("1.3.6.1.5.5.7.3.1"); -const CFStringRef kSecOIDStateProvinceName = CFSTR("2.5.4.8"); -const CFStringRef kSecOIDStreetAddress = CFSTR("2.5.4.9"); -const CFStringRef kSecOIDSubjectAltName = CFSTR("2.5.29.17"); -const CFStringRef kSecOIDSubjectDirectoryAttributes = CFSTR("2.5.29.9"); -const CFStringRef kSecOIDSubjectEmailAddress = CFSTR("2.16.840.1.113741.2.1.1.1.50.3"); -const CFStringRef kSecOIDSubjectInfoAccess = CFSTR("1.3.6.1.5.5.7.1.11"); -const CFStringRef kSecOIDSubjectKeyIdentifier = CFSTR("2.5.29.14"); -const CFStringRef kSecOIDSubjectPicture = CFSTR("2.16.840.1.113741.2.1.1.1.50.2"); -const CFStringRef kSecOIDSubjectSignatureBitmap = CFSTR("2.16.840.1.113741.2.1.1.1.50.1"); -const CFStringRef kSecOIDSurname = CFSTR("2.5.4.4"); -const CFStringRef kSecOIDTimeStamping = CFSTR("1.3.6.1.5.5.7.3.8"); -const CFStringRef kSecOIDTitle = CFSTR("2.5.4.12"); -const CFStringRef kSecOIDUseExemptions = CFSTR("2.16.840.1.113741.2.1.1.1.50.4"); -const CFStringRef kSecOIDX509V1CertificateIssuerUniqueId = CFSTR("2.16.840.1.113741.2.1.1.1.11"); -const CFStringRef kSecOIDX509V1CertificateSubjectUniqueId = CFSTR("2.16.840.1.113741.2.1.1.1.12"); -const CFStringRef kSecOIDX509V1IssuerName = CFSTR("2.16.840.1.113741.2.1.1.1.5"); -const CFStringRef kSecOIDX509V1IssuerNameCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.5.1"); -const CFStringRef kSecOIDX509V1IssuerNameLDAP = CFSTR("2.16.840.1.113741.2.1.1.1.5.2"); -const CFStringRef kSecOIDX509V1IssuerNameStd = CFSTR("2.16.840.1.113741.2.1.1.1.23"); -const CFStringRef kSecOIDX509V1SerialNumber = CFSTR("2.16.840.1.113741.2.1.1.1.3"); -const CFStringRef kSecOIDX509V1Signature = CFSTR("2.16.840.1.113741.2.1.3.2.2"); -const CFStringRef kSecOIDX509V1SignatureAlgorithm = CFSTR("2.16.840.1.113741.2.1.3.2.1"); -const CFStringRef kSecOIDX509V1SignatureAlgorithmParameters = CFSTR("2.16.840.1.113741.2.1.3.2.3"); -const CFStringRef kSecOIDX509V1SignatureAlgorithmTBS = CFSTR("2.16.840.1.113741.2.1.3.2.10"); -const CFStringRef kSecOIDX509V1SignatureCStruct = CFSTR("2.16.840.1.113741.2.1.3.2.0.1"); -const CFStringRef kSecOIDX509V1SignatureStruct = CFSTR("2.16.840.1.113741.2.1.3.2.0"); -const CFStringRef kSecOIDX509V1SubjectName = CFSTR("2.16.840.1.113741.2.1.1.1.8"); -const CFStringRef kSecOIDX509V1SubjectNameCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.8.1"); -const CFStringRef kSecOIDX509V1SubjectNameLDAP = CFSTR("2.16.840.1.113741.2.1.1.1.8.2"); -const CFStringRef kSecOIDX509V1SubjectNameStd = CFSTR("2.16.840.1.113741.2.1.1.1.22"); -const CFStringRef kSecOIDX509V1SubjectPublicKey = CFSTR("2.16.840.1.113741.2.1.1.1.10"); -const CFStringRef kSecOIDX509V1SubjectPublicKeyAlgorithm = CFSTR("2.16.840.1.113741.2.1.1.1.9"); -const CFStringRef kSecOIDX509V1SubjectPublicKeyAlgorithmParameters = CFSTR("2.16.840.1.113741.2.1.1.1.18"); -const CFStringRef kSecOIDX509V1SubjectPublicKeyCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.20.1"); -const CFStringRef kSecOIDX509V1ValidityNotAfter = CFSTR("2.16.840.1.113741.2.1.1.1.7"); -const CFStringRef kSecOIDX509V1ValidityNotBefore = CFSTR("2.16.840.1.113741.2.1.1.1.6"); -const CFStringRef kSecOIDX509V1Version = CFSTR("2.16.840.1.113741.2.1.1.1.2"); -const CFStringRef kSecOIDX509V3Certificate = CFSTR("2.16.840.1.113741.2.1.1.1.1"); -const CFStringRef kSecOIDX509V3CertificateCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.1.1"); -const CFStringRef kSecOIDX509V3CertificateExtensionCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.13.1"); -const CFStringRef kSecOIDX509V3CertificateExtensionCritical = CFSTR("2.16.840.1.113741.2.1.1.1.16"); -const CFStringRef kSecOIDX509V3CertificateExtensionId = CFSTR("2.16.840.1.113741.2.1.1.1.15"); -const CFStringRef kSecOIDX509V3CertificateExtensionStruct = CFSTR("2.16.840.1.113741.2.1.1.1.13"); -const CFStringRef kSecOIDX509V3CertificateExtensionType = CFSTR("2.16.840.1.113741.2.1.1.1.19"); -const CFStringRef kSecOIDX509V3CertificateExtensionValue = CFSTR("2.16.840.1.113741.2.1.1.1.17"); -const CFStringRef kSecOIDX509V3CertificateExtensionsCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.21.1"); -const CFStringRef kSecOIDX509V3CertificateExtensionsStruct = CFSTR("2.16.840.1.113741.2.1.1.1.21"); -const CFStringRef kSecOIDX509V3CertificateNumberOfExtensions = CFSTR("2.16.840.1.113741.2.1.1.1.14"); -const CFStringRef kSecOIDX509V3SignedCertificate = CFSTR("2.16.840.1.113741.2.1.1.1.0"); -const CFStringRef kSecOIDX509V3SignedCertificateCStruct = CFSTR("2.16.840.1.113741.2.1.1.1.0.1"); -const CFStringRef kSecOIDSRVName = CFSTR("1.3.6.1.5.5.7.8.7"); - diff --git a/OSX/include/security_keychain/CertificateValues.h b/OSX/include/security_keychain/CertificateValues.h deleted file mode 100644 index 5f56bbe9..00000000 --- a/OSX/include/security_keychain/CertificateValues.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2002-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// CertificateValues.h - Objects in a Certificate -// -#ifndef _SECURITY_CERTIFICATEVALUES_H_ -#define _SECURITY_CERTIFICATEVALUES_H_ - -#include -#include "SecBaseP.h" -//#include - -namespace Security -{ - -namespace KeychainCore -{ - -class CertificateValues// : public SecCFObject -{ - NOCOPY(CertificateValues) - -public: - - CertificateValues(SecCertificateRef certificateRef); - virtual ~CertificateValues() throw(); - - static CFStringRef remapLabelToKey(CFStringRef label); - CFDictionaryRef copyFieldValues(CFArrayRef keys, CFErrorRef *error); - CFDataRef copySerialNumber(CFErrorRef *error); - CFDataRef copyNormalizedIssuerContent(CFErrorRef *error); - CFDataRef copyNormalizedSubjectContent(CFErrorRef *error); - CFDataRef copyIssuerSequence(CFErrorRef *error); - CFDataRef copySubjectSequence(CFErrorRef *error); - bool isValid(CFAbsoluteTime verifyTime, CFErrorRef *error); - CFAbsoluteTime notValidBefore(CFErrorRef *error); - CFAbsoluteTime notValidAfter(CFErrorRef *error); - -private: - - SecCertificateRefP getSecCertificateRefP(CFErrorRef *error); - - SecCertificateRef mCertificateRef; - CFDataRef mCertificateData; - static CFDictionaryRef mOIDRemap; -}; - - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_CERTIFICATEVALUES_H_ diff --git a/OSX/include/security_keychain/DLDBListCFPref.cpp b/OSX/include/security_keychain/DLDBListCFPref.cpp deleted file mode 100644 index 4836f4dc..00000000 --- a/OSX/include/security_keychain/DLDBListCFPref.cpp +++ /dev/null @@ -1,1079 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - DLDBListCFPref.cpp -*/ - -#include "DLDBListCFPref.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -dispatch_once_t AppSandboxChecked; -xpc_object_t KeychainHomeFromXPC; - -using namespace CssmClient; - -static const double kDLDbListCFPrefRevertInterval = 30.0; - -// normal debug calls, which get stubbed out for deployment builds - -#define kKeyGUID CFSTR("GUID") -#define kKeySubserviceId CFSTR("SubserviceId") -#define kKeySubserviceType CFSTR("SubserviceType") -#define kKeyDbName CFSTR("DbName") -#define kKeyDbLocation CFSTR("DbLocation") -#define kKeyActive CFSTR("Active") -#define kKeyMajorVersion CFSTR("MajorVersion") -#define kKeyMinorVersion CFSTR("MinorVersion") -#define kDefaultDLDbListKey CFSTR("DLDBSearchList") -#define kDefaultKeychainKey CFSTR("DefaultKeychain") -#define kLoginKeychainKey CFSTR("LoginKeychain") -#define kUserDefaultPath "~/Library/Preferences/com.apple.security.plist" -#define kSystemDefaultPath "/Library/Preferences/com.apple.security.plist" -#define kCommonDefaultPath "/Library/Preferences/com.apple.security-common.plist" -#define kLoginKeychainPathPrefix "~/Library/Keychains/" -#define kUserLoginKeychainPath "~/Library/Keychains/login.keychain" -#define kSystemLoginKeychainPath "/Library/Keychains/System.keychain" - - -// A utility class for managing password database lookups - -const time_t kPasswordCacheExpire = 30; // number of seconds cached password db info is valid - -PasswordDBLookup::PasswordDBLookup () : mValid (false), mCurrent (0), mTime (0) -{ -} - -void PasswordDBLookup::lookupInfoOnUID (uid_t uid) -{ - time_t currentTime = time (NULL); - - if (!mValid || uid != mCurrent || currentTime - mTime >= kPasswordCacheExpire) - { - struct passwd* pw = getpwuid(uid); - if (pw == NULL) - { - UnixError::throwMe (EPERM); - } - - mDirectory = pw->pw_dir; - mName = pw->pw_name; - mValid = true; - mCurrent = uid; - mTime = currentTime; - - secdebug("secpref", "uid=%d caching home=%s", uid, pw->pw_dir); - - endpwent(); - } -} - -PasswordDBLookup *DLDbListCFPref::mPdbLookup = NULL; - -//------------------------------------------------------------------------------------- -// -// Lists of DL/DBs, with CFPreferences backing store -// -//------------------------------------------------------------------------------------- - -DLDbListCFPref::DLDbListCFPref(SecPreferencesDomain domain) : mDomain(domain), mPropertyList(NULL), mChanged(false), - mSearchListSet(false), mDefaultDLDbIdentifierSet(false), mLoginDLDbIdentifierSet(false) -{ - secdebug("secpref", "New DLDbListCFPref %p for domain %d", this, domain); - loadPropertyList(true); -} - -void DLDbListCFPref::set(SecPreferencesDomain domain) -{ - save(); - - mDomain = domain; - - secdebug("secpref", "DLDbListCFPref %p domain set to %d", this, domain); - - if (loadPropertyList(true)) - resetCachedValues(); -} - -DLDbListCFPref::~DLDbListCFPref() -{ - save(); - - if (mPropertyList) - CFRelease(mPropertyList); -} - -void -DLDbListCFPref::forceUserSearchListReread() -{ - // set mPrefsTimeStamp so that it will "expire" the next time loadPropertyList is called - mPrefsTimeStamp = CFAbsoluteTimeGetCurrent() - kDLDbListCFPrefRevertInterval; -} - -bool -DLDbListCFPref::loadPropertyList(bool force) -{ - string prefsPath; - - switch (mDomain) - { - case kSecPreferencesDomainUser: - prefsPath = ExpandTildesInPath(kUserDefaultPath); - break; - case kSecPreferencesDomainSystem: - prefsPath = kSystemDefaultPath; - break; - case kSecPreferencesDomainCommon: - prefsPath = kCommonDefaultPath; - break; - default: - MacOSError::throwMe(errSecInvalidPrefsDomain); - } - - secdebug("secpref", "force=%s prefsPath=%s", force ? "true" : "false", - prefsPath.c_str()); - - CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); - - // If for some reason the prefs file path has changed, blow away the old plist and force an update - if (mPrefsPath != prefsPath) - { - mPrefsPath = prefsPath; - if (mPropertyList) - { - CFRelease(mPropertyList); - mPropertyList = NULL; - } - - mPrefsTimeStamp = now; - } - else if (!force) - { - if (now - mPrefsTimeStamp < kDLDbListCFPrefRevertInterval) - return false; - - mPrefsTimeStamp = now; - } - - struct stat st; - if (stat(mPrefsPath.c_str(), &st)) - { - if (errno == ENOENT) - { - if (mPropertyList) - { - if (CFDictionaryGetCount(mPropertyList) == 0) - return false; - CFRelease(mPropertyList); - } - - mPropertyList = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - return true; - } - } - else - { - if (mPropertyList) - { - if (mTimespec.tv_sec == st.st_mtimespec.tv_sec - && mTimespec.tv_nsec == st.st_mtimespec.tv_nsec) - return false; - } - - mTimespec = st.st_mtimespec; - } - - CFMutableDictionaryRef thePropertyList = NULL; - CFMutableDataRef xmlData = NULL; - CFStringRef errorString = NULL; - int fd = -1; - - do - { - fd = open(mPrefsPath.c_str(), O_RDONLY, 0); - if (fd < 0) - break; - - off_t theSize = lseek(fd, 0, SEEK_END); - if (theSize <= 0) - break; - - if (lseek(fd, 0, SEEK_SET)) - break; - - xmlData = CFDataCreateMutable(NULL, CFIndex(theSize)); - if (!xmlData) - break; - CFDataSetLength(xmlData, CFIndex(theSize)); - void *buffer = reinterpret_cast(CFDataGetMutableBytePtr(xmlData)); - if (!buffer) - break; - ssize_t bytesRead = read(fd, buffer, (size_t)theSize); - if (bytesRead != theSize) - break; - - thePropertyList = CFMutableDictionaryRef(CFPropertyListCreateFromXMLData(NULL, xmlData, kCFPropertyListMutableContainers, &errorString)); - if (!thePropertyList) - break; - - if (CFGetTypeID(thePropertyList) != CFDictionaryGetTypeID()) - { - CFRelease(thePropertyList); - thePropertyList = NULL; - break; - } - } while (0); - - if (fd >= 0) - close(fd); - if (xmlData) - CFRelease(xmlData); - if (errorString) - CFRelease(errorString); - - if (!thePropertyList) - { - thePropertyList = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - } - - if (mPropertyList) - { - if (CFEqual(mPropertyList, thePropertyList)) - { - // The new property list is the same as the old one, so nothing has changed. - CFRelease(thePropertyList); - return false; - } - CFRelease(mPropertyList); - } - - mPropertyList = thePropertyList; - return true; -} - -void -DLDbListCFPref::writePropertyList() -{ - if (!mPropertyList || CFDictionaryGetCount(mPropertyList) == 0) - { - // There is nothing in the mPropertyList dictionary, - // so we don't need a prefs file. - unlink(mPrefsPath.c_str()); - } - else - { - if(testAndFixPropertyList()) - return; - - CFDataRef xmlData = CFPropertyListCreateXMLData(NULL, mPropertyList); - if (!xmlData) - return; // Bad out of memory or something evil happened let's act like CF and do nothing. - - // The prefs file should at least be made readable by user/group/other and writable by the owner. - // Change from euid to ruid if needed for the duration of the new prefs file creat. - - mode_t mode = 0666; - changeIdentity(UNPRIV); - int fd = open(mPrefsPath.c_str(), O_WRONLY|O_CREAT|O_TRUNC, mode); - changeIdentity(PRIV); - if (fd >= 0) - { - const void *buffer = CFDataGetBytePtr(xmlData); - size_t toWrite = CFDataGetLength(xmlData); - /* ssize_t bytesWritten = */ write(fd, buffer, toWrite); - // Emulate CFPreferences by not checking for any errors. - - fsync(fd); - struct stat st; - if (!fstat(fd, &st)) - mTimespec = st.st_mtimespec; - - close(fd); - } - - CFRelease(xmlData); - } - - mPrefsTimeStamp = CFAbsoluteTimeGetCurrent(); -} - -// This function can clean up some problems caused by setuid clients. We've had instances where the -// Keychain search list has become owned by root, but is still able to be re-written by the user because -// of the permissions on the directory above. We'll take advantage of that fact to recreate the file with -// the correct ownership by copying it. - -int -DLDbListCFPref::testAndFixPropertyList() -{ - char *prefsPath = (char *)mPrefsPath.c_str(); - - int fd1, fd2, retval; - struct stat stbuf; - - if((fd1 = open(prefsPath, O_RDONLY)) < 0) { - if (errno == ENOENT) return 0; // Doesn't exist - the default case - else return -1; - } - - if((retval = fstat(fd1, &stbuf)) == -1) return -1; - - if(stbuf.st_uid != getuid()) { - char tempfile[MAXPATHLEN+1]; - - snprintf(tempfile, MAXPATHLEN, "%s.XXXXX", prefsPath); - mktemp(tempfile); - changeIdentity(UNPRIV); - if((fd2 = open(tempfile, O_RDWR | O_CREAT | O_EXCL, 0666)) < 0) { - retval = -1; - } else { - copyfile_state_t s = copyfile_state_alloc(); - retval = fcopyfile(fd1, fd2, s, COPYFILE_DATA); - copyfile_state_free(s); - if(!retval) retval = ::unlink(prefsPath); - if(!retval) retval = ::rename(tempfile, prefsPath); - } - changeIdentity(PRIV); - close(fd2); - } - close(fd1); - return retval; -} - -// Encapsulated process uid/gid change routine. -void -DLDbListCFPref::changeIdentity(ID_Direction toPriv) -{ - if(toPriv == UNPRIV) { - savedEUID = geteuid(); - savedEGID = getegid(); - if(savedEGID != getgid()) setegid(getgid()); - if(savedEUID != getuid()) seteuid(getuid()); - } else { - if(savedEUID != getuid()) seteuid(savedEUID); - if(savedEGID != getgid()) setegid(savedEGID); - } -} - -void -DLDbListCFPref::resetCachedValues() -{ - // Unset the login and default Keychain. - mLoginDLDbIdentifier = mDefaultDLDbIdentifier = DLDbIdentifier(); - - // Clear the searchList. - mSearchList.clear(); - - changed(false); - - // Note that none of our cached values are valid - mSearchListSet = mDefaultDLDbIdentifierSet = mLoginDLDbIdentifierSet = false; - - mPrefsTimeStamp = CFAbsoluteTimeGetCurrent(); -} - -void DLDbListCFPref::save() -{ - if (!hasChanged()) - return; - - // Resync from disc to make sure we don't clobber anyone elses changes. - // @@@ This is probably already done by the next layer up so we don't - // really need to do it here again. - loadPropertyList(true); - - // Do the searchList first since it might end up invoking defaultDLDbIdentifier() which can set - // mLoginDLDbIdentifierSet and mDefaultDLDbIdentifierSet to true. - if (mSearchListSet) - { - // Make a temporary CFArray with the contents of the vector - if (mSearchList.size() == 1 && mSearchList[0] == defaultDLDbIdentifier() && mSearchList[0] == LoginDLDbIdentifier()) - { - // The only element in the search list is the default keychain, which is a - // post Jaguar style login keychain, so omit the entry from the prefs file. - CFDictionaryRemoveValue(mPropertyList, kDefaultDLDbListKey); - } - else - { - CFMutableArrayRef searchArray = CFArrayCreateMutable(kCFAllocatorDefault, mSearchList.size(), &kCFTypeArrayCallBacks); - for (DLDbList::const_iterator ix=mSearchList.begin();ix!=mSearchList.end();ix++) - { - CFDictionaryRef aDict = dlDbIdentifierToCFDictionaryRef(*ix); - CFArrayAppendValue(searchArray, aDict); - CFRelease(aDict); - } - - CFDictionarySetValue(mPropertyList, kDefaultDLDbListKey, searchArray); - CFRelease(searchArray); - } - } - - if (mLoginDLDbIdentifierSet) - { - // Make a temporary CFArray with the login keychain - CFArrayRef loginArray = NULL; - if (!mLoginDLDbIdentifier) - { - loginArray = CFArrayCreate(kCFAllocatorDefault, NULL, 0, &kCFTypeArrayCallBacks); - } - else if (!(mLoginDLDbIdentifier == LoginDLDbIdentifier())) - { - CFDictionaryRef aDict = dlDbIdentifierToCFDictionaryRef(mLoginDLDbIdentifier); - const void *value = reinterpret_cast(aDict); - loginArray = CFArrayCreate(kCFAllocatorDefault, &value, 1, &kCFTypeArrayCallBacks); - CFRelease(aDict); - } - - if (loginArray) - { - CFDictionarySetValue(mPropertyList, kLoginKeychainKey, loginArray); - CFRelease(loginArray); - } - else - CFDictionaryRemoveValue(mPropertyList, kLoginKeychainKey); - } - - if (mDefaultDLDbIdentifierSet) - { - // Make a temporary CFArray with the default keychain - CFArrayRef defaultArray = NULL; - if (!mDefaultDLDbIdentifier) - { - defaultArray = CFArrayCreate(kCFAllocatorDefault, NULL, 0, &kCFTypeArrayCallBacks); - } - else if (!(mDefaultDLDbIdentifier == LoginDLDbIdentifier())) - { - CFDictionaryRef aDict = dlDbIdentifierToCFDictionaryRef(mDefaultDLDbIdentifier); - const void *value = reinterpret_cast(aDict); - defaultArray = CFArrayCreate(kCFAllocatorDefault, &value, 1, &kCFTypeArrayCallBacks); - CFRelease(aDict); - } - - if (defaultArray) - { - CFDictionarySetValue(mPropertyList, kDefaultKeychainKey, defaultArray); - CFRelease(defaultArray); - } - else - CFDictionaryRemoveValue(mPropertyList, kDefaultKeychainKey); - } - - writePropertyList(); - changed(false); -} - - -//---------------------------------------------------------------------- -// Conversions -//---------------------------------------------------------------------- - -DLDbIdentifier DLDbListCFPref::LoginDLDbIdentifier() -{ - CSSM_VERSION theVersion={}; - CssmSubserviceUid ssuid(gGuidAppleCSPDL,&theVersion,0,CSSM_SERVICE_DL|CSSM_SERVICE_CSP); - CssmNetAddress *dbLocation=NULL; - - switch (mDomain) { - case kSecPreferencesDomainUser: - return DLDbIdentifier(ssuid, ExpandTildesInPath(kUserLoginKeychainPath).c_str(), dbLocation); - default: - assert(false); - case kSecPreferencesDomainSystem: - case kSecPreferencesDomainCommon: - return DLDbIdentifier(ssuid, kSystemLoginKeychainPath, dbLocation); - } -} - -DLDbIdentifier DLDbListCFPref::JaguarLoginDLDbIdentifier() -{ - CSSM_VERSION theVersion={}; - CssmSubserviceUid ssuid(gGuidAppleCSPDL,&theVersion,0,CSSM_SERVICE_DL|CSSM_SERVICE_CSP); - CssmNetAddress *dbLocation=NULL; - - switch (mDomain) { - case kSecPreferencesDomainUser: - { - string basepath = ExpandTildesInPath(kLoginKeychainPathPrefix) + getPwInfo(kUsername); - return DLDbIdentifier(ssuid,basepath.c_str(),dbLocation); - } - case kSecPreferencesDomainSystem: - case kSecPreferencesDomainCommon: - return DLDbIdentifier(ssuid, kSystemLoginKeychainPath, dbLocation); - default: - assert(false); - return DLDbIdentifier(); - } -} - -DLDbIdentifier DLDbListCFPref::makeDLDbIdentifier (const CSSM_GUID &guid, const CSSM_VERSION &version, - uint32 subserviceId, CSSM_SERVICE_TYPE subserviceType, - const char* dbName, CSSM_NET_ADDRESS *dbLocation) -{ - CssmSubserviceUid ssuid (guid, &version, subserviceId, subserviceType); - return DLDbIdentifier (ssuid, ExpandTildesInPath (dbName).c_str (), dbLocation); -} - -DLDbIdentifier DLDbListCFPref::cfDictionaryRefToDLDbIdentifier(CFDictionaryRef theDict) -{ - // We must get individual values from the dictionary and store in basic types - if (CFGetTypeID(theDict) != CFDictionaryGetTypeID()) - throw std::logic_error("wrong type in property list"); - - // GUID - CCFValue vGuid(::CFDictionaryGetValue(theDict,kKeyGUID)); - string guidStr=vGuid; - const Guid guid(guidStr.c_str()); - - //CSSM_VERSION - CSSM_VERSION theVersion={0,}; - CCFValue vMajor(::CFDictionaryGetValue(theDict,kKeyMajorVersion)); - theVersion.Major = vMajor; - CCFValue vMinor(::CFDictionaryGetValue(theDict,kKeyMinorVersion)); - theVersion.Minor = vMinor; - - //subserviceId - CCFValue vSsid(::CFDictionaryGetValue(theDict,kKeySubserviceId)); - uint32 subserviceId=sint32(vSsid); - - //CSSM_SERVICE_TYPE - CSSM_SERVICE_TYPE subserviceType=CSSM_SERVICE_DL; - CCFValue vSsType(::CFDictionaryGetValue(theDict,kKeySubserviceType)); - subserviceType=vSsType; - - // Get DbName from dictionary - CCFValue vDbName(::CFDictionaryGetValue(theDict,kKeyDbName)); - string dbName=vDbName; - - // jch Get DbLocation from dictionary - CssmNetAddress *dbLocation=NULL; - - return makeDLDbIdentifier (guid, theVersion, subserviceId, subserviceType, dbName.c_str (), dbLocation); -} - -void DLDbListCFPref::clearPWInfo () -{ - if (mPdbLookup != NULL) - { - delete mPdbLookup; - mPdbLookup = NULL; - } -} - -string DLDbListCFPref::getPwInfo(PwInfoType type) -{ - const char *value; - switch (type) - { - case kHomeDir: - if (KeychainHomeFromXPC) { - value = xpc_string_get_string_ptr(KeychainHomeFromXPC); - } else { - value = getenv("HOME"); - } - if (value) - return value; - break; - case kUsername: - value = getenv("USER"); - if (value) - return value; - break; - } - - // Get our effective uid - uid_t uid = geteuid(); - // If we are setuid root use the real uid instead - if (!uid) uid = getuid(); - - // get the password entries - if (mPdbLookup == NULL) - { - mPdbLookup = new PasswordDBLookup (); - } - - mPdbLookup->lookupInfoOnUID (uid); - - string result; - switch (type) - { - case kHomeDir: - result = mPdbLookup->getDirectory (); - break; - case kUsername: - result = mPdbLookup->getName (); - break; - } - - return result; -} - -static void check_app_sandbox() -{ - if (!_xpc_runtime_is_app_sandboxed()) { - // We are not in a sandbox, no work to do here - return; - } - - extern xpc_object_t xpc_create_with_format(const char * format, ...); - xpc_connection_t con = xpc_connection_create("com.apple.security.XPCKeychainSandboxCheck", NULL); - xpc_connection_set_event_handler(con, ^(xpc_object_t event) { - xpc_type_t xtype = xpc_get_type(event); - if (XPC_TYPE_ERROR == xtype) { - syslog(LOG_ERR, "Keychain sandbox connection error: %s\n", xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION)); - } else { - syslog(LOG_ERR, "Keychain sandbox unexpected connection event %p\n", event); - } - }); - xpc_connection_resume(con); - - xpc_object_t message = xpc_create_with_format("{op: GrantKeychainPaths}"); - xpc_object_t reply = xpc_connection_send_message_with_reply_sync(con, message); - xpc_type_t xtype = xpc_get_type(reply); - if (XPC_TYPE_DICTIONARY == xtype) { -#if 0 - // This is useful for debugging. - char *debug = xpc_copy_description(reply); - syslog(LOG_ERR, "DEBUG (KCsandbox) %s\n", debug); - free(debug); -#endif - - xpc_object_t extensions_array = xpc_dictionary_get_value(reply, "extensions"); - xpc_array_apply(extensions_array, ^(size_t index, xpc_object_t extension) { - char pbuf[MAXPATHLEN]; - char *path = pbuf; - int status = sandbox_consume_fs_extension(xpc_string_get_string_ptr(extension), &path); - if (status) { - syslog(LOG_ERR, "Keychain sandbox consume extension error: s=%d p=%s %m\n", status, path); - } - status = sandbox_release_fs_extension(xpc_string_get_string_ptr(extension)); - if (status) { - syslog(LOG_ERR, "Keychain sandbox release extension error: s=%d p=%s %m\n", status, path); - } - - return (bool)true; - }); - - KeychainHomeFromXPC = xpc_dictionary_get_value(reply, "keychain-home"); - xpc_retain(KeychainHomeFromXPC); - xpc_release(con); - } else if (XPC_TYPE_ERROR == xtype) { - syslog(LOG_ERR, "Keychain sandbox message error: %s\n", xpc_dictionary_get_string(reply, XPC_ERROR_KEY_DESCRIPTION)); - } else { - syslog(LOG_ERR, "Keychain sandbox unexpected message reply type %p\n", xtype); - } - xpc_release(message); - xpc_release(reply); -} - - - -string DLDbListCFPref::ExpandTildesInPath(const string &inPath) -{ - dispatch_once(&AppSandboxChecked, ^{ - check_app_sandbox(); - }); - - if ((short)inPath.find("~/",0,2) == 0) - return getPwInfo(kHomeDir) + inPath.substr(1, inPath.length() - 1); - else - return inPath; -} - -string DLDbListCFPref::StripPathStuff(const string &inPath) -{ - if (inPath.find("/private/var/automount/Network/",0,31) == 0) - return inPath.substr(22); - if (inPath.find("/private/automount/Servers/",0,27) == 0) - return "/Network" + inPath.substr(18); - if (inPath.find("/automount/Servers/",0,19) == 0) - return "/Network" + inPath.substr(10); - if (inPath.find("/private/automount/Network/",0,27) == 0) - return inPath.substr(18); - if (inPath.find("/automount/Network/",0,19) == 0) - return inPath.substr(10); - if (inPath.find("/private/Network/",0,17) == 0) - return inPath.substr(8); - return inPath; -} - -string DLDbListCFPref::AbbreviatedPath(const string &inPath) -{ - string path = StripPathStuff(inPath); - string home = StripPathStuff(getPwInfo(kHomeDir) + "/"); - size_t homeLen = home.length(); - - if (homeLen > 1 && path.find(home.c_str(), 0, homeLen) == 0) - return "~" + path.substr(homeLen - 1); - else - return path; -} - -CFDictionaryRef DLDbListCFPref::dlDbIdentifierToCFDictionaryRef(const DLDbIdentifier& dldbIdentifier) -{ - CFRef aDict(CFDictionaryCreateMutable(kCFAllocatorDefault,0, - &kCFTypeDictionaryKeyCallBacks,&kCFTypeDictionaryValueCallBacks)); - if (!aDict) - throw ::std::bad_alloc(); - - // Put SUBSERVICE_UID in dictionary - char buffer[Guid::stringRepLength+1]; - const CssmSubserviceUid& ssuid=dldbIdentifier.ssuid(); - const Guid &theGuid = Guid::overlay(ssuid.Guid); - CFRef stringGuid(::CFStringCreateWithCString(kCFAllocatorDefault, - theGuid.toString(buffer),kCFStringEncodingMacRoman)); - if (stringGuid) - ::CFDictionarySetValue(aDict,kKeyGUID,stringGuid); - - if (ssuid.SubserviceId!=0) - { - CFRef subserviceId(::CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt32Type,&ssuid.SubserviceId)); - if (subserviceId) - ::CFDictionarySetValue(aDict,kKeySubserviceId,subserviceId); - } - if (ssuid.SubserviceType!=0) - { - CFRef subserviceType(CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt32Type,&ssuid.SubserviceType)); - if (subserviceType) - ::CFDictionarySetValue(aDict,kKeySubserviceType,subserviceType); - } - if (ssuid.Version.Major!=0 && ssuid.Version.Minor!=0) - { - CFRef majorVersion(::CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt32Type,&ssuid.Version.Major)); - if (majorVersion) - ::CFDictionarySetValue(aDict,kKeyMajorVersion,majorVersion); - CFRef minorVersion(::CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt32Type,&ssuid.Version.Minor)); - if (minorVersion) - ::CFDictionarySetValue(aDict,kKeyMinorVersion,minorVersion); - } - - // Put DbName in dictionary - const char *dbName=dldbIdentifier.dbName(); - if (dbName) - { - CFRef theDbName(::CFStringCreateWithCString(kCFAllocatorDefault,AbbreviatedPath(dbName).c_str(),kCFStringEncodingUTF8)); - ::CFDictionarySetValue(aDict,kKeyDbName,theDbName); - } - // Put DbLocation in dictionary - const CSSM_NET_ADDRESS *dbLocation=dldbIdentifier.dbLocation(); - if (dbLocation!=NULL && dbLocation->AddressType!=CSSM_ADDR_NONE) - { - CFRef theData(::CFDataCreate(kCFAllocatorDefault,dbLocation->Address.Data,dbLocation->Address.Length)); - if (theData) - ::CFDictionarySetValue(aDict,kKeyDbLocation,theData); - } - - ::CFRetain(aDict); - return aDict; -} - -bool DLDbListCFPref::revert(bool force) -{ - // If the prefs have not been refreshed in the last kDLDbListCFPrefRevertInterval - // seconds or we are asked to force a reload, then reload. - if (!loadPropertyList(force)) - return false; - - resetCachedValues(); - return true; -} - -void -DLDbListCFPref::add(const DLDbIdentifier &dldbIdentifier) -{ - // convert the location specified in dldbIdentifier to a standard form - // make a canonical form of the database name - std::string canon = ExpandTildesInPath(AbbreviatedPath(dldbIdentifier.dbName()).c_str()); - - DLDbIdentifier localIdentifier (dldbIdentifier.ssuid(), canon.c_str(), dldbIdentifier.dbLocation ()); - - if (member(localIdentifier)) - return; - - mSearchList.push_back(localIdentifier); - changed(true); -} - -void -DLDbListCFPref::remove(const DLDbIdentifier &dldbIdentifier) -{ - // Make sure mSearchList is set - searchList(); - for (vector::iterator ix = mSearchList.begin(); ix != mSearchList.end(); ++ix) - { - if (*ix==dldbIdentifier) // found in list - { - mSearchList.erase(ix); - changed(true); - break; - } - } -} - -void -DLDbListCFPref::rename(const DLDbIdentifier &oldId, const DLDbIdentifier &newId) -{ - // Make sure mSearchList is set - searchList(); - for (vector::iterator ix = mSearchList.begin(); - ix != mSearchList.end(); ++ix) - { - if (*ix==oldId) - { - // replace oldId with newId - *ix = newId; - changed(true); - } - else if (*ix==newId) - { - // remove newId except where we just inserted it - mSearchList.erase(ix); - changed(true); - } - } -} - -bool -DLDbListCFPref::member(const DLDbIdentifier &dldbIdentifier) -{ - if (dldbIdentifier.IsImplEmpty()) - { - return false; - } - - for (vector::const_iterator ix = searchList().begin(); ix != mSearchList.end(); ++ix) - { - if (ix->mImpl == NULL) - { - continue; - } - - // compare the dldbIdentifiers based on the full, real path to the keychain - if (ix->ssuid() == dldbIdentifier.ssuid()) - { - char localPath[PATH_MAX], - inPath[PATH_MAX]; - - // try to resolve these down to a canonical form - const char* localPathPtr = cached_realpath(ix->dbName(), localPath); - const char* inPathPtr = cached_realpath(dldbIdentifier.dbName(), inPath); - - // if either of the paths didn't resolve for some reason, use the originals - if (localPathPtr == NULL) - { - localPathPtr = ix->dbName(); - } - - if (inPathPtr == NULL) - { - inPathPtr = dldbIdentifier.dbName(); - } - - if (strcmp(localPathPtr, inPathPtr) == 0) - { - return true; - } - } - } - - return false; -} - -const vector & -DLDbListCFPref::searchList() -{ - if (!mSearchListSet) - { - CFArrayRef searchList = reinterpret_cast(CFDictionaryGetValue(mPropertyList, kDefaultDLDbListKey)); - if (searchList && CFGetTypeID(searchList) != CFArrayGetTypeID()) - searchList = NULL; - - if (searchList) - { - CFIndex top = CFArrayGetCount(searchList); - // Each entry is a CFDictionary; peel it off & add it to the array - for (CFIndex idx = 0; idx < top; ++idx) - { - CFDictionaryRef theDict = reinterpret_cast(CFArrayGetValueAtIndex(searchList, idx)); - try - { - mSearchList.push_back(cfDictionaryRefToDLDbIdentifier(theDict)); - } - catch (...) - { - // Drop stuff that doesn't parse on the floor. - } - } - - // If there were entries specified, but they were invalid revert to using the - // default keychain in the searchlist. - if (top > 0 && mSearchList.size() == 0) - searchList = NULL; - } - - // The default when no search list is specified is to only search the - // default keychain. - if (!searchList && static_cast(defaultDLDbIdentifier())) - mSearchList.push_back(mDefaultDLDbIdentifier); - - mSearchListSet = true; - } - - return mSearchList; -} - -void -DLDbListCFPref::searchList(const vector &searchList) -{ - vector newList(searchList); - mSearchList.swap(newList); - mSearchListSet = true; - changed(true); -} - -void -DLDbListCFPref::defaultDLDbIdentifier(const DLDbIdentifier &dlDbIdentifier) -{ - if (!(defaultDLDbIdentifier() == dlDbIdentifier)) - { - mDefaultDLDbIdentifier = dlDbIdentifier; - changed(true); - } -} - -const DLDbIdentifier & -DLDbListCFPref::defaultDLDbIdentifier() -{ - - if (!mDefaultDLDbIdentifierSet) - { - CFArrayRef defaultArray = reinterpret_cast(CFDictionaryGetValue(mPropertyList, kDefaultKeychainKey)); - if (defaultArray && CFGetTypeID(defaultArray) != CFArrayGetTypeID()) - defaultArray = NULL; - - if (defaultArray && CFArrayGetCount(defaultArray) > 0) - { - CFDictionaryRef defaultDict = reinterpret_cast(CFArrayGetValueAtIndex(defaultArray, 0)); - try - { - secdebug("secpref", "getting default DLDbIdentifier from defaultDict"); - mDefaultDLDbIdentifier = cfDictionaryRefToDLDbIdentifier(defaultDict); - secdebug("secpref", "now we think the default keychain is %s", (mDefaultDLDbIdentifier) ? mDefaultDLDbIdentifier.dbName() : ""); - } - catch (...) - { - // If defaultArray doesn't parse fall back on the default way of getting the default keychain - defaultArray = NULL; - } - } - - if (!defaultArray) - { - - // If the Panther style login keychain actually exists we use that otherwise no - // default is set. - mDefaultDLDbIdentifier = loginDLDbIdentifier(); - secdebug("secpref", "now we think the default keychain is: %s", (mDefaultDLDbIdentifier) ? mDefaultDLDbIdentifier.dbName() : - "Name doesn't exist"); - - struct stat st; - int st_result = -1; - - if (mDefaultDLDbIdentifier.mImpl != NULL) - { - st_result = stat(mDefaultDLDbIdentifier.dbName(), &st); - } - - if (st_result) - { - secdebug("secpref", "stat(%s) -> %d", mDefaultDLDbIdentifier.dbName(), st_result); - mDefaultDLDbIdentifier = DLDbIdentifier(); // initialize a NULL keychain - secdebug("secpref", "after DLDbIdentifier(), we think the default keychain is %s", static_cast(mDefaultDLDbIdentifier) ? mDefaultDLDbIdentifier.dbName() : ""); - } - } - - mDefaultDLDbIdentifierSet = true; - } - - - return mDefaultDLDbIdentifier; -} - -void -DLDbListCFPref::loginDLDbIdentifier(const DLDbIdentifier &dlDbIdentifier) -{ - if (!(loginDLDbIdentifier() == dlDbIdentifier)) - { - mLoginDLDbIdentifier = dlDbIdentifier; - changed(true); - } -} - -const DLDbIdentifier & -DLDbListCFPref::loginDLDbIdentifier() -{ - if (!mLoginDLDbIdentifierSet) - { - CFArrayRef loginArray = reinterpret_cast(CFDictionaryGetValue(mPropertyList, kLoginKeychainKey)); - if (loginArray && CFGetTypeID(loginArray) != CFArrayGetTypeID()) - loginArray = NULL; - - if (loginArray && CFArrayGetCount(loginArray) > 0) - { - CFDictionaryRef loginDict = reinterpret_cast(CFArrayGetValueAtIndex(loginArray, 0)); - try - { - secdebug("secpref", "Getting login DLDbIdentifier from loginDict"); - mLoginDLDbIdentifier = cfDictionaryRefToDLDbIdentifier(loginDict); - secdebug("secpref", "we think the login keychain is %s", static_cast(mLoginDLDbIdentifier) ? mLoginDLDbIdentifier.dbName() : ""); - } - catch (...) - { - // If loginArray doesn't parse fall back on the default way of getting the login keychain. - loginArray = NULL; - } - } - - if (!loginArray) - { - mLoginDLDbIdentifier = LoginDLDbIdentifier(); - secdebug("secpref", "after LoginDLDbIdentifier(), we think the login keychain is %s", static_cast(mLoginDLDbIdentifier) ? mLoginDLDbIdentifier.dbName() : ""); - } - - mLoginDLDbIdentifierSet = true; - } - - return mLoginDLDbIdentifier; -} diff --git a/OSX/include/security_keychain/DLDBListCFPref.h b/OSX/include/security_keychain/DLDBListCFPref.h deleted file mode 100644 index 966f75f0..00000000 --- a/OSX/include/security_keychain/DLDBListCFPref.h +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * DLDBListCFPref.h - */ -#ifndef _SECURITY_DLDBLISTCFPREF_H_ -#define _SECURITY_DLDBLISTCFPREF_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Security -{ - -class PasswordDBLookup -{ -protected: - string mDirectory; - string mName; - bool mValid; - uid_t mCurrent; - time_t mTime; - -public: - PasswordDBLookup (); - - void lookupInfoOnUID (uid_t uid); - const string& getDirectory () {return mDirectory;} - const string& getName () {return mName;} -}; - -class DLDbListCFPref -{ -public: - DLDbListCFPref(SecPreferencesDomain domain = kSecPreferencesDomainUser); - ~DLDbListCFPref(); - - void set(SecPreferencesDomain domain); - - void save(); - vector& list() { return mSearchList; } - - static DLDbIdentifier makeDLDbIdentifier (const CSSM_GUID &guid, const CSSM_VERSION &version, - uint32 subserviceId, CSSM_SERVICE_TYPE subserviceType, - const char* dbName, CSSM_NET_ADDRESS *dbLocation); - - static DLDbIdentifier cfDictionaryRefToDLDbIdentifier(CFDictionaryRef theDict); - static CFDictionaryRef dlDbIdentifierToCFDictionaryRef(const DLDbIdentifier& dldbIdentifier); - bool revert(bool force); - - void add(const DLDbIdentifier &); - void remove(const DLDbIdentifier &); - void rename(const DLDbIdentifier &oldId, const DLDbIdentifier &newId); - bool member(const DLDbIdentifier &); - const vector &searchList(); - void searchList(const vector &); - void defaultDLDbIdentifier(const DLDbIdentifier &); - const DLDbIdentifier &defaultDLDbIdentifier(); - void loginDLDbIdentifier(const DLDbIdentifier &); - const DLDbIdentifier &loginDLDbIdentifier(); - void forceUserSearchListReread (); - - DLDbIdentifier LoginDLDbIdentifier(); - DLDbIdentifier JaguarLoginDLDbIdentifier(); - - static string ExpandTildesInPath(const string &inPath); - static string StripPathStuff(const string &inPath); - static string AbbreviatedPath(const string &inPath); - -protected: - SecPreferencesDomain mDomain; - bool hasChanged() const { return mChanged; } - void changed(bool hasChanged) { mChanged = hasChanged; } - - enum PwInfoType - { - kHomeDir, - kUsername - }; - - static PasswordDBLookup *mPdbLookup; - static string getPwInfo(PwInfoType type); - static void clearPWInfo (); - - void resetCachedValues(); - bool loadPropertyList(bool force); - void writePropertyList(); - int testAndFixPropertyList(); - - enum ID_Direction - { - UNPRIV, - PRIV - }; - uid_t savedEUID; - gid_t savedEGID; - - void changeIdentity(ID_Direction); - - -private: - CFAbsoluteTime mPrefsTimeStamp; - struct timespec mTimespec; - CFMutableDictionaryRef mPropertyList; - - string mPrefsPath, mHomeDir, mUserName; - vector mSearchList; - DLDbIdentifier mDefaultDLDbIdentifier; - DLDbIdentifier mLoginDLDbIdentifier; - bool mChanged, mSearchListSet, mDefaultDLDbIdentifierSet, mLoginDLDbIdentifierSet; -}; - -class CCFValue -{ -public: - template - T cfref() const { return reinterpret_cast(CFTypeRef(mRef)); } - - CCFValue() {} - CCFValue(CFTypeRef ref) : mRef(ref) {} - CCFValue &operator =(CFTypeRef ref) { mRef = ref; return *this; } - - CCFValue &operator = (bool value) - { - mRef = value?kCFBooleanTrue:kCFBooleanFalse; - return *this; - } - -/* - CCFValue &operator = (const string &value) { string(value); return *this; } - - void string(const string &value, CFStringEncoding encoding=kCFStringEncodingMacRoman) - { - mRef = CFStringCreate(); -CFStringRef CFStringCreateWithBytes(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalRepresentation); - if (!mRef) throw std::bad_alloc; - CFRelease(mRef); - } -*/ - - bool hasValue() const { return mRef; } - - operator bool() const - { - if (!mRef) return false; - if (::CFGetTypeID(mRef) != ::CFBooleanGetTypeID()) - throw std::logic_error("wrong type in property list"); - - return ::CFBooleanGetValue(cfref()); - } - - operator sint32() const - { - if (!mRef) return 0; - if (::CFGetTypeID(mRef) != ::CFNumberGetTypeID()) - throw std::logic_error("wrong type in property list"); - - sint32 val; - ::CFNumberGetValue(cfref(),kCFNumberSInt32Type,&val); - return val; - } - - operator uint32() const { return uint32(sint32(*this)); } - - operator const string() const { return getString(); } - - const string getString(CFStringEncoding encoding=kCFStringEncodingUTF8) const - { - if (!mRef) - throw std::logic_error("missing string in property list"); - if (::CFGetTypeID(mRef) != ::CFStringGetTypeID()) - throw std::logic_error("wrong type in property list"); - - const char *tmpStr=::CFStringGetCStringPtr(cfref(),encoding); - if (tmpStr == NULL) - { - CFIndex maxLen = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfref()), encoding); - auto_array buffer(maxLen + 1); - - if (!::CFStringGetCString(cfref(),buffer.get(),maxLen + 1,encoding)) - throw std::logic_error("could not convert string from property list"); - - tmpStr=buffer.get(); - return string(tmpStr?tmpStr:""); - } - return string(tmpStr?tmpStr:""); - } -private: - CFCopyRefmRef; -}; - -} // end namespace Security - -#endif /* !_SECURITY_DLDBLISTCFPREF_H_ */ diff --git a/OSX/include/security_keychain/DynamicDLDBList.cpp b/OSX/include/security_keychain/DynamicDLDBList.cpp deleted file mode 100644 index 0539e474..00000000 --- a/OSX/include/security_keychain/DynamicDLDBList.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - DynamicDLDBList.cpp -*/ - -#include "DynamicDLDBList.h" - -#include "Globals.h" - -#include -#include // For Required() -#include -#include -#include "KCEventNotifier.h" - -using namespace KeychainCore; - -// -// DynamicDLDBList -// -DynamicDLDBList::DynamicDLDBList() - : mMutex(Mutex::recursive), mSearchListSet(false) -{ -} - -DynamicDLDBList::~DynamicDLDBList() -{ -} - -CSSM_RETURN -DynamicDLDBList::appNotifyCallback(const CSSM_GUID *guid, void *context, - uint32 subserviceId, CSSM_SERVICE_TYPE subserviceType, CSSM_MODULE_EVENT eventType) -{ - CSSM_RETURN status = 0; - try - { - reinterpret_cast(context)->callback(Guid::required(guid), - subserviceId, subserviceType, eventType); - } - catch (const CommonError &error) - { - status = error.osStatus(); - } - catch (...) - { - } - - return status; -} - -/* Assume mLock is locked already. Add all databases for this module. */ -bool -DynamicDLDBList::_add(const Guid &guid, uint32 subserviceID, CSSM_SERVICE_TYPE subserviceType) -{ - return _add(dlDbIdentifier(guid, subserviceID, subserviceType)); -} - -/* Assume mLock is locked already. Add a single database to the searchlist. */ -bool -DynamicDLDBList::_add(const DLDbIdentifier &dlDbIdentifier) -{ - StLock_(mMutex); - - if (find(mSearchList.begin(), mSearchList.end(), dlDbIdentifier) == mSearchList.end()) - { - mSearchList.push_back(dlDbIdentifier); - return true; - } - - return false; -} - -/* Assume mLock is locked already. Remove all databases for this module. */ -bool -DynamicDLDBList::_remove(const Guid &guid, uint32 subserviceID, CSSM_SERVICE_TYPE subserviceType) -{ - return _remove(dlDbIdentifier(guid, subserviceID, subserviceType)); -} - -/* Assume mLock is locked already. Remove a single database from the - searchlist. */ -bool -DynamicDLDBList::_remove(const DLDbIdentifier &dlDbIdentifier) -{ - StLock_(mMutex); - - // search for subserviceUid but ignore the dbName, which is dynamic - for (SearchList::iterator it = mSearchList.begin(); it != mSearchList.end(); it++) - if (it->ssuid() == dlDbIdentifier.ssuid()) - { - mSearchList.erase(it); - - // Remove from the storageManager cache if it was there. - globals().storageManager.didRemoveKeychain(dlDbIdentifier); - return true; - } - // not found - return false; -} - -bool -DynamicDLDBList::_load() -{ - StLock_(mMutex); - - bool list_changed = false; - MDSClient::Directory &mds = MDSClient::mds(); - MDSClient::Table common(mds); - MDSClient::Table dl(mds); - MDSClient::Table csp(mds); - - for (MDSClient::Table::iterator commonIt = - common.find(MDSClient::Attribute("DynamicFlag") != false); - commonIt != common.end(); ++commonIt) - { - CSSM_SERVICE_MASK serviceMask = (*commonIt)->serviceMask(); - if (serviceMask & CSSM_SERVICE_DL) - { - string moduleID = (*commonIt)->moduleID(); - secdebug("dynamic", "Loading dynamic %sDL module: %s", - (serviceMask & CSSM_SERVICE_CSP) ? "CSP/" : "", moduleID.c_str()); - - /* Register module for callbacks and load it. */ - Guid moduleGuid(moduleID); - CssmClient::Module module(moduleGuid); - module->appNotifyCallback(appNotifyCallback, this); - module->load(); - mModules.push_back(module); - - /* Now that we have registered for notifications, Find all already - registered dl subsevices for this module. */ - for (MDSClient::Table::iterator dlIt = - dl.find(MDSClient::Attribute("ModuleID") == moduleID); - dlIt!= dl.end(); ++dlIt) - { - uint32 subserviceID = (*dlIt)->subserviceID(); - bool hasCSP = csp.find(MDSClient::Attribute("ModuleID") == moduleID - && MDSClient::Attribute("SSID") == subserviceID) != csp.end(); - - secdebug("dynamic", "Adding databases from %sDL SSID %lu module: %s", - hasCSP ? "CSP/" : "", (unsigned long)subserviceID, moduleID.c_str()); - list_changed |= _add(moduleGuid, subserviceID, - hasCSP ? CSSM_SERVICE_CSP | CSSM_SERVICE_DL : CSSM_SERVICE_DL); - } - } - } - - return list_changed; -} - -const vector & -DynamicDLDBList::searchList() -{ - StLock_(mMutex); - if (!mSearchListSet) - { - // Load all dynamic DL's so we start receiving notifications. - _load(); - - mSearchListSet = true; - } - - return mSearchList; -} - -void -DynamicDLDBList::callback(const Guid &guid, uint32 subserviceID, - CSSM_SERVICE_TYPE subserviceType, CSSM_MODULE_EVENT eventType) -{ - secdebug("event", "Received callback from guid: %s ssid: %lu type: %lu event: %lu", - guid.toString().c_str(), (unsigned long)subserviceID, (unsigned long)subserviceType, (unsigned long)eventType); - - StLock_(mMutex); - - bool list_changed = false; - - if (subserviceType & CSSM_SERVICE_DL) - { - if (eventType == CSSM_NOTIFY_INSERT) - { - /* A DL or CSP/DL was inserted. */ - secdebug("dynamic", "%sDL module: %s SSID: %lu inserted", - (subserviceType & CSSM_SERVICE_CSP) ? "CSP/" : "", guid.toString().c_str(), (unsigned long)subserviceID); - list_changed = _add(guid, subserviceID, subserviceType); - } - else if (eventType == CSSM_NOTIFY_REMOVE) - { - /* A DL or CSP/DL was removed. */ - secdebug("dynamic", "%sDL module: %s SSID: %lu removed", - (subserviceType & CSSM_SERVICE_CSP) ? "CSP/" : "", guid.toString().c_str(), (unsigned long)subserviceID); - list_changed = _remove(guid, subserviceID, subserviceType); - } - } - - if (list_changed) - { - // Make sure we are not holding mLock nor the StorageManager mLock when we post these events. - // @@@ Rather than posting we should simulate a receive since each client will receive this - // cssm level notification. - KCEventNotifier::PostKeychainEvent(kSecKeychainListChangedEvent); - } -} - -DLDbIdentifier DynamicDLDBList::dlDbIdentifier(const Guid &guid, - uint32 subserviceID, CSSM_SERVICE_TYPE subserviceType) -{ - CSSM_VERSION theVersion={}; - CssmSubserviceUid ssuid(guid, &theVersion, subserviceID, subserviceType); - CssmNetAddress *dbLocation=NULL; - - return DLDbIdentifier(ssuid, NULL, dbLocation); -} diff --git a/OSX/include/security_keychain/DynamicDLDBList.h b/OSX/include/security_keychain/DynamicDLDBList.h deleted file mode 100644 index 8f3656df..00000000 --- a/OSX/include/security_keychain/DynamicDLDBList.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * DynamicDLDBList.h - */ -#ifndef _SECURITY_DYNAMICDLDBLIST_H_ -#define _SECURITY_DYNAMICDLDBLIST_H_ - -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class DynamicDLDBList -{ -public: - DynamicDLDBList(); - ~DynamicDLDBList(); - - const vector &searchList(); - -protected: - Mutex mMutex; - bool _add(const Guid &guid, uint32 subserviceID, CSSM_SERVICE_TYPE subserviceType); - bool _add(const DLDbIdentifier &); - bool _remove(const Guid &guid, uint32 subserviceID, CSSM_SERVICE_TYPE subserviceType); - bool _remove(const DLDbIdentifier &); - bool _load(); - DLDbIdentifier dlDbIdentifier(const Guid &guid, uint32 subserviceID, - CSSM_SERVICE_TYPE subserviceType); - void callback(const Guid &guid, uint32 subserviceID, - CSSM_SERVICE_TYPE subserviceType, CSSM_MODULE_EVENT eventType); - -private: - static CSSM_RETURN appNotifyCallback(const CSSM_GUID *guid, void *context, - uint32 subserviceId, CSSM_SERVICE_TYPE subserviceType, CSSM_MODULE_EVENT eventType); - - vector mModules; - typedef vector SearchList; - SearchList mSearchList; - bool mSearchListSet; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif /* !_SECURITY_DYNAMICDLDBLIST_H_ */ diff --git a/OSX/include/security_keychain/ExtendedAttribute.cpp b/OSX/include/security_keychain/ExtendedAttribute.cpp deleted file mode 100644 index 88b5a5d7..00000000 --- a/OSX/include/security_keychain/ExtendedAttribute.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2006,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/* - * ExtendedAttribute.cpp - Extended Keychain Item Attribute class. - * - */ - -#include "ExtendedAttribute.h" -#include "SecKeychainItemExtendedAttributes.h" -#include "SecKeychainItemPriv.h" -#include "cssmdatetime.h" -#include - -using namespace KeychainCore; - -/* - * Construct new ExtendedAttr from API. - */ -ExtendedAttribute::ExtendedAttribute( - CSSM_DB_RECORDTYPE recordType, - const CssmData &itemID, - const CssmData attrName, - const CssmData attrValue) : - ItemImpl(CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, - reinterpret_cast(NULL), - 0, NULL), - mRecordType(recordType), - mItemID(Allocator::standard(), itemID.Data, itemID.Length), - mAttrName(Allocator::standard(), attrName.Data, attrName.Length), - mAttrValue(Allocator::standard(), attrValue.Data, attrValue.Length) -{ - setupAttrs(); -} - -// db item contstructor -ExtendedAttribute::ExtendedAttribute( - const Keychain &keychain, - const PrimaryKey &primaryKey, - const CssmClient::DbUniqueRecord &uniqueId) : - ItemImpl(keychain, primaryKey, uniqueId), - mRecordType(0), - mItemID(Allocator::standard()), - mAttrName(Allocator::standard()), - mAttrValue(Allocator::standard()) -{ - -} - -// PrimaryKey item contstructor -ExtendedAttribute::ExtendedAttribute( - const Keychain &keychain, - const PrimaryKey &primaryKey) : - ItemImpl(keychain, primaryKey), - mRecordType(0), - mItemID(Allocator::standard()), - mAttrName(Allocator::standard()), - mAttrValue(Allocator::standard()) -{ - -} - -ExtendedAttribute* ExtendedAttribute::make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) -{ - ExtendedAttribute* ea = new ExtendedAttribute(keychain, primaryKey, uniqueId); - keychain->addItem(primaryKey, ea); - return ea; -} - - - -ExtendedAttribute* ExtendedAttribute::make(const Keychain &keychain, const PrimaryKey &primaryKey) -{ - ExtendedAttribute* ea = new ExtendedAttribute(keychain, primaryKey); - keychain->addItem(primaryKey, ea); - return ea; -} - - - -// copy - required due to Item's weird constructor/vendor -ExtendedAttribute::ExtendedAttribute( - ExtendedAttribute &extendedAttr) : - ItemImpl(extendedAttr), - mRecordType(extendedAttr.mRecordType), - mItemID(Allocator::standard()), - mAttrName(Allocator::standard()), - mAttrValue(Allocator::standard()) -{ - // CssmData cd = extendedAttr.mItemID; - mItemID.copy(extendedAttr.mItemID); - // cd = extendedAttr.mAttrName; - mAttrName.copy(extendedAttr.mAttrName); - // cd = extendedAttr.mAttrValue; - mAttrValue.copy(extendedAttr.mAttrValue); - setupAttrs(); -} - -ExtendedAttribute::~ExtendedAttribute() throw() -{ - -} - -PrimaryKey -ExtendedAttribute::add(Keychain &keychain) -{ - StLock_(mMutex); - // If we already have a Keychain we can't be added. - if (mKeychain) - MacOSError::throwMe(errSecDuplicateItem); - - SInt64 date; - CSSMDateTimeUtils::GetCurrentMacLongDateTime(date); - CssmDbAttributeInfo attrInfo(kSecModDateItemAttr, CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE); - setAttribute(attrInfo, date); - - Db db(keychain->database()); - // add the item to the (regular) db - try - { - mUniqueId = db->insert(CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, mDbAttributes.get(), mData.get()); - } - catch (const CssmError &e) - { - if (e.osStatus() != CSSMERR_DL_INVALID_RECORDTYPE) - throw; - - /* - * First exposure of this keychain to the extended attribute record type. - * Create the relation and try again. - */ - db->createRelation(CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, - "CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE", - Schema::ExtendedAttributeSchemaAttributeCount, - Schema::ExtendedAttributeSchemaAttributeList, - Schema::ExtendedAttributeSchemaIndexCount, - Schema::ExtendedAttributeSchemaIndexList); - keychain->keychainSchema()->didCreateRelation( - CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, - "CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE", - Schema::ExtendedAttributeSchemaAttributeCount, - Schema::ExtendedAttributeSchemaAttributeList, - Schema::ExtendedAttributeSchemaIndexCount, - Schema::ExtendedAttributeSchemaIndexList); - - mUniqueId = db->insert(CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, mDbAttributes.get(), mData.get()); - } - - mPrimaryKey = keychain->makePrimaryKey(CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE, mUniqueId); - mKeychain = keychain; - - return mPrimaryKey; -} - -/* set up DB attrs based on member vars */ -void ExtendedAttribute::setupAttrs() -{ - StLock_(mMutex); - CssmDbAttributeInfo attrInfo1(kExtendedAttrRecordTypeAttr, CSSM_DB_ATTRIBUTE_FORMAT_UINT32); - setAttribute(attrInfo1, (uint32)mRecordType); - CssmData cd = mItemID; - CssmDbAttributeInfo attrInfo2(kExtendedAttrItemIDAttr, CSSM_DB_ATTRIBUTE_FORMAT_BLOB); - setAttribute(attrInfo2, cd); - cd = mAttrName; - CssmDbAttributeInfo attrInfo3(kExtendedAttrAttributeNameAttr, CSSM_DB_ATTRIBUTE_FORMAT_BLOB); - setAttribute(attrInfo3, cd); - cd = mAttrValue; - CssmDbAttributeInfo attrInfo4(kExtendedAttrAttributeValueAttr, CSSM_DB_ATTRIBUTE_FORMAT_BLOB); - setAttribute(attrInfo4, cd); -} - - diff --git a/OSX/include/security_keychain/ExtendedAttribute.h b/OSX/include/security_keychain/ExtendedAttribute.h deleted file mode 100644 index ed2b1f75..00000000 --- a/OSX/include/security_keychain/ExtendedAttribute.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/* - * ExtendedAttribute.h - Extended Keychain Item Attribute class. - * - */ - -#ifndef _SECURITY_EXTENDED_ATTRIBUTE_H_ -#define _SECURITY_EXTENDED_ATTRIBUTE_H_ - -#include -#include - -/* this is not public */ -typedef struct OpaqueSecExtendedAttributeRef *SecKeychainItemExtendedAttributeRef; - -namespace Security -{ - -namespace KeychainCore -{ - -class ExtendedAttribute : public ItemImpl -{ - NOCOPY(ExtendedAttribute) -public: - SECCFFUNCTIONS(ExtendedAttribute, SecKeychainItemExtendedAttributeRef, - errSecInvalidItemRef, gTypes().ExtendedAttribute) - - /* construct new ExtendedAttr from API */ - ExtendedAttribute(CSSM_DB_RECORDTYPE recordType, - const CssmData &itemID, - const CssmData attrName, - const CssmData attrValue); - -private: - // db item contstructor - ExtendedAttribute(const Keychain &keychain, - const PrimaryKey &primaryKey, - const CssmClient::DbUniqueRecord &uniqueId); - - // PrimaryKey item contstructor - ExtendedAttribute(const Keychain &keychain, const PrimaryKey &primaryKey); - -public: - static ExtendedAttribute* make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - static ExtendedAttribute* make(const Keychain &keychain, const PrimaryKey &primaryKey); - - ExtendedAttribute(ExtendedAttribute &extendedAttribute); - - virtual ~ExtendedAttribute() throw(); - - virtual PrimaryKey add(Keychain &keychain); - bool operator == (const ExtendedAttribute &other) const; -private: - /* set up DB attrs based on member vars */ - void setupAttrs(); - - CSSM_DB_RECORDTYPE mRecordType; - CssmAutoData mItemID; - CssmAutoData mAttrName; - CssmAutoData mAttrValue; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif /* _SECURITY_EXTENDED_ATTRIBUTES_H_ */ diff --git a/OSX/include/security_keychain/Globals.cpp b/OSX/include/security_keychain/Globals.cpp deleted file mode 100644 index f8d1e70e..00000000 --- a/OSX/include/security_keychain/Globals.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2000-2002,2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * Globals.cpp -- Private "globals" and interfaces for KeychainCore - */ - -#include "Globals.h" -#include "KCExceptions.h" - - -namespace Security { -namespace KeychainCore { - -using namespace CssmClient; - -ModuleNexus globals; -bool gServerMode; - -#pragma mark ÑÑÑÑ Constructor/Destructor ÑÑÑÑ - -Globals::Globals() : -mUI(true) -{ -} - -const AccessCredentials * Globals::keychainCredentials() -{ - return (mUI ? mACLFactory.unlockCred() : mACLFactory.cancelCred()); -} - -const AccessCredentials * Globals::smartcardCredentials() -{ - return (mUI ? mACLFactory.promptedPINCred() : mACLFactory.cancelCred()); -} - -const AccessCredentials * Globals::itemCredentials() -{ - return (mUI ? mACLFactory.promptCred() : mACLFactory.nullCred()); -} - -const AccessCredentials * Globals::smartcardItemCredentials() -{ - return (mUI ? mACLFactory.promptedPINItemCred() : mACLFactory.cancelCred()); -} - -} // namespace KeychainCore -} // namespace Security - - - -extern "C" bool GetServerMode() -{ - return Security::KeychainCore::gServerMode; -} diff --git a/OSX/include/security_keychain/Globals.h b/OSX/include/security_keychain/Globals.h deleted file mode 100644 index 4b192b0d..00000000 --- a/OSX/include/security_keychain/Globals.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// DefaultKeychain.h - Private "globals" and interfaces for KeychainCore -// -#ifndef _SECURITY_GLOBALS_H_ -#define _SECURITY_GLOBALS_H_ - -#ifdef check -#undef check -#endif -#include -#include - - -namespace Security -{ - -namespace KeychainCore -{ - -class Globals -{ -public: - Globals(); - - const AccessCredentials *keychainCredentials(); - const AccessCredentials *smartcardCredentials(); - const AccessCredentials *itemCredentials(); - const AccessCredentials *smartcardItemCredentials(); - - void setUserInteractionAllowed(bool bUI) { mUI=bUI; } - bool getUserInteractionAllowed() const { return mUI; } - - // Public globals - StorageManager storageManager; - -private: - - // Other "globals" - bool mUI; - CssmClient::AclFactory mACLFactory; -}; - -extern ModuleNexus globals; -extern bool gServerMode; - -} // end namespace KeychainCore - -} // end namespace Security - -extern "C" bool GetServerMode(); - -#endif // !_SECURITY_GLOBALS_H_ diff --git a/OSX/include/security_keychain/Identity.cpp b/OSX/include/security_keychain/Identity.cpp deleted file mode 100644 index 826ed985..00000000 --- a/OSX/include/security_keychain/Identity.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Identity.cpp - Working with Identities -// -#include - -#include -#include -#include - -using namespace KeychainCore; - -Identity::Identity(const SecPointer &privateKey, - const SecPointer &certificate) : - mPrivateKey(privateKey), - mCertificate(certificate) -{ -} - -Identity::Identity(const StorageManager::KeychainList &keychains, const SecPointer &certificate) : - mCertificate(certificate) -{ - // Find a key whose label matches the publicKeyHash of the public key in the certificate. - KCCursor keyCursor(keychains, CSSM_DL_DB_RECORD_PRIVATE_KEY, NULL); - keyCursor->add(CSSM_DB_EQUAL, KeySchema::Label, certificate->publicKeyHash()); - - Item key; - if (!keyCursor->next(key)) - MacOSError::throwMe(errSecItemNotFound); - - SecPointer keyItem(static_cast(&*key)); - mPrivateKey = keyItem; -} - -Identity::~Identity() throw() -{ -} - -SecPointer -Identity::privateKey() const -{ - return mPrivateKey; -} - -SecPointer -Identity::certificate() const -{ - return mCertificate; -} - -bool -Identity::operator < (const Identity &other) const -{ - // Certificates in different keychains are considered equal if data is equal - return (mCertificate < other.mCertificate); -} - -bool -Identity::operator == (const Identity &other) const -{ - // Certificates in different keychains are considered equal if data is equal; - // however, if their keys are in different keychains, the identities should - // not be considered equal (according to mb) - return (mCertificate == other.mCertificate && mPrivateKey == other.mPrivateKey); -} - -bool Identity::equal(SecCFObject &other) -{ - CFHashCode this_hash = hash(); - CFHashCode other_hash = other.hash(); - return (this_hash == other_hash); -} - -CFHashCode Identity::hash() -{ - CFHashCode result = SecCFObject::hash(); - - - struct keyAndCertHash - { - CFHashCode keyHash; - CFHashCode certHash; - }; - - struct keyAndCertHash hashes; - memset(&hashes, 0, sizeof(struct keyAndCertHash)); - - KeyItem* pKeyItem = mPrivateKey.get(); - if (NULL != pKeyItem) - { - hashes.keyHash = pKeyItem->hash(); - } - - Certificate* pCert = mCertificate.get(); - if (NULL != pCert) - { - hashes.certHash = pCert->hash(); - } - - if (hashes.keyHash != 0 || hashes.certHash != 0) - { - - CFDataRef temp_data = CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)&hashes, sizeof(struct keyAndCertHash), kCFAllocatorNull); - if (NULL != temp_data) - { - result = CFHash(temp_data); - CFRelease(temp_data); - } - } - - return result; -} - diff --git a/OSX/include/security_keychain/Identity.h b/OSX/include/security_keychain/Identity.h deleted file mode 100644 index 9a1d68c7..00000000 --- a/OSX/include/security_keychain/Identity.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Identity.h - Working with Identities -// -#ifndef _SECURITY_IDENTITY_H_ -#define _SECURITY_IDENTITY_H_ - -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class Identity : public SecCFObject -{ - NOCOPY(Identity) -public: - SECCFFUNCTIONS(Identity, SecIdentityRef, errSecInvalidItemRef, gTypes().Identity) - - Identity(const SecPointer &privateKey, - const SecPointer &certificate); - Identity(const StorageManager::KeychainList &keychains, const SecPointer &certificate); - virtual ~Identity() throw(); - - SecPointer privateKey() const; - SecPointer certificate() const; - - bool operator < (const Identity &other) const; - bool operator == (const Identity &other) const; - - bool equal(SecCFObject &other); - CFHashCode hash(); - -private: - SecPointer mPrivateKey; - SecPointer mCertificate; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_IDENTITY_H_ diff --git a/OSX/include/security_keychain/IdentityCursor.cpp b/OSX/include/security_keychain/IdentityCursor.cpp deleted file mode 100644 index e7f24d82..00000000 --- a/OSX/include/security_keychain/IdentityCursor.cpp +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2002-2008,2011-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * IdentityCursor.cpp -- Working with IdentityCursor - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace KeychainCore; - -IdentityCursorPolicyAndID::IdentityCursorPolicyAndID(const StorageManager::KeychainList &searchList, CSSM_KEYUSE keyUsage, CFStringRef idString, SecPolicyRef policy, bool returnOnlyValidIdentities) : - IdentityCursor(searchList, keyUsage), - mPolicy(policy), - mIDString(idString), - mReturnOnlyValidIdentities(returnOnlyValidIdentities), - mPreferredIdentityChecked(false), - mPreferredIdentity(nil) -{ - if (mPolicy) - CFRetain(mPolicy); - - if (mIDString) - CFRetain(mIDString); -} - -IdentityCursorPolicyAndID::~IdentityCursorPolicyAndID() throw() -{ - if (mPolicy) - CFRelease(mPolicy); - - if (mIDString) - CFRelease(mIDString); -} - -void -IdentityCursorPolicyAndID::findPreferredIdentity() -{ - char idUTF8[MAXPATHLEN]; - if (!mIDString || !CFStringGetCString(mIDString, idUTF8, sizeof(idUTF8)-1, kCFStringEncodingUTF8)) - idUTF8[0] = (char)'\0'; - uint32_t iprfValue = 'iprf'; // value is specified in host byte order, since kSecTypeItemAttr has type uint32 in the db schema - SecKeychainAttribute sAttrs[] = { - { kSecTypeItemAttr, sizeof(uint32_t), &iprfValue }, - { kSecServiceItemAttr, (UInt32)strlen(idUTF8), (char *)idUTF8 } - }; - SecKeychainAttributeList sAttrList = { sizeof(sAttrs) / sizeof(sAttrs[0]), sAttrs }; - -// StorageManager::KeychainList keychains; -// globals().storageManager.optionalSearchList((CFTypeRef)nil, keychains); - - Item item; - KCCursor cursor(mSearchList /*keychains*/, kSecGenericPasswordItemClass, &sAttrList); - if (!cursor->next(item)) - return; - - // get persistent certificate reference - SecKeychainAttribute itemAttrs[] = { { kSecGenericItemAttr, 0, NULL } }; - SecKeychainAttributeList itemAttrList = { sizeof(itemAttrs) / sizeof(itemAttrs[0]), itemAttrs }; - item->getContent(NULL, &itemAttrList, NULL, NULL); - - // find certificate, given persistent reference data - CFDataRef pItemRef = CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)itemAttrs[0].data, itemAttrs[0].length, kCFAllocatorNull); - SecKeychainItemRef certItemRef = nil; - OSStatus status = SecKeychainItemCopyFromPersistentReference(pItemRef, &certItemRef); - if (pItemRef) - CFRelease(pItemRef); - item->freeContent(&itemAttrList, NULL); - if (status || !certItemRef) - return; - - // create identity reference, given certificate - Item certItem = ItemImpl::required(SecKeychainItemRef(certItemRef)); - SecPointer certificate(static_cast(certItem.get())); - SecPointer identity(new Identity(mSearchList /*keychains*/, certificate)); - - mPreferredIdentity = identity; - - if (certItemRef) - CFRelease(certItemRef); -} - -bool -IdentityCursorPolicyAndID::next(SecPointer &identity) -{ - SecPointer currIdentity; - Boolean identityOK = true; - - if (!mPreferredIdentityChecked) - { - try - { - findPreferredIdentity(); - } - catch(...) {} - mPreferredIdentityChecked = true; - if (mPreferredIdentity) - { - identity = mPreferredIdentity; - return true; - } - } - - for (;;) - { - bool result = IdentityCursor::next(currIdentity); // base class finds the next identity by keyUsage - if ( result ) - { - if (mPreferredIdentity && (currIdentity == mPreferredIdentity)) - { - identityOK = false; // we already returned this one, move on to the next - continue; - } - - // If there was no policy specified, we're done. - if ( !mPolicy ) - { - identityOK = true; // return this identity - break; - } - - // To reduce the number of (potentially expensive) trust evaluations performed, we need - // to do some pre-processing to filter out certs that don't match the search criteria. - // Rather than try to duplicate the TP's policy logic here, we'll just call the TP with - // a single-element certificate array, no anchors, and no keychains to search. - - SecPointer certificate = currIdentity->certificate(); - CFRef certRef(certificate->handle()); - CFRef anchorsArray(CFArrayCreateMutable(NULL, 1, NULL)); - CFRef certArray(CFArrayCreateMutable(NULL, 1, NULL)); - if ( !certArray || !anchorsArray ) - { - identityOK = false; // skip this and move on to the next one - continue; - } - CFArrayAppendValue(certArray, certRef); - - SecPointer trustLite = new Trust(certArray, mPolicy); - StorageManager::KeychainList emptyList; - // Set the anchors and keychain search list to be empty - trustLite->anchors(anchorsArray); - trustLite->searchLibs(emptyList); - trustLite->evaluate(); - SecTrustResultType trustResult = trustLite->result(); - - if (trustResult == kSecTrustResultRecoverableTrustFailure || - trustResult == kSecTrustResultFatalTrustFailure) - { - CFArrayRef certChain = NULL; - CSSM_TP_APPLE_EVIDENCE_INFO *statusChain = NULL, *evInfo = NULL; - trustLite->buildEvidence(certChain, TPEvidenceInfo::overlayVar(statusChain)); - if (statusChain) - evInfo = &statusChain[0]; - if (!evInfo || evInfo->NumStatusCodes > 0) // per-cert codes means we can't use this cert for this policy - trustResult = kSecTrustResultInvalid; // handled below - if (certChain) - CFRelease(certChain); - } - if (trustResult == kSecTrustResultInvalid) - { - identityOK = false; // move on to the next one - continue; - } - - // If trust evaluation isn't requested, we're done. - if ( !mReturnOnlyValidIdentities ) - { - identityOK = true; // return this identity - break; - } - - // Perform a full trust evaluation on the certificate with the specified policy. - SecPointer trust = new Trust(certArray, mPolicy); - trust->evaluate(); - trustResult = trust->result(); - - if (trustResult == kSecTrustResultInvalid || - trustResult == kSecTrustResultRecoverableTrustFailure || - trustResult == kSecTrustResultFatalTrustFailure) - { - identityOK = false; // move on to the next one - continue; - } - - identityOK = true; // this one was OK; return it. - break; - } - else - { - identityOK = false; // no more left. - break; - } - } // for(;;) - - if ( identityOK ) - { - identity = currIdentity; // caller will release the identity - return true; - } - else - { - return false; - } -} - - -IdentityCursor::IdentityCursor(const StorageManager::KeychainList &searchList, CSSM_KEYUSE keyUsage) : - mSearchList(searchList), - mKeyCursor(mSearchList, CSSM_DL_DB_RECORD_PRIVATE_KEY, NULL), - mMutex(Mutex::recursive) -{ - StLock_(mMutex); - - // If keyUsage is CSSM_KEYUSE_ANY then we need a key that can do everything - if (keyUsage & CSSM_KEYUSE_ANY) - keyUsage = CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT - | CSSM_KEYUSE_DERIVE | CSSM_KEYUSE_SIGN - | CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_SIGN_RECOVER - | CSSM_KEYUSE_VERIFY_RECOVER | CSSM_KEYUSE_WRAP - | CSSM_KEYUSE_UNWRAP; - - if (keyUsage & CSSM_KEYUSE_ENCRYPT) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Encrypt, true); - if (keyUsage & CSSM_KEYUSE_DECRYPT) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Decrypt, true); - if (keyUsage & CSSM_KEYUSE_DERIVE) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Derive, true); - if (keyUsage & CSSM_KEYUSE_SIGN) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Sign, true); - if (keyUsage & CSSM_KEYUSE_VERIFY) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Verify, true); - if (keyUsage & CSSM_KEYUSE_SIGN_RECOVER) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::SignRecover, true); - if (keyUsage & CSSM_KEYUSE_VERIFY_RECOVER) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::VerifyRecover, true); - if (keyUsage & CSSM_KEYUSE_WRAP) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Wrap, true); - if (keyUsage & CSSM_KEYUSE_UNWRAP) - mKeyCursor->add(CSSM_DB_EQUAL, KeySchema::Unwrap, true); -} - -IdentityCursor::~IdentityCursor() throw() -{ -} - -CFDataRef -IdentityCursor::pubKeyHashForSystemIdentity(CFStringRef domain) -{ - StLock_(mMutex); - - CFDataRef entryValue = nil; - auto_ptr identDict; - Dictionary* d = Dictionary::CreateDictionary("com.apple.security.systemidentities", Dictionary::US_System); - if (d) - { - identDict.reset(d); - entryValue = identDict->getDataValue(domain); - if (entryValue == nil) { - /* try for default entry if we're not already looking for default */ - if(!CFEqual(domain, kSecIdentityDomainDefault)) { - entryValue = identDict->getDataValue(kSecIdentityDomainDefault); - } - } - } - - if (entryValue) { - CFRetain(entryValue); - } - return entryValue; -} - -bool -IdentityCursor::next(SecPointer &identity) -{ - StLock_(mMutex); - - for (;;) - { - if (!mCertificateCursor) - { - Item key; - if (!mKeyCursor->next(key)) - return false; - - mCurrentKey = static_cast(key.get()); - - CssmClient::DbUniqueRecord uniqueId = mCurrentKey->dbUniqueRecord(); - CssmClient::DbAttributes dbAttributes(uniqueId->database(), 1); - dbAttributes.add(KeySchema::Label); - uniqueId->get(&dbAttributes, NULL); - const CssmData &keyHash = dbAttributes[0]; - - mCertificateCursor = KCCursor(mSearchList, CSSM_DL_DB_RECORD_X509_CERTIFICATE, NULL); - mCertificateCursor->add(CSSM_DB_EQUAL, Schema::kX509CertificatePublicKeyHash, keyHash); - - // if we have entries for the system identities, exclude their public key hashes in the search - CFDataRef systemDefaultCertPubKeyHash = pubKeyHashForSystemIdentity(kSecIdentityDomainDefault); - if (systemDefaultCertPubKeyHash) { - CssmData pkHash((void *)CFDataGetBytePtr(systemDefaultCertPubKeyHash), CFDataGetLength(systemDefaultCertPubKeyHash)); - mCertificateCursor->add(CSSM_DB_NOT_EQUAL, Schema::kX509CertificatePublicKeyHash, pkHash); - CFRelease(systemDefaultCertPubKeyHash); - } - CFDataRef kerbKDCCertPubKeyHash = pubKeyHashForSystemIdentity(kSecIdentityDomainKerberosKDC); - if (kerbKDCCertPubKeyHash) { - CssmData pkHash((void *)CFDataGetBytePtr(kerbKDCCertPubKeyHash), CFDataGetLength(kerbKDCCertPubKeyHash)); - mCertificateCursor->add(CSSM_DB_NOT_EQUAL, Schema::kX509CertificatePublicKeyHash, pkHash); - CFRelease(kerbKDCCertPubKeyHash); - } - } - - Item cert; - if (mCertificateCursor->next(cert)) - { - SecPointer certificate(static_cast(cert.get())); - identity = new Identity(mCurrentKey, certificate); - return true; - } - else - mCertificateCursor = KCCursor(); - } -} diff --git a/OSX/include/security_keychain/IdentityCursor.h b/OSX/include/security_keychain/IdentityCursor.h deleted file mode 100644 index aa9d7f58..00000000 --- a/OSX/include/security_keychain/IdentityCursor.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2002-2008,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// IdentityCursor.h - Working with IdentityCursors -// -#ifndef _SECURITY_IDENTITYCURSOR_H_ -#define _SECURITY_IDENTITYCURSOR_H_ - -#include -#include -#include -#include -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class Identity; -class KeyItem; - -class IdentityCursor : public SecCFObject -{ - NOCOPY(IdentityCursor) -public: - SECCFFUNCTIONS(IdentityCursor, SecIdentitySearchRef, errSecInvalidSearchRef, gTypes().IdentityCursor) - - IdentityCursor(const StorageManager::KeychainList &searchList, CSSM_KEYUSE keyUsage); - virtual ~IdentityCursor() throw(); - virtual bool next(SecPointer &identity); - - CFDataRef pubKeyHashForSystemIdentity(CFStringRef domain); - -protected: - StorageManager::KeychainList mSearchList; - -private: - KCCursor mKeyCursor; - KCCursor mCertificateCursor; - SecPointer mCurrentKey; - Mutex mMutex; -}; - -class IdentityCursorPolicyAndID : public IdentityCursor -{ -public: - IdentityCursorPolicyAndID(const StorageManager::KeychainList &searchList, CSSM_KEYUSE keyUsage, CFStringRef idString, SecPolicyRef policy, bool returnOnlyValidIdentities); - virtual ~IdentityCursorPolicyAndID() throw(); - virtual bool next(SecPointer &identity); - virtual void findPreferredIdentity(); - -private: - SecPolicyRef mPolicy; - CFStringRef mIDString; - bool mReturnOnlyValidIdentities; - bool mPreferredIdentityChecked; - SecPointer mPreferredIdentity; -}; - - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_IDENTITYCURSOR_H_ diff --git a/OSX/include/security_keychain/Item.cpp b/OSX/include/security_keychain/Item.cpp deleted file mode 100644 index 057f0618..00000000 --- a/OSX/include/security_keychain/Item.cpp +++ /dev/null @@ -1,1548 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Item.cpp -// - -#include "Item.h" - -#include "Certificate.h" -#include "KeyItem.h" -#include "ExtendedAttribute.h" - -#include "Globals.h" -#include -#include "KCEventNotifier.h" -#include "KCExceptions.h" -#include "cssmdatetime.h" -#include -#include -#include -#include -#include -#include - -#define SENDACCESSNOTIFICATIONS 1 - -//%%% schema indexes should be defined in Schema.h -#define _kSecAppleSharePasswordItemClass 'ashp' -#define APPLEDB_CSSM_PRINTNAME_ATTRIBUTE 1 /* schema index for label attribute of keys or certificates */ -#define APPLEDB_GENERIC_PRINTNAME_ATTRIBUTE 7 /* schema index for label attribute of password items */ -#define IS_PASSWORD_ITEM_CLASS(X) ( (X) == kSecInternetPasswordItemClass || \ - (X) == kSecGenericPasswordItemClass || \ - (X) == _kSecAppleSharePasswordItemClass ) ? 1 : 0 - -using namespace KeychainCore; -using namespace CSSMDateTimeUtils; - -// -// ItemImpl -// - -// NewItemImpl constructor -ItemImpl::ItemImpl(SecItemClass itemClass, OSType itemCreator, UInt32 length, const void* data, bool dontDoAttributes) - : mDbAttributes(new DbAttributes()), - mKeychain(NULL), - secd_PersistentRef(NULL), - mDoNotEncrypt(false), - mInCache(false), - mMutex(Mutex::recursive) -{ - if (length && data) - mData = new CssmDataContainer(data, length); - - mDbAttributes->recordType(Schema::recordTypeFor(itemClass)); - - if (itemCreator) - mDbAttributes->add(Schema::attributeInfo(kSecCreatorItemAttr), itemCreator); -} - -ItemImpl::ItemImpl(SecItemClass itemClass, SecKeychainAttributeList *attrList, UInt32 length, const void* data) - : mDbAttributes(new DbAttributes()), - mKeychain(NULL), - secd_PersistentRef(NULL), - mDoNotEncrypt(false), - mInCache(false), - mMutex(Mutex::recursive) -{ - if (length && data) - mData = new CssmDataContainer(data, length); - - - mDbAttributes->recordType(Schema::recordTypeFor(itemClass)); - - if(attrList) - { - for(UInt32 i=0; i < attrList->count; i++) - { - mDbAttributes->add(Schema::attributeInfo(attrList->attr[i].tag), CssmData(attrList->attr[i].data, attrList->attr[i].length)); - } - } -} - -// DbItemImpl constructor -ItemImpl::ItemImpl(const Keychain &keychain, const PrimaryKey &primaryKey, const DbUniqueRecord &uniqueId) - : mUniqueId(uniqueId), mKeychain(keychain), mPrimaryKey(primaryKey), - secd_PersistentRef(NULL), mDoNotEncrypt(false), mInCache(false), - mMutex(Mutex::recursive) -{ -} - -// PrimaryKey ItemImpl constructor -ItemImpl::ItemImpl(const Keychain &keychain, const PrimaryKey &primaryKey) -: mKeychain(keychain), mPrimaryKey(primaryKey), secd_PersistentRef(NULL), mDoNotEncrypt(false), - mInCache(false), - mMutex(Mutex::recursive) -{ -} - -ItemImpl* ItemImpl::make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) -{ - ItemImpl* ii = new ItemImpl(keychain, primaryKey, uniqueId); - keychain->addItem(primaryKey, ii); - return ii; -} - - - -ItemImpl* ItemImpl::make(const Keychain &keychain, const PrimaryKey &primaryKey) -{ - ItemImpl* ii = new ItemImpl(keychain, primaryKey); - keychain->addItem(primaryKey, ii); - return ii; -} - - - -// Constructor used when copying an item to a keychain. - -ItemImpl::ItemImpl(ItemImpl &item) : - mData(item.modifiedData() ? NULL : new CssmDataContainer()), - mDbAttributes(new DbAttributes()), - mKeychain(NULL), - secd_PersistentRef(NULL), - mDoNotEncrypt(false), - mInCache(false), - mMutex(Mutex::recursive) -{ - mDbAttributes->recordType(item.recordType()); - CSSM_DB_RECORD_ATTRIBUTE_INFO *schemaAttributes = NULL; - - if (item.mKeychain) { - // get the entire source item from its keychain. This requires figuring - // out the schema for the item based on its record type. - - for (uint32 i = 0; i < Schema::DBInfo.NumberOfRecordTypes; i++) - if (item.recordType() == Schema::DBInfo.RecordAttributeNames[i].DataRecordType) { - schemaAttributes = &Schema::DBInfo.RecordAttributeNames[i]; - break; - } - - if (schemaAttributes == NULL) - // the source item is invalid - MacOSError::throwMe(errSecInvalidItemRef); - - for (uint32 i = 0; i < schemaAttributes->NumberOfAttributes; i++) - mDbAttributes->add(schemaAttributes->AttributeInfo[i]); - - item.getContent(mDbAttributes.get(), mData.get()); - } - - // @@@ We don't deal with modified attributes. - - if (item.modifiedData()) - // the copied data comes from the source item - mData = new CssmDataContainer(item.modifiedData()->Data, - item.modifiedData()->Length); -} - -ItemImpl::~ItemImpl() -{ - if (secd_PersistentRef) { - CFRelease(secd_PersistentRef); - } -} - - - -Mutex* -ItemImpl::getMutexForObject() -{ - if (mKeychain.get()) - { - return mKeychain->getKeychainMutex(); - } - - return NULL; -} - - - -void -ItemImpl::aboutToDestruct() -{ - if (mKeychain && *mPrimaryKey) - { - mKeychain->removeItem(mPrimaryKey, this); - } -} - - - -void -ItemImpl::didModify() -{ - StLock_(mMutex); - mData = NULL; - mDbAttributes.reset(NULL); -} - -const CSSM_DATA & -ItemImpl::defaultAttributeValue(const CSSM_DB_ATTRIBUTE_INFO &info) -{ - static const uint32 zeroInt = 0; - static const double zeroDouble = 0.0; - static const char timeBytes[] = "20010101000000Z"; - - static const CSSM_DATA defaultFourBytes = { 4, (uint8 *) &zeroInt }; - static const CSSM_DATA defaultEightBytes = { 8, (uint8 *) &zeroDouble }; - static const CSSM_DATA defaultTime = { 16, (uint8 *) timeBytes }; - static const CSSM_DATA defaultZeroBytes = { 0, NULL }; - - switch (info.AttributeFormat) - { - case CSSM_DB_ATTRIBUTE_FORMAT_SINT32: - case CSSM_DB_ATTRIBUTE_FORMAT_UINT32: - return defaultFourBytes; - - case CSSM_DB_ATTRIBUTE_FORMAT_REAL: - return defaultEightBytes; - - case CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE: - return defaultTime; - - default: - return defaultZeroBytes; - } -} - - - -PrimaryKey ItemImpl::addWithCopyInfo (Keychain &keychain, bool isCopy) -{ - StLock_(mMutex); - // If we already have a Keychain we can't be added. - if (mKeychain) - MacOSError::throwMe(errSecDuplicateItem); - - // If we don't have any attributes we can't be added. - // (this might occur if attempting to add the item twice, since our attributes - // and data are set to NULL at the end of this function.) - if (!mDbAttributes.get()) - MacOSError::throwMe(errSecDuplicateItem); - - CSSM_DB_RECORDTYPE recordType = mDbAttributes->recordType(); - - // update the creation and update dates on the new item - if (!isCopy) - { - KeychainSchema schema = keychain->keychainSchema(); - SInt64 date; - GetCurrentMacLongDateTime(date); - if (schema->hasAttribute(recordType, kSecCreationDateItemAttr)) - { - setAttribute(schema->attributeInfoFor(recordType, kSecCreationDateItemAttr), date); - } - - if (schema->hasAttribute(recordType, kSecModDateItemAttr)) - { - setAttribute(schema->attributeInfoFor(recordType, kSecModDateItemAttr), date); - } - } - - // If the label (PrintName) attribute isn't specified, set a default label. - if (!mDoNotEncrypt && !mDbAttributes->find(Schema::attributeInfo(kSecLabelItemAttr))) - { - // if doNotEncrypt was set all of the attributes are wrapped in the data blob. Don't calculate here. - CssmDbAttributeData *label = NULL; - switch (recordType) - { - case CSSM_DL_DB_RECORD_GENERIC_PASSWORD: - label = mDbAttributes->find(Schema::attributeInfo(kSecServiceItemAttr)); - break; - - case CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD: - case CSSM_DL_DB_RECORD_INTERNET_PASSWORD: - label = mDbAttributes->find(Schema::attributeInfo(kSecServerItemAttr)); - // if AppleShare server name wasn't specified, try the server address - if (!label) label = mDbAttributes->find(Schema::attributeInfo(kSecAddressItemAttr)); - break; - - default: - break; - } - // if all else fails, use the account name. - if (!label) - label = mDbAttributes->find(Schema::attributeInfo(kSecAccountItemAttr)); - - if (label && label->size()) - setAttribute (Schema::attributeInfo(kSecLabelItemAttr), label->at(0)); - } - - // get the attributes that are part of the primary key - const CssmAutoDbRecordAttributeInfo &primaryKeyInfos = - keychain->primaryKeyInfosFor(recordType); - - // make sure each primary key element has a value in the item, otherwise - // the database will complain. we make a set of the provided attribute infos - // to avoid O(N^2) behavior. - - DbAttributes *attributes = mDbAttributes.get(); - typedef set InfoSet; - InfoSet infoSet; - - if (!mDoNotEncrypt) - { - // make a set of all the attributes in the key - for (uint32 i = 0; i < attributes->size(); i++) - infoSet.insert(attributes->at(i).Info); - - for (uint32 i = 0; i < primaryKeyInfos.size(); i++) { // check to make sure all required attributes are in the key - InfoSet::const_iterator it = infoSet.find(primaryKeyInfos.at(i)); - - if (it == infoSet.end()) { // not in the key? add the default - // we need to add a default value to the item attributes - attributes->add(primaryKeyInfos.at(i), defaultAttributeValue(primaryKeyInfos.at(i))); - } - } - } - - Db db(keychain->database()); - if (mDoNotEncrypt) - { - mUniqueId = db->insertWithoutEncryption (recordType, NULL, mData.get()); - } - else if (useSecureStorage(db)) - { - // Add the item to the secure storage db - SSDbImpl* impl = dynamic_cast(&(*db)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDb ssDb(impl); - - TrackingAllocator allocator(Allocator::standard()); - - // hhs replaced with the new aclFactory class - AclFactory aclFactory; - const AccessCredentials *nullCred = aclFactory.nullCred(); - - SecPointer access = mAccess; - if (!access) { - // create default access controls for the new item - CssmDbAttributeData *data = mDbAttributes->find(Schema::attributeInfo(kSecLabelItemAttr)); - string printName = data ? CssmData::overlay(data->Value[0]).toString() : "keychain item"; - access = new Access(printName); - - // special case for "iTools" password - allow anyone to decrypt the item - if (recordType == CSSM_DL_DB_RECORD_GENERIC_PASSWORD) - { - CssmDbAttributeData *data = mDbAttributes->find(Schema::attributeInfo(kSecServiceItemAttr)); - if (data && data->Value[0].Length == 6 && !memcmp("iTools", data->Value[0].Data, 6)) - { - typedef vector > AclSet; - AclSet acls; - access->findAclsForRight(CSSM_ACL_AUTHORIZATION_DECRYPT, acls); - for (AclSet::const_iterator it = acls.begin(); it != acls.end(); it++) - (*it)->form(ACL::allowAllForm); - } - } - } - - // Get the handle of the DL underlying this CSPDL. - CSSM_DL_DB_HANDLE dldbh; - db->passThrough(CSSM_APPLECSPDL_DB_GET_HANDLE, NULL, - reinterpret_cast(&dldbh)); - - // Turn off autocommit on the underlying DL and remember the old state. - CSSM_BOOL autoCommit = CSSM_TRUE; - ObjectImpl::check(CSSM_DL_PassThrough(dldbh, - CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - 0, reinterpret_cast(&autoCommit))); - - try - { - // Create a new SSGroup with temporary access controls - Access::Maker maker; - ResourceControlContext prototype; - maker.initialOwner(prototype, nullCred); - SSGroup ssGroup(ssDb, &prototype); - - try - { - // Insert the record using the newly created group. - mUniqueId = ssDb->insert(recordType, mDbAttributes.get(), - mData.get(), ssGroup, maker.cred()); - } - catch(...) - { - ssGroup->deleteKey(nullCred); - throw; - } - - // now finalize the access controls on the group - access->setAccess(*ssGroup, maker); - mAccess = NULL; // use them and lose them - if (autoCommit) - { - // autoCommit was on so commit now that we are done and turn - // it back on. - ObjectImpl::check(CSSM_DL_PassThrough(dldbh, - CSSM_APPLEFILEDL_COMMIT, NULL, NULL)); - CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - reinterpret_cast(autoCommit), NULL); - } - } - catch (...) - { - if (autoCommit) - { - // autoCommit was off so rollback since we failed and turn - // autoCommit back on. - CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_ROLLBACK, NULL, NULL); - CSSM_DL_PassThrough(dldbh, CSSM_APPLEFILEDL_TOGGLE_AUTOCOMMIT, - reinterpret_cast(autoCommit), NULL); - } - throw; - } - } - else - { - // add the item to the (regular) db - mUniqueId = db->insert(recordType, mDbAttributes.get(), mData.get()); - } - - mPrimaryKey = keychain->makePrimaryKey(recordType, mUniqueId); - mKeychain = keychain; - - // Forget our data and attributes. - mData = NULL; - mDbAttributes.reset(NULL); - - return mPrimaryKey; -} - - - -PrimaryKey -ItemImpl::add (Keychain &keychain) -{ - return addWithCopyInfo (keychain, false); -} - - - -Item -ItemImpl::copyTo(const Keychain &keychain, Access *newAccess) -{ - StLock_(mMutex); - Item item(*this); - if (newAccess) - item->setAccess(newAccess); - else - { - /* Attempt to copy the access from the current item to the newly created one. */ - SSGroup myGroup = group(); - if (myGroup) - { - SecPointer access = new Access(*myGroup); - item->setAccess(access); - } - } - - keychain->addCopy(item); - return item; -} - -void -ItemImpl::update() -{ - StLock_(mMutex); - if (!mKeychain) - MacOSError::throwMe(errSecNoSuchKeychain); - - // Don't update if nothing changed. - if (!isModified()) - return; - - CSSM_DB_RECORDTYPE aRecordType = recordType(); - KeychainSchema schema = mKeychain->keychainSchema(); - - // Update the modification date on the item if there is a mod date attribute. - if (schema->hasAttribute(aRecordType, kSecModDateItemAttr)) - { - SInt64 date; - GetCurrentMacLongDateTime(date); - setAttribute(schema->attributeInfoFor(aRecordType, kSecModDateItemAttr), date); - } - - // Make sure that we have mUniqueId - dbUniqueRecord(); - Db db(mUniqueId->database()); - if (mDoNotEncrypt) - { - CSSM_DB_RECORD_ATTRIBUTE_DATA attrData; - memset (&attrData, 0, sizeof (attrData)); - attrData.DataRecordType = aRecordType; - - mUniqueId->modifyWithoutEncryption(aRecordType, - &attrData, - mData.get(), - CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - } - else if (useSecureStorage(db)) - { - // Add the item to the secure storage db - SSDbUniqueRecordImpl * impl = dynamic_cast(&(*mUniqueId)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDbUniqueRecord ssUniqueId(impl); - - // @@@ Share this instance - const AccessCredentials *autoPrompt = globals().itemCredentials(); - - - // Only call this is user interaction is enabled. - ssUniqueId->modify(aRecordType, - mDbAttributes.get(), - mData.get(), - CSSM_DB_MODIFY_ATTRIBUTE_REPLACE, - autoPrompt); - } - else - { - mUniqueId->modify(aRecordType, - mDbAttributes.get(), - mData.get(), - CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - } - - if (!mDoNotEncrypt) - { - PrimaryKey oldPK = mPrimaryKey; - mPrimaryKey = mKeychain->makePrimaryKey(aRecordType, mUniqueId); - - // Forget our data and attributes. - mData = NULL; - mDbAttributes.reset(NULL); - - // Let the Keychain update what it needs to. - mKeychain->didUpdate(this, oldPK, mPrimaryKey); - } -} - -void -ItemImpl::getClass(SecKeychainAttribute &attr, UInt32 *actualLength) -{ - StLock_(mMutex); - if (actualLength) - *actualLength = sizeof(SecItemClass); - - if (attr.length < sizeof(SecItemClass)) - MacOSError::throwMe(errSecBufferTooSmall); - - SecItemClass aClass = Schema::itemClassFor(recordType()); - memcpy(attr.data, &aClass, sizeof(SecItemClass)); -} - -void -ItemImpl::setAttribute(SecKeychainAttribute& attr) -{ - StLock_(mMutex); - setAttribute(Schema::attributeInfo(attr.tag), CssmData(attr.data, attr.length)); -} - -CSSM_DB_RECORDTYPE -ItemImpl::recordType() -{ - StLock_(mMutex); - if (mDbAttributes.get()) - return mDbAttributes->recordType(); - - return mPrimaryKey->recordType(); -} - -const DbAttributes * -ItemImpl::modifiedAttributes() -{ - StLock_(mMutex); - return mDbAttributes.get(); -} - -const CssmData * -ItemImpl::modifiedData() -{ - StLock_(mMutex); - return mData.get(); -} - -void -ItemImpl::setData(UInt32 length,const void *data) -{ - StLock_(mMutex); - mData = new CssmDataContainer(data, length); -} - -void -ItemImpl::setAccess(Access *newAccess) -{ - StLock_(mMutex); - mAccess = newAccess; -} - -CssmClient::DbUniqueRecord -ItemImpl::dbUniqueRecord() -{ - StLock_(mMutex); - if (!isPersistent()) // is there no database attached? - { - MacOSError::throwMe(errSecNotAvailable); - } - - if (!mUniqueId) - { - DbCursor cursor(mPrimaryKey->createCursor(mKeychain)); - if (!cursor->next(NULL, NULL, mUniqueId)) - MacOSError::throwMe(errSecInvalidItemRef); - } - - return mUniqueId; -} - -PrimaryKey -ItemImpl::primaryKey() -{ - return mPrimaryKey; -} - -bool -ItemImpl::isPersistent() -{ - return mKeychain; -} - -bool -ItemImpl::isModified() -{ - StLock_(mMutex); - return mData.get() || mDbAttributes.get(); -} - -Keychain -ItemImpl::keychain() -{ - return mKeychain; -} - -bool -ItemImpl::operator < (const ItemImpl &other) -{ - if (mData && *mData) - { - // Pointer compare - return this < &other; - } - - return mPrimaryKey < other.mPrimaryKey; -} - -void -ItemImpl::setAttribute(const CssmDbAttributeInfo &info, const CssmPolyData &data) -{ - StLock_(mMutex); - if (!mDbAttributes.get()) - { - mDbAttributes.reset(new DbAttributes()); - mDbAttributes->recordType(mPrimaryKey->recordType()); - } - - size_t length = data.Length; - const void *buf = reinterpret_cast(data.Data); - uint8 timeString[16]; - - // XXX This code is duplicated in KCCursorImpl::KCCursorImpl() - // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE - // style attribute value. - if (info.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) - { - if (length == sizeof(UInt32)) - { - MacSecondsToTimeString(*reinterpret_cast(buf), 16, &timeString); - buf = &timeString; - length = 16; - } - else if (length == sizeof(SInt64)) - { - MacLongDateTimeToTimeString(*reinterpret_cast(buf), 16, &timeString); - buf = &timeString; - length = 16; - } - } - - mDbAttributes->add(info, CssmData(const_cast(buf), length)); -} - -void -ItemImpl::modifyContent(const SecKeychainAttributeList *attrList, UInt32 dataLength, const void *inData) -{ - StLock_(mMutex); - if (!mDbAttributes.get()) - { - mDbAttributes.reset(new DbAttributes()); - mDbAttributes->recordType(mPrimaryKey->recordType()); - } - - if(attrList) // optional - { - for(UInt32 ix=0; ix < attrList->count; ix++) - { - SecKeychainAttrType attrTag = attrList->attr[ix].tag; - - if (attrTag == APPLEDB_CSSM_PRINTNAME_ATTRIBUTE) - { - // must remap a caller-supplied kSecKeyPrintName attribute tag for key items, since it isn't in the schema - // (note that this will ultimately match kGenericPrintName in Schema.cpp) - attrTag = kSecLabelItemAttr; - } - - mDbAttributes->add(Schema::attributeInfo(attrTag), CssmData(attrList->attr[ix].data, attrList->attr[ix].length)); - } - } - - if(inData) - { - mData = new CssmDataContainer(inData, dataLength); - } - - update(); -} - -void -ItemImpl::getContent(SecItemClass *itemClass, SecKeychainAttributeList *attrList, UInt32 *length, void **outData) -{ - StLock_(mMutex); - // If the data hasn't been set we can't return it. - if (!mKeychain && outData) - { - CssmData *data = mData.get(); - if (!data) - MacOSError::throwMe(errSecDataNotAvailable); - } - // TODO: need to check and make sure attrs are valid and handle error condition - - - if (itemClass) - *itemClass = Schema::itemClassFor(recordType()); - - bool getDataFromDatabase = mKeychain && mPrimaryKey; - if (getDataFromDatabase) // are we attached to a database? - { - dbUniqueRecord(); - - // get the number of attributes requested by the caller - UInt32 attrCount = attrList ? attrList->count : 0; - - // make a DBAttributes structure and populate it - DbAttributes dbAttributes(mUniqueId->database(), attrCount); - for (UInt32 ix = 0; ix < attrCount; ++ix) - { - dbAttributes.add(Schema::attributeInfo(attrList->attr[ix].tag)); - } - - // request the data from the database (since we are a reference "item" and the data is really stored there) - CssmDataContainer itemData; - getContent(&dbAttributes, outData ? &itemData : NULL); - - // retrieve the data from result - for (UInt32 ix = 0; ix < attrCount; ++ix) - { - if (dbAttributes.at(ix).NumberOfValues > 0) - { - attrList->attr[ix].data = dbAttributes.at(ix).Value[0].Data; - attrList->attr[ix].length = (UInt32)dbAttributes.at(ix).Value[0].Length; - - // We don't want the data released, it is up the client - dbAttributes.at(ix).Value[0].Data = NULL; - dbAttributes.at(ix).Value[0].Length = 0; - } - else - { - attrList->attr[ix].data = NULL; - attrList->attr[ix].length = 0; - } - } - - // clean up - if (outData) - { - *outData=itemData.data(); - itemData.Data = NULL; - - if (length) - *length=(UInt32)itemData.length(); - itemData.Length = 0; - } - } - else - { - getLocalContent(attrList, length, outData); - } - - // Inform anyone interested that we are doing this -#if SENDACCESSNOTIFICATIONS - if (outData) - { - secdebug("kcnotify", "ItemImpl::getContent(%p, %p, %p, %p) retrieved content", - itemClass, attrList, length, outData); - - KCEventNotifier::PostKeychainEvent(kSecDataAccessEvent, mKeychain, this); - } -#endif -} - -void -ItemImpl::freeContent(SecKeychainAttributeList *attrList, void *data) -{ - Allocator &allocator = Allocator::standard(); // @@@ This might not match the one used originally - if (data) - allocator.free(data); - - UInt32 attrCount = attrList ? attrList->count : 0; - for (UInt32 ix = 0; ix < attrCount; ++ix) - { - allocator.free(attrList->attr[ix].data); - attrList->attr[ix].data = NULL; - } -} - -void -ItemImpl::modifyAttributesAndData(const SecKeychainAttributeList *attrList, UInt32 dataLength, const void *inData) -{ - StLock_(mMutex); - if (!mKeychain) - MacOSError::throwMe(errSecNoSuchKeychain); - - if (!mDoNotEncrypt) - { - if (!mDbAttributes.get()) - { - mDbAttributes.reset(new DbAttributes()); - mDbAttributes->recordType(mPrimaryKey->recordType()); - } - - CSSM_DB_RECORDTYPE recordType = mDbAttributes->recordType(); - UInt32 attrCount = attrList ? attrList->count : 0; - for (UInt32 ix = 0; ix < attrCount; ix++) - { - SecKeychainAttrType attrTag = attrList->attr[ix].tag; - - if (attrTag == kSecLabelItemAttr) - { - // must remap a caller-supplied label attribute tag for password items, since it isn't in the schema - // (note that this will ultimately match kGenericPrintName in Schema.cpp) - if (IS_PASSWORD_ITEM_CLASS( Schema::itemClassFor(recordType) )) - attrTag = APPLEDB_GENERIC_PRINTNAME_ATTRIBUTE; - } - - CssmDbAttributeInfo info=mKeychain->attributeInfoFor(recordType, attrTag); - - if (attrList->attr[ix].length || info.AttributeFormat==CSSM_DB_ATTRIBUTE_FORMAT_STRING || info.AttributeFormat==CSSM_DB_ATTRIBUTE_FORMAT_BLOB - || info.AttributeFormat==CSSM_DB_ATTRIBUTE_FORMAT_STRING || info.AttributeFormat==CSSM_DB_ATTRIBUTE_FORMAT_BIG_NUM - || info.AttributeFormat==CSSM_DB_ATTRIBUTE_FORMAT_MULTI_UINT32) - mDbAttributes->add(info, CssmData(attrList->attr[ix].data, attrList->attr[ix].length)); - else - mDbAttributes->add(info); - } - } - - if(inData) - { - mData = new CssmDataContainer(inData, dataLength); - } - - update(); -} - -void -ItemImpl::getAttributesAndData(SecKeychainAttributeInfo *info, SecItemClass *itemClass, - SecKeychainAttributeList **attrList, UInt32 *length, void **outData) -{ - StLock_(mMutex); - // If the data hasn't been set we can't return it. - if (!mKeychain && outData) - { - CssmData *data = mData.get(); - if (!data) - MacOSError::throwMe(errSecDataNotAvailable); - } - // TODO: need to check and make sure attrs are valid and handle error condition - - SecItemClass myItemClass = Schema::itemClassFor(recordType()); - if (itemClass) - *itemClass = myItemClass; - - // @@@ This call won't work for floating items (like certificates). - dbUniqueRecord(); - - UInt32 attrCount = info ? info->count : 0; - DbAttributes dbAttributes(mUniqueId->database(), attrCount); - for (UInt32 ix = 0; ix < attrCount; ix++) - { - CssmDbAttributeData &record = dbAttributes.add(); - record.Info.AttributeNameFormat=CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - record.Info.Label.AttributeID=info->tag[ix]; - - if (record.Info.Label.AttributeID == kSecLabelItemAttr) - { - // must remap a caller-supplied label attribute tag for password items, since it isn't in the schema - if (IS_PASSWORD_ITEM_CLASS( myItemClass )) - record.Info.Label.AttributeID = APPLEDB_GENERIC_PRINTNAME_ATTRIBUTE; - } - } - - CssmDataContainer itemData; - getContent(&dbAttributes, outData ? &itemData : NULL); - - if (info && attrList) - { - SecKeychainAttributeList *theList=reinterpret_cast(malloc(sizeof(SecKeychainAttributeList))); - SecKeychainAttribute *attr=reinterpret_cast(malloc(sizeof(SecKeychainAttribute)*attrCount)); - theList->count=attrCount; - theList->attr=attr; - - for (UInt32 ix = 0; ix < attrCount; ++ix) - { - attr[ix].tag=info->tag[ix]; - - if (dbAttributes.at(ix).NumberOfValues > 0) - { - attr[ix].data = dbAttributes.at(ix).Value[0].Data; - attr[ix].length = (UInt32)dbAttributes.at(ix).Value[0].Length; - - // We don't want the data released, it is up the client - dbAttributes.at(ix).Value[0].Data = NULL; - dbAttributes.at(ix).Value[0].Length = 0; - } - else - { - attr[ix].data = NULL; - attr[ix].length = 0; - } - } - *attrList=theList; - } - - if (outData) - { - *outData=itemData.data(); - itemData.Data=NULL; - - if (length) *length=(UInt32)itemData.length(); - itemData.Length=0; - -#if SENDACCESSNOTIFICATIONS - secdebug("kcnotify", "ItemImpl::getAttributesAndData(%p, %p, %p, %p, %p) retrieved data", - info, itemClass, attrList, length, outData); - - KCEventNotifier::PostKeychainEvent(kSecDataAccessEvent, mKeychain, this); -#endif - } - -} - -void -ItemImpl::freeAttributesAndData(SecKeychainAttributeList *attrList, void *data) -{ - Allocator &allocator = Allocator::standard(); // @@@ This might not match the one used originally - - if (data) - allocator.free(data); - - if (attrList) - { - for (UInt32 ix = 0; ix < attrList->count; ++ix) - { - allocator.free(attrList->attr[ix].data); - } - free(attrList->attr); - free(attrList); - } -} - -void -ItemImpl::getAttribute(SecKeychainAttribute& attr, UInt32 *actualLength) -{ - StLock_(mMutex); - if (attr.tag == kSecClassItemAttr) - return getClass(attr, actualLength); - - if (mDbAttributes.get()) - { - CssmDbAttributeData *data = mDbAttributes->find(Schema::attributeInfo(attr.tag)); - if (data) - { - getAttributeFrom(data, attr, actualLength); - return; - } - } - - if (!mKeychain) - MacOSError::throwMe(errSecNoSuchAttr); - - dbUniqueRecord(); - DbAttributes dbAttributes(mUniqueId->database(), 1); - dbAttributes.add(Schema::attributeInfo(attr.tag)); - mUniqueId->get(&dbAttributes, NULL); - getAttributeFrom(&dbAttributes.at(0), attr, actualLength); -} - -void -ItemImpl::getAttributeFrom(CssmDbAttributeData *data, SecKeychainAttribute &attr, UInt32 *actualLength) -{ - StLock_(mMutex); - static const uint32 zero = 0; - UInt32 length; - const void *buf = NULL; - - // Temporary storage for buf. - sint64 macLDT; - uint32 macSeconds; - sint16 svalue16; - uint16 uvalue16; - sint8 svalue8; - uint8 uvalue8; - - if (!data) - length = 0; - else if (data->size() < 1) // Attribute has no values. - { - if (data->format() == CSSM_DB_ATTRIBUTE_FORMAT_SINT32 - || data->format() == CSSM_DB_ATTRIBUTE_FORMAT_UINT32) - { - length = sizeof(zero); - buf = &zero; - } - else if (CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) - length = 0; // Should we throw here? - else // All other formats - length = 0; - } - else // Get the first value - { - length = (UInt32)data->Value[0].Length; - buf = data->Value[0].Data; - - if (data->format() == CSSM_DB_ATTRIBUTE_FORMAT_SINT32) - { - if (attr.length == sizeof(sint8)) - { - length = attr.length; - svalue8 = sint8(*reinterpret_cast(buf)); - buf = &svalue8; - } - else if (attr.length == sizeof(sint16)) - { - length = attr.length; - svalue16 = sint16(*reinterpret_cast(buf)); - buf = &svalue16; - } - } - else if (data->format() == CSSM_DB_ATTRIBUTE_FORMAT_UINT32) - { - if (attr.length == sizeof(uint8)) - { - length = attr.length; - uvalue8 = uint8(*reinterpret_cast(buf)); - buf = &uvalue8; - } - else if (attr.length == sizeof(uint16)) - { - length = attr.length; - uvalue16 = uint16(*reinterpret_cast(buf)); - buf = &uvalue16; - } - } - else if (data->format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) - { - if (attr.length == sizeof(uint32)) - { - TimeStringToMacSeconds(data->Value[0], macSeconds); - buf = &macSeconds; - length = attr.length; - } - else if (attr.length == sizeof(sint64)) - { - TimeStringToMacLongDateTime(data->Value[0], macLDT); - buf = &macLDT; - length = attr.length; - } - } - } - - if (actualLength) - *actualLength = length; - - if (length) - { - if (attr.length < length) - MacOSError::throwMe(errSecBufferTooSmall); - - memcpy(attr.data, buf, length); - } -} - -void -ItemImpl::getData(CssmDataContainer& outData) -{ - StLock_(mMutex); - if (!mKeychain) - { - CssmData *data = mData.get(); - // If the data hasn't been set we can't return it. - if (!data) - MacOSError::throwMe(errSecDataNotAvailable); - - outData = *data; - return; - } - - getContent(NULL, &outData); - -#if SENDACCESSNOTIFICATIONS - secdebug("kcnotify", "ItemImpl::getData retrieved data"); - - //%%% be done elsewhere, but here is good for now - KCEventNotifier::PostKeychainEvent(kSecDataAccessEvent, mKeychain, this); -#endif -} - -SSGroup -ItemImpl::group() -{ - StLock_(mMutex); - SSGroup group; - if (!!mUniqueId) - { - Db db(mKeychain->database()); - if (useSecureStorage(db)) - { - group = safer_cast(*mUniqueId).group(); - } - } - - return group; -} - -void ItemImpl::getLocalContent(SecKeychainAttributeList *attributeList, UInt32 *outLength, void **outData) -{ - StLock_(mMutex); - willRead(); - Allocator &allocator = Allocator::standard(); // @@@ This might not match the one used originally - if (outData) - { - CssmData *data = mData.get(); - if (!data) - MacOSError::throwMe(errSecDataNotAvailable); - - // Copy the data out of our internal cached copy. - UInt32 length = (UInt32)data->Length; - *outData = allocator.malloc(length); - memcpy(*outData, data->Data, length); - if (outLength) - *outLength = length; - } - - if (attributeList) - { - if (!mDbAttributes.get()) - MacOSError::throwMe(errSecDataNotAvailable); - - // Pull attributes out of a "floating" item, i.e. one that isn't attached to a database - for (UInt32 ix = 0; ix < attributeList->count; ++ix) - { - SecKeychainAttribute &attribute = attributeList->attr[ix]; - CssmDbAttributeData *data = mDbAttributes->find(Schema::attributeInfo(attribute.tag)); - if (data && data->NumberOfValues > 0) - { - // Copy the data out of our internal cached copy. - UInt32 length = (UInt32)data->Value[0].Length; - attribute.data = allocator.malloc(length); - memcpy(attribute.data, data->Value[0].Data, length); - attribute.length = length; - } - else - { - attribute.length = 0; - attribute.data = NULL; - } - } - } -} - -void -ItemImpl::getContent(DbAttributes *dbAttributes, CssmDataContainer *itemData) -{ - StLock_(mMutex); - // Make sure mUniqueId is set. - dbUniqueRecord(); - if (itemData) - { - Db db(mUniqueId->database()); - if (mDoNotEncrypt) - { - mUniqueId->getWithoutEncryption (dbAttributes, itemData); - return; - } - if (useSecureStorage(db)) - { - SSDbUniqueRecordImpl* impl = dynamic_cast(&(*mUniqueId)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDbUniqueRecord ssUniqueId(impl); - const AccessCredentials *autoPrompt = globals().itemCredentials(); - ssUniqueId->get(dbAttributes, itemData, autoPrompt); - return; - } - } - - mUniqueId->get(dbAttributes, itemData); -} - -bool -ItemImpl::useSecureStorage(const Db &db) -{ - StLock_(mMutex); - switch (recordType()) - { - case CSSM_DL_DB_RECORD_GENERIC_PASSWORD: - case CSSM_DL_DB_RECORD_INTERNET_PASSWORD: - case CSSM_DL_DB_RECORD_APPLESHARE_PASSWORD: - if (db->dl()->subserviceMask() & CSSM_SERVICE_CSP) - return true; - break; - default: - break; - } - return false; -} - -void ItemImpl::willRead() -{ -} - -Item ItemImpl::makeFromPersistentReference(const CFDataRef persistentRef, bool *isIdentityRef) -{ - CssmData dictData((void*)::CFDataGetBytePtr(persistentRef), ::CFDataGetLength(persistentRef)); - NameValueDictionary dict(dictData); - - Keychain keychain; - Item item = (ItemImpl *) NULL; - - if (isIdentityRef) { - *isIdentityRef = (dict.FindByName(IDENTITY_KEY) != 0) ? true : false; - } - - // make sure we have a database identifier - if (dict.FindByName(SSUID_KEY) != 0) - { - DLDbIdentifier dlDbIdentifier = NameValueDictionary::MakeDLDbIdentifierFromNameValueDictionary(dict); - DLDbIdentifier newDlDbIdentifier(dlDbIdentifier.ssuid(), - DLDbListCFPref::ExpandTildesInPath(dlDbIdentifier.dbName()).c_str(), - dlDbIdentifier.dbLocation()); - - keychain = globals().storageManager.keychain(newDlDbIdentifier); - - const NameValuePair* aDictItem = dict.FindByName(ITEM_KEY); - if (aDictItem && keychain) - { - PrimaryKey primaryKey(aDictItem->Value()); - item = keychain->item(primaryKey); - } - } - KCThrowIf_( !item, errSecItemNotFound ); - return item; -} - -void ItemImpl::copyPersistentReference(CFDataRef &outDataRef, bool isSecIdentityRef) -{ - if (secd_PersistentRef) { - outDataRef = secd_PersistentRef; - return; - } - StLock_(mMutex); - // item must be in a keychain and have a primary key to be persistent - if (!mKeychain || !mPrimaryKey) { - MacOSError::throwMe(errSecItemNotFound); - } - DLDbIdentifier dlDbIdentifier = mKeychain->dlDbIdentifier(); - DLDbIdentifier newDlDbIdentifier(dlDbIdentifier.ssuid(), - DLDbListCFPref::AbbreviatedPath(mKeychain->name()).c_str(), - dlDbIdentifier.dbLocation()); - NameValueDictionary dict; - NameValueDictionary::MakeNameValueDictionaryFromDLDbIdentifier(newDlDbIdentifier, dict); - - CssmData* pKey = mPrimaryKey; - dict.Insert (new NameValuePair(ITEM_KEY, *pKey)); - - if (isSecIdentityRef) { - uint32_t value = -1; - CssmData valueData((void*)&value, sizeof(value)); - dict.Insert (new NameValuePair(IDENTITY_KEY, valueData)); - } - - // flatten the NameValueDictionary - CssmData dictData; - dict.Export(dictData); - outDataRef = ::CFDataCreate(kCFAllocatorDefault, dictData.Data, dictData.Length); - free (dictData.Data); -} - -void ItemImpl::copyRecordIdentifier(CSSM_DATA &data) -{ - StLock_(mMutex); - CssmClient::DbUniqueRecord uniqueRecord = dbUniqueRecord (); - uniqueRecord->getRecordIdentifier(data); -} - -/* - * Obtain blob used to bind a keychain item to an Extended Attribute record. - * We just use the PrimaryKey blob as the default. Note that for standard Items, - * this can cause the loss of extended attribute bindings if a Primary Key - * attribute changes. - */ -const CssmData &ItemImpl::itemID() -{ - StLock_(mMutex); - if(mPrimaryKey->length() == 0) { - /* not in a keychain; we don't have a primary key */ - MacOSError::throwMe(errSecNoSuchAttr); - } - return *mPrimaryKey; -} - -bool ItemImpl::equal(SecCFObject &other) -{ - // First check to see if both items have a primary key and - // if the primary key is the same. If so then these - // items must be equal - ItemImpl& other_item = (ItemImpl&)other; - if (mPrimaryKey != NULL && mPrimaryKey == other_item.mPrimaryKey) - { - return true; - } - - // The primary keys do not match so do a CFHash of the - // data of the item and compare those for equality - CFHashCode this_hash = hash(); - CFHashCode other_hash = other.hash(); - return (this_hash == other_hash); -} - -CFHashCode ItemImpl::hash() -{ - CFHashCode result = SecCFObject::hash(); - - StLock_(mMutex); - RefPointer data_to_hash; - - // Use the item data for the hash - if (mData && *mData) - { - data_to_hash = mData; - } - - // If there is no primary key AND not data ???? - // just return the 'old' hash value which is the - // object pointer. - if (NULL != data_to_hash.get()) - { - CFDataRef temp_data = NULL; - unsigned char digest[CC_SHA256_DIGEST_LENGTH]; - - if (data_to_hash->length() < 80) - { - // If it is less than 80 bytes then CFData can be used - temp_data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, - (const UInt8 *)data_to_hash->data(), data_to_hash->length(), kCFAllocatorNull); - - } - // CFData truncates its hash value to 80 bytes. ???? - // In order to do the 'right thing' a SHA 256 hash will be used to - // include all of the data - else - { - memset(digest, 0, CC_SHA256_DIGEST_LENGTH); - - CC_SHA256((const void *)data_to_hash->data(), (CC_LONG)data_to_hash->length(), digest); - - temp_data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, - (const UInt8 *)digest, CC_SHA256_DIGEST_LENGTH, kCFAllocatorNull); - } - - if (NULL != temp_data) - { - result = CFHash(temp_data); - CFRelease(temp_data); - } - - } - - return result; -} - - -void ItemImpl::postItemEvent(SecKeychainEvent theEvent) -{ - mKeychain->postEvent(theEvent, this); -} - - - -// -// Item -- This class is here to magically create the right subclass of ItemImpl -// when constructing new items. -// -Item::Item() -{ -} - -Item::Item(ItemImpl *impl) : SecPointer(impl) -{ -} - -Item::Item(SecItemClass itemClass, OSType itemCreator, UInt32 length, const void* data, bool inhibitCheck) -{ - if (!inhibitCheck) - { - if (itemClass == CSSM_DL_DB_RECORD_X509_CERTIFICATE - || itemClass == CSSM_DL_DB_RECORD_PUBLIC_KEY - || itemClass == CSSM_DL_DB_RECORD_PRIVATE_KEY - || itemClass == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - MacOSError::throwMe(errSecNoSuchClass); /* @@@ errSecInvalidClass */ - } - - *this = new ItemImpl(itemClass, itemCreator, length, data, inhibitCheck); -} - -Item::Item(SecItemClass itemClass, SecKeychainAttributeList *attrList, UInt32 length, const void* data) -{ - *this = new ItemImpl(itemClass, attrList, length, data); -} - -Item::Item(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) - : SecPointer( - primaryKey->recordType() == CSSM_DL_DB_RECORD_X509_CERTIFICATE - ? Certificate::make(keychain, primaryKey, uniqueId) - : (primaryKey->recordType() == CSSM_DL_DB_RECORD_PUBLIC_KEY - || primaryKey->recordType() == CSSM_DL_DB_RECORD_PRIVATE_KEY - || primaryKey->recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - ? KeyItem::make(keychain, primaryKey, uniqueId) - : primaryKey->recordType() == CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE - ? ExtendedAttribute::make(keychain, primaryKey, uniqueId) - : ItemImpl::make(keychain, primaryKey, uniqueId)) -{ -} - -Item::Item(const Keychain &keychain, const PrimaryKey &primaryKey) - : SecPointer( - primaryKey->recordType() == CSSM_DL_DB_RECORD_X509_CERTIFICATE - ? Certificate::make(keychain, primaryKey) - : (primaryKey->recordType() == CSSM_DL_DB_RECORD_PUBLIC_KEY - || primaryKey->recordType() == CSSM_DL_DB_RECORD_PRIVATE_KEY - || primaryKey->recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - ? KeyItem::make(keychain, primaryKey) - : primaryKey->recordType() == CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE - ? ExtendedAttribute::make(keychain, primaryKey) - : ItemImpl::make(keychain, primaryKey)) -{ -} - -Item::Item(ItemImpl &item) - : SecPointer( - item.recordType() == CSSM_DL_DB_RECORD_X509_CERTIFICATE - ? new Certificate(safer_cast(item)) - : (item.recordType() == CSSM_DL_DB_RECORD_PUBLIC_KEY - || item.recordType() == CSSM_DL_DB_RECORD_PRIVATE_KEY - || item.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - ? new KeyItem(safer_cast(item)) - : item.recordType() == CSSM_DL_DB_RECORD_EXTENDED_ATTRIBUTE - ? new ExtendedAttribute(safer_cast(item)) - : new ItemImpl(item)) -{ -} - -CFIndex KeychainCore::GetItemRetainCount(Item& item) -{ - return CFGetRetainCount(item->handle(false)); -} - -void ItemImpl::setPersistentRef(CFDataRef ref) -{ - if (secd_PersistentRef) { - CFRelease(secd_PersistentRef); - } - secd_PersistentRef = ref; - CFRetain(ref); -} - -CFDataRef ItemImpl::getPersistentRef() -{ - return secd_PersistentRef; -} - - - -bool ItemImpl::mayDelete() -{ - ObjectImpl* uniqueIDImpl = mUniqueId.get(); - - if (uniqueIDImpl != NULL) - { - bool result = mUniqueId->isIdle(); - return result; - } - else - { - return true; - } -} diff --git a/OSX/include/security_keychain/Item.h b/OSX/include/security_keychain/Item.h deleted file mode 100644 index ff1e205a..00000000 --- a/OSX/include/security_keychain/Item.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Item.h -// -#ifndef _SECURITY_ITEM_H_ -#define _SECURITY_ITEM_H_ - -#include -#include -#include -#include - -namespace Security -{ - -using namespace CssmClient; - -namespace KeychainCore -{ -class Keychain; - -class ItemImpl : public SecCFObject -{ -public: - SECCFFUNCTIONS(ItemImpl, SecKeychainItemRef, errSecInvalidItemRef, gTypes().ItemImpl) - - friend class Item; - friend class KeychainImpl; -protected: - - // new item constructors - ItemImpl(SecItemClass itemClass, OSType itemCreator, UInt32 length, const void* data, bool inhibitCheck = false); - - ItemImpl(SecItemClass itemClass, SecKeychainAttributeList *attrList, UInt32 length, const void* data); - - // db item constructor - ItemImpl(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - - // PrimaryKey item constructor - ItemImpl(const Keychain &keychain, const PrimaryKey &primaryKey); - -public: - - static ItemImpl* make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - static ItemImpl* make(const Keychain &keychain, const PrimaryKey &primaryKey); - - ItemImpl(ItemImpl &item); - - // Return true if we got the attribute, false if we only got the actualLength. - void getAttributeFrom(CssmDbAttributeData *data, SecKeychainAttribute &attr, UInt32 *actualLength); - void getClass(SecKeychainAttribute &attr, UInt32 *actualLength); - - // For iOS keys - void setPersistentRef(CFDataRef ref); - // returns NULL for securityd keys, or the (non-NULL) persistent ref for iOS keys - CFDataRef getPersistentRef(); - - PrimaryKey addWithCopyInfo(Keychain &keychain, bool isCopy); - Mutex* getMutexForObject(); - -protected: - // Methods called by KeychainImpl; - - // Add the receiver to keychain - virtual PrimaryKey add(Keychain &keychain); - - // Get the default value for an attribute - static const CSSM_DATA &defaultAttributeValue(const CSSM_DB_ATTRIBUTE_INFO &info); - -public: - virtual ~ItemImpl(); - bool isPersistent(); - bool isModified(); - - virtual void update(); - - void aboutToDestruct(); - - // put a copy of the item into a given keychain - virtual Item copyTo(const Keychain &keychain, Access *newAccess = NULL); - - CSSM_DB_RECORDTYPE recordType(); - - // Used for writing the record to the database. - CssmClient::DbUniqueRecord dbUniqueRecord(); - const CssmClient::DbAttributes *modifiedAttributes(); - const CssmData *modifiedData(); - virtual void didModify(); // Forget any attributes and data we just wrote to the db - - Keychain keychain(); - PrimaryKey primaryKey(); - bool operator < (const ItemImpl &other); - - void getAttribute(SecKeychainAttribute& attr, UInt32 *actualLength); - void getData(CssmDataContainer& outData); - - void modifyContent(const SecKeychainAttributeList *attrList, UInt32 dataLength, const void *inData); - void getContent(SecItemClass *itemClass, SecKeychainAttributeList *attrList, UInt32 *length, void **outData); - static void freeContent(SecKeychainAttributeList *attrList, void *data); - static void freeAttributesAndData(SecKeychainAttributeList *attrList, void *data); - - void getAttributesAndData(SecKeychainAttributeInfo *info, SecItemClass *itemClass, - SecKeychainAttributeList **attrList, UInt32 *length, void **outData); - void modifyAttributesAndData(const SecKeychainAttributeList *attrList, UInt32 dataLength, const void *inData); - - void setAttribute(SecKeychainAttribute& attr); - void setAttribute(const CssmDbAttributeInfo &info, const CssmPolyData &data); - void setData(UInt32 length,const void *data); - void setAccess(Access *newAccess); - void copyRecordIdentifier(CSSM_DATA &data); - SSGroup group(); - - void getContent(DbAttributes *dbAttributes, CssmDataContainer *itemData); - void getLocalContent(SecKeychainAttributeList *attributeList, UInt32 *outLength, void **outData); - - bool useSecureStorage(const CssmClient::Db &db); - virtual void willRead(); - - // create a persistent reference to this item - void copyPersistentReference(CFDataRef &outDataRef, bool isSecIdentityRef=false); - static Item makeFromPersistentReference(const CFDataRef persistentRef, bool *isIdentityRef=NULL); - - // for keychain syncing - void doNotEncrypt () {mDoNotEncrypt = true;} - - // for posting events on this item - void postItemEvent (SecKeychainEvent theEvent); - - // Only call these functions while holding globals().apiLock. - bool inCache() const throw() { return mInCache; } - void inCache(bool inCache) throw() { mInCache = inCache; } - - /* For binding to extended attributes. */ - virtual const CssmData &itemID(); - - /* Overrides for SecCFObject methods */ - bool equal(SecCFObject &other); - virtual CFHashCode hash(); - - bool mayDelete(); - -protected: - // new item members - RefPointer mData; - auto_ptr mDbAttributes; - SecPointer mAccess; - - // db item members - CssmClient::DbUniqueRecord mUniqueId; - Keychain mKeychain; - PrimaryKey mPrimaryKey; - - // non-NULL only for secd items (managed by secd, not securityd) - CFDataRef secd_PersistentRef; - -private: - // keychain syncing flags - bool mDoNotEncrypt; - - // mInCache is protected by globals().apiLock - // True iff we are in the cache of items in mKeychain - bool mInCache; - -protected: - Mutex mMutex; -}; - - -class Item : public SecPointer -{ -public: - Item(); - Item(ItemImpl *impl); - Item(SecItemClass itemClass, OSType itemCreator, UInt32 length, const void* data, bool inhibitCheck); - Item(SecItemClass itemClass, SecKeychainAttributeList *attrList, UInt32 length, const void* data); - Item(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - Item(const Keychain &keychain, const PrimaryKey &primaryKey); - Item(ItemImpl &item); -}; - - -CFIndex GetItemRetainCount(Item& item); - -} // end namespace KeychainCore - -} // end namespace Security - - - -#endif // !_SECURITY_ITEM_H_ diff --git a/OSX/include/security_keychain/KCCursor.cpp b/OSX/include/security_keychain/KCCursor.cpp deleted file mode 100644 index fc968cfc..00000000 --- a/OSX/include/security_keychain/KCCursor.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// KCCursor.cpp -// - -#include "KCCursor.h" - -#include "Item.h" -#include -#include -#include "cssmdatetime.h" -#include "Globals.h" -#include "StorageManager.h" -#include -#include - -using namespace KeychainCore; -using namespace CssmClient; -using namespace CSSMDateTimeUtils; - -using namespace KeySchema; - -// define a table of our attributes for easy lookup -static const CSSM_DB_ATTRIBUTE_INFO* gKeyAttributeLookupTable[] = -{ - &KeyClass, &PrintName, &Alias, &Permanent, &Private, &Modifiable, &Label, &ApplicationTag, &KeyCreator, - &KeyType, &KeySizeInBits, &EffectiveKeySize, &StartDate, &EndDate, &Sensitive, &AlwaysSensitive, &Extractable, - &NeverExtractable, &Encrypt, &Decrypt, &Derive, &Sign, &Verify, &SignRecover, &VerifyRecover, &Wrap, &Unwrap -}; - -// -// KCCursorImpl -// -KCCursorImpl::KCCursorImpl(const StorageManager::KeychainList &searchList, SecItemClass itemClass, const SecKeychainAttributeList *attrList, CSSM_DB_CONJUNCTIVE dbConjunctive, CSSM_DB_OPERATOR dbOperator) : - mSearchList(searchList), - mCurrent(mSearchList.begin()), - mAllFailed(true), - mMutex(Mutex::recursive) -{ - recordType(Schema::recordTypeFor(itemClass)); - - if (!attrList) // No additional selectionPredicates: we are done - return; - - conjunctive(dbConjunctive); - const SecKeychainAttribute *end=&attrList->attr[attrList->count]; - // Add all the attrs in attrs list to the cursor. - for (const SecKeychainAttribute *attr=attrList->attr; attr != end; ++attr) - { - const CSSM_DB_ATTRIBUTE_INFO *temp; - - if (attr->tag <' ') // ok, is this a key schema? Handle differently, just because we can... - { - temp = gKeyAttributeLookupTable[attr->tag]; - } - else - { - temp = &Schema::attributeInfo(attr->tag); - } - const CssmDbAttributeInfo &info = *temp; - void *buf = attr->data; - UInt32 length = attr->length; - uint8 timeString[16]; - - // XXX This code is duplicated in NewItemImpl::setAttribute() - // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE - // style attribute value. - if (info.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) - { - if (length == sizeof(UInt32)) - { - MacSecondsToTimeString(*reinterpret_cast(buf), - 16, &timeString); - buf = &timeString; - length = 16; - } - else if (length == sizeof(SInt64)) - { - MacLongDateTimeToTimeString(*reinterpret_cast(buf), - 16, &timeString); - buf = &timeString; - length = 16; - } - } - add(dbOperator ,info, CssmData(buf,length)); - } -} - -KCCursorImpl::KCCursorImpl(const StorageManager::KeychainList &searchList, const SecKeychainAttributeList *attrList) : - mSearchList(searchList), - mCurrent(mSearchList.begin()), - mAllFailed(true), - mMutex(Mutex::recursive) -{ - if (!attrList) // No additional selectionPredicates: we are done - return; - - conjunctive(CSSM_DB_AND); - bool foundClassAttribute=false; - const SecKeychainAttribute *end=&attrList->attr[attrList->count]; - // Add all the attrs in attrs list to the cursor. - for (const SecKeychainAttribute *attr=attrList->attr; attr != end; ++attr) - { - if (attr->tag!=kSecClassItemAttr) // a regular attribute - { - const CssmDbAttributeInfo &info = Schema::attributeInfo(attr->tag); - void *buf = attr->data; - UInt32 length = attr->length; - uint8 timeString[16]; - - // XXX This code is duplicated in NewItemImpl::setAttribute() - // Convert a 4 or 8 byte TIME_DATE to a CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE - // style attribute value. - if (info.format() == CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) - { - if (length == sizeof(UInt32)) - { - MacSecondsToTimeString(*reinterpret_cast(buf), - 16, &timeString); - buf = &timeString; - length = 16; - } - else if (length == sizeof(SInt64)) - { - MacLongDateTimeToTimeString(*reinterpret_cast(buf), - 16, &timeString); - buf = &timeString; - length = 16; - } - } - add(CSSM_DB_EQUAL,info, CssmData(buf,length)); - - continue; - } - - // the class attribute - if (foundClassAttribute || attr->length != sizeof(SecItemClass)) - MacOSError::throwMe(errSecParam); // We have 2 different 'clas' attributes - - recordType(Schema::recordTypeFor(*reinterpret_cast(attr->data))); - foundClassAttribute=true; - } -} - -KCCursorImpl::~KCCursorImpl() throw() -{ -} - -//static ModuleNexus gActivationMutex; - -bool -KCCursorImpl::next(Item &item) -{ - StLock_(mMutex); - DbAttributes dbAttributes; - DbUniqueRecord uniqueId; - OSStatus status = 0; - - for (;;) - { - while (!mDbCursor) - { - if (mCurrent == mSearchList.end()) - { - // If we got always failed when calling mDbCursor->next return the error from - // the last call to mDbCursor->next now - if (mAllFailed && status) - CssmError::throwMe(status); - - // No more keychains to search so we are done. - return false; - } - - try - { - // StLock _(gActivationMutex()); // force serialization of cursor creation - Keychain &kc = *mCurrent; - Mutex* mutex = kc->getKeychainMutex(); - StLock _(*mutex); - (*mCurrent)->database()->activate(); - mDbCursor = DbCursor((*mCurrent)->database(), *this); - } - catch(const CommonError &err) - { - ++mCurrent; - } - } - - Keychain &kc = *mCurrent; - Mutex* mutex = kc->getKeychainMutex(); - StLock _(*mutex); - - bool gotRecord; - try - { - // Clear out existing attributes first! - // (the previous iteration may have left attributes from a different schema) - dbAttributes.clear(); - - gotRecord = mDbCursor->next(&dbAttributes, NULL, uniqueId); - mAllFailed = false; - } - catch(const CommonError &err) - { - // Catch the last error we get and move on to the next keychain - // This error will be returned when we reach the end of our keychain list - // iff all calls to KCCursorImpl::next failed - status = err.osStatus(); - gotRecord = false; - dbAttributes.invalidate(); - } - catch(...) - { - // Catch all other errors - status = errSecItemNotFound; - gotRecord = false; - } - - // If we did not get a record from the current keychain or the current - // keychain did not exist skip to the next keychain in the list. - if (!gotRecord) - { - ++mCurrent; - mDbCursor = DbCursor(); - continue; - } - - // If doing a search for all records, skip the db blob added by the CSPDL - if (dbAttributes.recordType() == CSSM_DL_DB_RECORD_METADATA && - mDbCursor->recordType() == CSSM_DL_DB_RECORD_ANY) - continue; - - // Filter out group keys at this layer - if (dbAttributes.recordType() == CSSM_DL_DB_RECORD_SYMMETRIC_KEY) - { - bool groupKey = false; - try - { - // fetch the key label attribute, if it exists - dbAttributes.add(KeySchema::Label); - Db db((*mCurrent)->database()); - CSSM_RETURN getattr_result = CSSM_DL_DataGetFromUniqueRecordId(db->handle(), uniqueId, &dbAttributes, NULL); - if (getattr_result == CSSM_OK) - { - CssmDbAttributeData *label = dbAttributes.find(KeySchema::Label); - CssmData attrData; - if (label) - attrData = *label; - if (attrData.length() > 4 && !memcmp(attrData.data(), "ssgp", 4)) - groupKey = true; - } - else - { - dbAttributes.invalidate(); - } - } - catch (...) {} - - if (groupKey) - continue; - } - - break; - } - - // Go though Keychain since item might already exist. - Keychain &kc = *mCurrent; - StLock _mutexLocker(*kc->getKeychainMutex()); - item = (*mCurrent)->item(dbAttributes.recordType(), uniqueId); - return true; -} - - - -bool KCCursorImpl::mayDelete() -{ - if (mDbCursor.get() != NULL) - { - return mDbCursor->isIdle(); - } - else - { - return true; - } -} diff --git a/OSX/include/security_keychain/KCCursor.h b/OSX/include/security_keychain/KCCursor.h deleted file mode 100644 index a05db8e7..00000000 --- a/OSX/include/security_keychain/KCCursor.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// KCCursor.h -// -#ifndef _SECURITY_KCCURSOR_H_ -#define _SECURITY_KCCURSOR_H_ - -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class KCCursorImpl : public SecCFObject, public CssmAutoQuery -{ - NOCOPY(KCCursorImpl) -public: - SECCFFUNCTIONS(KCCursorImpl, SecKeychainSearchRef, errSecInvalidSearchRef, gTypes().KCCursorImpl) - - friend class KCCursor; -protected: - KCCursorImpl(const StorageManager::KeychainList &searchList, SecItemClass itemClass, const SecKeychainAttributeList *attrList, CSSM_DB_CONJUNCTIVE dbConjunctive, CSSM_DB_OPERATOR dbOperator); - KCCursorImpl(const StorageManager::KeychainList &searchList, const SecKeychainAttributeList *attrList); - -public: - virtual ~KCCursorImpl() throw(); - bool next(Item &item); - bool mayDelete(); - -private: - StorageManager::KeychainList mSearchList; - StorageManager::KeychainList::iterator mCurrent; - CssmClient::DbCursor mDbCursor; - bool mAllFailed; - -protected: - Mutex mMutex; -}; - - -class KCCursor : public SecPointer -{ -public: - KCCursor() {} - - KCCursor(KCCursorImpl *impl) : SecPointer(impl) {} - - KCCursor(const StorageManager::KeychainList &searchList, const SecKeychainAttributeList *attrList) - : SecPointer(new KCCursorImpl(searchList, attrList)) {} - - KCCursor(const StorageManager::KeychainList &searchList, SecItemClass itemClass, const SecKeychainAttributeList *attrList, CSSM_DB_CONJUNCTIVE dbConjunctive=CSSM_DB_AND, CSSM_DB_OPERATOR dbOperator=CSSM_DB_EQUAL) - : SecPointer(new KCCursorImpl(searchList, itemClass, attrList, dbConjunctive, dbOperator)) {} - - typedef KCCursorImpl Impl; -}; - - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_KCCURSOR_H_ diff --git a/OSX/include/security_keychain/KCEventNotifier.cpp b/OSX/include/security_keychain/KCEventNotifier.cpp deleted file mode 100644 index fd78da60..00000000 --- a/OSX/include/security_keychain/KCEventNotifier.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - * - * KCEventNotifier.cpp -- OS X CF Notifier for Keychain Events - */ - -#include -#include "KCEventNotifier.h" -#include "KCExceptions.h" -#include "Keychains.h" - -using namespace KeychainCore; - -void KCEventNotifier::PostKeychainEvent(SecKeychainEvent whichEvent, const Keychain &keychain, const Item &kcItem) -{ - DLDbIdentifier dlDbIdentifier; - PrimaryKey primaryKey; - - if (keychain) - dlDbIdentifier = keychain->dlDbIdentifier(); - - if (kcItem) - primaryKey = kcItem->primaryKey(); - - PostKeychainEvent(whichEvent, dlDbIdentifier, primaryKey); -} - - -void KCEventNotifier::PostKeychainEvent(SecKeychainEvent whichEvent, - const DLDbIdentifier &dlDbIdentifier, - const PrimaryKey &primaryKey) -{ - NameValueDictionary nvd; - - Endian thePid = getpid(); - nvd.Insert (new NameValuePair (PID_KEY, CssmData (reinterpret_cast(&thePid), sizeof (pid_t)))); - - if (dlDbIdentifier) - { - NameValueDictionary::MakeNameValueDictionaryFromDLDbIdentifier (dlDbIdentifier, nvd); - } - - CssmData* pKey = primaryKey; - - if (primaryKey) - { - nvd.Insert (new NameValuePair (ITEM_KEY, *pKey)); - } - - // flatten the dictionary - CssmData data; - nvd.Export (data); - - SecurityServer::ClientSession cs (Allocator::standard(), Allocator::standard()); - cs.postNotification (SecurityServer::kNotificationDomainDatabase, whichEvent, data); - - secdebug("kcnotify", "KCEventNotifier::PostKeychainEvent posted event %u", (unsigned int) whichEvent); - - free (data.data ()); -} diff --git a/OSX/include/security_keychain/KCEventNotifier.h b/OSX/include/security_keychain/KCEventNotifier.h deleted file mode 100644 index 30d8713b..00000000 --- a/OSX/include/security_keychain/KCEventNotifier.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * KCEventNotifier.h -- OS X CF Notifier for Keychain Events - */ -#ifndef _SECURITY_KCEVENTNOTIFIER_H_ -#define _SECURITY_KCEVENTNOTIFIER_H_ - -#include -#include -#include -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class Keychain; - -class KCEventNotifier -{ -public: - static void PostKeychainEvent(SecKeychainEvent kcEvent, - const Keychain& keychain, - const Item &item = Item()); - static void PostKeychainEvent(SecKeychainEvent kcEvent, - const DLDbIdentifier &dlDbIdentifier = DLDbIdentifier(), - const PrimaryKey &primaryKey = PrimaryKey()); -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif /* _SECURITY_KCEVENTNOTIFIER_H_ */ diff --git a/OSX/include/security_keychain/KCExceptions.h b/OSX/include/security_keychain/KCExceptions.h deleted file mode 100644 index 4f1fb819..00000000 --- a/OSX/include/security_keychain/KCExceptions.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -/* - * KCExceptions.h - */ -#ifndef _SECURITY_KCEXCEPTIONS_H_ -#define _SECURITY_KCEXCEPTIONS_H_ - -#include -#include -#ifdef lock -#undef lock -#endif -//#include - -#ifdef check -#undef check -#endif - -namespace Security -{ - -namespace KeychainCore -{ - -// -// Helpers for memory pointer validation -// - -/* remove RequiredParam when cdsa does namespaces -template -inline T &Required(T *ptr,OSStatus err = errSecParam) -{ - return Required(ptr,err); -} -*/ - -template -inline void KCThrowIfMemFail_(const T *ptr) -{ - if (ptr==NULL) - MacOSError::throwMe(errSecAllocate); -} - -inline void KCThrowIf_(OSStatus theErr) -{ - // will also work for OSErr - if (theErr!=errSecSuccess) - MacOSError::throwMe(theErr); -} - -inline void KCThrowIf_(bool test,OSStatus theErr) -{ - // will also work for OSErr - if (test) - MacOSError::throwMe(theErr); -} - -inline void KCThrowParamErrIf_(bool test) -{ - if (test) - MacOSError::throwMe(errSecParam); -} - -inline void KCUnimplemented_() -{ - MacOSError::throwMe(errSecUnimplemented); -} - -} // end namespace KeychainCore - -} // end namespace Security - -#endif /* !_SECURITY_KCEXCEPTIONS_H_ */ diff --git a/OSX/include/security_keychain/KCUtilities.cpp b/OSX/include/security_keychain/KCUtilities.cpp deleted file mode 100644 index f9e0f57e..00000000 --- a/OSX/include/security_keychain/KCUtilities.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -#include - -namespace Security -{ - -} // end namespace Security diff --git a/OSX/include/security_keychain/KCUtilities.h b/OSX/include/security_keychain/KCUtilities.h deleted file mode 100644 index b0174e5b..00000000 --- a/OSX/include/security_keychain/KCUtilities.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#ifndef _SECURITY_KCUTILITIES_H_ -#define _SECURITY_KCUTILITIES_H_ - -#include -#include -namespace Security -{ - -// -// Helpers for memory pointer validation -// -template -inline T &RequiredParam(T *ptr,OSStatus err = errSecParam) -{ - if (ptr == NULL) - MacOSError::throwMe(err); - return *ptr; -} - -} // end namespace Security - -#endif // !_SECURITY_KCUTILITIES_H_ diff --git a/OSX/include/security_keychain/KeyItem.cpp b/OSX/include/security_keychain/KeyItem.cpp deleted file mode 100644 index 69e7f919..00000000 --- a/OSX/include/security_keychain/KeyItem.cpp +++ /dev/null @@ -1,1420 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// KeyItem.cpp -// -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "KCEventNotifier.h" -#include -#include - -// @@@ This needs to be shared. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-const-variable" -static CSSM_DB_NAME_ATTR(kInfoKeyPrintName, kSecKeyPrintName, (char*) "PrintName", 0, NULL, BLOB); -static CSSM_DB_NAME_ATTR(kInfoKeyLabel, kSecKeyLabel, (char*) "Label", 0, NULL, BLOB); -static CSSM_DB_NAME_ATTR(kInfoKeyApplicationTag, kSecKeyApplicationTag, (char*) "ApplicationTag", 0, NULL, BLOB); -#pragma clang diagnostic pop - -using namespace KeychainCore; -using namespace CssmClient; - -KeyItem::KeyItem(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) : - ItemImpl(keychain, primaryKey, uniqueId), - mKey(), - algid(NULL), - mPubKeyHash(Allocator::standard()) -{ -} - -KeyItem::KeyItem(const Keychain &keychain, const PrimaryKey &primaryKey) : - ItemImpl(keychain, primaryKey), - mKey(), - algid(NULL), - mPubKeyHash(Allocator::standard()) -{ -} - -KeyItem* KeyItem::make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId) -{ - KeyItem* k = new KeyItem(keychain, primaryKey, uniqueId); - keychain->addItem(primaryKey, k); - return k; -} - - - -KeyItem* KeyItem::make(const Keychain &keychain, const PrimaryKey &primaryKey) -{ - KeyItem* k = new KeyItem(keychain, primaryKey); - keychain->addItem(primaryKey, k); - return k; -} - - - -KeyItem::KeyItem(KeyItem &keyItem) : - ItemImpl(keyItem), - mKey(), - algid(NULL), - mPubKeyHash(Allocator::standard()) -{ - // @@@ this doesn't work for keys that are not in a keychain. -} - -KeyItem::KeyItem(const CssmClient::Key &key) : - ItemImpl(key->keyClass() + CSSM_DL_DB_RECORD_PUBLIC_KEY, (OSType)0, (UInt32)0, (const void*)NULL), - mKey(key), - algid(NULL), - mPubKeyHash(Allocator::standard()) -{ - if (key->keyClass() > CSSM_KEYCLASS_SESSION_KEY) - MacOSError::throwMe(errSecParam); -} - -KeyItem::~KeyItem() -{ -} - -void -KeyItem::update() -{ - ItemImpl::update(); -} - -Item -KeyItem::copyTo(const Keychain &keychain, Access *newAccess) -{ - if (!(keychain->database()->dl()->subserviceMask() & CSSM_SERVICE_CSP)) - MacOSError::throwMe(errSecInvalidKeychain); - - /* Get the destination keychain's db. */ - SSDbImpl* dbImpl = dynamic_cast(&(*keychain->database())); - if (dbImpl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDb ssDb(dbImpl); - - /* Make sure mKey is valid. */ - const CSSM_KEY *cssmKey = key(); - if (cssmKey && (0==(cssmKey->KeyHeader.KeyAttr & CSSM_KEYATTR_EXTRACTABLE))) - { - MacOSError::throwMe(errSecDataNotAvailable); - } - - // Generate a random label to use initially - CssmClient::CSP appleCsp(gGuidAppleCSP); - CssmClient::Random random(appleCsp, CSSM_ALGID_APPLE_YARROW); - uint8 labelBytes[20]; - CssmData label(labelBytes, sizeof(labelBytes)); - random.generate(label, (uint32)label.Length); - - /* Set up the ACL for the new key. */ - SecPointer access; - if (newAccess) - access = newAccess; - else - access = new Access(*mKey); - - /* Generate a random 3DES wrapping Key. */ - CssmClient::GenerateKey genKey(csp(), CSSM_ALGID_3DES_3KEY, 192); - CssmClient::Key wrappingKey(genKey(KeySpec(CSSM_KEYUSE_WRAP | CSSM_KEYUSE_UNWRAP, - CSSM_KEYATTR_EXTRACTABLE /* | CSSM_KEYATTR_RETURN_DATA */))); - - /* make a random IV */ - uint8 ivBytes[8]; - CssmData iv(ivBytes, sizeof(ivBytes)); - random.generate(iv, (uint32)iv.length()); - - /* Extract the key by wrapping it with the wrapping key. */ - CssmClient::WrapKey wrap(csp(), CSSM_ALGID_3DES_3KEY_EDE); - wrap.key(wrappingKey); - wrap.cred(getCredentials(CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED, kSecCredentialTypeDefault)); - wrap.mode(CSSM_ALGMODE_ECBPad); - wrap.padding(CSSM_PADDING_PKCS7); - wrap.initVector(iv); - CssmClient::Key wrappedKey(wrap(mKey)); - - /* Unwrap the new key into the new Keychain. */ - CssmClient::UnwrapKey unwrap(keychain->csp(), CSSM_ALGID_3DES_3KEY_EDE); - unwrap.key(wrappingKey); - unwrap.mode(CSSM_ALGMODE_ECBPad); - unwrap.padding(CSSM_PADDING_PKCS7); - unwrap.initVector(iv); - - /* Setup the dldbHandle in the context. */ - unwrap.add(CSSM_ATTRIBUTE_DL_DB_HANDLE, ssDb->handle()); - - /* Set up an initial aclEntry so we can change it after the unwrap. */ - Access::Maker maker(Allocator::standard(), Access::Maker::kAnyMakerType); - ResourceControlContext rcc; - maker.initialOwner(rcc, NULL); - unwrap.owner(rcc.input()); - - /* Unwrap the key. */ - uint32 usage = mKey->usage(); - /* Work around csp brokeness where it sets all usage bits in the Keyheader when CSSM_KEYUSE_ANY is set. */ - if (usage & CSSM_KEYUSE_ANY) - usage = CSSM_KEYUSE_ANY; - - CssmClient::Key unwrappedKey(unwrap(wrappedKey, KeySpec(usage, - (mKey->attributes() | CSSM_KEYATTR_PERMANENT) & ~(CSSM_KEYATTR_ALWAYS_SENSITIVE | CSSM_KEYATTR_NEVER_EXTRACTABLE), - label))); - - /* Look up unwrapped key in the DLDB. */ - DbUniqueRecord uniqueId; - SSDbCursor dbCursor(ssDb, 1); - dbCursor->recordType(recordType()); - dbCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, label); - CssmClient::Key copiedKey; - if (!dbCursor->nextKey(NULL, copiedKey, uniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - /* Copy the Label, PrintName and ApplicationTag attributes from the old key to the new one. */ - dbUniqueRecord(); - DbAttributes oldDbAttributes(mUniqueId->database(), 3); - oldDbAttributes.add(kInfoKeyLabel); - oldDbAttributes.add(kInfoKeyPrintName); - oldDbAttributes.add(kInfoKeyApplicationTag); - mUniqueId->get(&oldDbAttributes, NULL); - try - { - uniqueId->modify(recordType(), &oldDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - } - catch (CssmError e) - { - // clean up after trying to insert a duplicate key - uniqueId->deleteRecord (); - throw; - } - - /* Set the acl and owner on the unwrapped key. */ - access->setAccess(*unwrappedKey, maker); - - /* Return a keychain item which represents the new key. */ - Item item(keychain->item(recordType(), uniqueId)); - - KCEventNotifier::PostKeychainEvent(kSecAddEvent, keychain, item); - - return item; -} - -Item -KeyItem::importTo(const Keychain &keychain, Access *newAccess, SecKeychainAttributeList *attrList) -{ - if (!(keychain->database()->dl()->subserviceMask() & CSSM_SERVICE_CSP)) - MacOSError::throwMe(errSecInvalidKeychain); - - /* Get the destination keychain's db. */ - SSDbImpl* dbImpl = dynamic_cast(&(*keychain->database())); - if (dbImpl == NULL) - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - - SSDb ssDb(dbImpl); - - /* Make sure mKey is valid. */ - /* We can't call key() here, since we won't have a unique record id yet */ - if (!mKey) - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - - // Generate a random label to use initially - CssmClient::CSP appleCsp(gGuidAppleCSP); - CssmClient::Random random(appleCsp, CSSM_ALGID_APPLE_YARROW); - uint8 labelBytes[20]; - CssmData label(labelBytes, sizeof(labelBytes)); - random.generate(label, (uint32)label.Length); - - /* Set up the ACL for the new key. */ - SecPointer access; - if (newAccess) - access = newAccess; - else - access = new Access(*mKey); - - /* Generate a random 3DES wrapping Key. */ - CssmClient::GenerateKey genKey(csp(), CSSM_ALGID_3DES_3KEY, 192); - CssmClient::Key wrappingKey(genKey(KeySpec(CSSM_KEYUSE_WRAP | CSSM_KEYUSE_UNWRAP, - CSSM_KEYATTR_EXTRACTABLE /* | CSSM_KEYATTR_RETURN_DATA */))); - - /* make a random IV */ - uint8 ivBytes[8]; - CssmData iv(ivBytes, sizeof(ivBytes)); - random.generate(iv, (uint32)iv.length()); - - /* Extract the key by wrapping it with the wrapping key. */ - CssmClient::WrapKey wrap(csp(), CSSM_ALGID_3DES_3KEY_EDE); - wrap.key(wrappingKey); - wrap.cred(getCredentials(CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED, kSecCredentialTypeDefault)); - wrap.mode(CSSM_ALGMODE_ECBPad); - wrap.padding(CSSM_PADDING_PKCS7); - wrap.initVector(iv); - CssmClient::Key wrappedKey(wrap(mKey)); - - /* Unwrap the new key into the new Keychain. */ - CssmClient::UnwrapKey unwrap(keychain->csp(), CSSM_ALGID_3DES_3KEY_EDE); - unwrap.key(wrappingKey); - unwrap.mode(CSSM_ALGMODE_ECBPad); - unwrap.padding(CSSM_PADDING_PKCS7); - unwrap.initVector(iv); - - /* Setup the dldbHandle in the context. */ - unwrap.add(CSSM_ATTRIBUTE_DL_DB_HANDLE, ssDb->handle()); - - /* Set up an initial aclEntry so we can change it after the unwrap. */ - Access::Maker maker(Allocator::standard(), Access::Maker::kAnyMakerType); - ResourceControlContext rcc; - maker.initialOwner(rcc, NULL); - unwrap.owner(rcc.input()); - - /* Unwrap the key. */ - uint32 usage = mKey->usage(); - /* Work around csp brokeness where it sets all usage bits in the Keyheader when CSSM_KEYUSE_ANY is set. */ - if (usage & CSSM_KEYUSE_ANY) - usage = CSSM_KEYUSE_ANY; - - CssmClient::Key unwrappedKey(unwrap(wrappedKey, KeySpec(usage, - (mKey->attributes() | CSSM_KEYATTR_PERMANENT) & ~(CSSM_KEYATTR_ALWAYS_SENSITIVE | CSSM_KEYATTR_NEVER_EXTRACTABLE), - label))); - - /* Look up unwrapped key in the DLDB. */ - DbUniqueRecord uniqueId; - SSDbCursor dbCursor(ssDb, 1); - dbCursor->recordType(recordType()); - dbCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, label); - CssmClient::Key copiedKey; - if (!dbCursor->nextKey(NULL, copiedKey, uniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - // Set the initial label, application label, and application tag (if provided) - if (attrList) { - DbAttributes newDbAttributes; - SSDbCursor otherDbCursor(ssDb, 1); - otherDbCursor->recordType(recordType()); - bool checkForDuplicates = false; - - for (UInt32 index=0; index < attrList->count; index++) { - SecKeychainAttribute attr = attrList->attr[index]; - CssmData attrData(attr.data, attr.length); - if (attr.tag == kSecKeyPrintName) { - newDbAttributes.add(kInfoKeyPrintName, attrData); - } - if (attr.tag == kSecKeyLabel) { - newDbAttributes.add(kInfoKeyLabel, attrData); - otherDbCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, attrData); - checkForDuplicates = true; - } - if (attr.tag == kSecKeyApplicationTag) { - newDbAttributes.add(kInfoKeyApplicationTag, attrData); - otherDbCursor->add(CSSM_DB_EQUAL, kInfoKeyApplicationTag, attrData); - checkForDuplicates = true; - } - } - - DbAttributes otherDbAttributes; - DbUniqueRecord otherUniqueId; - CssmClient::Key otherKey; - try - { - if (checkForDuplicates && otherDbCursor->nextKey(&otherDbAttributes, otherKey, otherUniqueId)) - MacOSError::throwMe(errSecDuplicateItem); - - uniqueId->modify(recordType(), &newDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - } - catch (CssmError e) - { - // clean up after trying to insert a duplicate key - uniqueId->deleteRecord (); - throw; - } - } - - /* Set the acl and owner on the unwrapped key. */ - access->setAccess(*unwrappedKey, maker); - - /* Return a keychain item which represents the new key. */ - Item item(keychain->item(recordType(), uniqueId)); - - KCEventNotifier::PostKeychainEvent(kSecAddEvent, keychain, item); - - return item; -} - -void -KeyItem::didModify() -{ -} - -PrimaryKey -KeyItem::add(Keychain &keychain) -{ - MacOSError::throwMe(errSecUnimplemented); -} - -CssmClient::SSDbUniqueRecord -KeyItem::ssDbUniqueRecord() -{ - DbUniqueRecordImpl *impl = &*dbUniqueRecord(); - Security::CssmClient::SSDbUniqueRecordImpl *simpl = dynamic_cast(impl); - if (simpl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - return CssmClient::SSDbUniqueRecord(simpl); -} - -CssmClient::Key & -KeyItem::key() -{ - StLock_(mMutex); - if (!mKey) - { - CssmClient::SSDbUniqueRecord uniqueId(ssDbUniqueRecord()); - CssmDataContainer dataBlob(uniqueId->allocator()); - uniqueId->get(NULL, &dataBlob); - mKey = CssmClient::Key(uniqueId->database()->csp(), *reinterpret_cast(dataBlob.Data)); - } - - return mKey; -} - -CssmClient::CSP -KeyItem::csp() -{ - return key()->csp(); -} - - -const CSSM_X509_ALGORITHM_IDENTIFIER& -KeyItem::algorithmIdentifier() -{ -#if 0 - CssmKey *mKey; - CSSM_KEY_TYPE algorithm - CSSM_KEY_PTR cssmKey = (CSSM_KEY_PTR)thisData->Data; -cssmKey->KeyHeader - static void printKeyHeader( - const CSSM_KEYHEADER &hdr) -{ - printf(" Algorithm : "); - switch(hdr.AlgorithmId) { -CSSM_X509_ALGORITHM_IDENTIFIER algID; - -CSSM_OID *CL_algToOid( - CSSM_ALGORITHMS algId) -typedef struct cssm_x509_algorithm_identifier { - CSSM_OID algorithm; - CSSM_DATA parameters; -} CSSM_X509_ALGORITHM_IDENTIFIER, *CSSM_X509_ALGORITHM_IDENTIFIER_PTR; -#endif - - abort(); -} - -/* - * itemID, used to locate Extended Attributes, is the public key hash for keys. - */ -const CssmData &KeyItem::itemID() -{ - if(mPubKeyHash.length() == 0) { - /* - * Fetch the attribute from disk. - */ - UInt32 tag = kSecKeyLabel; - UInt32 format = 0; - SecKeychainAttributeInfo attrInfo = {1, &tag, &format}; - SecKeychainAttributeList *attrList = NULL; - getAttributesAndData(&attrInfo, NULL, &attrList, NULL, NULL); - if((attrList == NULL) || (attrList->count != 1)) { - MacOSError::throwMe(errSecNoSuchAttr); - } - mPubKeyHash.copy(attrList->attr->data, attrList->attr->length); - freeAttributesAndData(attrList, NULL); - } - return mPubKeyHash; -} - - -unsigned int -KeyItem::strengthInBits(const CSSM_X509_ALGORITHM_IDENTIFIER *algid) -{ - // @@@ Make a context with key based on algid and use that to get the effective keysize and not just the logical one. - CSSM_KEY_SIZE keySize = {}; - CSSM_RETURN rv = CSSM_QueryKeySizeInBits (csp()->handle(), - CSSM_INVALID_HANDLE, - key(), - &keySize); - if (rv) - return 0; - - return keySize.LogicalKeySizeInBits; -} - -const AccessCredentials * -KeyItem::getCredentials( - CSSM_ACL_AUTHORIZATION_TAG operation, - SecCredentialType credentialType) -{ - // @@@ Fix this to actually examine the ACL for this key and consider operation and do the right thing. - //AutoAclEntryInfoList aclInfos; - //key()->getAcl(aclInfos); - - bool smartcard = keychain() != NULL ? (keychain()->database()->dl()->guid() == gGuidAppleSdCSPDL) : false; - - AclFactory factory; - switch (credentialType) - { - case kSecCredentialTypeDefault: - return smartcard?globals().smartcardItemCredentials():globals().itemCredentials(); - case kSecCredentialTypeWithUI: - return smartcard?globals().smartcardItemCredentials():factory.promptCred(); - case kSecCredentialTypeNoUI: - return factory.nullCred(); - default: - MacOSError::throwMe(errSecParam); - } -} - -bool -KeyItem::operator == (KeyItem &other) -{ - if (mKey && *mKey) - { - // Pointer compare - return this == &other; - } - - // If keychains are different, then keys are different - Keychain otherKeychain = other.keychain(); - return (mKeychain && otherKeychain && (*mKeychain == *otherKeychain)); -} - -void -KeyItem::createPair( - Keychain keychain, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE publicKeyUsage, - uint32 publicKeyAttr, - CSSM_KEYUSE privateKeyUsage, - uint32 privateKeyAttr, - SecPointer initialAccess, - SecPointer &outPublicKey, - SecPointer &outPrivateKey) -{ - bool freeKeys = false; - bool deleteContext = false; - - if (!(keychain->database()->dl()->subserviceMask() & CSSM_SERVICE_CSP)) - MacOSError::throwMe(errSecInvalidKeychain); - - SSDbImpl* impl = dynamic_cast(&(*keychain->database())); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDb ssDb(impl); - CssmClient::CSP csp(keychain->csp()); - CssmClient::CSP appleCsp(gGuidAppleCSP); - - // Generate a random label to use initially - CssmClient::Random random(appleCsp, CSSM_ALGID_APPLE_YARROW); - uint8 labelBytes[20]; - CssmData label(labelBytes, sizeof(labelBytes)); - random.generate(label, (uint32)label.Length); - - // Create a Access::Maker for the initial owner of the private key. - ResourceControlContext rcc; - memset(&rcc, 0, sizeof(rcc)); - Access::Maker maker; - // @@@ Potentially provide a credential argument which allows us to generate keys in the csp. Currently the CSP let's anyone do this, but we might restrict this in the future, f.e. a smartcard could require out of band pin entry before a key can be generated. - maker.initialOwner(rcc); - // Create the cred we need to manipulate the keys until we actually set a new access control for them. - const AccessCredentials *cred = maker.cred(); - - CSSM_KEY publicCssmKey, privateCssmKey; - memset(&publicCssmKey, 0, sizeof(publicCssmKey)); - memset(&privateCssmKey, 0, sizeof(privateCssmKey)); - - CSSM_CC_HANDLE ccHandle = 0; - - Item publicKeyItem, privateKeyItem; - try - { - CSSM_RETURN status; - if (contextHandle) - ccHandle = contextHandle; - else - { - status = CSSM_CSP_CreateKeyGenContext(csp->handle(), algorithm, keySizeInBits, NULL, NULL, NULL, NULL, NULL, &ccHandle); - if (status) - CssmError::throwMe(status); - deleteContext = true; - } - - CSSM_DL_DB_HANDLE dldbHandle = ssDb->handle(); - CSSM_DL_DB_HANDLE_PTR dldbHandlePtr = &dldbHandle; - CSSM_CONTEXT_ATTRIBUTE contextAttributes = { CSSM_ATTRIBUTE_DL_DB_HANDLE, sizeof(dldbHandle), { (char *)dldbHandlePtr } }; - status = CSSM_UpdateContextAttributes(ccHandle, 1, &contextAttributes); - if (status) - CssmError::throwMe(status); - - // Generate the keypair - status = CSSM_GenerateKeyPair(ccHandle, publicKeyUsage, publicKeyAttr, &label, &publicCssmKey, privateKeyUsage, privateKeyAttr, &label, &rcc, &privateCssmKey); - if (status) - CssmError::throwMe(status); - freeKeys = true; - - // Find the keys we just generated in the DL to get SecKeyRef's to them - // so we can change the label to be the hash of the public key, and - // fix up other attributes. - - // Look up public key in the DLDB. - DbAttributes pubDbAttributes; - DbUniqueRecord pubUniqueId; - SSDbCursor dbPubCursor(ssDb, 1); - dbPubCursor->recordType(CSSM_DL_DB_RECORD_PUBLIC_KEY); - dbPubCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, label); - CssmClient::Key publicKey; - if (!dbPubCursor->nextKey(&pubDbAttributes, publicKey, pubUniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - // Look up private key in the DLDB. - DbAttributes privDbAttributes; - DbUniqueRecord privUniqueId; - SSDbCursor dbPrivCursor(ssDb, 1); - dbPrivCursor->recordType(CSSM_DL_DB_RECORD_PRIVATE_KEY); - dbPrivCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, label); - CssmClient::Key privateKey; - if (!dbPrivCursor->nextKey(&privDbAttributes, privateKey, privUniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - // Convert reference public key to a raw key so we can use it - // in the appleCsp. - CssmClient::WrapKey wrap(csp, CSSM_ALGID_NONE); - wrap.cred(cred); - CssmClient::Key rawPubKey = wrap(publicKey); - - // Calculate the hash of the public key using the appleCSP. - CssmClient::PassThrough passThrough(appleCsp); - void *outData; - CssmData *cssmData; - - /* Given a CSSM_KEY_PTR in any format, obtain the SHA-1 hash of the - * associated key blob. - * Key is specified in CSSM_CSP_CreatePassThroughContext. - * Hash is allocated bythe CSP, in the App's memory, and returned - * in *outData. */ - passThrough.key(rawPubKey); - passThrough(CSSM_APPLECSP_KEYDIGEST, NULL, &outData); - cssmData = reinterpret_cast(outData); - CssmData &pubKeyHash = *cssmData; - - auto_ptrprivDescription; - auto_ptrpubDescription; - try { - privDescription.reset(new string(initialAccess->promptDescription())); - pubDescription.reset(new string(initialAccess->promptDescription())); - } - catch(...) { - /* this path taken if no promptDescription available, e.g., for complex ACLs */ - privDescription.reset(new string("Private key")); - pubDescription.reset(new string("Public key")); - } - - // Set the label of the public key to the public key hash. - // Set the PrintName of the public key to the description in the acl. - pubDbAttributes.add(kInfoKeyLabel, pubKeyHash); - pubDbAttributes.add(kInfoKeyPrintName, *pubDescription); - pubUniqueId->modify(CSSM_DL_DB_RECORD_PUBLIC_KEY, &pubDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - - // Set the label of the private key to the public key hash. - // Set the PrintName of the private key to the description in the acl. - privDbAttributes.add(kInfoKeyLabel, pubKeyHash); - privDbAttributes.add(kInfoKeyPrintName, *privDescription); - privUniqueId->modify(CSSM_DL_DB_RECORD_PRIVATE_KEY, &privDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - - // @@@ Not exception safe! - csp.allocator().free(cssmData->Data); - csp.allocator().free(cssmData); - - // Finally fix the acl and owner of the private key to the specified access control settings. - initialAccess->setAccess(*privateKey, maker); - - if(publicKeyAttr & CSSM_KEYATTR_PUBLIC_KEY_ENCRYPT) { - /* - * Make the public key acl completely open. - * If the key was not encrypted, it already has a wide-open - * ACL (though that is a feature of securityd; it's not - * CDSA-specified behavior). - */ - SecPointer pubKeyAccess(new Access()); - pubKeyAccess->setAccess(*publicKey, maker); - } - - // Create keychain items which will represent the keys. - publicKeyItem = keychain->item(CSSM_DL_DB_RECORD_PUBLIC_KEY, pubUniqueId); - privateKeyItem = keychain->item(CSSM_DL_DB_RECORD_PRIVATE_KEY, privUniqueId); - - KeyItem* impl = dynamic_cast(&(*publicKeyItem)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - outPublicKey = impl; - - impl = dynamic_cast(&(*privateKeyItem)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - outPrivateKey = impl; - } - catch (...) - { - if (freeKeys) - { - // Delete the keys if something goes wrong so we don't end up with inaccessible keys in the database. - CSSM_FreeKey(csp->handle(), cred, &publicCssmKey, TRUE); - CSSM_FreeKey(csp->handle(), cred, &privateCssmKey, TRUE); - } - - if (deleteContext) - CSSM_DeleteContext(ccHandle); - - throw; - } - - if (freeKeys) - { - CSSM_FreeKey(csp->handle(), NULL, &publicCssmKey, FALSE); - CSSM_FreeKey(csp->handle(), NULL, &privateCssmKey, FALSE); - } - - if (deleteContext) - CSSM_DeleteContext(ccHandle); - - if (keychain && publicKeyItem && privateKeyItem) - { - keychain->postEvent(kSecAddEvent, publicKeyItem); - keychain->postEvent(kSecAddEvent, privateKeyItem); - } -} - -void -KeyItem::importPair( - Keychain keychain, - const CSSM_KEY &publicWrappedKey, - const CSSM_KEY &privateWrappedKey, - SecPointer initialAccess, - SecPointer &outPublicKey, - SecPointer &outPrivateKey) -{ - bool freePublicKey = false; - bool freePrivateKey = false; - bool deleteContext = false; - - if (!(keychain->database()->dl()->subserviceMask() & CSSM_SERVICE_CSP)) - MacOSError::throwMe(errSecInvalidKeychain); - - SSDbImpl* impl = dynamic_cast(&(*keychain->database())); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDb ssDb(impl); - CssmClient::CSP csp(keychain->csp()); - CssmClient::CSP appleCsp(gGuidAppleCSP); - - // Create a Access::Maker for the initial owner of the private key. - ResourceControlContext rcc; - memset(&rcc, 0, sizeof(rcc)); - Access::Maker maker(Allocator::standard(), Access::Maker::kAnyMakerType); - // @@@ Potentially provide a credential argument which allows us to unwrap keys in the csp. - // Currently the CSP lets anyone do this, but we might restrict this in the future, e.g. - // a smartcard could require out of band pin entry before a key can be generated. - maker.initialOwner(rcc); - // Create the cred we need to manipulate the keys until we actually set a new access control for them. - const AccessCredentials *cred = maker.cred(); - - CSSM_KEY publicCssmKey, privateCssmKey; - memset(&publicCssmKey, 0, sizeof(publicCssmKey)); - memset(&privateCssmKey, 0, sizeof(privateCssmKey)); - - CSSM_CC_HANDLE ccHandle = 0; - - Item publicKeyItem, privateKeyItem; - try - { - CSSM_RETURN status; - - // Calculate the hash of the public key using the appleCSP. - CssmClient::PassThrough passThrough(appleCsp); - void *outData; - CssmData *cssmData; - - /* Given a CSSM_KEY_PTR in any format, obtain the SHA-1 hash of the - * associated key blob. - * Key is specified in CSSM_CSP_CreatePassThroughContext. - * Hash is allocated bythe CSP, in the App's memory, and returned - * in *outData. */ - passThrough.key(&publicWrappedKey); - passThrough(CSSM_APPLECSP_KEYDIGEST, NULL, &outData); - cssmData = reinterpret_cast(outData); - CssmData &pubKeyHash = *cssmData; - - status = CSSM_CSP_CreateSymmetricContext(csp->handle(), publicWrappedKey.KeyHeader.WrapAlgorithmId, CSSM_ALGMODE_NONE, NULL, NULL, NULL, CSSM_PADDING_NONE, NULL, &ccHandle); - if (status) - CssmError::throwMe(status); - deleteContext = true; - - CSSM_DL_DB_HANDLE dldbHandle = ssDb->handle(); - CSSM_DL_DB_HANDLE_PTR dldbHandlePtr = &dldbHandle; - CSSM_CONTEXT_ATTRIBUTE contextAttributes = { CSSM_ATTRIBUTE_DL_DB_HANDLE, sizeof(dldbHandle), { (char *)dldbHandlePtr } }; - status = CSSM_UpdateContextAttributes(ccHandle, 1, &contextAttributes); - if (status) - CssmError::throwMe(status); - - // Unwrap the the keys - CSSM_DATA descriptiveData = {0, NULL}; - - status = CSSM_UnwrapKey( - ccHandle, - NULL, - &publicWrappedKey, - publicWrappedKey.KeyHeader.KeyUsage, - publicWrappedKey.KeyHeader.KeyAttr | CSSM_KEYATTR_PERMANENT, - &pubKeyHash, - &rcc, - &publicCssmKey, - &descriptiveData); - - if (status) - CssmError::throwMe(status); - freePublicKey = true; - - if (descriptiveData.Data != NULL) - free (descriptiveData.Data); - - status = CSSM_UnwrapKey( - ccHandle, - NULL, - &privateWrappedKey, - privateWrappedKey.KeyHeader.KeyUsage, - privateWrappedKey.KeyHeader.KeyAttr | CSSM_KEYATTR_PERMANENT, - &pubKeyHash, - &rcc, - &privateCssmKey, - &descriptiveData); - - if (status) - CssmError::throwMe(status); - - if (descriptiveData.Data != NULL) - free (descriptiveData.Data); - - freePrivateKey = true; - - // Find the keys we just generated in the DL to get SecKeyRefs to them - // so we can change the label to be the hash of the public key, and - // fix up other attributes. - - // Look up public key in the DLDB. - DbAttributes pubDbAttributes; - DbUniqueRecord pubUniqueId; - SSDbCursor dbPubCursor(ssDb, 1); - dbPubCursor->recordType(CSSM_DL_DB_RECORD_PUBLIC_KEY); - dbPubCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, pubKeyHash); - CssmClient::Key publicKey; - if (!dbPubCursor->nextKey(&pubDbAttributes, publicKey, pubUniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - // Look up private key in the DLDB. - DbAttributes privDbAttributes; - DbUniqueRecord privUniqueId; - SSDbCursor dbPrivCursor(ssDb, 1); - dbPrivCursor->recordType(CSSM_DL_DB_RECORD_PRIVATE_KEY); - dbPrivCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, pubKeyHash); - CssmClient::Key privateKey; - if (!dbPrivCursor->nextKey(&privDbAttributes, privateKey, privUniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - // @@@ Not exception safe! - csp.allocator().free(cssmData->Data); - csp.allocator().free(cssmData); - - auto_ptrprivDescription; - auto_ptrpubDescription; - try { - privDescription.reset(new string(initialAccess->promptDescription())); - pubDescription.reset(new string(initialAccess->promptDescription())); - } - catch(...) { - /* this path taken if no promptDescription available, e.g., for complex ACLs */ - privDescription.reset(new string("Private key")); - pubDescription.reset(new string("Public key")); - } - - // Set the label of the public key to the public key hash. - // Set the PrintName of the public key to the description in the acl. - pubDbAttributes.add(kInfoKeyPrintName, *pubDescription); - pubUniqueId->modify(CSSM_DL_DB_RECORD_PUBLIC_KEY, &pubDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - - // Set the label of the private key to the public key hash. - // Set the PrintName of the private key to the description in the acl. - privDbAttributes.add(kInfoKeyPrintName, *privDescription); - privUniqueId->modify(CSSM_DL_DB_RECORD_PRIVATE_KEY, &privDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - - // Finally fix the acl and owner of the private key to the specified access control settings. - initialAccess->setAccess(*privateKey, maker); - - // Make the public key acl completely open - SecPointer pubKeyAccess(new Access()); - pubKeyAccess->setAccess(*publicKey, maker); - - // Create keychain items which will represent the keys. - publicKeyItem = keychain->item(CSSM_DL_DB_RECORD_PUBLIC_KEY, pubUniqueId); - privateKeyItem = keychain->item(CSSM_DL_DB_RECORD_PRIVATE_KEY, privUniqueId); - - KeyItem* impl = dynamic_cast(&(*publicKeyItem)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - outPublicKey = impl; - - impl = dynamic_cast(&(*privateKeyItem)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - outPrivateKey = impl; - } - catch (...) - { - if (freePublicKey) - CSSM_FreeKey(csp->handle(), cred, &publicCssmKey, TRUE); - if (freePrivateKey) - CSSM_FreeKey(csp->handle(), cred, &privateCssmKey, TRUE); - - if (deleteContext) - CSSM_DeleteContext(ccHandle); - - throw; - } - - if (freePublicKey) - CSSM_FreeKey(csp->handle(), cred, &publicCssmKey, FALSE); - if (freePrivateKey) - CSSM_FreeKey(csp->handle(), cred, &privateCssmKey, FALSE); - - if (deleteContext) - CSSM_DeleteContext(ccHandle); - - if (keychain && publicKeyItem && privateKeyItem) - { - KCEventNotifier::PostKeychainEvent(kSecAddEvent, keychain, publicKeyItem); - KCEventNotifier::PostKeychainEvent(kSecAddEvent, keychain, privateKeyItem); - } -} - -SecPointer -KeyItem::generateWithAttributes(const SecKeychainAttributeList *attrList, - Keychain keychain, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE keyUsage, - uint32 keyAttr, - SecPointer initialAccess) -{ - CssmClient::CSP appleCsp(gGuidAppleCSP); - CssmClient::CSP csp(NULL); - SSDb ssDb(NULL); - uint8 labelBytes[20]; - CssmData label(labelBytes, sizeof(labelBytes)); - bool freeKey = false; - bool deleteContext = false; - const CSSM_DATA *plabel = NULL; - - if (keychain) - { - if (!(keychain->database()->dl()->subserviceMask() & CSSM_SERVICE_CSP)) - MacOSError::throwMe(errSecInvalidKeychain); - - SSDbImpl* impl = dynamic_cast(&(*keychain->database())); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - ssDb = SSDb(impl); - csp = keychain->csp(); - - // Generate a random label to use initially - CssmClient::Random random(appleCsp, CSSM_ALGID_APPLE_YARROW); - random.generate(label, (uint32)label.Length); - plabel = &label; - } - else - { - // Not a persistent key so create it in the regular csp - csp = appleCsp; - } - - // Create a Access::Maker for the initial owner of the private key. - ResourceControlContext *prcc = NULL, rcc; - const AccessCredentials *cred = NULL; - Access::Maker maker; - if (keychain && initialAccess) - { - memset(&rcc, 0, sizeof(rcc)); - // @@@ Potentially provide a credential argument which allows us to generate keys in the csp. - // Currently the CSP lets anyone do this, but we might restrict this in the future, e.g. a smartcard - // could require out-of-band pin entry before a key can be generated. - maker.initialOwner(rcc); - // Create the cred we need to manipulate the keys until we actually set a new access control for them. - cred = maker.cred(); - prcc = &rcc; - } - - CSSM_KEY cssmKey; - - CSSM_CC_HANDLE ccHandle = 0; - - Item keyItem; - try - { - CSSM_RETURN status; - if (contextHandle) - ccHandle = contextHandle; - else - { - status = CSSM_CSP_CreateKeyGenContext(csp->handle(), algorithm, keySizeInBits, NULL, NULL, NULL, NULL, NULL, &ccHandle); - if (status) - CssmError::throwMe(status); - deleteContext = true; - } - - if (ssDb) - { - CSSM_DL_DB_HANDLE dldbHandle = ssDb->handle(); - CSSM_DL_DB_HANDLE_PTR dldbHandlePtr = &dldbHandle; - CSSM_CONTEXT_ATTRIBUTE contextAttributes = { CSSM_ATTRIBUTE_DL_DB_HANDLE, sizeof(dldbHandle), { (char *)dldbHandlePtr } }; - status = CSSM_UpdateContextAttributes(ccHandle, 1, &contextAttributes); - if (status) - CssmError::throwMe(status); - - keyAttr |= CSSM_KEYATTR_PERMANENT; - } - - // Generate the key - status = CSSM_GenerateKey(ccHandle, keyUsage, keyAttr, plabel, prcc, &cssmKey); - if (status) - CssmError::throwMe(status); - - if (ssDb) - { - freeKey = true; - // Find the key we just generated in the DL and get a SecKeyRef - // so we can specify the label attribute(s) and initial ACL. - - // Look up key in the DLDB. - DbAttributes dbAttributes; - DbUniqueRecord uniqueId; - SSDbCursor dbCursor(ssDb, 1); - dbCursor->recordType(CSSM_DL_DB_RECORD_SYMMETRIC_KEY); - dbCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, label); - CssmClient::Key key; - if (!dbCursor->nextKey(&dbAttributes, key, uniqueId)) - MacOSError::throwMe(errSecItemNotFound); - - // Set the initial label, application label, and application tag (if provided) - if (attrList) { - DbAttributes newDbAttributes; - SSDbCursor otherDbCursor(ssDb, 1); - otherDbCursor->recordType(CSSM_DL_DB_RECORD_SYMMETRIC_KEY); - bool checkForDuplicates = false; - - for (UInt32 index=0; index < attrList->count; index++) { - SecKeychainAttribute attr = attrList->attr[index]; - CssmData attrData(attr.data, attr.length); - if (attr.tag == kSecKeyPrintName) { - newDbAttributes.add(kInfoKeyPrintName, attrData); - } - if (attr.tag == kSecKeyLabel) { - newDbAttributes.add(kInfoKeyLabel, attrData); - otherDbCursor->add(CSSM_DB_EQUAL, kInfoKeyLabel, attrData); - checkForDuplicates = true; - } - if (attr.tag == kSecKeyApplicationTag) { - newDbAttributes.add(kInfoKeyApplicationTag, attrData); - otherDbCursor->add(CSSM_DB_EQUAL, kInfoKeyApplicationTag, attrData); - checkForDuplicates = true; - } - } - - DbAttributes otherDbAttributes; - DbUniqueRecord otherUniqueId; - CssmClient::Key otherKey; - if (checkForDuplicates && otherDbCursor->nextKey(&otherDbAttributes, otherKey, otherUniqueId)) - MacOSError::throwMe(errSecDuplicateItem); - - uniqueId->modify(CSSM_DL_DB_RECORD_SYMMETRIC_KEY, &newDbAttributes, NULL, CSSM_DB_MODIFY_ATTRIBUTE_REPLACE); - } - - // Finally, fix the acl and owner of the key to the specified access control settings. - if (initialAccess) - initialAccess->setAccess(*key, maker); - - // Create keychain item which will represent the key. - keyItem = keychain->item(CSSM_DL_DB_RECORD_SYMMETRIC_KEY, uniqueId); - } - else - { - CssmClient::Key tempKey(csp, cssmKey); - keyItem = new KeyItem(tempKey); - } - } - catch (...) - { - if (freeKey) - { - // Delete the key if something goes wrong so we don't end up with inaccessible keys in the database. - CSSM_FreeKey(csp->handle(), cred, &cssmKey, TRUE); - } - - if (deleteContext) - CSSM_DeleteContext(ccHandle); - - throw; - } - - if (freeKey) - { - CSSM_FreeKey(csp->handle(), NULL, &cssmKey, FALSE); - } - - if (deleteContext) - CSSM_DeleteContext(ccHandle); - - if (keychain && keyItem) - keychain->postEvent(kSecAddEvent, keyItem); - - KeyItem* item = dynamic_cast(&*keyItem); - if (item == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - return item; -} - -SecPointer -KeyItem::generate(Keychain keychain, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE keyUsage, - uint32 keyAttr, - SecPointer initialAccess) -{ - return KeyItem::generateWithAttributes(NULL, keychain, - algorithm, keySizeInBits, contextHandle, - keyUsage, keyAttr, initialAccess); -} - - -void KeyItem::RawSign(SecPadding padding, CSSM_DATA dataToSign, const AccessCredentials *credentials, CSSM_DATA& signature) -{ - CSSM_ALGORITHMS baseAlg = key()->header().algorithm(); - - if ((baseAlg != CSSM_ALGID_RSA) && (baseAlg != CSSM_ALGID_ECDSA)) - { - MacOSError::throwMe(errSecParam); - } - - CSSM_ALGORITHMS paddingAlg = CSSM_PADDING_PKCS1; - - switch (padding) - { - case kSecPaddingPKCS1: - { - paddingAlg = CSSM_PADDING_PKCS1; - break; - } - - case kSecPaddingPKCS1MD2: - { - baseAlg = CSSM_ALGID_MD2WithRSA; - break; - } - - case kSecPaddingPKCS1MD5: - { - baseAlg = CSSM_ALGID_MD5WithRSA; - break; - } - - case kSecPaddingPKCS1SHA1: - { - baseAlg = CSSM_ALGID_SHA1WithRSA; - break; - } - - case kSecPaddingSigRaw: - { - paddingAlg = CSSM_PADDING_SIGRAW; - break; - } - - default: - { - paddingAlg = CSSM_PADDING_NONE; - break; - } - } - - Sign signContext(csp(), baseAlg); - signContext.key(key()); - signContext.cred(credentials); - // Fields required for CSSM_CSP_CreateSignatureContext set above. Using add instead of set ensures - // that the context is constructed before the set is attempted, which would fail silently otherwise. - signContext.add(CSSM_ATTRIBUTE_PADDING, paddingAlg); - - CssmData data(dataToSign.Data, dataToSign.Length); - signContext.sign(data); - - CssmData sig(signature.Data, signature.Length); - signContext(sig); // yes, this is an accessor. Believe it, or not. - signature.Length = sig.length(); -} - - - -void KeyItem::RawVerify(SecPadding padding, CSSM_DATA dataToVerify, const AccessCredentials *credentials, CSSM_DATA sig) -{ - CSSM_ALGORITHMS baseAlg = key()->header().algorithm(); - if ((baseAlg != CSSM_ALGID_RSA) && (baseAlg != CSSM_ALGID_ECDSA)) - { - MacOSError::throwMe(errSecParam); - } - - CSSM_ALGORITHMS paddingAlg = CSSM_PADDING_PKCS1; - - switch (padding) - { - case kSecPaddingPKCS1: - { - paddingAlg = CSSM_PADDING_PKCS1; - break; - } - - case kSecPaddingPKCS1MD2: - { - baseAlg = CSSM_ALGID_MD2WithRSA; - break; - } - - case kSecPaddingPKCS1MD5: - { - baseAlg = CSSM_ALGID_MD5WithRSA; - break; - } - - case kSecPaddingPKCS1SHA1: - { - baseAlg = CSSM_ALGID_SHA1WithRSA; - break; - } - - case kSecPaddingSigRaw: - { - paddingAlg = CSSM_PADDING_SIGRAW; - break; - } - - default: - { - paddingAlg = CSSM_PADDING_NONE; - break; - } - } - - Verify verifyContext(csp(), baseAlg); - verifyContext.key(key()); - verifyContext.cred(credentials); - // Fields required for CSSM_CSP_CreateSignatureContext set above. Using add instead of set ensures - // that the context is constructed before the set is attempted, which would fail silently otherwise. - verifyContext.add(CSSM_ATTRIBUTE_PADDING, paddingAlg); - - CssmData data(dataToVerify.Data, dataToVerify.Length); - CssmData signature(sig.Data, sig.Length); - verifyContext.verify(data, signature); -} - - - -void KeyItem::Encrypt(SecPadding padding, CSSM_DATA dataToEncrypt, const AccessCredentials *credentials, CSSM_DATA& encryptedData) -{ - CSSM_ALGORITHMS baseAlg = key()->header().algorithm(); - if (baseAlg != CSSM_ALGID_RSA) - { - MacOSError::throwMe(errSecParam); - } - - CSSM_ALGORITHMS paddingAlg = CSSM_PADDING_PKCS1; - - switch (padding) - { - case kSecPaddingPKCS1: - { - paddingAlg = CSSM_PADDING_PKCS1; - break; - } - - default: - { - paddingAlg = CSSM_PADDING_NONE; - break; - } - } - - CssmClient::Encrypt encryptContext(csp(), baseAlg); - encryptContext.key(key()); - encryptContext.padding(paddingAlg); - encryptContext.cred(credentials); - - CssmData inData(dataToEncrypt.Data, dataToEncrypt.Length); - CssmData outData(encryptedData.Data, encryptedData.Length); - CssmData remData((void*) NULL, 0); - - encryptedData.Length = encryptContext.encrypt(inData, outData, remData); -} - - - -void KeyItem::Decrypt(SecPadding padding, CSSM_DATA dataToDecrypt, const AccessCredentials *credentials, CSSM_DATA& decryptedData) -{ - CSSM_ALGORITHMS baseAlg = key()->header().algorithm(); - if (baseAlg != CSSM_ALGID_RSA) - { - MacOSError::throwMe(errSecParam); - } - - CSSM_ALGORITHMS paddingAlg = CSSM_PADDING_PKCS1; - - switch (padding) - { - case kSecPaddingPKCS1: - { - paddingAlg = CSSM_PADDING_PKCS1; - break; - } - - - default: - { - paddingAlg = CSSM_PADDING_NONE; - break; - } - } - - CssmClient::Decrypt decryptContext(csp(), baseAlg); - decryptContext.key(key()); - decryptContext.padding(paddingAlg); - decryptContext.cred(credentials); - - CssmData inData(dataToDecrypt.Data, dataToDecrypt.Length); - CssmData outData(decryptedData.Data, decryptedData.Length); - CssmData remData((void*) NULL, 0); - decryptedData.Length = decryptContext.decrypt(inData, outData, remData); - if (remData.Data != NULL) - { - free(remData.Data); - } -} - -CFHashCode KeyItem::hash() -{ - CFHashCode result = 0; - const CSSM_KEY *cssmKey = key(); - if (NULL != cssmKey) - { - unsigned char digest[CC_SHA256_DIGEST_LENGTH]; - - CFIndex size_of_data = sizeof(CSSM_KEYHEADER) + cssmKey->KeyData.Length; - - CFMutableDataRef temp_cfdata = CFDataCreateMutable(kCFAllocatorDefault, size_of_data); - if (NULL == temp_cfdata) - { - return result; - } - - CFDataAppendBytes(temp_cfdata, (const UInt8 *)cssmKey, sizeof(CSSM_KEYHEADER)); - CFDataAppendBytes(temp_cfdata, cssmKey->KeyData.Data, cssmKey->KeyData.Length); - - if (size_of_data < 80) - { - // If it is less than 80 bytes then CFData can be used - result = CFHash(temp_cfdata); - CFRelease(temp_cfdata); - } - // CFData truncates its hash value to 80 bytes. ???? - // In order to do the 'right thing' a SHA 256 hash will be used to - // include all of the data - else - { - memset(digest, 0, CC_SHA256_DIGEST_LENGTH); - - CC_SHA256((const void *)CFDataGetBytePtr(temp_cfdata), (CC_LONG)CFDataGetLength(temp_cfdata), digest); - - CFDataRef data_to_hash = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, - (const UInt8 *)digest, CC_SHA256_DIGEST_LENGTH, kCFAllocatorNull); - result = CFHash(data_to_hash); - CFRelease(data_to_hash); - CFRelease(temp_cfdata); - } - } - return result; -} - diff --git a/OSX/include/security_keychain/KeyItem.h b/OSX/include/security_keychain/KeyItem.h deleted file mode 100644 index 9ac071d1..00000000 --- a/OSX/include/security_keychain/KeyItem.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2002-2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// KeyItem.h -// -#ifndef _SECURITY_KEYITEM_H_ -#define _SECURITY_KEYITEM_H_ - -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class KeyItem : public ItemImpl -{ - NOCOPY(KeyItem) -public: - SECCFFUNCTIONS(KeyItem, SecKeyRef, errSecInvalidItemRef, gTypes().KeyItem) - - // db item constructor -private: - KeyItem(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - - // PrimaryKey item constructor - KeyItem(const Keychain &keychain, const PrimaryKey &primaryKey); - -public: - static KeyItem* make(const Keychain &keychain, const PrimaryKey &primaryKey, const CssmClient::DbUniqueRecord &uniqueId); - static KeyItem* make(const Keychain &keychain, const PrimaryKey &primaryKey); - - KeyItem(KeyItem &keyItem); - - KeyItem(const CssmClient::Key &key); - - virtual ~KeyItem(); - - virtual void update(); - virtual Item copyTo(const Keychain &keychain, Access *newAccess = NULL); - virtual Item importTo(const Keychain &keychain, Access *newAccess = NULL, SecKeychainAttributeList *attrList = NULL); - virtual void didModify(); - - CssmClient::SSDbUniqueRecord ssDbUniqueRecord(); - CssmClient::Key &key(); - CssmClient::CSP csp(); - - const CSSM_X509_ALGORITHM_IDENTIFIER& algorithmIdentifier(); - unsigned int strengthInBits(const CSSM_X509_ALGORITHM_IDENTIFIER *algid); - - const AccessCredentials *getCredentials( - CSSM_ACL_AUTHORIZATION_TAG operation, - SecCredentialType credentialType); - - bool operator == (KeyItem &other); - - static void createPair( - Keychain keychain, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE publicKeyUsage, - uint32 publicKeyAttr, - CSSM_KEYUSE privateKeyUsage, - uint32 privateKeyAttr, - SecPointer initialAccess, - SecPointer &outPublicKey, - SecPointer &outPrivateKey); - - static void importPair( - Keychain keychain, - const CSSM_KEY &publicCssmKey, - const CSSM_KEY &privateCssmKey, - SecPointer initialAccess, - SecPointer &outPublicKey, - SecPointer &outPrivateKey); - - static SecPointer generate( - Keychain keychain, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE keyUsage, - uint32 keyAttr, - SecPointer initialAccess); - - static SecPointer generateWithAttributes( - const SecKeychainAttributeList *attrList, - Keychain keychain, - CSSM_ALGORITHMS algorithm, - uint32 keySizeInBits, - CSSM_CC_HANDLE contextHandle, - CSSM_KEYUSE keyUsage, - uint32 keyAttr, - SecPointer initialAccess); - - virtual const CssmData &itemID(); - - void RawSign(SecPadding padding, CSSM_DATA dataToSign, const AccessCredentials *credentials, CSSM_DATA& signedData); - void RawVerify(SecPadding padding, CSSM_DATA dataToVerify, const AccessCredentials *credentials, CSSM_DATA signature); - void Encrypt(SecPadding padding, CSSM_DATA dataToEncrypt, const AccessCredentials *credentials, CSSM_DATA& encryptedData); - void Decrypt(SecPadding padding, CSSM_DATA dataToEncrypt, const AccessCredentials *credentials, CSSM_DATA& encryptedData); - - virtual CFHashCode hash(); - -protected: - virtual PrimaryKey add(Keychain &keychain); -private: - CssmClient::Key mKey; - const CSSM_X509_ALGORITHM_IDENTIFIER *algid; - CssmAutoData mPubKeyHash; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_KEYITEM_H_ diff --git a/OSX/include/security_keychain/Keychains.cpp b/OSX/include/security_keychain/Keychains.cpp deleted file mode 100644 index 1d94dee2..00000000 --- a/OSX/include/security_keychain/Keychains.cpp +++ /dev/null @@ -1,1332 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Keychains.cpp -// - -#include "KCEventNotifier.h" -#include "Keychains.h" - -#include "Item.h" -#include "KCCursor.h" -#include "Globals.h" -#include -#include -#include -#include -#include -#include - -#include "SecKeychainPriv.h" - -#include -#include -#include "DLDbListCFPref.h" -#include -#include -#include -#include -#include -#include -#include -#include - -static dispatch_once_t SecKeychainSystemKeychainChecked; - -OSStatus SecKeychainSystemKeychainCheckWouldDeadlock() -{ - dispatch_once(&SecKeychainSystemKeychainChecked, ^{}); - return errSecSuccess; -} - -using namespace KeychainCore; -using namespace CssmClient; - - -typedef struct EventItem -{ - SecKeychainEvent kcEvent; - Item item; -} EventItem; - -typedef std::list EventBufferSuper; -class EventBuffer : public EventBufferSuper -{ -public: - EventBuffer () {} - virtual ~EventBuffer (); -}; - - -EventBuffer::~EventBuffer () -{ -} - - - -// -// KeychainSchemaImpl -// -KeychainSchemaImpl::KeychainSchemaImpl(const Db &db) : mMutex(Mutex::recursive) -{ - DbCursor relations(db); - relations->recordType(CSSM_DL_DB_SCHEMA_INFO); - DbAttributes relationRecord(db, 1); - relationRecord.add(Schema::RelationID); - DbUniqueRecord outerUniqueId(db); - - while (relations->next(&relationRecord, NULL, outerUniqueId)) - { - DbUniqueRecord uniqueId(db); - - uint32 relationID = relationRecord.at(0); - if (CSSM_DB_RECORDTYPE_SCHEMA_START <= relationID - && relationID < CSSM_DB_RECORDTYPE_SCHEMA_END) - continue; - - // Create a cursor on the SCHEMA_ATTRIBUTES table for records with - // RelationID == relationID - DbCursor attributes(db); - attributes->recordType(CSSM_DL_DB_SCHEMA_ATTRIBUTES); - attributes->add(CSSM_DB_EQUAL, Schema::RelationID, relationID); - - // Set up a record for retriving the SCHEMA_ATTRIBUTES - DbAttributes attributeRecord(db, 2); - attributeRecord.add(Schema::AttributeFormat); - attributeRecord.add(Schema::AttributeID); - - RelationInfoMap &rim = mDatabaseInfoMap[relationID]; - while (attributes->next(&attributeRecord, NULL, uniqueId)) - rim[attributeRecord.at(1)] = attributeRecord.at(0); - - // Create a cursor on the CSSM_DL_DB_SCHEMA_INDEXES table for records - // with RelationID == relationID - DbCursor indexes(db); - indexes->recordType(CSSM_DL_DB_SCHEMA_INDEXES); - indexes->conjunctive(CSSM_DB_AND); - indexes->add(CSSM_DB_EQUAL, Schema::RelationID, relationID); - indexes->add(CSSM_DB_EQUAL, Schema::IndexType, - uint32(CSSM_DB_INDEX_UNIQUE)); - - // Set up a record for retriving the SCHEMA_INDEXES - DbAttributes indexRecord(db, 1); - indexRecord.add(Schema::AttributeID); - - CssmAutoDbRecordAttributeInfo &infos = - *new CssmAutoDbRecordAttributeInfo(); - mPrimaryKeyInfoMap. - insert(PrimaryKeyInfoMap::value_type(relationID, &infos)); - infos.DataRecordType = relationID; - while (indexes->next(&indexRecord, NULL, uniqueId)) - { - CssmDbAttributeInfo &info = infos.add(); - info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - info.Label.AttributeID = indexRecord.at(0); - // @@@ Might insert bogus value if DB is corrupt - info.AttributeFormat = rim[info.Label.AttributeID]; - } - } -} - -KeychainSchemaImpl::~KeychainSchemaImpl() -{ - try - { - map::iterator it = mPrimaryKeyInfoMap.begin(); - while (it != mPrimaryKeyInfoMap.end()) - { - delete it->second; - it++; - } - // for_each_map_delete(mPrimaryKeyInfoMap.begin(), mPrimaryKeyInfoMap.end()); - } - catch(...) - { - } -} - -const KeychainSchemaImpl::RelationInfoMap & -KeychainSchemaImpl::relationInfoMapFor(CSSM_DB_RECORDTYPE recordType) const -{ - DatabaseInfoMap::const_iterator dit = mDatabaseInfoMap.find(recordType); - if (dit == mDatabaseInfoMap.end()) - MacOSError::throwMe(errSecNoSuchClass); - return dit->second; -} - -bool KeychainSchemaImpl::hasRecordType (CSSM_DB_RECORDTYPE recordType) const -{ - DatabaseInfoMap::const_iterator it = mDatabaseInfoMap.find(recordType); - return it != mDatabaseInfoMap.end(); -} - -bool -KeychainSchemaImpl::hasAttribute(CSSM_DB_RECORDTYPE recordType, uint32 attributeId) const -{ - try - { - const RelationInfoMap &rmap = relationInfoMapFor(recordType); - RelationInfoMap::const_iterator rit = rmap.find(attributeId); - return rit != rmap.end(); - } - catch (MacOSError result) - { - if (result.osStatus () == errSecNoSuchClass) - { - return false; - } - else - { - throw; - } - } -} - -CSSM_DB_ATTRIBUTE_FORMAT -KeychainSchemaImpl::attributeFormatFor(CSSM_DB_RECORDTYPE recordType, uint32 attributeId) const -{ - const RelationInfoMap &rmap = relationInfoMapFor(recordType); - RelationInfoMap::const_iterator rit = rmap.find(attributeId); - if (rit == rmap.end()) - MacOSError::throwMe(errSecNoSuchAttr); - - return rit->second; -} - -CssmDbAttributeInfo -KeychainSchemaImpl::attributeInfoFor(CSSM_DB_RECORDTYPE recordType, uint32 attributeId) const -{ - CSSM_DB_ATTRIBUTE_INFO info; - info.AttributeFormat = attributeFormatFor(recordType, attributeId); - info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - info.Label.AttributeID = attributeId; - - return info; -} - -void -KeychainSchemaImpl::getAttributeInfoForRecordType(CSSM_DB_RECORDTYPE recordType, SecKeychainAttributeInfo **Info) const -{ - const RelationInfoMap &rmap = relationInfoMapFor(recordType); - - SecKeychainAttributeInfo *theList=reinterpret_cast(malloc(sizeof(SecKeychainAttributeInfo))); - - size_t capacity=rmap.size(); - UInt32 *tagBuf=reinterpret_cast(malloc(capacity*sizeof(UInt32))); - UInt32 *formatBuf=reinterpret_cast(malloc(capacity*sizeof(UInt32))); - UInt32 i=0; - - - for (RelationInfoMap::const_iterator rit = rmap.begin(); rit != rmap.end(); ++rit) - { - if (i>=capacity) - { - capacity *= 2; - if (capacity <= i) capacity = i + 1; - tagBuf=reinterpret_cast(realloc(tagBuf, (capacity*sizeof(UInt32)))); - formatBuf=reinterpret_cast(realloc(tagBuf, (capacity*sizeof(UInt32)))); - } - tagBuf[i]=rit->first; - formatBuf[i++]=rit->second; - } - - theList->count=i; - theList->tag=tagBuf; - theList->format=formatBuf; - *Info=theList; -} - - -const CssmAutoDbRecordAttributeInfo & -KeychainSchemaImpl::primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType) const -{ - PrimaryKeyInfoMap::const_iterator it; - it = mPrimaryKeyInfoMap.find(recordType); - - if (it == mPrimaryKeyInfoMap.end()) - MacOSError::throwMe(errSecNoSuchClass); // @@@ Not really but whatever. - - return *it->second; -} - -bool -KeychainSchemaImpl::operator <(const KeychainSchemaImpl &other) const -{ - return mDatabaseInfoMap < other.mDatabaseInfoMap; -} - -bool -KeychainSchemaImpl::operator ==(const KeychainSchemaImpl &other) const -{ - return mDatabaseInfoMap == other.mDatabaseInfoMap; -} - -void -KeychainSchemaImpl::didCreateRelation(CSSM_DB_RECORDTYPE relationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo) -{ - StLock_(mMutex); - - if (CSSM_DB_RECORDTYPE_SCHEMA_START <= relationID - && relationID < CSSM_DB_RECORDTYPE_SCHEMA_END) - return; - - // if our schema is already in the map, return - if (mPrimaryKeyInfoMap.find(relationID) != mPrimaryKeyInfoMap.end()) - { - return; - } - - RelationInfoMap &rim = mDatabaseInfoMap[relationID]; - for (uint32 ix = 0; ix < inNumberOfAttributes; ++ix) - rim[pAttributeInfo[ix].AttributeId] = pAttributeInfo[ix].DataType; - - CssmAutoDbRecordAttributeInfo *infos = new CssmAutoDbRecordAttributeInfo(); - - mPrimaryKeyInfoMap. - insert(PrimaryKeyInfoMap::value_type(relationID, infos)); - infos->DataRecordType = relationID; - for (uint32 ix = 0; ix < inNumberOfIndexes; ++ix) - if (pIndexInfo[ix].IndexType == CSSM_DB_INDEX_UNIQUE) - { - CssmDbAttributeInfo &info = infos->add(); - info.AttributeNameFormat = CSSM_DB_ATTRIBUTE_NAME_AS_INTEGER; - info.Label.AttributeID = pIndexInfo[ix].AttributeId; - info.AttributeFormat = rim[info.Label.AttributeID]; - } -} - - - -KeychainSchema::~KeychainSchema() - -{ -} - - - -struct Event -{ - SecKeychainEvent eventCode; - PrimaryKey primaryKey; -}; -typedef std::list EventList; - -#define SYSTEM_KEYCHAIN_CHECK_UNIX_BASE_NAME "/var/run/systemkeychaincheck" -#define SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME (SYSTEM_KEYCHAIN_CHECK_UNIX_BASE_NAME ".socket") -#define SYSTEM_KEYCHAIN_CHECK_COMPLETE_FILE_NAME (SYSTEM_KEYCHAIN_CHECK_UNIX_BASE_NAME ".done") - -static void check_system_keychain() -{ - // sadly we can't use XPC here, XPC_DOMAIN_TYPE_SYSTEM doesn't exist yet. Also xpc-helper uses the - // keychain API (I assume for checking codesign things). So we use Unix Domain Sockets. - - // NOTE: if we hit a system error we attempt to log it, and then just don't check the system keychain. - // In theory a system might be able to recover from this state if we let it try to muddle along, and - // past behaviour didn't even try this hard to do the keychain check. In particular we could be in a - // sandbox'ed process. So we just do our best and let another process try again. - - struct stat keycheck_file_info; - if (stat(SYSTEM_KEYCHAIN_CHECK_COMPLETE_FILE_NAME, &keycheck_file_info) < 0) { - int server_fd = socket(PF_UNIX, SOCK_STREAM, 0); - if (server_fd < 0) { - syslog(LOG_ERR, "Can't get socket (%m) system keychain may be unchecked"); - return; - } - - struct sockaddr_un keychain_check_server_address; - keychain_check_server_address.sun_family = AF_UNIX; - if (strlcpy(keychain_check_server_address.sun_path, SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME, sizeof(keychain_check_server_address.sun_path)) > sizeof(keychain_check_server_address.sun_path)) { - // It would be nice if we could compile time assert this - syslog(LOG_ERR, "Socket path too long, max length %lu, your length %lu", (unsigned long)sizeof(keychain_check_server_address.sun_path), (unsigned long)strlen(SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME)); - close(server_fd); - return; - } - keychain_check_server_address.sun_len = SUN_LEN(&keychain_check_server_address); - - int rc = connect(server_fd, (struct sockaddr *)&keychain_check_server_address, keychain_check_server_address.sun_len); - if (rc < 0) { - syslog(LOG_ERR, "Can not connect to %s: %m", SYSTEM_KEYCHAIN_CHECK_UNIX_DOMAIN_SOCKET_NAME); - close(server_fd); - return; - } - - // this read lets us block until the EOF comes, we don't ever get a byte (and if we do, we don't care about it) - char byte; - ssize_t read_size = read(server_fd, &byte, 1); - if (read_size < 0) { - syslog(LOG_ERR, "Error reading from system keychain checker: %m"); - } - - close(server_fd); - return; - } -} - -// -// KeychainImpl -// -KeychainImpl::KeychainImpl(const Db &db) - : mInCache(false), mDb(db), mCustomUnlockCreds (this), mIsInBatchMode (false), mMutex(Mutex::recursive) -{ - dispatch_once(&SecKeychainSystemKeychainChecked, ^{ - check_system_keychain(); - }); - mDb->defaultCredentials(this); // install activation hook - mEventBuffer = new EventBuffer; -} - -KeychainImpl::~KeychainImpl() -{ - try - { - // Remove ourselves from the cache if we are in it. - // fprintf(stderr, "Removing %p from storage manager cache.\n", handle(false)); - globals().storageManager.removeKeychain(dlDbIdentifier(), this); - delete mEventBuffer; - } - catch(...) - { - } -} - -Mutex* -KeychainImpl::getMutexForObject() -{ - return globals().storageManager.getStorageManagerMutex(); -} - -Mutex* -KeychainImpl::getKeychainMutex() -{ - return &mMutex; -} - -void KeychainImpl::aboutToDestruct() -{ - // remove me from the global cache, we are done - // fprintf(stderr, "Destructing keychain object\n"); - DLDbIdentifier identifier = dlDbIdentifier(); - globals().storageManager.removeKeychain(identifier, this); -} - -bool -KeychainImpl::operator ==(const KeychainImpl &keychain) const -{ - return dlDbIdentifier() == keychain.dlDbIdentifier(); -} - -KCCursor -KeychainImpl::createCursor(SecItemClass itemClass, const SecKeychainAttributeList *attrList) -{ - StLock_(mMutex); - - StorageManager::KeychainList keychains; - keychains.push_back(Keychain(this)); - return KCCursor(keychains, itemClass, attrList); -} - -KCCursor -KeychainImpl::createCursor(const SecKeychainAttributeList *attrList) -{ - StLock_(mMutex); - - StorageManager::KeychainList keychains; - keychains.push_back(Keychain(this)); - return KCCursor(keychains, attrList); -} - -void -KeychainImpl::create(UInt32 passwordLength, const void *inPassword) -{ - StLock_(mMutex); - - if (!inPassword) - { - create(); - return; - } - - Allocator &alloc = Allocator::standard(); - - // @@@ Share this instance - - const CssmData password(const_cast(inPassword), passwordLength); - AclFactory::PasswordChangeCredentials pCreds (password, alloc); - AclFactory::AnyResourceContext rcc(pCreds); - create(&rcc); -} - -void KeychainImpl::create(ConstStringPtr inPassword) -{ - StLock_(mMutex); - - if ( inPassword ) - create(static_cast(inPassword[0]), &inPassword[1]); - else - create(); -} - -void -KeychainImpl::create() -{ - StLock_(mMutex); - - AclFactory aclFactory; - AclFactory::AnyResourceContext rcc(aclFactory.unlockCred()); - create(&rcc); -} - -void KeychainImpl::createWithBlob(CssmData &blob) -{ - StLock_(mMutex); - - mDb->dbInfo(&Schema::DBInfo); - AclFactory aclFactory; - AclFactory::AnyResourceContext rcc(aclFactory.unlockCred()); - mDb->resourceControlContext (&rcc); - try - { - mDb->createWithBlob(blob); - } - catch (...) - { - mDb->resourceControlContext(NULL); - mDb->dbInfo(NULL); - throw; - } - mDb->resourceControlContext(NULL); - mDb->dbInfo(NULL); // Clear the schema (to not break an open call later) - globals().storageManager.created(Keychain(this)); - - KCEventNotifier::PostKeychainEvent (kSecKeychainListChangedEvent, this, NULL); -} - -void -KeychainImpl::create(const ResourceControlContext *rcc) -{ - StLock_(mMutex); - - mDb->dbInfo(&Schema::DBInfo); // Set the schema (to force a create) - mDb->resourceControlContext(rcc); - try - { - mDb->create(); - } - catch (...) - { - mDb->resourceControlContext(NULL); - mDb->dbInfo(NULL); // Clear the schema (to not break an open call later) - throw; - } - mDb->resourceControlContext(NULL); - mDb->dbInfo(NULL); // Clear the schema (to not break an open call later) - globals().storageManager.created(Keychain(this)); -} - -void -KeychainImpl::open() -{ - StLock_(mMutex); - - mDb->open(); -} - -void -KeychainImpl::lock() -{ - StLock_(mMutex); - - mDb->lock(); -} - -void -KeychainImpl::unlock() -{ - StLock_(mMutex); - - mDb->unlock(); -} - -void -KeychainImpl::unlock(const CssmData &password) -{ - StLock_(mMutex); - - mDb->unlock(password); -} - -void -KeychainImpl::unlock(ConstStringPtr password) -{ - StLock_(mMutex); - - if (password) - { - const CssmData data(const_cast(&password[1]), password[0]); - unlock(data); - } - else - unlock(); -} - -void -KeychainImpl::stash() -{ - StLock_(mMutex); - - mDb->stash(); -} - -void -KeychainImpl::stashCheck() -{ - StLock_(mMutex); - - mDb->stashCheck(); -} - -void -KeychainImpl::getSettings(uint32 &outIdleTimeOut, bool &outLockOnSleep) -{ - StLock_(mMutex); - - mDb->getSettings(outIdleTimeOut, outLockOnSleep); -} - -void -KeychainImpl::setSettings(uint32 inIdleTimeOut, bool inLockOnSleep) -{ - StLock_(mMutex); - - // The .Mac syncing code only makes sense for the AppleFile CSP/DL, - // but other DLs such as the OCSP and LDAP DLs do not expose a way to - // change settings or the password. To make a minimal change that only affects - // the smartcard case, we only look for that CSP/DL - - bool isSmartcard = (mDb->dl()->guid() == gGuidAppleSdCSPDL); - - // get the old keychain blob so that we can tell .Mac to resync it - CssmAutoData oldBlob(mDb ->allocator()); - if (!isSmartcard) - mDb->copyBlob(oldBlob.get()); - - mDb->setSettings(inIdleTimeOut, inLockOnSleep); -} - -void -KeychainImpl::changePassphrase(UInt32 oldPasswordLength, const void *oldPassword, - UInt32 newPasswordLength, const void *newPassword) -{ - StLock_(mMutex); - - bool isSmartcard = (mDb->dl()->guid() == gGuidAppleSdCSPDL); - - TrackingAllocator allocator(Allocator::standard()); - AutoCredentials cred = AutoCredentials(allocator); - if (oldPassword) - { - const CssmData &oldPass = *new(allocator) CssmData(const_cast(oldPassword), oldPasswordLength); - TypedList &oldList = *new(allocator) TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_LOCK); - oldList.append(new(allocator) ListElement(CSSM_SAMPLE_TYPE_PASSWORD)); - oldList.append(new(allocator) ListElement(oldPass)); - cred += oldList; - } - - if (newPassword) - { - const CssmData &newPass = *new(allocator) CssmData(const_cast(newPassword), newPasswordLength); - TypedList &newList = *new(allocator) TypedList(allocator, CSSM_SAMPLE_TYPE_KEYCHAIN_CHANGE_LOCK); - newList.append(new(allocator) ListElement(CSSM_SAMPLE_TYPE_PASSWORD)); - newList.append(new(allocator) ListElement(newPass)); - cred += newList; - } - - // get the old keychain blob so that we can tell .Mac to resync it - CssmAutoData oldBlob(mDb->allocator()); - if (!isSmartcard) - mDb->copyBlob(oldBlob.get()); - - mDb->changePassphrase(&cred); -} - -void -KeychainImpl::changePassphrase(ConstStringPtr oldPassword, ConstStringPtr newPassword) -{ - StLock_(mMutex); - - const void *oldPtr, *newPtr; - UInt32 oldLen, newLen; - if (oldPassword) - { - oldLen = oldPassword[0]; - oldPtr = oldPassword + 1; - } - else - { - oldLen = 0; - oldPtr = NULL; - } - - if (newPassword) - { - newLen = newPassword[0]; - newPtr = newPassword + 1; - } - else - { - newLen = 0; - newPtr = NULL; - } - - changePassphrase(oldLen, oldPtr, newLen, newPtr); -} - -void -KeychainImpl::authenticate(const CSSM_ACCESS_CREDENTIALS *cred) -{ - StLock_(mMutex); - - if (!exists()) - MacOSError::throwMe(errSecNoSuchKeychain); - - MacOSError::throwMe(errSecUnimplemented); -} - -UInt32 -KeychainImpl::status() const -{ - // @@@ We should figure out the read/write status though a DL passthrough - // or some other way. Also should locked be unlocked read only or just - // read-only? - return (mDb->isLocked() ? 0 : kSecUnlockStateStatus | kSecWritePermStatus) - | kSecReadPermStatus; -} - -bool -KeychainImpl::exists() -{ - StLock_(mMutex); - - bool exists = true; - try - { - open(); - // Ok to leave the mDb open since it will get closed when it goes away. - } - catch (const CssmError &e) - { - if (e.osStatus() != CSSMERR_DL_DATASTORE_DOESNOT_EXIST) - throw; - exists = false; - } - - return exists; -} - -bool -KeychainImpl::isActive() const -{ - return mDb->isActive(); -} - -void KeychainImpl::completeAdd(Item &inItem, PrimaryKey &primaryKey) -{ - - - // The inItem shouldn't be in the cache yet - assert(!inItem->inCache()); - - // Insert inItem into mDbItemMap with key primaryKey. p.second will be - // true if it got inserted. If not p.second will be false and p.first - // will point to the current entry with key primaryKey. - pair p = - mDbItemMap.insert(DbItemMap::value_type(primaryKey, inItem.get())); - if (!p.second) - { - // There was already an ItemImpl * in mDbItemMap with key - // primaryKey. Get a ref to the pointer to it so we can assign a - // new value to it below. - ItemImpl *oldItem = p.first->second; - - // @@@ If this happens we are breaking our API contract of - // uniquifying items. We really need to insert the item into the - // map before we start the add. And have the item be in an - // "is being added" state. - assert(oldItem->inCache()); - secdebug("keychain", "add of new item %p somehow replaced %p", - inItem.get(), oldItem); - - // make sure that we both mark the item and remove the item from the cache - removeItem(oldItem->primaryKey(), oldItem); - oldItem = inItem.get(); - } - - inItem->inCache(true); -} - -void -KeychainImpl::addCopy(Item &inItem) -{ - Keychain keychain(this); - PrimaryKey primaryKey = inItem->addWithCopyInfo(keychain, true); - completeAdd(inItem, primaryKey); - postEvent(kSecAddEvent, inItem); -} - -void -KeychainImpl::add(Item &inItem) -{ - Keychain keychain(this); - PrimaryKey primaryKey = inItem->add(keychain); - completeAdd(inItem, primaryKey); - postEvent(kSecAddEvent, inItem); -} - -void -KeychainImpl::didUpdate(const Item &inItem, PrimaryKey &oldPK, - PrimaryKey &newPK) -{ - // If the primary key hasn't changed we don't need to update mDbItemMap. - if (oldPK != newPK) - { - // If inItem isn't in the cache we don't need to update mDbItemMap. - assert(inItem->inCache()); - if (inItem->inCache()) - { - // First remove the entry for inItem in mDbItemMap with key oldPK. - DbItemMap::iterator it = mDbItemMap.find(oldPK); - if (it != mDbItemMap.end() && (ItemImpl*) it->second == inItem.get()) - mDbItemMap.erase(it); - - // Insert inItem into mDbItemMap with key newPK. p.second will be - // true if it got inserted. If not p.second will be false and - // p.first will point to the current entry with key newPK. - pair p = - mDbItemMap.insert(DbItemMap::value_type(newPK, inItem.get())); - if (!p.second) - { - // There was already an ItemImpl * in mDbItemMap with key - // primaryKey. Get a ref to the pointer to it so we can assign - // a new value to it below. - ItemImpl *oldItem = p.first->second; - - // @@@ If this happens we are breaking our API contract of - // uniquifying items. We really need to insert the item into - // the map with the new primary key before we start the update. - // And have the item be in an "is being updated" state. - assert(oldItem->inCache()); - secdebug("keychain", "update of item %p somehow replaced %p", - inItem.get(), oldItem); - oldItem->inCache(false); - oldItem = inItem.get(); - } - } - } - - postEvent(kSecUpdateEvent, inItem); -} - -void -KeychainImpl::deleteItem(Item &inoutItem) -{ - { - // We don't need to hold the DO mutex through event posting, and, in fact, doing so causes deadlock. - // Hold it only as long as needed, instead. - - - // item must be persistent - if (!inoutItem->isPersistent()) - MacOSError::throwMe(errSecInvalidItemRef); - - DbUniqueRecord uniqueId = inoutItem->dbUniqueRecord(); - PrimaryKey primaryKey = inoutItem->primaryKey(); - uniqueId->deleteRecord(); - - // Don't remove the item from the mDbItemMap here since this would cause - // us to report a new item to our caller when we receive the - // kSecDeleteEvent notification. - // It will be removed before we post the notification, because - // CCallbackMgr will call didDeleteItem() - - // Post the notification for the item deletion with - // the primaryKey obtained when the item still existed - } - - postEvent(kSecDeleteEvent, inoutItem); -} - - -CssmClient::CSP -KeychainImpl::csp() -{ - StLock_(mMutex); - - if (!mDb->dl()->subserviceMask() & CSSM_SERVICE_CSP) - MacOSError::throwMe(errSecInvalidKeychain); - - // Try to cast first to a CSPDL to handle case where we don't have an SSDb - try - { - CssmClient::CSPDL cspdl(dynamic_cast(&*mDb->dl())); - return CSP(cspdl); - } - catch (...) - { - SSDbImpl* impl = dynamic_cast(&(*mDb)); - if (impl == NULL) - { - CssmError::throwMe(CSSMERR_CSSM_INVALID_POINTER); - } - - SSDb ssDb(impl); - return ssDb->csp(); - } -} - -PrimaryKey -KeychainImpl::makePrimaryKey(CSSM_DB_RECORDTYPE recordType, DbUniqueRecord &uniqueId) -{ - StLock_(mMutex); - - DbAttributes primaryKeyAttrs(uniqueId->database()); - primaryKeyAttrs.recordType(recordType); - gatherPrimaryKeyAttributes(primaryKeyAttrs); - uniqueId->get(&primaryKeyAttrs, NULL); - return PrimaryKey(primaryKeyAttrs); -} - -const CssmAutoDbRecordAttributeInfo & -KeychainImpl::primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType) -{ - StLock_(mMutex); - - try - { - return keychainSchema()->primaryKeyInfosFor(recordType); - } - catch (const CommonError &error) - { - switch (error.osStatus()) - { - case errSecNoSuchClass: - case CSSMERR_DL_INVALID_RECORDTYPE: - resetSchema(); - return keychainSchema()->primaryKeyInfosFor(recordType); - default: - throw; - } - } -} - -void KeychainImpl::gatherPrimaryKeyAttributes(DbAttributes& primaryKeyAttrs) -{ - StLock_(mMutex); - - const CssmAutoDbRecordAttributeInfo &infos = - primaryKeyInfosFor(primaryKeyAttrs.recordType()); - - // @@@ fix this to not copy info. - for (uint32 i = 0; i < infos.size(); i++) - primaryKeyAttrs.add(infos.at(i)); -} - -ItemImpl * -KeychainImpl::_lookupItem(const PrimaryKey &primaryKey) -{ - DbItemMap::iterator it = mDbItemMap.find(primaryKey); - if (it != mDbItemMap.end()) - { - if (it->second == NULL) - { - // we've been weak released... - mDbItemMap.erase(it); - } - else - { - return it->second; - } - } - - return NULL; -} - -Item -KeychainImpl::item(const PrimaryKey &primaryKey) -{ - StLock_(mMutex); - - // Lookup the item in the map while holding the apiLock. - ItemImpl *itemImpl = _lookupItem(primaryKey); - if (itemImpl) - return Item(itemImpl); - - try - { - // We didn't find it so create a new item with just a keychain and - // a primary key. However since we aren't holding - // globals().apiLock anymore some other thread might have beaten - // us to creating this item and adding it to the cache. If that - // happens we retry the lookup. - return Item(this, primaryKey); - } - catch (const MacOSError &e) - { - // If the item creation failed because some other thread already - // inserted this item into the cache we retry the lookup. - if (e.osStatus() == errSecDuplicateItem) - { - // Lookup the item in the map while holding the apiLock. - ItemImpl *itemImpl = _lookupItem(primaryKey); - if (itemImpl) - return Item(itemImpl); - } - throw; - } -} - - -Item -KeychainImpl::item(CSSM_DB_RECORDTYPE recordType, DbUniqueRecord &uniqueId) -{ - StLock_(mMutex); - - PrimaryKey primaryKey = makePrimaryKey(recordType, uniqueId); - { - // Lookup the item in the map while holding the apiLock. - ItemImpl *itemImpl = _lookupItem(primaryKey); - - if (itemImpl) - { - return Item(itemImpl); - } - } - - try - { - // We didn't find it so create a new item with a keychain, a primary key - // and a DbUniqueRecord. However since we aren't holding - // globals().apiLock anymore some other thread might have beaten - // us to creating this item and adding it to the cache. If that - // happens we retry the lookup. - return Item(this, primaryKey, uniqueId); - } - catch (const MacOSError &e) - { - // If the item creation failed because some other thread already - // inserted this item into the cache we retry the lookup. - if (e.osStatus() == errSecDuplicateItem) - { - // Lookup the item in the map while holding the apiLock. - ItemImpl *itemImpl = _lookupItem(primaryKey); - if (itemImpl) - return Item(itemImpl); - } - throw; - } -} - -KeychainSchema -KeychainImpl::keychainSchema() -{ - StLock_(mMutex); - if (!mKeychainSchema) - mKeychainSchema = KeychainSchema(mDb); - - return mKeychainSchema; -} - -void KeychainImpl::resetSchema() -{ - mKeychainSchema = NULL; // re-fetch it from db next time -} - - -// Called from DbItemImpl's constructor (so it is only partially constructed), -// add it to the map. -void -KeychainImpl::addItem(const PrimaryKey &primaryKey, ItemImpl *dbItemImpl) -{ - StLock_(mMutex); - - // The dbItemImpl shouldn't be in the cache yet - assert(!dbItemImpl->inCache()); - - // Insert dbItemImpl into mDbItemMap with key primaryKey. p.second will - // be true if it got inserted. If not p.second will be false and p.first - // will point to the current entry with key primaryKey. - pair p = - mDbItemMap.insert(DbItemMap::value_type(primaryKey, dbItemImpl)); - - if (!p.second) - { - // There was already an ItemImpl * in mDbItemMap with key primaryKey. - // There is a race condition here when being called in multiple threads - // We might have added an item using add and received a notification at - // the same time. - MacOSError::throwMe(errSecDuplicateItem); - } - - dbItemImpl->inCache(true); -} - -void -KeychainImpl::didDeleteItem(ItemImpl *inItemImpl) -{ - StLock_(mMutex); - - // Called by CCallbackMgr - secdebug("kcnotify", "%p notified that item %p was deleted", this, inItemImpl); - removeItem(inItemImpl->primaryKey(), inItemImpl); -} - -void -KeychainImpl::removeItem(const PrimaryKey &primaryKey, ItemImpl *inItemImpl) -{ - StLock_(mMutex); - - // If inItemImpl isn't in the cache to begin with we are done. - if (!inItemImpl->inCache()) - return; - - DbItemMap::iterator it = mDbItemMap.find(primaryKey); - if (it != mDbItemMap.end() && (ItemImpl*) it->second == inItemImpl) - mDbItemMap.erase(it); - - inItemImpl->inCache(false); -} - -void -KeychainImpl::getAttributeInfoForItemID(CSSM_DB_RECORDTYPE itemID, - SecKeychainAttributeInfo **Info) -{ - StLock_(mMutex); - - try - { - keychainSchema()->getAttributeInfoForRecordType(itemID, Info); - } - catch (const CommonError &error) - { - switch (error.osStatus()) - { - case errSecNoSuchClass: - case CSSMERR_DL_INVALID_RECORDTYPE: - resetSchema(); - keychainSchema()->getAttributeInfoForRecordType(itemID, Info); - default: - throw; - } - } -} - -void -KeychainImpl::freeAttributeInfo(SecKeychainAttributeInfo *Info) -{ - free(Info->tag); - free(Info->format); - free(Info); -} - -CssmDbAttributeInfo -KeychainImpl::attributeInfoFor(CSSM_DB_RECORDTYPE recordType, UInt32 tag) -{ - StLock_(mMutex); - - try - { - return keychainSchema()->attributeInfoFor(recordType, tag); - } - catch (const CommonError &error) - { - switch (error.osStatus()) - { - case errSecNoSuchClass: - case CSSMERR_DL_INVALID_RECORDTYPE: - resetSchema(); - return keychainSchema()->attributeInfoFor(recordType, tag); - default: - throw; - } - } -} - -void -KeychainImpl::recode(const CssmData &data, const CssmData &extraData) -{ - StLock_(mMutex); - - mDb->recode(data, extraData); -} - -void -KeychainImpl::copyBlob(CssmData &data) -{ - StLock_(mMutex); - - mDb->copyBlob(data); -} - -void -KeychainImpl::setBatchMode(Boolean mode, Boolean rollback) -{ - StLock_(mMutex); - - mDb->setBatchMode(mode, rollback); - mIsInBatchMode = mode; - if (!mode) - { - if (!rollback) // was batch mode being turned off without an abort? - { - // dump the buffer - EventBuffer::iterator it = mEventBuffer->begin(); - while (it != mEventBuffer->end()) - { - PrimaryKey primaryKey; - if (it->item) - { - primaryKey = it->item->primaryKey(); - } - - KCEventNotifier::PostKeychainEvent(it->kcEvent, mDb->dlDbIdentifier(), primaryKey); - - ++it; - } - - } - - // notify that a keychain has changed in too many ways to count - KCEventNotifier::PostKeychainEvent(kSecKeychainLeftBatchModeEvent); - mEventBuffer->clear(); - } - else - { - KCEventNotifier::PostKeychainEvent(kSecKeychainEnteredBatchModeEvent); - } -} - -void -KeychainImpl::postEvent(SecKeychainEvent kcEvent, ItemImpl* item) -{ - PrimaryKey primaryKey; - - { - StLock_(mMutex); - - if (item != NULL) - { - primaryKey = item->primaryKey(); - } - } - - if (!mIsInBatchMode) - { - KCEventNotifier::PostKeychainEvent(kcEvent, mDb->dlDbIdentifier(), primaryKey); - } - else - { - StLock_(mMutex); - - EventItem it; - it.kcEvent = kcEvent; - if (item != NULL) - { - it.item = item; - } - - mEventBuffer->push_back (it); - } -} - -Keychain::Keychain() -{ - dispatch_once(&SecKeychainSystemKeychainChecked, ^{ - check_system_keychain(); - }); -} - -Keychain::~Keychain() -{ -} - - - -Keychain -Keychain::optional(SecKeychainRef handle) -{ - if (handle) - return KeychainImpl::required(handle); - else - return globals().storageManager.defaultKeychain(); -} - - -CFIndex KeychainCore::GetKeychainRetainCount(Keychain& kc) -{ - CFTypeRef ref = kc->handle(false); - return CFGetRetainCount(ref); -} - - -// -// Create default credentials for this keychain. -// This is triggered upon default open (i.e. a Db::activate() with no set credentials). -// -// This function embodies the "default credentials" logic for Keychain-layer databases. -// -const AccessCredentials * -KeychainImpl::makeCredentials() -{ - return defaultCredentials(); -} - - -const AccessCredentials * -KeychainImpl::defaultCredentials() -{ - StLock_(mMutex); - - // Use custom unlock credentials for file keychains which have a referral - // record and the standard credentials for all others. - - if (mDb->dl()->guid() == gGuidAppleCSPDL && mCustomUnlockCreds(mDb)) - return &mCustomUnlockCreds; - else - if (mDb->dl()->guid() == gGuidAppleSdCSPDL) - return globals().smartcardCredentials(); - else - return globals().keychainCredentials(); -} - - - -bool KeychainImpl::mayDelete() -{ - return true; -} diff --git a/OSX/include/security_keychain/Keychains.h b/OSX/include/security_keychain/Keychains.h deleted file mode 100644 index 7931313e..00000000 --- a/OSX/include/security_keychain/Keychains.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Keychains.h - The Keychain class -// -#ifndef _SECURITY_KEYCHAINS_H_ -#define _SECURITY_KEYCHAINS_H_ - -#include -#include -#include -#include -#include -#include -#include -#include "SecCFTypes.h" -#include "defaultcreds.h" - -class EventBuffer; - -namespace Security -{ - -namespace KeychainCore -{ - -class KCCursor; -class Item; -class PrimaryKey; -class StorageManager; - -class KeychainSchemaImpl : public RefCount -{ - NOCOPY(KeychainSchemaImpl) -public: - friend class KeychainSchema; -protected: - KeychainSchemaImpl(const CssmClient::Db &db); -public: - virtual ~KeychainSchemaImpl(); - - CSSM_DB_ATTRIBUTE_FORMAT attributeFormatFor(CSSM_DB_RECORDTYPE recordType, uint32 attributeId) const; - const CssmAutoDbRecordAttributeInfo &primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType) const; - - bool operator <(const KeychainSchemaImpl &other) const; - bool operator ==(const KeychainSchemaImpl &other) const; - - void getAttributeInfoForRecordType(CSSM_DB_RECORDTYPE recordType, SecKeychainAttributeInfo **Info) const; - CssmDbAttributeInfo attributeInfoFor(CSSM_DB_RECORDTYPE recordType, uint32 attributeId) const; - bool hasAttribute(CSSM_DB_RECORDTYPE recordType, uint32 attributeId) const; - bool hasRecordType(CSSM_DB_RECORDTYPE recordType) const; - - void didCreateRelation(CSSM_DB_RECORDTYPE inRelationID, - const char *inRelationName, - uint32 inNumberOfAttributes, - const CSSM_DB_SCHEMA_ATTRIBUTE_INFO *pAttributeInfo, - uint32 inNumberOfIndexes, - const CSSM_DB_SCHEMA_INDEX_INFO *pIndexInfo); - -private: - typedef map PrimaryKeyInfoMap; - PrimaryKeyInfoMap mPrimaryKeyInfoMap; - - typedef map RelationInfoMap; - typedef map DatabaseInfoMap; - DatabaseInfoMap mDatabaseInfoMap; - Mutex mMutex; - -private: - const RelationInfoMap &relationInfoMapFor(CSSM_DB_RECORDTYPE recordType) const; -}; - - -class KeychainSchema : public RefPointer -{ -public: - KeychainSchema() {} - KeychainSchema(KeychainSchemaImpl *impl) : RefPointer(impl) {} - KeychainSchema(const CssmClient::Db &db) : RefPointer(new KeychainSchemaImpl(db)) {} - ~KeychainSchema(); - - bool operator <(const KeychainSchema &other) const - { return ptr && other.ptr ? *ptr < *other.ptr : ptr < other.ptr; } - bool operator ==(const KeychainSchema &other) const - { return ptr && other.ptr ? *ptr == *other.ptr : ptr == other.ptr; } - -private: - typedef KeychainSchemaImpl Impl; -}; - - -class ItemImpl; - -class KeychainImpl : public SecCFObject, private CssmClient::Db::DefaultCredentialsMaker -{ - NOCOPY(KeychainImpl) -public: - SECCFFUNCTIONS(KeychainImpl, SecKeychainRef, errSecInvalidKeychain, gTypes().KeychainImpl) - - friend class Keychain; - friend class ItemImpl; -protected: - KeychainImpl(const CssmClient::Db &db); - -protected: - // Methods called by ItemImpl; - void didUpdate(const Item &inItem, PrimaryKey &oldPK, - PrimaryKey &newPK); - void completeAdd(Item &item, PrimaryKey &key); - -public: - virtual ~KeychainImpl(); - - Mutex* getKeychainMutex(); - Mutex* getMutexForObject(); - void aboutToDestruct(); - - bool operator ==(const KeychainImpl &) const; - - // Item calls - void add(Item &item); - void addCopy(Item &item); - void deleteItem(Item &item); // item must be persistent. - - // Keychain calls - void create(UInt32 passwordLength, const void *inPassword); - void createWithBlob(CssmData &blob); - void create(ConstStringPtr inPassword); - void create(); - void create(const ResourceControlContext *rcc); - void open(); - - // Locking and unlocking a keychain. - void lock(); - void unlock(); - void unlock(const CssmData &password); - void unlock(ConstStringPtr password); // @@@ This has a length limit, we should remove it. - void stash(); - void stashCheck(); - - void getSettings(uint32 &outIdleTimeOut, bool &outLockOnSleep); - void setSettings(uint32 inIdleTimeOut, bool inLockOnSleep); - - // Passing in NULL for either oldPassword or newPassword will cause them to be prompted for. - // To specify a zero length password in either case the oldPasswordLength or newPasswordLength - // value must be 0 and the oldPassword or newPassword must not be NULL. - void changePassphrase(UInt32 oldPasswordLength, const void *oldPassword, - UInt32 newPasswordLength, const void *newPassword); - void changePassphrase(ConstStringPtr oldPassword, ConstStringPtr newPassword); - - void authenticate(const CSSM_ACCESS_CREDENTIALS *cred); // Does not do an unlock. - - const char *name() const { return mDb->name(); } - UInt32 status() const; - bool exists(); - bool isActive() const; - - KCCursor createCursor(const SecKeychainAttributeList *attrList); - KCCursor createCursor(SecItemClass itemClass, const SecKeychainAttributeList *attrList); - CssmClient::Db database() { return mDb; } - DLDbIdentifier dlDbIdentifier() const { return mDb->dlDbIdentifier(); } - - CssmClient::CSP csp(); - - PrimaryKey makePrimaryKey(CSSM_DB_RECORDTYPE recordType, CssmClient::DbUniqueRecord &uniqueId); - void gatherPrimaryKeyAttributes(CssmClient::DbAttributes& primaryKeyAttrs); - - const CssmAutoDbRecordAttributeInfo &primaryKeyInfosFor(CSSM_DB_RECORDTYPE recordType); - - Item item(const PrimaryKey& primaryKey); - Item item(CSSM_DB_RECORDTYPE recordType, CssmClient::DbUniqueRecord &uniqueId); - - CssmDbAttributeInfo attributeInfoFor(CSSM_DB_RECORDTYPE recordType, UInt32 tag); - void getAttributeInfoForItemID(CSSM_DB_RECORDTYPE itemID, SecKeychainAttributeInfo **Info); - static void freeAttributeInfo(SecKeychainAttributeInfo *Info); - KeychainSchema keychainSchema(); - void resetSchema(); - void didDeleteItem(ItemImpl *inItemImpl); - - void recode(const CssmData &data, const CssmData &extraData); - void copyBlob(CssmData &dbBlob); - - void setBatchMode(Boolean mode, Boolean rollBack); - - // yield default open() credentials for this keychain (as of now) - const AccessCredentials *defaultCredentials(); - - // Only call these functions while holding globals().apiLock. - bool inCache() const throw() { return mInCache; } - void inCache(bool inCache) throw() { mInCache = inCache; } - - void postEvent(SecKeychainEvent kcEvent, ItemImpl* item); - - void addItem(const PrimaryKey &primaryKey, ItemImpl *dbItemImpl); - - bool mayDelete(); - -private: - void removeItem(const PrimaryKey &primaryKey, ItemImpl *inItemImpl); - ItemImpl *_lookupItem(const PrimaryKey &primaryKey); - - const AccessCredentials *makeCredentials(); - - typedef map DbItemMap; - // Weak reference map of all items we know about that have a primaryKey - DbItemMap mDbItemMap; - // True iff we are in the cache of keychains in StorageManager - bool mInCache; - - CssmClient::Db mDb; - - KeychainSchema mKeychainSchema; - - // Data for auto-unlock credentials - DefaultCredentials mCustomUnlockCreds; - bool mIsInBatchMode; - EventBuffer *mEventBuffer; - Mutex mMutex; -}; - - -CFIndex GetKeychainRetainCount(Keychain& kc); - -class Keychain : public SecPointer -{ -public: - Keychain(); - Keychain(KeychainImpl *impl) : SecPointer(impl) {} - ~Keychain(); - - static Keychain optional(SecKeychainRef handle); - -private: - friend class StorageManager; - Keychain(const CssmClient::Db &db) - : SecPointer(new KeychainImpl(db)) {} - - typedef KeychainImpl Impl; -}; - - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_KEYCHAINS_H_ diff --git a/OSX/include/security_keychain/MacOSErrorStrings.h b/OSX/include/security_keychain/MacOSErrorStrings.h deleted file mode 100644 index bac2d85f..00000000 --- a/OSX/include/security_keychain/MacOSErrorStrings.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2003-2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/* - Note: the comments that appear after these errors are used to create SecErrorMessages.strings. - The comments must not be multi-line, and should be in a form meaningful to an end user. If - a different or additional comment is needed, it can be put in the header doc format, or on a - line that does not start with errZZZ. -*/ - -/* Definitions for miscellaneous OS errors that can be returned (with appropriate error strings) */ -enum -{ - errSecMisc_nsvErr = -35, /* The disk couldn't be found. It may have been ejected. */ - errSecMisc_bdNamErr = -37, /* Tried to open a file whose name contains an illegal character. */ - errSecMisc_fnfErr = -43, /* The file could not be found. */ - errSecMisc_wPrErr = -44, /* The disk is write-protected. */ - errSecMisc_fLckdErr = -45, /* The file is locked. */ - errSecMisc_vLckdErr = -46, /* The volume is locked. */ - errSecMisc_fBsyErr = -47, /* The file is busy. It may be in use by another application. */ - errSecMisc_dupFNErr = -48, /* A file with the same name already exists. */ - errSecMisc_opWrErr = -49, /* The file is already open with write permission. */ - errSecMisc_volOffLinErr = -53, /* The volume is no longer available. It may have been ejected. */ - errSecMisc_permErr = -54, /* The file could not be opened. It may be in use by another application. */ - errSecMisc_extFSErr = -58, /* This volume does not appear to be compatible. */ - errSecMisc_wrPermErr = -61, /* Could not write to the file. It may have been opened with insufficient access privileges. */ - errSecMisc_offLinErr = -65, /* The storage device is no longer available. It may have been ejected. */ - errSecMisc_memFullErr = -108, - errSecMisc_dirNFErr = -120, /* The directory could not be found. */ - errSecMisc_volGoneErr = -124, /* The server volume is no longer available. It may have been disconnected. */ - errSecMisc_userCanceledErr = -128, // The operation was cancelled by the user. - errSecMisc_resNotFound = -192, /* A required resource could not be found. */ - errSecMisc_resFNotFound = -193, /* A required resource is missing or damaged. */ - errSecMisc_icNoURLErr = -673, /* The specified location (URL) is an unknown type, or does not contain enough information. */ - errSecMisc_icConfigNotFoundErr = -674, /* A helper application to open the specified URL could not be found. */ - errSecMisc_cantGetFlavorErr = -1854, /* The location (URL) of this item is missing or improperly formatted. */ - errSecMisc_afpAccessDenied = -5000, /* Access to this item was denied. */ - errSecMisc_afpUserNotAuth = -5023, /* Authentication failed. The password for this server may have changed since the item was added to the keychain. */ - errSecMisc_afpPwdPolicyErr = -5046 /* This AppleShare IP server is configured to not allow users to save passwords for automatic login. Contact the server administrator for more information. */ -}; - diff --git a/OSX/include/security_keychain/Password.cpp b/OSX/include/security_keychain/Password.cpp deleted file mode 100644 index 68cdcce2..00000000 --- a/OSX/include/security_keychain/Password.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Password.cpp -// -#include "Password.h" -#include -#include "SecBridge.h" - -#include "KCCursor.h" - -using namespace KeychainCore; -using namespace CssmClient; - -PasswordImpl::PasswordImpl(SecItemClass itemClass, SecKeychainAttributeList *searchAttrList, SecKeychainAttributeList *itemAttrList) : - mItem(itemClass, itemAttrList, 0, NULL), mUseKeychain(false), mFoundInKeychain(false), mRememberInKeychain(false), mMutex(Mutex::recursive) -{ - if (searchAttrList && itemAttrList) - { - mUseKeychain = true; - mKeychain = Keychain::optional(NULL); - mRememberInKeychain = true; - - // initialize mFoundInKeychain to true if mItem is found - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(NULL, keychains); - KCCursor cursor(keychains, itemClass, searchAttrList); - - if (cursor->next(mItem)) - mFoundInKeychain = true; - } -} - -PasswordImpl::PasswordImpl(PasswordImpl& existing) -{ - mKeychain = existing.mKeychain; - mItem = existing.mItem; - mUseKeychain = existing.mUseKeychain; - mFoundInKeychain = existing.mFoundInKeychain; - mRememberInKeychain = existing.mRememberInKeychain; -} - - - -PasswordImpl::~PasswordImpl() throw() -{ -} - -void -PasswordImpl::setAccess(Access *access) -{ - // changing an existing ACL is more work than this SPI wants to do - if (!mFoundInKeychain) - mItem->setAccess(access); -} - -void -PasswordImpl::setData(UInt32 length, const void *data) -{ - assert(mUseKeychain); - - // do different things based on mFoundInKeychain? - mItem->setData(length,data); -} - -bool -PasswordImpl::getData(UInt32 *length, const void **data) -{ - if (mItem->isPersistent()) - { - // try to retrieve it - CssmDataContainer outData; - try - { - mItem->getData(outData); - if (length && data) - { - *length=(uint32)outData.length(); - outData.Length=0; - *data=outData.data(); - outData.Data=NULL; - } - return true; - } - catch (...) - { - // cancel unlock: CSP_USER_CANCELED - // deny rogue app CSP_OPERATION_AUTH_DENIED - return false; - } - } - else - return false; -} - -void -PasswordImpl::save() -{ - assert(mUseKeychain); - - if (mFoundInKeychain) - { - mItem->update(); - } - else - { - mKeychain->add(mItem); - - // reinitialize mItem now it's on mKeychain - mFoundInKeychain = true; // should be set by member that resets mItem - } -} - -Password::Password(SecItemClass itemClass, SecKeychainAttributeList *searchAttrList, SecKeychainAttributeList *itemAttrList) : - SecPointer(new PasswordImpl(itemClass, searchAttrList, itemAttrList)) -{ -} - -Password::Password(PasswordImpl *impl) : SecPointer(impl) -{ -} - -Password::Password(PasswordImpl &impl) : SecPointer(new PasswordImpl(impl)) -{ -} diff --git a/OSX/include/security_keychain/Password.h b/OSX/include/security_keychain/Password.h deleted file mode 100644 index f142a9a4..00000000 --- a/OSX/include/security_keychain/Password.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Password.h - Password acquiring wrapper -// -#ifndef _SECURITY_PASSWORD_H_ -#define _SECURITY_PASSWORD_H_ - -#include -// included by item #include -#include - - -namespace Security { -namespace KeychainCore { - -class PasswordImpl : public SecCFObject { -public: - SECCFFUNCTIONS(PasswordImpl, SecPasswordRef, errSecInvalidPasswordRef, gTypes().PasswordImpl) - -public: - // make default forms - PasswordImpl(SecItemClass itemClass, SecKeychainAttributeList *searchAttrList, SecKeychainAttributeList *itemAttrList); - PasswordImpl(PasswordImpl& existing); - - virtual ~PasswordImpl() throw(); - - bool getData(UInt32 *length, const void **data); - void setData(UInt32 length,const void *data); - void save(); - bool useKeychain() const { return mUseKeychain; } - bool rememberInKeychain() const { return mRememberInKeychain; } - void setRememberInKeychain(bool remember) { mRememberInKeychain = remember; } - void setAccess(Access *access); - -private: - // keychain item cached? - Keychain mKeychain; - Item mItem; - bool mUseKeychain; - bool mFoundInKeychain; - bool mRememberInKeychain; - Mutex mMutex; -}; - -class Password : public SecPointer -{ -public: - Password(SecItemClass itemClass, SecKeychainAttributeList *searchAttrList, SecKeychainAttributeList *itemAttrList); - Password(PasswordImpl *impl); - Password(PasswordImpl &impl); -}; - - - - -} // end namespace KeychainCore -} // end namespace Security - -#endif // !_SECURITY_PASSWORD_H_ diff --git a/OSX/include/security_keychain/Policies.cpp b/OSX/include/security_keychain/Policies.cpp deleted file mode 100644 index 43f5c5a5..00000000 --- a/OSX/include/security_keychain/Policies.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// Policy.cpp - Working with Policies -// -#include -#include -#include -#include - -/* Oids longer than this are considered invalid. */ -#define MAX_OID_SIZE 32 - -//%%FIXME: need to use a common copy of this utility function -static -CFStringRef SecDERItemCopyOIDDecimalRepresentation(uint8 *oid, size_t oidLen) -{ - if (oidLen == 0) - return CFSTR(""); - - if (oidLen > MAX_OID_SIZE) - return CFSTR("Oid too long"); - - CFMutableStringRef result = CFStringCreateMutable(kCFAllocatorDefault, 0); - - // The first two levels are encoded into one byte, since the root level - // has only 3 nodes (40*x + y). However if x = joint-iso-itu-t(2) then - // y may be > 39, so we have to add special-case handling for this. - uint32_t x = oid[0] / 40; - uint32_t y = oid[0] % 40; - if (x > 2) - { - // Handle special case for large y if x = 2 - y += (x - 2) * 40; - x = 2; - } - CFStringAppendFormat(result, NULL, CFSTR("%u.%u"), x, y); - - unsigned long value = 0; - for (x = 1; x < oidLen; ++x) - { - value = (value << 7) | (oid[x] & 0x7F); - /* @@@ value may not span more than 4 bytes. */ - /* A max number of 20 values is allowed. */ - if (!(oid[x] & 0x80)) - { - CFStringAppendFormat(result, NULL, CFSTR(".%lu"), value); - value = 0; - } - } - return result; -} - - -using namespace KeychainCore; - -Policy::Policy(TP supportingTp, const CssmOid &policyOid) - : mTp(supportingTp), - mOid(Allocator::standard(), policyOid), - mValue(Allocator::standard()), - mAuxValue(Allocator::standard()) -{ - // value is as yet unimplemented - secdebug("policy", "Policy() this %p", this); -} - -Policy::~Policy() throw() -{ - secdebug("policy", "~Policy() this %p", this); -} - -void Policy::setValue(const CssmData &value) -{ - StLock_(mMutex); - mValue = value; - mAuxValue.reset(); - - // Certain policy values may contain an embedded pointer. Ask me how I feel about that. - if (mOid == CSSMOID_APPLE_TP_SSL || - mOid == CSSMOID_APPLE_TP_EAP || - mOid == CSSMOID_APPLE_TP_IP_SEC || - mOid == CSSMOID_APPLE_TP_APPLEID_SHARING) - { - CSSM_APPLE_TP_SSL_OPTIONS *opts = (CSSM_APPLE_TP_SSL_OPTIONS *)value.data(); - if (opts->Version == CSSM_APPLE_TP_SSL_OPTS_VERSION) - { - if (opts->ServerNameLen > 0) - { - // Copy auxiliary data, then update the embedded pointer to reference our copy - mAuxValue.copy(const_cast(opts->ServerName), opts->ServerNameLen); - mValue.get().interpretedAs()->ServerName = - reinterpret_cast(mAuxValue.data()); - } - else - { - // Clear the embedded pointer! - mValue.get().interpretedAs()->ServerName = - reinterpret_cast(NULL); - } - } - } - else if (mOid == CSSMOID_APPLE_TP_SMIME || - mOid == CSSMOID_APPLE_TP_ICHAT || - mOid == CSSMOID_APPLE_TP_PASSBOOK_SIGNING) - { - CSSM_APPLE_TP_SMIME_OPTIONS *opts = (CSSM_APPLE_TP_SMIME_OPTIONS *)value.data(); - if (opts->Version == CSSM_APPLE_TP_SMIME_OPTS_VERSION) - { - if (opts->SenderEmailLen > 0) - { - // Copy auxiliary data, then update the embedded pointer to reference our copy - mAuxValue.copy(const_cast(opts->SenderEmail), opts->SenderEmailLen); - mValue.get().interpretedAs()->SenderEmail = - reinterpret_cast(mAuxValue.data()); - } - else - { - // Clear the embedded pointer! - mValue.get().interpretedAs()->SenderEmail = - reinterpret_cast(NULL); - } - } - } -} - -void Policy::setProperties(CFDictionaryRef properties) -{ - // Set the policy value based on the provided dictionary keys. - if (properties == NULL) - return; - - if (mOid == CSSMOID_APPLE_TP_SSL || - mOid == CSSMOID_APPLE_TP_EAP || - mOid == CSSMOID_APPLE_TP_IP_SEC || - mOid == CSSMOID_APPLE_TP_APPLEID_SHARING) - { - CSSM_APPLE_TP_SSL_OPTIONS options = { CSSM_APPLE_TP_SSL_OPTS_VERSION, 0, NULL, 0 }; - char *buf = NULL; - CFStringRef nameStr = NULL; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyName, (const void **)&nameStr)) { - buf = (char *)malloc(MAXPATHLEN); - if (buf) { - if (CFStringGetCString(nameStr, buf, MAXPATHLEN, kCFStringEncodingUTF8)) { - options.ServerName = buf; - options.ServerNameLen = (unsigned)(strlen(buf)+1); // include terminating null - } - } - } - CFBooleanRef clientRef = NULL; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyClient, (const void **)&clientRef) - && CFBooleanGetValue(clientRef) == true) - options.Flags |= CSSM_APPLE_TP_SSL_CLIENT; - - const CssmData value((uint8*)&options, sizeof(options)); - this->setValue(value); - - if (buf) free(buf); - } - else if (mOid == CSSMOID_APPLE_TP_SMIME || - mOid == CSSMOID_APPLE_TP_ICHAT || - mOid == CSSMOID_APPLE_TP_PASSBOOK_SIGNING) - { - CSSM_APPLE_TP_SMIME_OPTIONS options = { CSSM_APPLE_TP_SMIME_OPTS_VERSION, 0, 0, NULL }; - char *buf = NULL; - CFStringRef nameStr = NULL; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyName, (const void **)&nameStr)) { - buf = (char *)malloc(MAXPATHLEN); - if (buf) { - if (CFStringGetCString(nameStr, buf, MAXPATHLEN, kCFStringEncodingUTF8)) { - CFStringRef teamIDStr = NULL; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyTeamIdentifier, (const void **)&teamIDStr)) { - char *buf2 = (char *)malloc(MAXPATHLEN); - if (buf2) { - if (CFStringGetCString(teamIDStr, buf2, MAXPATHLEN, kCFStringEncodingUTF8)) { - /* append tab separator and team identifier */ - strlcat(buf, "\t", MAXPATHLEN); - strlcat(buf, buf2, MAXPATHLEN); - } - free(buf2); - } - } - options.SenderEmail = buf; - options.SenderEmailLen = (unsigned)(strlen(buf)+1); // include terminating null - } - } - } - CFBooleanRef kuRef = NULL; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_DigitalSignature, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_DigitalSignature; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_NonRepudiation, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_NonRepudiation; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_KeyEncipherment, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_KeyEncipherment; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_DataEncipherment, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_DataEncipherment; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_KeyAgreement, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_KeyAgreement; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_KeyCertSign, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_KeyCertSign; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_CRLSign, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_CRLSign; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_EncipherOnly, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_EncipherOnly; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyKU_DecipherOnly, (const void **)&kuRef) - && CFBooleanGetValue(kuRef) == true) - options.IntendedUsage |= CE_KU_DecipherOnly; - - const CssmData value((uint8*)&options, sizeof(options)); - this->setValue(value); - - if (buf) free(buf); - } - else if (mOid == CSSMOID_APPLE_TP_REVOCATION) - { - CFNumberRef num = NULL; - if (CFDictionaryGetValueIfPresent(properties, (const void *)kSecPolicyRevocationFlags, (const void **)&num)) { - CFOptionFlags revocationFlags = 0; - if (num) { - (void)CFNumberGetValue(num, kCFNumberCFIndexType, &revocationFlags); - } - const CssmData value((uint8*)&revocationFlags, sizeof(revocationFlags)); - this->setValue(value); - } - } - -} - -CFDictionaryRef Policy::properties() -{ - // Builds and returns a dictionary which the caller must release. - CFMutableDictionaryRef properties = CFDictionaryCreateMutable(NULL, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - if (!properties) return NULL; - - // kSecPolicyOid - CFStringRef oidStr = SecDERItemCopyOIDDecimalRepresentation((uint8*)mOid.data(), mOid.length()); - if (oidStr) { - CFDictionarySetValue(properties, (const void *)kSecPolicyOid, (const void *)oidStr); - CFRelease(oidStr); - } - - // kSecPolicyName - if (mAuxValue) { - CFStringRef nameStr = CFStringCreateWithBytes(NULL, - (const UInt8 *)reinterpret_cast(mAuxValue.data()), - (CFIndex)mAuxValue.length(), kCFStringEncodingUTF8, false); - if (nameStr) { - if (mOid == CSSMOID_APPLE_TP_PASSBOOK_SIGNING) { - CFArrayRef strs = CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault, nameStr, CFSTR("\t")); - if (strs) { - CFIndex count = CFArrayGetCount(strs); - if (count > 0) - CFDictionarySetValue(properties, (const void *)kSecPolicyName, (const void *)CFArrayGetValueAtIndex(strs, 0)); - if (count > 1) - CFDictionarySetValue(properties, (const void *)kSecPolicyTeamIdentifier, (const void *)CFArrayGetValueAtIndex(strs, 1)); - CFRelease(strs); - } - } - else { - CFDictionarySetValue(properties, (const void *)kSecPolicyName, (const void *)nameStr); - } - CFRelease(nameStr); - } - } - - // kSecPolicyClient - if (mValue) { - if (mOid == CSSMOID_APPLE_TP_SSL || - mOid == CSSMOID_APPLE_TP_EAP || - mOid == CSSMOID_APPLE_TP_IP_SEC || - mOid == CSSMOID_APPLE_TP_APPLEID_SHARING) - { - CSSM_APPLE_TP_SSL_OPTIONS *opts = (CSSM_APPLE_TP_SSL_OPTIONS *)mValue.data(); - if (opts->Flags & CSSM_APPLE_TP_SSL_CLIENT) { - CFDictionarySetValue(properties, (const void *)kSecPolicyClient, (const void *)kCFBooleanTrue); - } - } - } - - // key usage flags (currently only for S/MIME and iChat policies) - if (mValue) { - if (mOid == CSSMOID_APPLE_TP_SMIME || - mOid == CSSMOID_APPLE_TP_ICHAT) - { - CSSM_APPLE_TP_SMIME_OPTIONS *opts = (CSSM_APPLE_TP_SMIME_OPTIONS *)mValue.data(); - CE_KeyUsage usage = opts->IntendedUsage; - if (usage & CE_KU_DigitalSignature) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_DigitalSignature, (const void *)kCFBooleanTrue); - if (usage & CE_KU_NonRepudiation) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_NonRepudiation, (const void *)kCFBooleanTrue); - if (usage & CE_KU_KeyEncipherment) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_KeyEncipherment, (const void *)kCFBooleanTrue); - if (usage & CE_KU_DataEncipherment) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_DataEncipherment, (const void *)kCFBooleanTrue); - if (usage & CE_KU_KeyAgreement) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_KeyAgreement, (const void *)kCFBooleanTrue); - if (usage & CE_KU_KeyCertSign) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_KeyCertSign, (const void *)kCFBooleanTrue); - if (usage & CE_KU_CRLSign) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_CRLSign, (const void *)kCFBooleanTrue); - if (usage & CE_KU_EncipherOnly) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_EncipherOnly, (const void *)kCFBooleanTrue); - if (usage & CE_KU_DecipherOnly) - CFDictionarySetValue(properties, (const void *)kSecPolicyKU_DecipherOnly, (const void *)kCFBooleanTrue); - } - else if (mOid == CSSMOID_APPLE_TP_REVOCATION) - { - CFOptionFlags *revocationFlagsPtr = (CFOptionFlags *)mValue.data(); - if (revocationFlagsPtr) { - CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, revocationFlagsPtr); - if (num) { - CFDictionarySetValue(properties, (const void *)kSecPolicyRevocationFlags, num); - CFRelease(num); - } - } - } - } - return properties; -} - - -bool Policy::operator < (const Policy& other) const -{ - //@@@ inefficient - return (oid() < other.oid()) || - (oid() == other.oid() && value() < other.value()); -} - -bool Policy::operator == (const Policy& other) const -{ - return oid() == other.oid() && value() == other.value(); -} diff --git a/OSX/include/security_keychain/Policies.h b/OSX/include/security_keychain/Policies.h deleted file mode 100644 index f4331b4d..00000000 --- a/OSX/include/security_keychain/Policies.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// Policies.h -// -#ifndef _SECURITY_POLICY_H_ -#define _SECURITY_POLICY_H_ - -#include -#include -#include -#include -#include "SecCFTypes.h" - -namespace Security -{ - -namespace KeychainCore -{ - -using namespace CssmClient; - -// -// A Policy[Impl] represents a particular -// CSSM "policy" managed by a particular TP. -// -class Policy : public SecCFObject -{ - NOCOPY(Policy) -public: - SECCFFUNCTIONS(Policy, SecPolicyRef, errSecInvalidItemRef, gTypes().Policy) - - Policy(TP supportingTp, const CssmOid &policyOid); - -public: - virtual ~Policy() throw(); - - TP &tp() { return mTp; } - const TP &tp() const { return mTp; } - const CssmOid &oid() const { return mOid; } - const CssmData &value() const { return mValue; } - CssmOwnedData &value() { return mValue; } - - void setValue(const CssmData &value); - void setProperties(CFDictionaryRef properties); - CFDictionaryRef properties(); - - bool operator < (const Policy& other) const; - bool operator == (const Policy& other) const; - -private: - TP mTp; // TP module for this Policy - CssmAutoData mOid; // OID for this policy - CssmAutoData mValue; // value for this policy - CssmAutoData mAuxValue; // variable-length value data for this policy - Mutex mMutex; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_POLICY_H_ diff --git a/OSX/include/security_keychain/PolicyCursor.cpp b/OSX/include/security_keychain/PolicyCursor.cpp deleted file mode 100644 index aa12338f..00000000 --- a/OSX/include/security_keychain/PolicyCursor.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// PolicyCursor.cpp -// -#include -#include -#include -#include - -using namespace KeychainCore; -using namespace CssmClient; - - -// -// This preliminary implementation bypasses MDS and uses -// a fixed set of policies known to exist in the one known TP. -// -struct TheOneTP : public TP { - TheOneTP() : TP(gGuidAppleX509TP) { } -}; - -static ModuleNexus theOneTP; -static const CssmOid *theOidList[] = { - static_cast(&CSSMOID_APPLE_ISIGN), - static_cast(&CSSMOID_APPLE_X509_BASIC), - static_cast(&CSSMOID_APPLE_TP_SSL), - static_cast(&CSSMOID_APPLE_TP_SMIME), - static_cast(&CSSMOID_APPLE_TP_EAP), - static_cast(&CSSMOID_APPLE_TP_SW_UPDATE_SIGNING), - static_cast(&CSSMOID_APPLE_TP_IP_SEC), - static_cast(&CSSMOID_APPLE_TP_ICHAT), - static_cast(&CSSMOID_APPLE_TP_RESOURCE_SIGN), - static_cast(&CSSMOID_APPLE_TP_PKINIT_CLIENT), - static_cast(&CSSMOID_APPLE_TP_PKINIT_SERVER), - static_cast(&CSSMOID_APPLE_TP_CODE_SIGNING), - static_cast(&CSSMOID_APPLE_TP_PACKAGE_SIGNING), - static_cast(&CSSMOID_APPLE_TP_REVOCATION_CRL), - static_cast(&CSSMOID_APPLE_TP_REVOCATION_OCSP), - static_cast(&CSSMOID_APPLE_TP_MACAPPSTORE_RECEIPT), - static_cast(&CSSMOID_APPLE_TP_APPLEID_SHARING), - static_cast(&CSSMOID_APPLE_TP_TIMESTAMPING), - NULL // sentinel -}; - - -// -// Canonical Construction -// -PolicyCursor::PolicyCursor(const CSSM_OID* oid, const CSSM_DATA* value) - : mOid(Allocator::standard()), mOidGiven(false), mMutex(Mutex::recursive) -{ - if (oid) { - mOid = CssmOid::required(oid); - mOidGiven = true; - } - mSearchPos = 0; -} - - -// -// Destroy -// -PolicyCursor::~PolicyCursor() throw() -{ -} - - -// -// Crank the iterator -// -bool PolicyCursor::next(SecPointer &policy) -{ - StLock_(mMutex); - - while (theOidList[mSearchPos]) { - if (mOidGiven && mOid != *theOidList[mSearchPos]) { - mSearchPos++; - continue; // no oid match - } - // ignoring mValue - not used by current TP - policy = new Policy(theOneTP(), *theOidList[mSearchPos]); - mSearchPos++; // advance cursor - return true; // return next match - } - return false; // end of table, no more matches -} - -// -// Return a new policy instance for an OID, outside of cursor iteration -// -void PolicyCursor::policy(const CSSM_OID* oid, SecPointer &policy) -{ - const CssmOid *policyOid = static_cast(oid); - policy = new Policy(theOneTP(), *policyOid); -} - diff --git a/OSX/include/security_keychain/PolicyCursor.h b/OSX/include/security_keychain/PolicyCursor.h deleted file mode 100644 index c7503b68..00000000 --- a/OSX/include/security_keychain/PolicyCursor.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2012,2014-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// PolicyCursor.h -// -#ifndef _SECURITY_POLICYCURSOR_H_ -#define _SECURITY_POLICYCURSOR_H_ - -#include -#include -#include -#include -#include -#include "SecCFTypes.h" - -namespace Security -{ - -namespace KeychainCore -{ - -class Policy; - -class PolicyCursor : public SecCFObject -{ - NOCOPY(PolicyCursor) -public: - SECCFFUNCTIONS(PolicyCursor, SecPolicySearchRef, errSecInvalidSearchRef, gTypes().PolicyCursor) - - PolicyCursor(const CSSM_OID* oid, const CSSM_DATA* value); - virtual ~PolicyCursor() throw(); - bool next(SecPointer &policy); - bool oidProvided() { return mOidGiven; } - - static void policy(const CSSM_OID* oid, SecPointer &policy); - -private: - //CFArrayRef mKeychainSearchList; - //SecKeyUsage mKeyUsage; - //SecPolicyRef mPolicy; - CssmAutoData mOid; - bool mOidGiven; - // value ignored (for now?) - -#if 1 // quick version -- using built-in policy list - - int mSearchPos; // next untried table entry - -#else // MDS version -- later - bool mFirstLookup; - - // - // Initialization - // - MDS_HANDLE mMdsHand; - CSSM_DB_HANDLE mDbHand; - // - // Used for searching (lookups) - // - MDS_DB_HANDLE mObjDlDb; - MDS_DB_HANDLE mCdsaDlDb; - MDS_FUNCS* mMdsFuncs; -#endif - - Mutex mMutex; -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_POLICYCURSOR_H_ diff --git a/OSX/include/security_keychain/PrimaryKey.cpp b/OSX/include/security_keychain/PrimaryKey.cpp deleted file mode 100644 index b0170141..00000000 --- a/OSX/include/security_keychain/PrimaryKey.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2000-2001,2004,2011-2012,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// PrimaryKey.cpp -// - -#include "PrimaryKey.h" - -using namespace KeychainCore; -using namespace CssmClient; - - -PrimaryKeyImpl::PrimaryKeyImpl(const CSSM_DATA &data) -: CssmDataContainer(data.Data, data.Length), mMutex(Mutex::recursive) -{ - -//@@@ do bounds checking here, throw if invalid - -} - -PrimaryKeyImpl::PrimaryKeyImpl(const DbAttributes &primaryKeyAttrs) : mMutex(Mutex::recursive) -{ - Length = sizeof(uint32); - for (uint32 ix = 0; ix < primaryKeyAttrs.size(); ++ix) - { - if (primaryKeyAttrs.at(ix).size() == 0) - MacOSError::throwMe(errSecInvalidKeychain); - - Length += sizeof(uint32) + primaryKeyAttrs.at(ix).Value[0].Length; - } - - // Careful with exceptions - Data = mAllocator.alloc((UInt32)Length); - uint8 *p = Data; - - putUInt32(p, primaryKeyAttrs.recordType()); - for (uint32 ix = 0; ix < primaryKeyAttrs.size(); ++ix) - { - UInt32 len = (UInt32)primaryKeyAttrs.at(ix).Value[0].Length; - putUInt32(p, len); - memcpy(p, primaryKeyAttrs.at(ix).Value[0].Data, len); - p += len; - } -} - -CssmClient::DbCursor -PrimaryKeyImpl::createCursor(const Keychain &keychain) -{ - StLock_(mMutex); - DbCursor cursor(keychain->database()); - - // @@@ Set up cursor to find item with this. - uint8 *p = Data; - uint32 left = (uint32)Length; - if (left < sizeof(*p)) - MacOSError::throwMe(errSecNoSuchAttr); // XXX Not really but whatever. - - CSSM_DB_RECORDTYPE rt = getUInt32(p, left); - const CssmAutoDbRecordAttributeInfo &infos = keychain->primaryKeyInfosFor(rt); - - cursor->recordType(rt); - cursor->conjunctive(CSSM_DB_AND); - for (uint32 ix = 0; ix < infos.size(); ++ix) - { - uint32 len = getUInt32(p, left); - - if (left < len) - MacOSError::throwMe(errSecNoSuchAttr); // XXX Not really but whatever. - - CssmData value(p, len); - left -= len; - p += len; - - cursor->add(CSSM_DB_EQUAL, infos.at(ix), value); - } - - return cursor; -} - - -void -PrimaryKeyImpl::putUInt32(uint8 *&p, uint32 value) -{ - *p++ = (value >> 24); - *p++ = (value >> 16) & 0xff; - *p++ = (value >> 8) & 0xff; - *p++ = value & 0xff; -} - -uint32 -PrimaryKeyImpl::getUInt32(uint8 *&p, uint32 &left) const -{ - if (left < sizeof(uint32)) - MacOSError::throwMe(errSecNoSuchAttr); // XXX Not really but whatever. - - - // @@@ Assumes data written in big endian. - uint32 value = (p[0] << 24) + (p[1] << 16) + (p[2] << 8) + p[3]; - p += sizeof(uint32); - left -= sizeof(uint32); - return value; -} - - - -CSSM_DB_RECORDTYPE -PrimaryKeyImpl::recordType() const -{ - uint8 *data = Data; - uint32 length = (uint32)Length; - return getUInt32(data, length); -} diff --git a/OSX/include/security_keychain/PrimaryKey.h b/OSX/include/security_keychain/PrimaryKey.h deleted file mode 100644 index b8845028..00000000 --- a/OSX/include/security_keychain/PrimaryKey.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - - -// -// PrimaryKey.h -// -#ifndef _SECURITY_PRIMARYKEY_H_ -#define _SECURITY_PRIMARYKEY_H_ - -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -class PrimaryKeyImpl : public CssmDataContainer -{ -public: - PrimaryKeyImpl(const CSSM_DATA &data); - PrimaryKeyImpl(const CssmClient::DbAttributes &primaryKeyAttrs); - ~PrimaryKeyImpl() {} - - void putUInt32(uint8 *&p, uint32 value); - uint32 getUInt32(uint8 *&p, uint32 &left) const; - - CssmClient::DbCursor createCursor(const Keychain &keychain); - - CSSM_DB_RECORDTYPE recordType() const; -private: - -protected: - Mutex mMutex; -}; - - -class PrimaryKey : public RefPointer -{ -public: - PrimaryKey() {} - PrimaryKey(PrimaryKeyImpl *impl) : RefPointer(impl) {} - PrimaryKey(const CSSM_DATA &data) - : RefPointer(new PrimaryKeyImpl(data)) {} - PrimaryKey(const CssmClient::DbAttributes &primaryKeyAttrs) - : RefPointer(new PrimaryKeyImpl(primaryKeyAttrs)) {} -}; - -} // end namespace KeychainCore - -} // end namespace Security - -#endif // !_SECURITY_PRIMARYKEY_H_ diff --git a/OSX/include/security_keychain/SecACL.cpp b/OSX/include/security_keychain/SecACL.cpp deleted file mode 100644 index 335c6cf9..00000000 --- a/OSX/include/security_keychain/SecACL.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include - -#include "SecBridge.h" - -// Forward reference -/*! - @function GetACLAuthorizationTagFromString - @abstract Get the CSSM ACL item from the CFString - @param aclStr The String name of the ACL - @result The CSSM ACL value -*/ -sint32 GetACLAuthorizationTagFromString(CFStringRef aclStr); - -CFStringRef GetAuthStringFromACLAuthorizationTag(sint32 tag); - -// -// Local functions -// -static void setApplications(ACL *acl, CFArrayRef applicationList); - -CFTypeID -SecACLGetTypeID(void) -{ - BEGIN_SECAPI - - return gTypes().ACL.typeID; - - END_SECAPI1(_kCFRuntimeNotATypeID) -} - - -/*! - */ -OSStatus SecACLCreateFromSimpleContents(SecAccessRef accessRef, - CFArrayRef applicationList, - CFStringRef description, const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector, - SecACLRef *newAcl) -{ - BEGIN_SECAPI - SecPointer access = Access::required(accessRef); - SecPointer acl = new ACL(*access, cfString(description), *promptSelector); - if (applicationList) { - // application-list + prompt - acl->form(ACL::appListForm); - setApplications(acl, applicationList); - } else { - // allow-any - acl->form(ACL::allowAllForm); - } - access->add(acl.get()); - Required(newAcl) = acl->handle(); - END_SECAPI -} - -OSStatus SecACLCreateWithSimpleContents(SecAccessRef access, - CFArrayRef applicationList, - CFStringRef description, - SecKeychainPromptSelector promptSelector, - SecACLRef *newAcl) -{ - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR cdsaPromptSelector; - cdsaPromptSelector.version = CSSM_ACL_KEYCHAIN_PROMPT_CURRENT_VERSION; - cdsaPromptSelector.flags = promptSelector; - return SecACLCreateFromSimpleContents(access, applicationList, description, &cdsaPromptSelector, newAcl); -} - - -/*! - */ -OSStatus SecACLRemove(SecACLRef aclRef) -{ - BEGIN_SECAPI - ACL::required(aclRef)->remove(); - END_SECAPI -} - - -static SecTrustedApplicationRef -convert(const SecPointer &trustedApplication) -{ - return *trustedApplication; -} - -/*! - */ -OSStatus SecACLCopySimpleContents(SecACLRef aclRef, - CFArrayRef *applicationList, - CFStringRef *promptDescription, CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector) -{ - BEGIN_SECAPI - SecPointer acl = ACL::required(aclRef); - switch (acl->form()) { - case ACL::allowAllForm: - Required(applicationList) = NULL; - Required(promptDescription) = - acl->promptDescription().empty() ? NULL - : makeCFString(acl->promptDescription()); - Required(promptSelector) = acl->promptSelector(); - break; - case ACL::appListForm: - Required(applicationList) = - makeCFArray(convert, acl->applications()); - Required(promptDescription) = makeCFString(acl->promptDescription()); - Required(promptSelector) = acl->promptSelector(); - break; - default: - return errSecACLNotSimple; // custom or unknown - } - END_SECAPI -} - -OSStatus SecACLCopyContents(SecACLRef acl, - CFArrayRef *applicationList, - CFStringRef *description, - SecKeychainPromptSelector *promptSelector) -{ - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR cdsaPromptSelector; - memset(&cdsaPromptSelector, 0, sizeof(cdsaPromptSelector)); - OSStatus err = errSecSuccess; - - err = SecACLCopySimpleContents(acl, applicationList, description, &cdsaPromptSelector); - *promptSelector = cdsaPromptSelector.flags; - return err; -} - -OSStatus SecACLSetSimpleContents(SecACLRef aclRef, - CFArrayRef applicationList, - CFStringRef description, const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector) -{ - BEGIN_SECAPI - SecPointer acl = ACL::required(aclRef); - acl->promptDescription() = description ? cfString(description) : ""; - acl->promptSelector() = promptSelector ? *promptSelector : ACL::defaultSelector; - if (applicationList) { - // application-list + prompt - acl->form(ACL::appListForm); - setApplications(acl, applicationList); - } else { - // allow-any - acl->form(ACL::allowAllForm); - } - acl->modify(); - END_SECAPI -} - -OSStatus SecACLSetContents(SecACLRef acl, - CFArrayRef applicationList, - CFStringRef description, - SecKeychainPromptSelector promptSelector) -{ - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR cdsaPromptSelector; - cdsaPromptSelector.version = CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION; - cdsaPromptSelector.flags = promptSelector; - return SecACLSetSimpleContents(acl, applicationList, description, &cdsaPromptSelector); -} - -// -// Stuff a CFArray-of-SecTrustedApplications into an ACL object -// -static void setApplications(ACL *acl, CFArrayRef applicationList) -{ - ACL::ApplicationList &appList = acl->applications(); - appList.clear(); - //@@@ should really use STL iterator overlay on CFArray. By hand... - CFIndex count = CFArrayGetCount(applicationList); - for (CFIndex n = 0; n < count; n++) - appList.push_back(TrustedApplication::required( - SecTrustedApplicationRef(CFArrayGetValueAtIndex(applicationList, n)))); -} - - -// -// Set and get the authorization tags of an ACL entry -// -OSStatus SecACLGetAuthorizations(SecACLRef acl, - CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 *tagCount) -{ - BEGIN_SECAPI - AclAuthorizationSet auths = ACL::required(acl)->authorizations(); - if (Required(tagCount) < auths.size()) { // overflow - *tagCount = (uint32)auths.size(); // report size required - CssmError::throwMe(errSecParam); - } - *tagCount = (uint32)auths.size(); - copy(auths.begin(), auths.end(), tags); - END_SECAPI -} - -CFArrayRef SecACLCopyAuthorizations(SecACLRef acl) -{ - CFArrayRef result = NULL; - if (NULL == acl) - { - return result; - } - - AclAuthorizationSet auths = ACL::required(acl)->authorizations(); - uint32 numAuths = (uint32)auths.size(); - - CSSM_ACL_AUTHORIZATION_TAG* tags = new CSSM_ACL_AUTHORIZATION_TAG[numAuths]; - int i; - for (i = 0; i < numAuths; ++i) - { - tags[i] = NULL; - } - - OSStatus err = SecACLGetAuthorizations(acl, tags, &numAuths); - if (errSecSuccess != err) - { - - return result; - } - - CFTypeRef* strings = new CFTypeRef[numAuths]; - for (i = 0; i < numAuths; ++i) - { - strings[i] = NULL; - } - - for (size_t iCnt = 0; iCnt < numAuths; iCnt++) - { - strings[iCnt] = (CFTypeRef)GetAuthStringFromACLAuthorizationTag(tags[iCnt]); - } - - result = CFArrayCreate(kCFAllocatorDefault, (const void **)strings, numAuths, NULL); - - delete[] strings; - delete[] tags; - - return result; - -} - -OSStatus SecACLSetAuthorizations(SecACLRef aclRef, - CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 tagCount) -{ - BEGIN_SECAPI - SecPointer acl = ACL::required(aclRef); - if (acl->isOwner()) // can't change rights of the owner ACL - MacOSError::throwMe(errSecInvalidOwnerEdit); - AclAuthorizationSet &auths = acl->authorizations(); - auths.clear(); - copy(tags, tags + tagCount, insert_iterator(auths, auths.begin())); - acl->modify(); - END_SECAPI -} - -OSStatus SecACLUpdateAuthorizations(SecACLRef acl, CFArrayRef authorizations) -{ - if (NULL == acl || NULL == authorizations) - { - return errSecParam; - } - uint32 tagCount = (uint32)CFArrayGetCount(authorizations); - - size_t tagSize = (tagCount * sizeof(CSSM_ACL_AUTHORIZATION_TAG)); - - CSSM_ACL_AUTHORIZATION_TAG* tags = (CSSM_ACL_AUTHORIZATION_TAG*)malloc(tagSize); - memset(tags, 0, tagSize); - for (uint32 iCnt = 0; iCnt < tagCount; iCnt++) - { - tags[iCnt] = GetACLAuthorizationTagFromString((CFStringRef)CFArrayGetValueAtIndex(authorizations, iCnt)); - } - - OSStatus result = SecACLSetAuthorizations(acl, tags, tagCount); - free(tags); - return result; -} diff --git a/OSX/include/security_keychain/SecACL.h b/OSX/include/security_keychain/SecACL.h deleted file mode 100644 index a0f4514d..00000000 --- a/OSX/include/security_keychain/SecACL.h +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2002-2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecACL - The functions provided in SecACL are for managing entries in the access control list. - */ - -#ifndef _SECURITY_SECACL_H_ -#define _SECURITY_SECACL_H_ - -#include -#include -#include -#include -#include - - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN -CF_IMPLICIT_BRIDGING_ENABLED - - typedef CF_OPTIONS(uint16, SecKeychainPromptSelector) - { - kSecKeychainPromptRequirePassphase = 0x0001, /* require re-entering of passphrase */ - /* the following bits are ignored by 10.4 and earlier */ - kSecKeychainPromptUnsigned = 0x0010, /* prompt for unsigned clients */ - kSecKeychainPromptUnsignedAct = 0x0020, /* UNSIGNED bit overrides system default */ - kSecKeychainPromptInvalid = 0x0040, /* prompt for invalid signed clients */ - kSecKeychainPromptInvalidAct = 0x0080, - }; - - - /*! - @function SecACLGetTypeID - @abstract Returns the type identifier of SecACL instances. - @result The CFTypeID of SecACL instances. - */ - CFTypeID SecACLGetTypeID(void) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - - /*! - @function SecACLCreateFromSimpleContents - @abstract Creates a new access control list entry from the application list, description, and prompt selector provided and adds it to an item's access. - @param access An access reference. - @param applicationList An array of SecTrustedApplication instances that will be allowed access without prompting. - @param description The human readable name that will be used to refer to this item when the user is prompted. - @param promptSelector A pointer to a CSSM prompt selector. - @param newAcl A pointer to an access control list entry. On return, this points to the reference of the new access control list entry. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function is deprecated in 10.7 and later; - use SecACLCreateWithSimpleContents instead. - */ - OSStatus SecACLCreateFromSimpleContents(SecAccessRef access, - CFArrayRef __nullable applicationList, - CFStringRef description, - const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector, - SecACLRef * __nonnull CF_RETURNS_RETAINED newAcl) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - - /*! - @function SecACLCreateWithSimpleContents - @abstract Creates a new access control list entry from the application list, description, and prompt selector provided and adds it to an item's access. - @param access An access reference. - @param applicationList An array of SecTrustedApplication instances that will be allowed access without prompting. - @param description The human readable name that will be used to refer to this item when the user is prompted. - @param promptSelector A SecKeychainPromptSelector selector. - @param newAcl A pointer to an access control list entry. On return, this points to the reference of the new access control list entry. - @result A result code. See "Security Error Codes" (SecBase.h). - */ - OSStatus SecACLCreateWithSimpleContents(SecAccessRef access, - CFArrayRef __nullable applicationList, - CFStringRef description, - SecKeychainPromptSelector promptSelector, - SecACLRef * __nonnull CF_RETURNS_RETAINED newAcl) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - - /*! - @function SecACLRemove - @abstract Removes the access control list entry specified. - @param aclRef The reference to the access control list entry to remove. - @result A result code. See "Security Error Codes" (SecBase.h). - */ - OSStatus SecACLRemove(SecACLRef aclRef) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - - /*! - @function SecACLCopySimpleContents - @abstract Returns the application list, description, and CSSM prompt selector for a given access control list entry. - @param acl An access control list entry reference. - @param applicationList On return, An array of SecTrustedApplication instances that will be allowed access without prompting, for the given access control list entry. The caller needs to call CFRelease on this array when it's no longer needed. - @param description On return, the human readable name that will be used to refer to this item when the user is prompted, for the given access control list entry. The caller needs to call CFRelease on this string when it's no longer needed. - @param promptSelector A pointer to a CSSM prompt selector. On return, this points to the CSSM prompt selector for the given access control list entry. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function is deprecated in 10.7 and later; - use SecACLCopyContents instead. - */ - OSStatus SecACLCopySimpleContents(SecACLRef acl, - CFArrayRef * __nonnull CF_RETURNS_RETAINED applicationList, - CFStringRef * __nonnull CF_RETURNS_RETAINED description, - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - - /*! - @function SecACLCopyContents - @abstract Returns the application list, description, and prompt selector for a given access control list entry. - @param acl An access control list entry reference. - @param applicationList On return, An array of SecTrustedApplication instances that will be allowed access without prompting, for the given access control list entry. The caller needs to call CFRelease on this array when it's no longer needed. - @param description On return, the human readable name that will be used to refer to this item when the user is prompted, for the given access control list entry. The caller needs to call CFRelease on this string when it's no longer needed. - @param promptSelector A pointer to a SecKeychainPromptSelector. On return, this points to the SecKeychainPromptSelector for the given access control list entry. - @result A result code. See "Security Error Codes" (SecBase.h). - */ - OSStatus SecACLCopyContents(SecACLRef acl, - CFArrayRef * __nonnull CF_RETURNS_RETAINED applicationList, - CFStringRef * __nonnull CF_RETURNS_RETAINED description, - SecKeychainPromptSelector *promptSelector) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - /*! - @function SecACLSetSimpleContents - @abstract Sets the application list, description, and CSSM prompt selector for a given access control list entry. - @param acl A reference to the access control list entry to edit. - @param applicationList An application list reference. - @param description The human readable name that will be used to refer to this item when the user is prompted. - @param promptSelector A pointer to a CSSM prompt selector. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function is deprecated in 10.7 and later; - use SecACLSetContents instead. - */ - OSStatus SecACLSetSimpleContents(SecACLRef acl, - CFArrayRef __nullable applicationList, - CFStringRef description, - const CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR *promptSelector) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - - /*! - @function SecACLSetContents - @abstract Sets the application list, description, and prompt selector for a given access control list entry. - @param acl A reference to the access control list entry to edit. - @param applicationList An application list reference. - @param description The human readable name that will be used to refer to this item when the user is prompted. - @param promptSelector A SecKeychainPromptSelector selector. - @result A result code. See "Security Error Codes" (SecBase.h). - */ - OSStatus SecACLSetContents(SecACLRef acl, - CFArrayRef __nullable applicationList, - CFStringRef description, - SecKeychainPromptSelector promptSelector) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - - /*! - @function SecACLGetAuthorizations - @abstract Retrieve the CSSM authorization tags of a given access control list entry. - @param acl An access control list entry reference. - @param tags On return, this points to the first item in an array of CSSM authorization tags. - @param tagCount On return, this points to the number of tags in the CSSM authorization tag array. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function is deprecated in 10.7 and later; - use SecACLCopyAuthorizations instead. - */ - OSStatus SecACLGetAuthorizations(SecACLRef acl, - CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 *tagCount) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - - /*! - @function SecACLCopyAuthorizations - @abstract Retrieve the authorization tags of a given access control list entry. - @param acl An access control list entry reference. - @result On return, a CFArrayRef of the authorizations for this ACL. - */ - CFArrayRef SecACLCopyAuthorizations(SecACLRef acl) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - - /*! - @function SecACLSetAuthorizations - @abstract Sets the CSSM authorization tags of a given access control list entry. - @param acl An access control list entry reference. - @param tags A pointer to the first item in an array of CSSM authorization tags. - @param tagCount The number of tags in the CSSM authorization tag array. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function is deprecated in 10.7 and later; - use SecACLUpdateAuthorizations instead. - */ - OSStatus SecACLSetAuthorizations(SecACLRef acl, - CSSM_ACL_AUTHORIZATION_TAG *tags, uint32 tagCount) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - - - /*! - @function SecACLUpdateAuthorizations - @abstract Sets the authorization tags of a given access control list entry. - @param acl An access control list entry reference. - @param authorizations A pointer to an array of authorization tags. - @result A result code. See "Security Error Codes" (SecBase.h). - */ - OSStatus SecACLUpdateAuthorizations(SecACLRef acl, CFArrayRef authorizations) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -CF_IMPLICIT_BRIDGING_DISABLED -CF_ASSUME_NONNULL_END - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECACL_H_ */ diff --git a/OSX/include/security_keychain/SecAccess.cpp b/OSX/include/security_keychain/SecAccess.cpp deleted file mode 100644 index 9491f85c..00000000 --- a/OSX/include/security_keychain/SecAccess.cpp +++ /dev/null @@ -1,715 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include -#include -#include -#include "SecBridge.h" -#include - -#undef secdebug -#include - - -/* No restrictions. Permission to perform all operations on - the resource or available to an ACL owner. */ - - -const CFStringRef kSecACLAuthorizationAny = CFSTR("ACLAuthorizationAny"); - -const CFStringRef kSecACLAuthorizationLogin = CFSTR("ACLAuthorizationLogin"); -const CFStringRef kSecACLAuthorizationGenKey = CFSTR("ACLAuthorizationGenKey"); -const CFStringRef kSecACLAuthorizationDelete = CFSTR("ACLAuthorizationDelete"); -const CFStringRef kSecACLAuthorizationExportWrapped = CFSTR("ACLAuthorizationExportWrapped"); -const CFStringRef kSecACLAuthorizationExportClear = CFSTR("ACLAuthorizationExportClear"); -const CFStringRef kSecACLAuthorizationImportWrapped = CFSTR("ACLAuthorizationImportWrapped"); -const CFStringRef kSecACLAuthorizationImportClear = CFSTR("ACLAuthorizationImportClear"); -const CFStringRef kSecACLAuthorizationSign = CFSTR("ACLAuthorizationSign"); -const CFStringRef kSecACLAuthorizationEncrypt = CFSTR("ACLAuthorizationEncrypt"); -const CFStringRef kSecACLAuthorizationDecrypt = CFSTR("ACLAuthorizationDecrypt"); -const CFStringRef kSecACLAuthorizationMAC = CFSTR("ACLAuthorizationMAC"); -const CFStringRef kSecACLAuthorizationDerive = CFSTR("ACLAuthorizationDerive"); - -/* Defined authorization tag values for Keychain */ - - - -const CFStringRef kSecACLAuthorizationKeychainCreate = CFSTR("ACLAuthorizationKeychainCreate"); -const CFStringRef kSecACLAuthorizationKeychainDelete = CFSTR("ACLAuthorizationKeychainDelete"); -const CFStringRef kSecACLAuthorizationKeychainItemRead = CFSTR("ACLAuthorizationKeychainItemRead"); -const CFStringRef kSecACLAuthorizationKeychainItemInsert = CFSTR("ACLAuthorizationKeychainItemInsert"); -const CFStringRef kSecACLAuthorizationKeychainItemModify = CFSTR("ACLAuthorizationKeychainItemModify"); -const CFStringRef kSecACLAuthorizationKeychainItemDelete = CFSTR("ACLAuthorizationKeychainItemDelete"); - -const CFStringRef kSecACLAuthorizationChangeACL = CFSTR("ACLAuthorizationChangeACL"); -const CFStringRef kSecACLAuthorizationChangeOwner = CFSTR("ACLAuthorizationChangeOwner"); - - -static CFArrayRef copyTrustedAppListFromBundle(CFStringRef bundlePath, CFStringRef trustedAppListFileName); - -static CFStringRef gKeys[] = -{ - kSecACLAuthorizationAny, - kSecACLAuthorizationLogin, - kSecACLAuthorizationGenKey, - kSecACLAuthorizationDelete, - kSecACLAuthorizationExportWrapped, - kSecACLAuthorizationExportClear, - kSecACLAuthorizationImportWrapped, - kSecACLAuthorizationImportClear, - kSecACLAuthorizationSign, - kSecACLAuthorizationEncrypt, - kSecACLAuthorizationDecrypt, - kSecACLAuthorizationMAC, - kSecACLAuthorizationDerive, - - /* Defined authorization tag values for Keychain */ - kSecACLAuthorizationKeychainCreate, - kSecACLAuthorizationKeychainDelete, - kSecACLAuthorizationKeychainItemRead, - kSecACLAuthorizationKeychainItemInsert, - kSecACLAuthorizationKeychainItemModify, - kSecACLAuthorizationKeychainItemDelete, - - kSecACLAuthorizationChangeACL, - kSecACLAuthorizationChangeOwner - -}; - -static sint32 gValues[] = -{ - CSSM_ACL_AUTHORIZATION_ANY, - CSSM_ACL_AUTHORIZATION_LOGIN, - CSSM_ACL_AUTHORIZATION_GENKEY, - CSSM_ACL_AUTHORIZATION_DELETE, - CSSM_ACL_AUTHORIZATION_EXPORT_WRAPPED, - CSSM_ACL_AUTHORIZATION_EXPORT_CLEAR, - CSSM_ACL_AUTHORIZATION_IMPORT_WRAPPED, - CSSM_ACL_AUTHORIZATION_IMPORT_CLEAR, - CSSM_ACL_AUTHORIZATION_SIGN, - CSSM_ACL_AUTHORIZATION_ENCRYPT, - CSSM_ACL_AUTHORIZATION_DECRYPT, - CSSM_ACL_AUTHORIZATION_MAC, - CSSM_ACL_AUTHORIZATION_DERIVE, - CSSM_ACL_AUTHORIZATION_DBS_CREATE, - CSSM_ACL_AUTHORIZATION_DBS_DELETE, - CSSM_ACL_AUTHORIZATION_DB_READ, - CSSM_ACL_AUTHORIZATION_DB_INSERT, - CSSM_ACL_AUTHORIZATION_DB_MODIFY, - CSSM_ACL_AUTHORIZATION_DB_DELETE, - CSSM_ACL_AUTHORIZATION_CHANGE_ACL, - CSSM_ACL_AUTHORIZATION_CHANGE_OWNER -}; - -static -CFDictionaryRef CreateStringToNumDictionary() -{ - int numItems = (sizeof(gValues) / sizeof(sint32)); - CFMutableDictionaryRef tempDict = CFDictionaryCreateMutable(kCFAllocatorDefault, numItems, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - - for (int iCnt = 0; iCnt < numItems; iCnt++) - { - sint32 aNumber = gValues[iCnt]; - CFNumberRef aNum = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &aNumber); - - CFStringRef aString = gKeys[iCnt]; - CFDictionaryAddValue(tempDict, aString, aNum); - CFRelease(aNum); - } - - CFDictionaryRef result = CFDictionaryCreateCopy(kCFAllocatorDefault, tempDict); - CFRelease(tempDict); - return result; - -} - -static -CFDictionaryRef CreateNumToStringDictionary() -{ - int numItems = (sizeof(gValues) / sizeof(sint32)); - - CFMutableDictionaryRef tempDict = CFDictionaryCreateMutable(kCFAllocatorDefault, numItems, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - - for (int iCnt = 0; iCnt < numItems; iCnt++) - { - sint32 aNumber = gValues[iCnt]; - CFNumberRef aNum = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &aNumber); - - CFStringRef aString = gKeys[iCnt]; - CFDictionaryAddValue(tempDict, aNum, aString); - CFRelease(aNum); - - } - - CFDictionaryRef result = CFDictionaryCreateCopy(kCFAllocatorDefault, tempDict); - CFRelease(tempDict); - return result; -} - - -/* TODO: This should be in some header */ -sint32 GetACLAuthorizationTagFromString(CFStringRef aclStr); -sint32 GetACLAuthorizationTagFromString(CFStringRef aclStr) -{ - if (NULL == aclStr) - { -#ifndef NDEBUG - CFShow(CFSTR("GetACLAuthorizationTagFromString aclStr is NULL")); -#endif - return 0; - } - - static CFDictionaryRef gACLMapping = NULL; - - if (NULL == gACLMapping) - { - gACLMapping = CreateStringToNumDictionary(); - } - - sint32 result = 0; - CFNumberRef valueResult = (CFNumberRef)CFDictionaryGetValue(gACLMapping, aclStr); - if (NULL != valueResult) - { - if (!CFNumberGetValue(valueResult, kCFNumberSInt32Type, &result)) - { - return 0; - } - - } - else - { - return 0; - } - - return result; - -} - -/* TODO: This should be in some header */ -CFStringRef GetAuthStringFromACLAuthorizationTag(sint32 tag); -CFStringRef GetAuthStringFromACLAuthorizationTag(sint32 tag) -{ - static CFDictionaryRef gTagMapping = NULL; - CFNumberRef aNum = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &tag); - - if (NULL == gTagMapping) - { - gTagMapping = CreateNumToStringDictionary(); - } - - CFStringRef result = (CFStringRef)kSecACLAuthorizationAny; - - if (NULL != gTagMapping && CFDictionaryContainsKey(gTagMapping, aNum)) - { - result = (CFStringRef)CFDictionaryGetValue(gTagMapping, aNum); - } - return result; -} - -// -// CF boilerplate -// -CFTypeID SecAccessGetTypeID(void) -{ - BEGIN_SECAPI - return gTypes().Access.typeID; - END_SECAPI1(_kCFRuntimeNotATypeID) -} - - -// -// API bridge calls -// -/*! - * Create a new SecAccessRef that is set to the default configuration - * of a (newly created) security object. - */ -OSStatus SecAccessCreate(CFStringRef descriptor, CFArrayRef trustedList, SecAccessRef *accessRef) -{ - BEGIN_SECAPI - Required(descriptor); - SecPointer access; - if (trustedList) { - CFIndex length = CFArrayGetCount(trustedList); - ACL::ApplicationList trusted; - for (CFIndex n = 0; n < length; n++) - trusted.push_back(TrustedApplication::required( - SecTrustedApplicationRef(CFArrayGetValueAtIndex(trustedList, n)))); - access = new Access(cfString(descriptor), trusted); - } else { - access = new Access(cfString(descriptor)); - } - Required(accessRef) = access->handle(); - END_SECAPI -} - - -/*! - */ -OSStatus SecAccessCreateFromOwnerAndACL(const CSSM_ACL_OWNER_PROTOTYPE *owner, - uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls, - SecAccessRef *accessRef) -{ - BEGIN_SECAPI - Required(accessRef); // preflight - SecPointer access = new Access(Required(owner), aclCount, &Required(acls)); - *accessRef = access->handle(); - END_SECAPI -} - -SecAccessRef SecAccessCreateWithOwnerAndACL(uid_t userId, gid_t groupId, SecAccessOwnerType ownerType, CFArrayRef acls, CFErrorRef *error) -{ - SecAccessRef result = NULL; - - CSSM_ACL_PROCESS_SUBJECT_SELECTOR selector = - { - CSSM_ACL_PROCESS_SELECTOR_CURRENT_VERSION, // selector version - ownerType, - userId, - groupId - }; - - CSSM_LIST_ELEMENT subject2 = { NULL, 0 }; - subject2.Element.Word.Data = (UInt8 *)&selector; - subject2.Element.Word.Length = sizeof(selector); - CSSM_LIST_ELEMENT subject1 = - { - &subject2, CSSM_ACL_SUBJECT_TYPE_PROCESS, CSSM_LIST_ELEMENT_WORDID - }; - - CFIndex numAcls = 0; - - if (NULL != acls) - { - numAcls = CFArrayGetCount(acls); - } - -#ifndef NDEBUG - CFStringRef debugStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR("SecAccessCreateWithOwnerAndACL: processing %d acls"), (int)numAcls); - CFShow(debugStr); - CFRelease(debugStr); -#endif - - CSSM_ACL_AUTHORIZATION_TAG rights[numAcls]; - memset(rights, 0, sizeof(rights)); - - for (CFIndex iCnt = 0; iCnt < numAcls; iCnt++) - { - CFStringRef aclStr = (CFStringRef)CFArrayGetValueAtIndex(acls, iCnt); - -#ifndef NDEBUG - debugStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR("SecAccessCreateWithOwnerAndACL: acls[%d] = %@"), (int)iCnt, aclStr); - - CFShow(debugStr); - CFRelease(debugStr); -#endif - - CSSM_ACL_AUTHORIZATION_TAG aTag = GetACLAuthorizationTagFromString(aclStr); - -#ifndef NDEBUG - debugStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR("SecAccessCreateWithOwnerAndACL: rights[%d] = %d"), (int)iCnt, aTag); - - CFShow(debugStr); - CFRelease(debugStr); -#endif - - rights[iCnt] = aTag; - } - - - for (CFIndex iCnt = 0; iCnt < numAcls; iCnt++) - { -#ifndef NDEBUG - debugStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR("SecAccessCreateWithOwnerAndACL: rights[%d] = %d"), (int)iCnt, rights[iCnt]); - - CFShow(debugStr); - CFRelease(debugStr); -#endif - - - } - - CSSM_ACL_OWNER_PROTOTYPE owner = - { - // TypedSubject - { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 }, - // Delegate - false - }; - - - // ACL entries (any number, just one here) - CSSM_ACL_ENTRY_INFO acl_rights[] = - { - { - // prototype - { - // TypedSubject - { CSSM_LIST_TYPE_UNKNOWN, &subject1, &subject2 }, - false, // Delegate - // rights for this entry - { (uint32)(sizeof(rights) / sizeof(rights[0])), rights }, - // rest is defaulted - } - } - }; - - OSStatus err = SecAccessCreateFromOwnerAndACL(&owner, - sizeof(acl_rights) / sizeof(acl_rights[0]), acl_rights, &result); - - if (errSecSuccess != err) - { - result = NULL; - if (NULL != error) - { - *error = CFErrorCreate(kCFAllocatorDefault, CFSTR("FIX ME"), err, NULL); - } - } - return result; -} - - -/*! - */ -OSStatus SecAccessGetOwnerAndACL(SecAccessRef accessRef, - CSSM_ACL_OWNER_PROTOTYPE_PTR *owner, - uint32 *aclCount, CSSM_ACL_ENTRY_INFO_PTR *acls) -{ - BEGIN_SECAPI - Access::required(accessRef)->copyOwnerAndAcl( - Required(owner), Required(aclCount), Required(acls)); - END_SECAPI -} - -OSStatus SecAccessCopyOwnerAndACL(SecAccessRef accessRef, uid_t* userId, gid_t* groupId, SecAccessOwnerType* ownerType, CFArrayRef* aclList) -{ - CSSM_ACL_OWNER_PROTOTYPE_PTR owner = NULL; - CSSM_ACL_ENTRY_INFO_PTR acls = NULL; - uint32 aclCount = 0; - OSStatus result = SecAccessGetOwnerAndACL(accessRef, &owner, &aclCount, &acls); - if (errSecSuccess != result ) - { - return result; - } - - if (NULL != owner) - { - CSSM_LIST_ELEMENT_PTR listHead = owner->TypedSubject.Head; - if (listHead != NULL && listHead->ElementType == CSSM_LIST_ELEMENT_WORDID) - { - CSSM_LIST_ELEMENT_PTR nextElement = listHead->NextElement; - if (listHead->WordID == CSSM_ACL_SUBJECT_TYPE_PROCESS && listHead->ElementType == CSSM_LIST_ELEMENT_WORDID) - { - // nextElement contains the required data - CSSM_ACL_PROCESS_SUBJECT_SELECTOR* selectorPtr = (CSSM_ACL_PROCESS_SUBJECT_SELECTOR*)nextElement->Element.Word.Data; - if (NULL != selectorPtr) - { - if (NULL != userId) - { - *userId = (uid_t)selectorPtr->uid; - } - - if (NULL != groupId) - { - *groupId = (gid_t)selectorPtr->gid; - } - - if (NULL != ownerType) - { - *ownerType = (SecAccessOwnerType)selectorPtr->mask; - } - } - } - - } - - } - - if (NULL != aclList) - { -#ifndef NDEBUG - CFShow(CFSTR("SecAccessCopyOwnerAndACL: processing the ACL list")); -#endif - - CFMutableArrayRef stringArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - CSSM_ACL_OWNER_PROTOTYPE_PTR protoPtr = NULL; - uint32 numAcls = 0L; - CSSM_ACL_ENTRY_INFO_PTR aclEntry = NULL; - - result = SecAccessGetOwnerAndACL(accessRef, &protoPtr, &numAcls, &aclEntry); - if (errSecSuccess == result) - { -#ifndef NDEBUG - CFStringRef tempStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("SecAccessCopyOwnerAndACL: numAcls = %d"), numAcls); - CFShow(tempStr); - CFRelease(tempStr); -#endif - - for (uint32 iCnt = 0; iCnt < numAcls; iCnt++) - { - CSSM_ACL_ENTRY_PROTOTYPE prototype = aclEntry[iCnt].EntryPublicInfo; - CSSM_AUTHORIZATIONGROUP authGroup = prototype.Authorization; - int numAuthTags = (int)authGroup.NumberOfAuthTags; - - for (int jCnt = 0; jCnt < numAuthTags; jCnt++) - { - - sint32 aTag = authGroup.AuthTags[jCnt]; - CFStringRef aString = GetAuthStringFromACLAuthorizationTag(aTag); - - CFArrayAppendValue(stringArray, aString); - } - } - } - - if (NULL != stringArray) - { - if (0 < CFArrayGetCount(stringArray)) - { - *aclList = CFArrayCreateCopy(kCFAllocatorDefault, stringArray); - } - CFRelease(stringArray); - } - } - - return result; -} - -/*! - */ -OSStatus SecAccessCopyACLList(SecAccessRef accessRef, - CFArrayRef *aclList) -{ - BEGIN_SECAPI - Required(aclList) = Access::required(accessRef)->copySecACLs(); - END_SECAPI -} - - -/*! - */ -OSStatus SecAccessCopySelectedACLList(SecAccessRef accessRef, - CSSM_ACL_AUTHORIZATION_TAG action, - CFArrayRef *aclList) -{ - BEGIN_SECAPI - Required(aclList) = Access::required(accessRef)->copySecACLs(action); - END_SECAPI -} - -CFArrayRef SecAccessCopyMatchingACLList(SecAccessRef accessRef, CFTypeRef authorizationTag) -{ - CFArrayRef result = NULL; - CSSM_ACL_AUTHORIZATION_TAG tag = GetACLAuthorizationTagFromString((CFStringRef)authorizationTag); - OSStatus err = SecAccessCopySelectedACLList(accessRef, tag, &result); - if (errSecSuccess != err) - { - result = NULL; - } - return result; -} - -CFArrayRef copyTrustedAppListFromBundle(CFStringRef bundlePath, CFStringRef trustedAppListFileName) -{ - CFStringRef errorString = nil; - CFURLRef bundleURL,trustedAppsURL = NULL; - CFBundleRef secBundle = NULL; - CFPropertyListRef trustedAppsPlist = NULL; - CFDataRef xmlDataRef = NULL; - SInt32 errorCode; - CFArrayRef trustedAppList = NULL; - CFMutableStringRef trustedAppListFileNameWithoutExtension = NULL; - - // Make a CFURLRef from the CFString representation of the bundleÕs path. - bundleURL = CFURLCreateWithFileSystemPath( - kCFAllocatorDefault,bundlePath,kCFURLPOSIXPathStyle,true); - - CFRange wholeStrRange; - - if (!bundleURL) - goto xit; - - // Make a bundle instance using the URLRef. - secBundle = CFBundleCreate(kCFAllocatorDefault,bundleURL); - if (!secBundle) - goto xit; - - trustedAppListFileNameWithoutExtension = - CFStringCreateMutableCopy(NULL,CFStringGetLength(trustedAppListFileName),trustedAppListFileName); - wholeStrRange = CFStringFind(trustedAppListFileName,CFSTR(".plist"),0); - - CFStringDelete(trustedAppListFileNameWithoutExtension,wholeStrRange); - - // Look for a resource in the bundle by name and type - trustedAppsURL = CFBundleCopyResourceURL(secBundle,trustedAppListFileNameWithoutExtension,CFSTR("plist"),NULL); - if (!trustedAppsURL) - goto xit; - - if ( trustedAppListFileNameWithoutExtension ) - CFRelease(trustedAppListFileNameWithoutExtension); - - if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault,trustedAppsURL,&xmlDataRef,NULL,NULL,&errorCode)) - goto xit; - - trustedAppsPlist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault,xmlDataRef,kCFPropertyListImmutable,&errorString); - trustedAppList = (CFArrayRef)trustedAppsPlist; - -xit: - if (bundleURL) - CFRelease(bundleURL); - if (secBundle) - CFRelease(secBundle); - if (trustedAppsURL) - CFRelease(trustedAppsURL); - if (xmlDataRef) - CFRelease(xmlDataRef); - if (errorString) - CFRelease(errorString); - - return trustedAppList; -} - -OSStatus SecAccessCreateWithTrustedApplications(CFStringRef trustedApplicationsPListPath, CFStringRef accessLabel, Boolean allowAny, SecAccessRef* returnedAccess) -{ - OSStatus err = errSecSuccess; - SecAccessRef accessToReturn=nil; - CFMutableArrayRef trustedApplications=nil; - - if (!allowAny) // use default access ("confirm access") - { - // make an exception list of applications you want to trust, - // which are allowed to access the item without requiring user confirmation - SecTrustedApplicationRef myself=NULL, someOther=NULL; - CFArrayRef trustedAppListFromBundle=NULL; - - trustedApplications=CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks); - err = SecTrustedApplicationCreateFromPath(NULL, &myself); - if (!err) - CFArrayAppendValue(trustedApplications,myself); - - CFURLRef url = CFURLCreateWithFileSystemPath(NULL, trustedApplicationsPListPath, kCFURLPOSIXPathStyle, 0); - CFStringRef leafStr = NULL; - leafStr = CFURLCopyLastPathComponent(url); - - CFURLRef bndlPathURL = NULL; - bndlPathURL = CFURLCreateCopyDeletingLastPathComponent(NULL, url); - CFStringRef bndlPath = NULL; - bndlPath = CFURLCopyFileSystemPath(bndlPathURL, kCFURLPOSIXPathStyle); - trustedAppListFromBundle=copyTrustedAppListFromBundle(bndlPath, leafStr); - if ( leafStr ) - CFRelease(leafStr); - if ( bndlPath ) - CFRelease(bndlPath); - if ( url ) - CFRelease(url); - if ( bndlPathURL ) - CFRelease(bndlPathURL); - if (trustedAppListFromBundle) - { - CFIndex ix,top; - char buffer[MAXPATHLEN]; - top = CFArrayGetCount(trustedAppListFromBundle); - for (ix=0;ix 1)) - { - CFStringRef descStr = (CFStringRef) CFArrayGetValueAtIndex(descArray, 1); - if (descStr) - buf = CFStringToCString(descStr); - } - SecRequirementRef reqRef = NULL; - err = SecRequirementCreateWithString(reqStr, kSecCSDefaultFlags, &reqRef); - if (!err) - err = SecTrustedApplicationCreateFromRequirement((const char *)buf, reqRef, &someOther); - if (buf) - free(buf); - CFReleaseSafe(reqRef); - CFReleaseSafe(descArray); - } - if (!err) - CFArrayAppendValue(trustedApplications,someOther); - - if (someOther) - CFReleaseNull(someOther); - } - CFRelease(trustedAppListFromBundle); - } - } - - err = SecAccessCreate((CFStringRef)accessLabel, (CFArrayRef)trustedApplications, &accessToReturn); - if (!err) - { - if (allowAny) // change access to be wide-open for decryption ("always allow access") - { - // get the access control list for decryption operations - CFArrayRef aclList=nil; - err = SecAccessCopySelectedACLList(accessToReturn, CSSM_ACL_AUTHORIZATION_DECRYPT, &aclList); - if (!err) - { - // get the first entry in the access control list - SecACLRef aclRef=(SecACLRef)CFArrayGetValueAtIndex(aclList, 0); - CFArrayRef appList=nil; - CFStringRef promptDescription=nil; - CSSM_ACL_KEYCHAIN_PROMPT_SELECTOR promptSelector; - err = SecACLCopySimpleContents(aclRef, &appList, &promptDescription, &promptSelector); - - // modify the default ACL to not require the passphrase, and have a nil application list - promptSelector.flags &= ~CSSM_ACL_KEYCHAIN_PROMPT_REQUIRE_PASSPHRASE; - err = SecACLSetSimpleContents(aclRef, NULL, promptDescription, &promptSelector); - - if (appList) CFRelease(appList); - if (promptDescription) CFRelease(promptDescription); - } - } - } - *returnedAccess = accessToReturn; - return err; -} diff --git a/OSX/include/security_keychain/SecAccess.h b/OSX/include/security_keychain/SecAccess.h deleted file mode 100644 index 9464790f..00000000 --- a/OSX/include/security_keychain/SecAccess.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecAccess - SecAccess implements a way to set and manipulate access control rules and - restrictions on SecKeychainItems. -*/ - -#ifndef _SECURITY_SECACCESS_H_ -#define _SECURITY_SECACCESS_H_ - -#include -#include -#include -#include -#include -#include - - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN -CF_IMPLICIT_BRIDGING_ENABLED - -typedef UInt32 SecAccessOwnerType; -enum -{ - kSecUseOnlyUID = 1, - kSecUseOnlyGID = 2, - kSecHonorRoot = 0x100, - kSecMatchBits = (kSecUseOnlyUID | kSecUseOnlyGID) -}; - -/* No restrictions. Permission to perform all operations on - the resource or available to an ACL owner. */ -extern const CFStringRef kSecACLAuthorizationAny - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -extern const CFStringRef kSecACLAuthorizationLogin - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationGenKey - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationDelete - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationExportWrapped - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationExportClear - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationImportWrapped - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationImportClear - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationSign - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationEncrypt - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationDecrypt - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationMAC - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationDerive - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/* Defined authorization tag values for Keychain */ -extern const CFStringRef kSecACLAuthorizationKeychainCreate - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationKeychainDelete - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationKeychainItemRead - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationKeychainItemInsert - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationKeychainItemModify - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationKeychainItemDelete - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -extern const CFStringRef kSecACLAuthorizationChangeACL - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecACLAuthorizationChangeOwner - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecAccessGetTypeID - @abstract Returns the type identifier of SecAccess instances. - @result The CFTypeID of SecAccess instances. -*/ -CFTypeID SecAccessGetTypeID(void); - -/*! - @function SecAccessCreate - @abstract Creates a new SecAccessRef that is set to the currently designated system default - configuration of a (newly created) security object. Note that the precise nature of - this default may change between releases. - @param descriptor The name of the item as it should appear in security dialogs - @param trustedlist A CFArray of TrustedApplicationRefs, specifying which applications - should be allowed to access an item without triggering confirmation dialogs. - If NULL, defaults to (just) the application creating the item. To set no applications, - pass a CFArray with no elements. - @param accessRef On return, a pointer to the new access reference. - @result A result code. See "Security Error Codes" (SecBase.h). -*/ -OSStatus SecAccessCreate(CFStringRef descriptor, CFArrayRef __nullable trustedlist, SecAccessRef * __nonnull CF_RETURNS_RETAINED accessRef); - -/*! - @function SecAccessCreateFromOwnerAndACL - @abstract Creates a new SecAccessRef using the owner and access control list you provide. - @param owner A pointer to a CSSM access control list owner. - @param aclCount An unsigned 32-bit integer representing the number of items in the access control list. - @param acls A pointer to the access control list. - @param On return, a pointer to the new access reference. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion For 10.7 and later please use the SecAccessCreateWithOwnerAndACL API -*/ -OSStatus SecAccessCreateFromOwnerAndACL(const CSSM_ACL_OWNER_PROTOTYPE *owner, uint32 aclCount, const CSSM_ACL_ENTRY_INFO *acls, SecAccessRef * __nonnull CF_RETURNS_RETAINED accessRef) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecAccessCreateWithOwnerAndACL - @abstract Creates a new SecAccessRef using either for a user or a group with a list of ACLs - @param userId An user id that specifies the user to associate with this SecAccessRef. - @param groupId A group id that specifies the group to associate with this SecAccessRef. - @param ownerType Specifies the how the ownership of the new SecAccessRef is defined. - @param acls A CFArrayRef of the ACLs to associate with this SecAccessRef - @param error Optionally a pointer to a CFErrorRef to return any errors with may have occured - @result A pointer to the new access reference. -*/ -__nullable -SecAccessRef SecAccessCreateWithOwnerAndACL(uid_t userId, gid_t groupId, SecAccessOwnerType ownerType, CFArrayRef __nullable acls, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecAccessGetOwnerAndACL - @abstract Retrieves the owner and the access control list of a given access. - @param accessRef A reference to the access from which to retrieve the information. - @param owner On return, a pointer to the access control list owner. - @param aclCount On return, a pointer to an unsigned 32-bit integer representing the number of items in the access control list. - @param acls On return, a pointer to the access control list. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion For 10.7 and later please use the SecAccessCopyOwnerAndACL API - */ -OSStatus SecAccessGetOwnerAndACL(SecAccessRef accessRef, CSSM_ACL_OWNER_PROTOTYPE_PTR __nullable * __nonnull owner, uint32 *aclCount, CSSM_ACL_ENTRY_INFO_PTR __nullable * __nonnull acls) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecAccessCopyOwnerAndACL - @abstract Retrieves the owner and the access control list of a given access. - @param accessRef A reference to the access from which to retrieve the information. - @param userId On return, the user id of the owner - @param groupId On return, the group id of the owner - @param ownerType On return, the type of owner for this AccessRef - @param aclList On return, a pointer to a new created CFArray of SecACL instances. The caller is responsible for calling CFRelease on this array. - @result A result code. See "Security Error Codes" (SecBase.h). - */ -OSStatus SecAccessCopyOwnerAndACL(SecAccessRef accessRef, uid_t * __nullable userId, gid_t * __nullable groupId, SecAccessOwnerType * __nullable ownerType, CFArrayRef * __nullable CF_RETURNS_RETAINED aclList) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecAccessCopyACLList - @abstract Copies all the access control lists of a given access. - @param accessRef A reference to the access from which to retrieve the information. - @param aclList On return, a pointer to a new created CFArray of SecACL instances. The caller is responsible for calling CFRelease on this array. - @result A result code. See "Security Error Codes" (SecBase.h). -*/ -OSStatus SecAccessCopyACLList(SecAccessRef accessRef, CFArrayRef * __nonnull CF_RETURNS_RETAINED aclList); - -/*! - @function SecAccessCopySelectedACLList - @abstract Copies selected access control lists from a given access. - @param accessRef A reference to the access from which to retrieve the information. - @param action An authorization tag specifying what action with which to select the action control lists. - @param aclList On return, a pointer to the selected access control lists. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion For 10.7 and later please use the SecAccessCopyMatchingACLList API -*/ -OSStatus SecAccessCopySelectedACLList(SecAccessRef accessRef, CSSM_ACL_AUTHORIZATION_TAG action, CFArrayRef * __nonnull CF_RETURNS_RETAINED aclList) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - - -/*! - @function SecAccessCopyMatchingACLList - @abstract Copies selected access control lists from a given access. - @param accessRef A reference to the access from which to retrieve the information. - @param authorizationTag An authorization tag specifying what action with which to select the action control lists. - @result A pointer to the selected access control lists. -*/ -__nullable -CFArrayRef SecAccessCopyMatchingACLList(SecAccessRef accessRef, CFTypeRef authorizationTag) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -CF_IMPLICIT_BRIDGING_DISABLED -CF_ASSUME_NONNULL_END - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECACCESS_H_ */ diff --git a/OSX/include/security_keychain/SecAccessPriv.h b/OSX/include/security_keychain/SecAccessPriv.h deleted file mode 100644 index 6b1e5ce2..00000000 --- a/OSX/include/security_keychain/SecAccessPriv.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecAccessPriv - SecAccessPriv implements a way to set and manipulate access control rules and - restrictions on SecKeychainItems. The functions here are private. -*/ - -#ifndef _SECURITY_SECACCESS_PRIV_H_ -#define _SECURITY_SECACCESS_PRIV_H_ - -#include -#include -#include - - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - @function SecKeychainAddIToolsPassword - @abstract Creates a new iTools password using the access control list from iToolsTrustedApps.plist. - @param keychain A reference to the keychain to which to add the password. Pass NULL to add the password to the default keychain. - @param accountNameLength The length of the buffer pointed to by accountName. - @param accountName A pointer to a string containing the account name associated with this password. - @param passwordLength The length of the buffer pointed to by passwordData. - @param passwordData A pointer to a buffer containing the password data to be stored in the keychain. - @param itemRef On return, a reference to the new keychain item. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion The SecKeychainAddIToolsPassword function adds a new iTools password to the specified keychain with an ACL composed of a list of trusted applications. A required parameter to identify the password is the accountName, which is an application-defined string. The servicename will always be "iTools". SecKeychainAddIToolsPassword optionally returns a reference to the newly added item. -*/ - -OSStatus SecKeychainAddIToolsPassword(SecKeychainRef keychain, UInt32 accountNameLength, const char *accountName, - UInt32 passwordLength, const void *passwordData, SecKeychainItemRef *itemRef); - -/*! - @function SecAccessCreateWithTrustedApplications - @abstract Creates a SecAccess object with the specified trusted applications. - @param trustedApplicationsPListPath A full path to the .plist file that contains the trusted applications. The extension must end in ".plist". - @param accessLabel The access label for the new SecAccessRef. - @param allowAny Flag that determines allow access to any application. - @param returnedAccess On return, a new SecAccessRef. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion The SecAccessCreateWithPList creates a SecAccess with the provided list of trusted applications. -*/ - -OSStatus SecAccessCreateWithTrustedApplications(CFStringRef trustedApplicationsPListPath, CFStringRef accessLabel, Boolean allowAny, SecAccessRef* returnedAccess); - - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECACCESS_PRIV_H_ */ diff --git a/OSX/include/security_keychain/SecAsn1TypesP.h b/OSX/include/security_keychain/SecAsn1TypesP.h deleted file mode 100644 index 2a027acb..00000000 --- a/OSX/include/security_keychain/SecAsn1TypesP.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * The contents of this file are subject to the Mozilla Public - * License Version 1.1 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of - * the License at http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS - * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or - * implied. See the License for the specific language governing - * rights and limitations under the License. - * - * The Original Code is the Netscape security libraries. - * - * The Initial Developer of the Original Code is Netscape - * Communications Corporation. Portions created by Netscape are - * Copyright (C) 1994-2000 Netscape Communications Corporation. All - * Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the - * terms of the GNU General Public License Version 2 or later (the - * "GPL"), in which case the provisions of the GPL are applicable - * instead of those above. If you wish to allow use of your - * version of this file only under the terms of the GPL and not to - * allow others to use your version of this file under the MPL, - * indicate your decision by deleting the provisions above and - * replace them with the notice and other provisions required by - * the GPL. If you do not delete the provisions above, a recipient - * may use your version of this file under either the MPL or the - * GPL. - */ - -/* - * Types for encoding/decoding of ASN.1 using BER/DER (Basic/Distinguished - * Encoding Rules). - */ - -#ifndef _SEC_ASN1_TYPES_H_ -#define _SEC_ASN1_TYPES_H_ - -#include /* Boolean */ -#include -#include - -#include -#if 1 /* TARGET_OS_EMBEDDED */ -/* @@@ We need something that tells us which platform we are building - for that let's us distinguish if we are doing an emulator build. */ - -typedef struct { - size_t Length; - uint8_t *Data; -} SecAsn1Item, SecAsn1Oid; - -typedef struct { - SecAsn1Oid algorithm; - SecAsn1Item parameters; -} SecAsn1AlgId; - -typedef struct { - SecAsn1AlgId algorithm; - SecAsn1Item subjectPublicKey; -} SecAsn1PubKeyInfo; - -#else -#include -#include - -typedef CSSM_DATA SecAsn1Item; -typedef CSSM_OID SecAsn1Oid; -typedef CSSM_X509_ALGORITHM_IDENTIFIER SecAsn1AlgId; -typedef CSSM_X509_SUBJECT_PUBLIC_KEY_INFO SecAsn1PubKeyInfo; - -#endif - -/* - * An array of these structures defines a BER/DER encoding for an object. - * - * The array usually starts with a dummy entry whose kind is SEC_ASN1_SEQUENCE; - * such an array is terminated with an entry where kind == 0. (An array - * which consists of a single component does not require a second dummy - * entry -- the array is only searched as long as previous component(s) - * instruct it.) - */ -typedef struct SecAsn1Template_struct { - /* - * Kind of item being decoded/encoded, including tags and modifiers. - */ - uint32_t kind; - - /* - * This value is the offset from the base of the structure (i.e., the - * (void *) passed as 'src' to SecAsn1EncodeItem, or the 'dst' argument - * passed to SecAsn1CoderRef()) to the field that holds the value being - * decoded/encoded. - */ - uint32_t offset; - - /* - * When kind suggests it (e.g., SEC_ASN1_POINTER, SEC_ASN1_GROUP, - * SEC_ASN1_INLINE, or a component that is *not* a SEC_ASN1_UNIVERSAL), - * this points to a sub-template for nested encoding/decoding. - * OR, iff SEC_ASN1_DYNAMIC is set, then this is a pointer to a pointer - * to a function which will return the appropriate template when called - * at runtime. NOTE! that explicit level of indirection, which is - * necessary because ANSI does not allow you to store a function - * pointer directly as a "void *" so we must store it separately and - * dereference it to get at the function pointer itself. - */ - const void *sub; - - /* - * In the first element of a template array, the value is the size - * of the structure to allocate when this template is being referenced - * by another template via SEC_ASN1_POINTER or SEC_ASN1_GROUP. - * In all other cases, the value is ignored. - */ - uint32_t size; -} SecAsn1Template; - - -/* - * BER/DER values for ASN.1 identifier octets. - */ -#define SEC_ASN1_TAG_MASK 0xff - -/* - * BER/DER universal type tag numbers. - */ -#define SEC_ASN1_TAGNUM_MASK 0x1f -#define SEC_ASN1_BOOLEAN 0x01 -#define SEC_ASN1_INTEGER 0x02 -#define SEC_ASN1_BIT_STRING 0x03 -#define SEC_ASN1_OCTET_STRING 0x04 -#define SEC_ASN1_NULL 0x05 -#define SEC_ASN1_OBJECT_ID 0x06 -#define SEC_ASN1_OBJECT_DESCRIPTOR 0x07 -/* External type and instance-of type 0x08 */ -#define SEC_ASN1_REAL 0x09 -#define SEC_ASN1_ENUMERATED 0x0a -#define SEC_ASN1_EMBEDDED_PDV 0x0b -#define SEC_ASN1_UTF8_STRING 0x0c -/* not used 0x0d */ -/* not used 0x0e */ -/* not used 0x0f */ -#define SEC_ASN1_SEQUENCE 0x10 -#define SEC_ASN1_SET 0x11 -#define SEC_ASN1_NUMERIC_STRING 0x12 -#define SEC_ASN1_PRINTABLE_STRING 0x13 -#define SEC_ASN1_T61_STRING 0x14 -#define SEC_ASN1_VIDEOTEX_STRING 0x15 -#define SEC_ASN1_IA5_STRING 0x16 -#define SEC_ASN1_UTC_TIME 0x17 -#define SEC_ASN1_GENERALIZED_TIME 0x18 -#define SEC_ASN1_GRAPHIC_STRING 0x19 -#define SEC_ASN1_VISIBLE_STRING 0x1a -#define SEC_ASN1_GENERAL_STRING 0x1b -#define SEC_ASN1_UNIVERSAL_STRING 0x1c -/* not used 0x1d */ -#define SEC_ASN1_BMP_STRING 0x1e -#define SEC_ASN1_HIGH_TAG_NUMBER 0x1f -#define SEC_ASN1_TELETEX_STRING SEC_ASN1_T61_STRING - -/* - * Modifiers to type tags. These are also specified by a/the - * standard, and must not be changed. - */ -#define SEC_ASN1_METHOD_MASK 0x20 -#define SEC_ASN1_PRIMITIVE 0x00 -#define SEC_ASN1_CONSTRUCTED 0x20 - -#define SEC_ASN1_CLASS_MASK 0xc0 -#define SEC_ASN1_UNIVERSAL 0x00 -#define SEC_ASN1_APPLICATION 0x40 -#define SEC_ASN1_CONTEXT_SPECIFIC 0x80 -#define SEC_ASN1_PRIVATE 0xc0 - -/* - * Our additions, used for templates. - * These are not defined by any standard; the values are used internally only. - * Just be careful to keep them out of the low 8 bits. - */ -#define SEC_ASN1_OPTIONAL 0x00100 -#define SEC_ASN1_EXPLICIT 0x00200 -#define SEC_ASN1_ANY 0x00400 -#define SEC_ASN1_INLINE 0x00800 -#define SEC_ASN1_POINTER 0x01000 -#define SEC_ASN1_GROUP 0x02000 /* with SET or SEQUENCE means - * SET OF or SEQUENCE OF */ -#define SEC_ASN1_DYNAMIC 0x04000 /* subtemplate is found by calling - * a function at runtime */ -#define SEC_ASN1_SKIP 0x08000 /* skip a field; only for decoding */ -#define SEC_ASN1_INNER 0x10000 /* with ANY means capture the - * contents only (not the id, len, - * or eoc); only for decoding */ -#define SEC_ASN1_SAVE 0x20000 /* stash away the encoded bytes first; - * only for decoding */ -#define SEC_ASN1_SKIP_REST 0x80000 /* skip all following fields; - * only for decoding */ -#define SEC_ASN1_CHOICE 0x100000 /* pick one from a template */ - -/* - * Indicate that a type SEC_ASN1_INTEGER is actually signed. - * The default is unsigned, which causes a leading zero to be - * encoded if the MS bit of the source data is 1. - */ -#define SEC_ASN1_SIGNED_INT 0X800000 - -/* Shorthand/Aliases */ -#define SEC_ASN1_SEQUENCE_OF (SEC_ASN1_GROUP | SEC_ASN1_SEQUENCE) -#define SEC_ASN1_SET_OF (SEC_ASN1_GROUP | SEC_ASN1_SET) -#define SEC_ASN1_ANY_CONTENTS (SEC_ASN1_ANY | SEC_ASN1_INNER) - -/* - * Function used for SEC_ASN1_DYNAMIC. - * "arg" is a pointer to the top-level structure being encoded or - * decoded. - * - * "enc" when true, means that we are encoding (false means decoding) - * - * "buf" For decode only; points to the start of the decoded data for - * the current template. Callee can use the tag at this location - * to infer the returned template. Not used on encode. - * - * "Dest" points to the template-specific item being decoded to - * or encoded from. (This is as opposed to arg, which - * points to the start of the struct associated with the - * current array of templates). - */ - -typedef const SecAsn1Template * SecAsn1TemplateChooser( - void *arg, - Boolean enc, - const char *buf, - void *dest); - -typedef SecAsn1TemplateChooser * SecAsn1TemplateChooserPtr; - - -#endif /* _SEC_ASN1_TYPES_H_ */ diff --git a/OSX/include/security_keychain/SecBase.cpp b/OSX/include/security_keychain/SecBase.cpp deleted file mode 100644 index cb7d0152..00000000 --- a/OSX/include/security_keychain/SecBase.cpp +++ /dev/null @@ -1,1120 +0,0 @@ -/* - * Copyright (c) 2003-2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include -#include "SecBridge.h" - -static CFStringRef copyErrorMessageFromBundle(OSStatus status,CFStringRef tableName); - -// caller MUST release the string, since it is gotten with "CFCopyLocalizedStringFromTableInBundle" -// intended use of reserved param is to pass in CFStringRef with name of the Table for lookup -// Will look by default in "SecErrorMessages.strings" in the resources of Security.framework. - - -CFStringRef -SecCopyErrorMessageString(OSStatus status, void *reserved) -{ - try - { - CFStringRef result = copyErrorMessageFromBundle(status,CFSTR("SecErrorMessages")); - if (result == NULL) - result = copyErrorMessageFromBundle(status,CFSTR("SecDebugErrorMessages")); - - if (result == NULL) - { - if (status >= errSecErrnoBase && status <= errSecErrnoLimit) - { - result = CFStringCreateWithFormat (NULL, NULL, CFSTR("UNIX[%s]"), strerror(status-errSecErrnoBase)); - } - else - { - // no error message found, so format a faked-up error message from the status - result = CFStringCreateWithFormat(NULL, NULL, CFSTR("OSStatus %d"), (int)status); - } - } - - return result; - } - catch (...) - { - return NULL; - } -} - - -void -cssmPerror(const char *how, CSSM_RETURN error) -{ - try - { - const char* errMsg = cssmErrorString(error); - fprintf(stderr, "%s: %s\n", how ? how : "error", errMsg); - } - catch (...) - { - fprintf(stderr, "failed to print error: %lu\n", (unsigned long)error); - } -} - - -const char * -cssmErrorString(CSSM_RETURN error) -{ - static ThreadNexus lastError; - - try { - string err; - - if (error >= errSecErrnoBase && error <= errSecErrnoLimit) - { - err = string ("UNIX[") + strerror(error - errSecErrnoBase) + "]"; - } - else - { - CFStringRef result = copyErrorMessageFromBundle(error,CFSTR("SecErrorMessages")); - if (result == NULL) - result = copyErrorMessageFromBundle(error,CFSTR("SecDebugErrorMessages")); - err = cfString(result, true); - } - - if (err.empty()) - { - char buf[200]; - snprintf(buf, sizeof(buf), "unknown error %ld=%lx", (long) error, (long) error); - err = buf; - } - - lastError() = err; - return lastError().c_str(); - } - catch (...) - { - char buf[256]; - snprintf (buf, sizeof (buf), "unknown error %ld=%lx", (long) error, (long) error); - lastError() = buf; - return lastError().c_str(); - } -} - - -static ModuleNexus gBundleLock; - -CFStringRef -copyErrorMessageFromBundle(OSStatus status,CFStringRef tableName) -{ - StLock _lock(gBundleLock()); - - CFStringRef errorString = nil; - CFStringRef keyString = nil; - CFBundleRef secBundle = NULL; - - // Make a bundle instance using the URLRef. - secBundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.security")); - if (!secBundle) - goto xit; - - // Convert status to Int32 string representation, e.g. "-25924" - keyString = CFStringCreateWithFormat (kCFAllocatorDefault,NULL,CFSTR("%d"),(int)status); - if (!keyString) - goto xit; - - errorString = CFCopyLocalizedStringFromTableInBundle(keyString,tableName,secBundle,NULL); - if (CFStringCompare(errorString, keyString, 0)==kCFCompareEqualTo) // no real error message - { - if (errorString) - CFRelease(errorString); - errorString = nil; - } -xit: - if (keyString) - CFRelease(keyString); - - return errorString; -} - -/* Convert a possible CSSM type osStatus error to a more Keychain friendly OSStatus. */ -OSStatus SecKeychainErrFromOSStatus(OSStatus osStatus) -{ - if (CSSM_ERR_IS_CONVERTIBLE(osStatus)) - { - switch (CSSM_ERRCODE(osStatus)) - { - // CONVERTIBLE ERROR CODES. - case CSSM_ERRCODE_SERVICE_NOT_AVAILABLE: - return errSecNotAvailable; - case CSSM_ERRCODE_USER_CANCELED: - return errSecUserCanceled; - case CSSM_ERRCODE_OPERATION_AUTH_DENIED: - return errSecAuthFailed; - case CSSM_ERRCODE_NO_USER_INTERACTION: - return errSecInteractionNotAllowed; - case CSSM_ERRCODE_IN_DARK_WAKE: - return errSecInDarkWake; - case CSSM_ERRCODE_OS_ACCESS_DENIED: - return errSecWrPerm; - case CSSM_ERRCODE_INSUFFICIENT_CLIENT_IDENTIFICATION: - return errSecInsufficientClientID; - case CSSM_ERRCODE_DEVICE_RESET: - return errSecDeviceReset; - case CSSM_ERRCODE_DEVICE_FAILED: - return errSecDeviceFailed; - case CSSM_ERRCODE_INTERNAL_ERROR: - return errSecInternalError; - case CSSM_ERRCODE_MEMORY_ERROR: - return errSecMemoryError; - case CSSM_ERRCODE_MDS_ERROR: - return errSecMDSError; - case CSSM_ERRCODE_INVALID_POINTER: - case CSSM_ERRCODE_INVALID_INPUT_POINTER: - case CSSM_ERRCODE_INVALID_OUTPUT_POINTER: - case CSSM_ERRCODE_INVALID_CERTGROUP_POINTER: - case CSSM_ERRCODE_INVALID_CERT_POINTER: - case CSSM_ERRCODE_INVALID_CRL_POINTER: - case CSSM_ERRCODE_INVALID_FIELD_POINTER: - case CSSM_ERRCODE_INVALID_DB_LIST_POINTER: - return errSecInvalidPointer; - case CSSM_ERRCODE_FUNCTION_NOT_IMPLEMENTED: - return errSecUnimplemented; - case CSSM_ERRCODE_SELF_CHECK_FAILED: - case CSSMERR_CL_SELF_CHECK_FAILED: - case CSSMERR_DL_SELF_CHECK_FAILED: - return errSecSelfCheckFailed; - case CSSM_ERRCODE_FUNCTION_FAILED: - return errSecFunctionFailed; - case CSSM_ERRCODE_MODULE_MANIFEST_VERIFY_FAILED: - return errSecModuleManifestVerifyFailed; - case CSSM_ERRCODE_INVALID_GUID: - return errSecInvalidGUID; - case CSSM_ERRCODE_OBJECT_USE_AUTH_DENIED: - case CSSM_ERRCODE_OBJECT_MANIP_AUTH_DENIED: - return errAuthorizationDenied; - case CSSM_ERRCODE_OBJECT_ACL_NOT_SUPPORTED: - case CSSM_ERRCODE_OBJECT_ACL_REQUIRED: - case CSSM_ERRCODE_INVALID_ACL_SUBJECT_VALUE: - case CSSM_ERRCODE_ACL_SUBJECT_TYPE_NOT_SUPPORTED: - case CSSM_ERRCODE_INVALID_ACL_EDIT_MODE: - case CSSM_ERRCODE_INVALID_NEW_ACL_ENTRY: - case CSSM_ERRCODE_INVALID_NEW_ACL_OWNER: - return errSecInvalidACL; - case CSSM_ERRCODE_INVALID_ACCESS_CREDENTIALS: - return errSecInvalidAccessCredentials; - case CSSM_ERRCODE_INVALID_ACL_BASE_CERTS: - case CSSM_ERRCODE_ACL_BASE_CERTS_NOT_SUPPORTED: - return errSecInvalidCertificateGroup; - case CSSM_ERRCODE_INVALID_SAMPLE_VALUE: - return errSecInvalidSampleValue; - case CSSM_ERRCODE_SAMPLE_VALUE_NOT_SUPPORTED: - return errSecInvalidSampleValue; - case CSSM_ERRCODE_INVALID_ACL_CHALLENGE_CALLBACK: - return errSecInvalidCallback; - case CSSM_ERRCODE_ACL_CHALLENGE_CALLBACK_FAILED: - return errSecCallbackFailed; - case CSSM_ERRCODE_INVALID_ACL_ENTRY_TAG: - case CSSM_ERRCODE_UNKNOWN_TAG: - return errSecUnknownTag; - case CSSM_ERRCODE_ACL_ENTRY_TAG_NOT_FOUND: - return errSecTagNotFound; - case CSSM_ERRCODE_ACL_CHANGE_FAILED: - return errSecACLChangeFailed; - case CSSM_ERRCODE_ACL_DELETE_FAILED: - return errSecACLDeleteFailed; - case CSSM_ERRCODE_ACL_REPLACE_FAILED: - return errSecACLReplaceFailed; - case CSSM_ERRCODE_ACL_ADD_FAILED: - return errSecACLAddFailed; - case CSSM_ERRCODE_INVALID_CONTEXT_HANDLE: - case CSSM_ERRCODE_INVALID_DB_HANDLE: - case CSSM_ERRCODE_INVALID_CSP_HANDLE: - case CSSM_ERRCODE_INVALID_DL_HANDLE: - case CSSM_ERRCODE_INVALID_CL_HANDLE: - case CSSM_ERRCODE_INVALID_TP_HANDLE: - case CSSM_ERRCODE_INVALID_KR_HANDLE: - case CSSM_ERRCODE_INVALID_AC_HANDLE: - return errSecInvalidHandle; - case CSSM_ERRCODE_INCOMPATIBLE_VERSION: - return errSecIncompatibleVersion; - case CSSM_ERRCODE_INVALID_DATA: - return errSecInvalidData; - case CSSM_ERRCODE_CRL_ALREADY_SIGNED: - return errSecCRLAlreadySigned; - case CSSM_ERRCODE_INVALID_NUMBER_OF_FIELDS: - return errSecInvalidNumberOfFields; - case CSSM_ERRCODE_VERIFICATION_FAILURE: - return errSecVerificationFailure; - case CSSM_ERRCODE_PRIVILEGE_NOT_GRANTED: - return errSecPrivilegeNotGranted; - case CSSM_ERRCODE_INVALID_DB_LIST: - return errSecInvalidDBList; - case CSSM_ERRCODE_UNKNOWN_FORMAT: - return errSecUnknownFormat; - case CSSM_ERRCODE_INVALID_PASSTHROUGH_ID: - return errSecInvalidPassthroughID; - case CSSM_ERRCODE_INVALID_NETWORK_ADDR: - return errSecInvalidNetworkAddress; - case CSSM_ERRCODE_INVALID_CRYPTO_DATA: - return errSecInvalidData; - } - } - switch (osStatus) - { - // Some CSSM errors mapped to OSStatus-type (SnowLeopard and earlier). - // - case CSSMERR_DL_RECORD_NOT_FOUND: - case CSSMERR_APPLETP_CERT_NOT_FOUND_FROM_ISSUER: - case CSSMERR_CSP_PRIVATE_KEY_NOT_FOUND: - return errSecItemNotFound; - case CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA: - case CSSMERR_CSP_PRIVATE_KEY_ALREADY_EXISTS: - case CSSMERR_CSP_KEY_LABEL_ALREADY_EXISTS: - return errSecDuplicateItem; - case CSSMERR_DL_DATABASE_CORRUPT: - return errSecInvalidKeychain; - case CSSMERR_DL_DATASTORE_DOESNOT_EXIST: - return errSecNoSuchKeychain; - case CSSMERR_DL_DATASTORE_ALREADY_EXISTS: - return errSecDuplicateKeychain; - case CSSMERR_APPLEDL_DISK_FULL: - return errSecDskFull; - case CSSMERR_DL_INVALID_OPEN_PARAMETERS: - case CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS: - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_PARAM: - return errSecParam; - case CSSMERR_DL_INVALID_FIELD_NAME: - case CSSMERR_CSSM_INVALID_ATTRIBUTE: - return errSecNoSuchAttr; - case CSSMERR_DL_OS_ACCESS_DENIED: - case CSSMERR_CSP_OS_ACCESS_DENIED: - case CSSMERR_TP_OS_ACCESS_DENIED: - case CSSMERR_AC_OS_ACCESS_DENIED: - case CSSMERR_CL_OS_ACCESS_DENIED: - return errSecWrPerm; - case CSSMERR_CSSM_BUFFER_TOO_SMALL: - return errSecBufferTooSmall; - case CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED: - case CSSMERR_CSP_FUNCTION_NOT_IMPLEMENTED: - case CSSMERR_TP_FUNCTION_NOT_IMPLEMENTED: - case CSSMERR_AC_FUNCTION_NOT_IMPLEMENTED: - case CSSMERR_CL_FUNCTION_NOT_IMPLEMENTED: - case CSSMERR_DL_FUNCTION_NOT_IMPLEMENTED: - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_UNIMPL: - return errSecUnimplemented; - case CSSMERR_CSSM_INTERNAL_ERROR: - case CSSMERR_CSP_INTERNAL_ERROR: - case CSSMERR_TP_INTERNAL_ERROR: - case CSSMERR_AC_INTERNAL_ERROR: - case CSSMERR_CL_INTERNAL_ERROR: - case CSSMERR_DL_INTERNAL_ERROR: - return errSecInternalError; - case CSSMERR_CSSM_MEMORY_ERROR: - case CSSMERR_CSP_MEMORY_ERROR: - case CSSMERR_TP_MEMORY_ERROR: - case CSSMERR_AC_MEMORY_ERROR: - case CSSMERR_CSP_DEVICE_MEMORY_ERROR: - case CSSMERR_CL_MEMORY_ERROR: - case CSSMERR_DL_MEMORY_ERROR: - return errSecMemoryError; - case CSSMERR_CSSM_MDS_ERROR: - case CSSMERR_CSP_MDS_ERROR: - case CSSMERR_TP_MDS_ERROR: - case CSSMERR_AC_MDS_ERROR: - case CSSMERR_CL_MDS_ERROR: - case CSSMERR_DL_MDS_ERROR: - return errSecMDSError; - case CSSMERR_CSSM_INVALID_POINTER: - case CSSMERR_CSP_INVALID_POINTER: - case CSSMERR_TP_INVALID_POINTER: - case CSSMERR_AC_INVALID_POINTER: - case CSSMERR_CL_INVALID_POINTER: - case CSSMERR_DL_INVALID_POINTER: - case CSSMERR_CSSM_INVALID_INPUT_POINTER: - case CSSMERR_CSP_INVALID_INPUT_POINTER: - case CSSMERR_TP_INVALID_INPUT_POINTER: - case CSSMERR_AC_INVALID_INPUT_POINTER: - case CSSMERR_CL_INVALID_INPUT_POINTER: - case CSSMERR_DL_INVALID_INPUT_POINTER: - case CSSMERR_TP_INVALID_DB_LIST_POINTER: - case CSSMERR_AC_INVALID_DB_LIST_POINTER: - case CSSMERR_DL_INVALID_DB_LIST_POINTER: - case CSSMERR_TP_INVALID_CERTGROUP_POINTER: - case CSSMERR_TP_INVALID_CERT_POINTER: - case CSSMERR_TP_INVALID_CRL_POINTER: - case CSSMERR_TP_INVALID_FIELD_POINTER: - case CSSMERR_CSP_INVALID_KEY_POINTER: - case CSSMERR_TP_INVALID_CALLERAUTH_CONTEXT_POINTER: - case CSSMERR_TP_INVALID_IDENTIFIER_POINTER: - case CSSMERR_TP_INVALID_CRLGROUP_POINTER: - case CSSMERR_TP_INVALID_TUPLEGROUP_POINTER: - case CSSMERR_CL_INVALID_CERTGROUP_POINTER: - case CSSMERR_CL_INVALID_CERT_POINTER: - case CSSMERR_CL_INVALID_CRL_POINTER: - case CSSMERR_CL_INVALID_FIELD_POINTER: - case CSSMERR_CL_INVALID_BUNDLE_POINTER: - case CSSMERR_CSSM_INVALID_OUTPUT_POINTER: - case CSSMERR_CSP_INVALID_OUTPUT_POINTER: - case CSSMERR_TP_INVALID_OUTPUT_POINTER: - case CSSMERR_AC_INVALID_OUTPUT_POINTER: - case CSSMERR_CL_INVALID_OUTPUT_POINTER: - case CSSMERR_DL_INVALID_OUTPUT_POINTER: - return errSecInvalidPointer; - case CSSMERR_CSSM_FUNCTION_FAILED: - case CSSMERR_CSP_FUNCTION_FAILED: - case CSSMERR_TP_FUNCTION_FAILED: - case CSSMERR_AC_FUNCTION_FAILED: - case CSSMERR_CL_FUNCTION_FAILED: - case CSSMERR_DL_FUNCTION_FAILED: - return errSecFunctionFailed; - case CSSMERR_CSP_INVALID_DATA: - case CSSMERR_TP_INVALID_DATA: - case CSSMERR_AC_INVALID_DATA: - case CSSMERR_CL_INVALID_DATA: - case CSSMERR_CSP_INVALID_CRYPTO_DATA: - case CSSMERR_CSP_INVALID_DATA_COUNT: - case CSSMERR_TP_INVALID_ACTION_DATA: - return errSecInvalidData; - case CSSMERR_TP_INVALID_DB_LIST: - case CSSMERR_AC_INVALID_DB_LIST: - return errSecInvalidDBList; - case CSSMERR_CSP_INVALID_PASSTHROUGH_ID: - case CSSMERR_TP_INVALID_PASSTHROUGH_ID: - case CSSMERR_AC_INVALID_PASSTHROUGH_ID: - case CSSMERR_CL_INVALID_PASSTHROUGH_ID: - case CSSMERR_DL_INVALID_PASSTHROUGH_ID: - return errSecInvalidPassthroughID; - case CSSMERR_TP_INVALID_CSP_HANDLE: - case CSSMERR_TP_INVALID_CL_HANDLE: - case CSSMERR_TP_INVALID_DL_HANDLE: - case CSSMERR_AC_INVALID_TP_HANDLE: - case CSSMERR_AC_INVALID_DL_HANDLE: - case CSSMERR_DL_INVALID_DL_HANDLE: - case CSSMERR_AC_INVALID_CL_HANDLE: - case CSSMERR_DL_INVALID_CL_HANDLE: - case CSSMERR_DL_INVALID_CSP_HANDLE: - case CSSMERR_TP_INVALID_DB_HANDLE: - case CSSMERR_CSSM_INVALID_ADDIN_HANDLE: - case CSSMERR_CSSM_INVALID_CONTEXT_HANDLE: - case CSSMERR_CL_INVALID_CACHE_HANDLE: - case CSSMERR_CL_INVALID_RESULTS_HANDLE: - case CSSMERR_DL_INVALID_RESULTS_HANDLE: - case CSSMERR_TP_INVALID_KEYCACHE_HANDLE: - case CSSMERR_CSP_INVALID_CONTEXT_HANDLE: - case CSSMERR_TP_INVALID_CONTEXT_HANDLE: - case CSSMERR_AC_INVALID_CONTEXT_HANDLE: - case CSSMERR_CL_INVALID_CONTEXT_HANDLE: - return errSecInvalidHandle; - case CSSMERR_TP_CRL_ALREADY_SIGNED: - case CSSMERR_CL_CRL_ALREADY_SIGNED: - return errSecCRLAlreadySigned; - case CSSMERR_TP_INVALID_NUMBER_OF_FIELDS: - case CSSMERR_CL_INVALID_NUMBER_OF_FIELDS: - return errSecInvalidNumberOfFields; - case CSSMERR_TP_VERIFICATION_FAILURE: - case CSSMERR_CL_VERIFICATION_FAILURE: - return errSecVerificationFailure; - case CSSMERR_TP_INVALID_NETWORK_ADDR: - case CSSMERR_DL_INVALID_NETWORK_ADDR: - return errSecInvalidNetworkAddress; - case CSSMERR_TP_UNKNOWN_TAG: - case CSSMERR_CL_UNKNOWN_TAG: - case CSSMERR_CSP_INVALID_ACL_ENTRY_TAG: - case CSSMERR_DL_INVALID_ACL_ENTRY_TAG: - case CSSMERR_DL_INVALID_SELECTION_TAG: - return errSecUnknownTag; - case CSSMERR_CSP_INVALID_SIGNATURE: - case CSSMERR_TP_INVALID_SIGNATURE: - return errSecInvalidSignature; - case CSSMERR_CSSM_USER_CANCELED: - case CSSMERR_CSP_USER_CANCELED: - case CSSMERR_TP_USER_CANCELED: - case CSSMERR_AC_USER_CANCELED: - case CSSMERR_CL_USER_CANCELED: - case CSSMERR_DL_USER_CANCELED: - return errSecUserCanceled; - case CSSMERR_CSSM_NO_USER_INTERACTION: - case CSSMERR_CSP_NO_USER_INTERACTION: - case CSSMERR_TP_NO_USER_INTERACTION: - case CSSMERR_AC_NO_USER_INTERACTION: - case CSSMERR_CL_NO_USER_INTERACTION: - case CSSMERR_DL_NO_USER_INTERACTION: - return errSecInteractionNotAllowed; - case CSSMERR_CSSM_IN_DARK_WAKE: - case CSSMERR_CSP_IN_DARK_WAKE: - case CSSMERR_TP_IN_DARK_WAKE: - case CSSMERR_AC_IN_DARK_WAKE: - case CSSMERR_CL_IN_DARK_WAKE: - case CSSMERR_DL_IN_DARK_WAKE: - return errSecInDarkWake; - case CSSMERR_CSSM_SERVICE_NOT_AVAILABLE: - case CSSMERR_CSP_SERVICE_NOT_AVAILABLE: - case CSSMERR_TP_SERVICE_NOT_AVAILABLE: - case CSSMERR_AC_SERVICE_NOT_AVAILABLE: - case CSSMERR_CL_SERVICE_NOT_AVAILABLE: - case CSSMERR_DL_SERVICE_NOT_AVAILABLE: - return errSecServiceNotAvailable; - case CSSMERR_CSSM_INSUFFICIENT_CLIENT_IDENTIFICATION: - case CSSMERR_CSP_INSUFFICIENT_CLIENT_IDENTIFICATION: - case CSSMERR_TP_INSUFFICIENT_CLIENT_IDENTIFICATION: - case CSSMERR_AC_INSUFFICIENT_CLIENT_IDENTIFICATION: - case CSSMERR_CL_INSUFFICIENT_CLIENT_IDENTIFICATION: - case CSSMERR_DL_INSUFFICIENT_CLIENT_IDENTIFICATION: - return errSecInsufficientClientID; - case CSSMERR_CSSM_DEVICE_RESET: - case CSSMERR_CSP_DEVICE_RESET: - case CSSMERR_TP_DEVICE_RESET: - case CSSMERR_AC_DEVICE_RESET: - case CSSMERR_CL_DEVICE_RESET: - case CSSMERR_DL_DEVICE_RESET: - return errSecDeviceReset; - case CSSMERR_CSSM_DEVICE_FAILED: - case CSSMERR_CSP_DEVICE_FAILED: - case CSSMERR_TP_DEVICE_FAILED: - case CSSMERR_AC_DEVICE_FAILED: - case CSSMERR_CL_DEVICE_FAILED: - case CSSMERR_DL_DEVICE_FAILED: - return errSecDeviceFailed; - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_AUTH: - case CSSMERR_CSSM_EMM_AUTHENTICATE_FAILED: - case CSSMERR_CSSM_ADDIN_AUTHENTICATE_FAILED: - case CSSMERR_CSP_OPERATION_AUTH_DENIED: - case CSSMERR_CSP_OBJECT_USE_AUTH_DENIED: - case CSSMERR_CSP_OBJECT_MANIP_AUTH_DENIED: - case CSSMERR_TP_AUTHENTICATION_FAILED: - case CSSMERR_DL_OPERATION_AUTH_DENIED: - case CSSMERR_DL_OBJECT_USE_AUTH_DENIED: - case CSSMERR_DL_OBJECT_MANIP_AUTH_DENIED: - return errAuthorizationDenied; - case CSSMERR_CSSM_SCOPE_NOT_SUPPORTED: - case CSSMERR_CL_SCOPE_NOT_SUPPORTED: - case CSSMERR_CL_INVALID_SCOPE: - return errSecInvalidScope; - case CSSMERR_TP_INVALID_NAME: - case CSSMERR_DL_INVALID_DB_NAME: - return errSecInvalidName; - case CSSMERR_APPLETP_BAD_CERT_FROM_ISSUER: - case CSSMERR_TP_INVALID_CERTIFICATE: - case CSSMERR_TP_INVALID_ANCHOR_CERT: - case CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT: - case CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT: - return errSecInvalidCertificateRef; - case CSSMERR_CSP_ACL_ENTRY_TAG_NOT_FOUND: - case CSSMERR_DL_ACL_ENTRY_TAG_NOT_FOUND: - return errSecTagNotFound; - case CSSMERR_DL_UNSUPPORTED_QUERY: - case CSSMERR_DL_INVALID_QUERY: - return errSecInvalidQuery; - case CSSMERR_CSP_INVALID_ACL_CHALLENGE_CALLBACK: - case CSSMERR_TP_INVALID_CALLBACK: - case CSSMERR_DL_INVALID_ACL_CHALLENGE_CALLBACK: - return errSecInvalidCallback; - case CSSMERR_CSP_ACL_CHALLENGE_CALLBACK_FAILED: - case CSSMERR_CSP_CRYPTO_DATA_CALLBACK_FAILED: - case CSSMERR_DL_ACL_CHALLENGE_CALLBACK_FAILED: - return errSecCallbackFailed; - case CSSMERR_TP_INVALID_CERTGROUP: - case CSSMERR_TP_CERTGROUP_INCOMPLETE: - case CSSMERR_DL_INVALID_ACL_BASE_CERTS: - case CSSMERR_DL_ACL_BASE_CERTS_NOT_SUPPORTED: - case CSSMERR_CSP_INVALID_ACL_BASE_CERTS: - return errSecInvalidCertificateGroup; - case CSSMERR_CSP_ACL_DELETE_FAILED: - case CSSMERR_DL_ACL_DELETE_FAILED: - return errSecACLDeleteFailed; - case CSSMERR_CSP_ACL_REPLACE_FAILED: - case CSSMERR_DL_ACL_REPLACE_FAILED: - return errSecACLReplaceFailed; - case CSSMERR_CSP_ACL_ADD_FAILED: - case CSSMERR_DL_ACL_ADD_FAILED: - return errSecACLAddFailed; - case CSSMERR_DL_ACL_CHANGE_FAILED: - case CSSMERR_CSP_ACL_CHANGE_FAILED: - return errSecACLChangeFailed; - case CSSMERR_CSSM_PRIVILEGE_NOT_GRANTED: - case CSSMERR_CSP_PRIVILEGE_NOT_GRANTED: - return errSecPrivilegeNotGranted; - case CSSMERR_CSP_INVALID_ACCESS_CREDENTIALS: - case CSSMERR_DL_INVALID_ACCESS_CREDENTIALS: - return errSecInvalidAccessCredentials; - case CSSMERR_DL_INVALID_RECORD_INDEX: - case CSSMERR_DL_INVALID_RECORDTYPE: - case CSSMERR_DL_UNSUPPORTED_RECORDTYPE: - case CSSMERR_DL_INVALID_RECORD_UID: - case CSSMERR_DL_STALE_UNIQUE_RECORD: - return errSecInvalidRecord; - case CSSMERR_CSP_INVALID_KEY: - case CSSMERR_CSP_INVALID_KEY_REFERENCE: - case CSSMERR_CSP_INVALID_KEY_CLASS: - return errSecInvalidKeyRef; - case CSSMERR_CSP_OBJECT_ACL_NOT_SUPPORTED: - case CSSMERR_CSP_OBJECT_ACL_REQUIRED: - case CSSMERR_CSP_ACL_BASE_CERTS_NOT_SUPPORTED: - case CSSMERR_CSP_INVALID_ACL_SUBJECT_VALUE: - case CSSMERR_CSP_ACL_SUBJECT_TYPE_NOT_SUPPORTED: - case CSSMERR_DL_OBJECT_ACL_NOT_SUPPORTED: - case CSSMERR_DL_OBJECT_ACL_REQUIRED: - case CSSMERR_DL_INVALID_ACL_SUBJECT_VALUE: - case CSSMERR_DL_ACL_SUBJECT_TYPE_NOT_SUPPORTED: - case CSSMERR_DL_INVALID_NEW_ACL_ENTRY: - case CSSMERR_DL_INVALID_NEW_ACL_OWNER: - case CSSMERR_DL_INVALID_ACL_EDIT_MODE: - case CSSMERR_CSP_INVALID_ACL_EDIT_MODE: - case CSSMERR_CSP_INVALID_NEW_ACL_ENTRY: - case CSSMERR_CSP_INVALID_NEW_ACL_OWNER: - return errSecInvalidACL; - case CSSMERR_CSP_INVALID_SAMPLE_VALUE: - case CSSMERR_DL_INVALID_SAMPLE_VALUE: - case CSSMERR_CSP_SAMPLE_VALUE_NOT_SUPPORTED: - case CSSMERR_DL_SAMPLE_VALUE_NOT_SUPPORTED: - return errSecInvalidSampleValue; - case CSSMERR_TP_UNKNOWN_FORMAT: - case CSSMERR_CL_UNKNOWN_FORMAT: - return errSecUnknownFormat; - case CSSMERR_CSP_APPLE_ADD_APPLICATION_ACL_SUBJECT: - return errSecAppleAddAppACLSubject; - case CSSMERR_CSP_APPLE_PUBLIC_KEY_INCOMPLETE: - return errSecApplePublicKeyIncomplete; - case CSSMERR_CSP_APPLE_SIGNATURE_MISMATCH: - return errSecAppleSignatureMismatch; - case CSSMERR_CSP_APPLE_INVALID_KEY_START_DATE: - return errSecAppleInvalidKeyStartDate; - case CSSMERR_CSP_APPLE_INVALID_KEY_END_DATE: - return errSecAppleInvalidKeyEndDate; - case CSSMERR_CSPDL_APPLE_DL_CONVERSION_ERROR: - return errSecConversionError; - case CSSMERR_CSP_APPLE_SSLv2_ROLLBACK: - return errSecAppleSSLv2Rollback; - case CSSMERR_APPLEDL_QUOTA_EXCEEDED: - return errSecQuotaExceeded; - case CSSMERR_APPLEDL_FILE_TOO_BIG: - return errSecFileTooBig; - case CSSMERR_APPLEDL_INVALID_DATABASE_BLOB: - return errSecInvalidDatabaseBlob; - case CSSMERR_APPLEDL_INVALID_KEY_BLOB: - return errSecInvalidKeyBlob; - case CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB: - return errSecIncompatibleDatabaseBlob; - case CSSMERR_APPLEDL_INCOMPATIBLE_KEY_BLOB: - return errSecIncompatibleKeyBlob; - case CSSMERR_APPLETP_HOSTNAME_MISMATCH: - return errSecHostNameMismatch; - case CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN: - return errSecUnknownCriticalExtensionFlag; - case CSSMERR_APPLETP_NO_BASIC_CONSTRAINTS: - return errSecNoBasicConstraints; - case CSSMERR_APPLETP_INVALID_AUTHORITY_ID: - return errSecInvalidAuthorityKeyID; - case CSSMERR_APPLETP_INVALID_SUBJECT_ID: - return errSecInvalidSubjectKeyID; - case CSSMERR_APPLETP_INVALID_KEY_USAGE: - return errSecInvalidKeyUsageForPolicy; - case CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE: - return errSecInvalidExtendedKeyUsage; - case CSSMERR_APPLETP_INVALID_ID_LINKAGE: - return errSecInvalidIDLinkage; - case CSSMERR_APPLETP_PATH_LEN_CONSTRAINT: - return errSecPathLengthConstraintExceeded; - case CSSMERR_APPLETP_INVALID_ROOT: - return errSecInvalidRoot; - case CSSMERR_APPLETP_CRL_EXPIRED: - return errSecCRLExpired; - case CSSMERR_APPLETP_CRL_NOT_VALID_YET: - return errSecCRLNotValidYet; - case CSSMERR_APPLETP_CRL_NOT_FOUND: - return errSecCRLNotFound; - case CSSMERR_APPLETP_CRL_SERVER_DOWN: - return errSecCRLServerDown; - case CSSMERR_APPLETP_CRL_BAD_URI: - return errSecCRLBadURI; - case CSSMERR_APPLETP_UNKNOWN_CERT_EXTEN: - return errSecUnknownCertExtension; - case CSSMERR_APPLETP_UNKNOWN_CRL_EXTEN: - return errSecUnknownCRLExtension; - case CSSMERR_APPLETP_CRL_NOT_TRUSTED: - return errSecCRLNotTrusted; - case CSSMERR_APPLETP_CRL_POLICY_FAIL: - return errSecCRLPolicyFailed; - case CSSMERR_APPLETP_IDP_FAIL: - return errSecIDPFailure; - case CSSMERR_APPLETP_SMIME_EMAIL_ADDRS_NOT_FOUND: - return errSecSMIMEEmailAddressesNotFound; - case CSSMERR_APPLETP_SMIME_BAD_EXT_KEY_USE: - return errSecSMIMEBadExtendedKeyUsage; - case CSSMERR_APPLETP_SMIME_BAD_KEY_USE: - return errSecSMIMEBadKeyUsage; - case CSSMERR_APPLETP_SMIME_KEYUSAGE_NOT_CRITICAL: - return errSecSMIMEKeyUsageNotCritical; - case CSSMERR_APPLETP_SMIME_NO_EMAIL_ADDRS: - return errSecSMIMENoEmailAddress; - case CSSMERR_APPLETP_SMIME_SUBJ_ALT_NAME_NOT_CRIT: - return errSecSMIMESubjAltNameNotCritical; - case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE: - return errSecSSLBadExtendedKeyUsage; - case CSSMERR_APPLETP_OCSP_BAD_RESPONSE: - return errSecOCSPBadResponse; - case CSSMERR_APPLETP_OCSP_BAD_REQUEST: - return errSecOCSPBadRequest; - case CSSMERR_APPLETP_OCSP_UNAVAILABLE: - return errSecOCSPUnavailable; - case CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED: - return errSecOCSPStatusUnrecognized; - case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK: - return errSecIncompleteCertRevocationCheck; - case CSSMERR_APPLETP_NETWORK_FAILURE: - return errSecNetworkFailure; - case CSSMERR_APPLETP_OCSP_NOT_TRUSTED: - return errSecOCSPNotTrustedToAnchor; - case CSSMERR_APPLETP_OCSP_SIG_ERROR: - return errSecOCSPSignatureError; - case CSSMERR_APPLETP_OCSP_NO_SIGNER: - return errSecOCSPNoSigner; - case CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ: - return errSecOCSPResponderMalformedReq; - case CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR: - return errSecOCSPResponderInternalError; - case CSSMERR_APPLETP_OCSP_RESP_TRY_LATER: - return errSecOCSPResponderTryLater; - case CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED: - return errSecOCSPResponderSignatureRequired; - case CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED: - return errSecOCSPResponderUnauthorized; - case CSSMERR_APPLETP_OCSP_NONCE_MISMATCH: - return errSecOCSPResponseNonceMismatch; - case CSSMERR_APPLETP_CS_BAD_CERT_CHAIN_LENGTH: - return errSecCodeSigningBadCertChainLength; - case CSSMERR_APPLETP_CS_NO_BASIC_CONSTRAINTS: - return errSecCodeSigningNoBasicConstraints; - case CSSMERR_APPLETP_CS_BAD_PATH_LENGTH: - return errSecCodeSigningBadPathLengthConstraint; - case CSSMERR_APPLETP_CS_NO_EXTENDED_KEY_USAGE: - return errSecCodeSigningNoExtendedKeyUsage; - case CSSMERR_APPLETP_CODE_SIGN_DEVELOPMENT: - return errSecCodeSigningDevelopment; - case CSSMERR_APPLETP_RS_BAD_CERT_CHAIN_LENGTH: - return errSecResourceSignBadCertChainLength; - case CSSMERR_APPLETP_RS_BAD_EXTENDED_KEY_USAGE: - return errSecResourceSignBadExtKeyUsage; - case CSSMERR_APPLETP_TRUST_SETTING_DENY: - return errSecTrustSettingDeny; - case CSSMERR_APPLETP_INVALID_EMPTY_SUBJECT: - return errSecInvalidSubjectName; - case CSSMERR_APPLETP_UNKNOWN_QUAL_CERT_STATEMENT: - return errSecUnknownQualifiedCertStatement; - case CSSMERR_APPLETP_MISSING_REQUIRED_EXTENSION: - return errSecMissingRequiredExtension; - case CSSMERR_APPLETP_EXT_KEYUSAGE_NOT_CRITICAL: - return errSecExtendedKeyUsageNotCritical; - case CSSMERR_APPLE_DOTMAC_REQ_QUEUED: - return errSecMobileMeRequestQueued; - case CSSMERR_APPLE_DOTMAC_REQ_REDIRECT: - return errSecMobileMeRequestRedirected; - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_ERR: - return errSecMobileMeServerError; - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_NOT_AVAIL: - return errSecMobileMeServerNotAvailable; - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_ALREADY_EXIST: - return errSecMobileMeServerAlreadyExists; - case CSSMERR_APPLE_DOTMAC_REQ_SERVER_SERVICE_ERROR: - return errSecMobileMeServerServiceErr; - case CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING: - return errSecMobileMeRequestAlreadyPending; - case CSSMERR_APPLE_DOTMAC_NO_REQ_PENDING: - return errSecMobileMeNoRequestPending; - case CSSMERR_APPLE_DOTMAC_CSR_VERIFY_FAIL: - return errSecMobileMeCSRVerifyFailure; - case CSSMERR_APPLE_DOTMAC_FAILED_CONSISTENCY_CHECK: - return errSecMobileMeFailedConsistencyCheck; - case CSSMERR_CSSM_NOT_INITIALIZED: - return errSecNotInitialized; - case CSSMERR_CSSM_INVALID_HANDLE_USAGE: - return errSecInvalidHandleUsage; - case CSSMERR_CSSM_PVC_REFERENT_NOT_FOUND: - return errSecPVCReferentNotFound; - case CSSMERR_CSSM_FUNCTION_INTEGRITY_FAIL: - return errSecFunctionIntegrityFail; - case CSSMERR_CSSM_SELF_CHECK_FAILED: - case CSSMERR_CSP_SELF_CHECK_FAILED: - return errSecSelfCheckFailed; - case CSSMERR_CSSM_MODULE_MANIFEST_VERIFY_FAILED: - return errSecModuleManifestVerifyFailed; - case CSSMERR_CSSM_INVALID_GUID: - return errSecInvalidGUID; - case CSSMERR_CSSM_INCOMPATIBLE_VERSION: - return errSecIncompatibleVersion; - case CSSMERR_CSSM_PVC_ALREADY_CONFIGURED: - return errSecPVCAlreadyConfigured; - case CSSMERR_CSSM_INVALID_PVC: - return errSecInvalidPVC; - case CSSMERR_CSSM_EMM_LOAD_FAILED: - return errSecEMMLoadFailed; - case CSSMERR_CSSM_EMM_UNLOAD_FAILED: - return errSecEMMUnloadFailed; - case CSSMERR_CSSM_ADDIN_LOAD_FAILED: - return errSecAddinLoadFailed; - case CSSMERR_CSSM_INVALID_KEY_HIERARCHY: - return errSecInvalidKeyHierarchy; - case CSSMERR_CSSM_ADDIN_UNLOAD_FAILED: - return errSecAddinUnloadFailed; - case CSSMERR_CSSM_LIB_REF_NOT_FOUND: - return errSecLibraryReferenceNotFound; - case CSSMERR_CSSM_INVALID_ADDIN_FUNCTION_TABLE: - return errSecInvalidAddinFunctionTable; - case CSSMERR_CSSM_INVALID_SERVICE_MASK: - return errSecInvalidServiceMask; - case CSSMERR_CSSM_MODULE_NOT_LOADED: - return errSecModuleNotLoaded; - case CSSMERR_CSSM_INVALID_SUBSERVICEID: - return errSecInvalidSubServiceID; - case CSSMERR_CSSM_ATTRIBUTE_NOT_IN_CONTEXT: - return errSecAttributeNotInContext; - case CSSMERR_CSSM_MODULE_MANAGER_INITIALIZE_FAIL: - return errSecModuleManagerInitializeFailed; - case CSSMERR_CSSM_MODULE_MANAGER_NOT_FOUND: - return errSecModuleManagerNotFound; - case CSSMERR_CSSM_EVENT_NOTIFICATION_CALLBACK_NOT_FOUND: - return errSecEventNotificationCallbackNotFound; - case CSSMERR_CSP_INPUT_LENGTH_ERROR: - return errSecInputLengthError; - case CSSMERR_CSP_OUTPUT_LENGTH_ERROR: - return errSecOutputLengthError; - case CSSMERR_CSP_PRIVILEGE_NOT_SUPPORTED: - return errSecPrivilegeNotSupported; - case CSSMERR_CSP_DEVICE_ERROR: - return errSecDeviceError; - case CSSMERR_CSP_ATTACH_HANDLE_BUSY: - return errSecAttachHandleBusy; - case CSSMERR_CSP_NOT_LOGGED_IN: - return errSecNotLoggedIn; - case CSSMERR_CSP_ALGID_MISMATCH: - return errSecAlgorithmMismatch; - case CSSMERR_CSP_KEY_USAGE_INCORRECT: - return errSecKeyUsageIncorrect; - case CSSMERR_CSP_KEY_BLOB_TYPE_INCORRECT: - return errSecKeyBlobTypeIncorrect; - case CSSMERR_CSP_KEY_HEADER_INCONSISTENT: - return errSecKeyHeaderInconsistent; - case CSSMERR_CSP_UNSUPPORTED_KEY_FORMAT: - return errSecUnsupportedKeyFormat; - case CSSMERR_CSP_UNSUPPORTED_KEY_SIZE: - return errSecUnsupportedKeySize; - case CSSMERR_CSP_INVALID_KEYUSAGE_MASK: - return errSecInvalidKeyUsageMask; - case CSSMERR_CSP_UNSUPPORTED_KEYUSAGE_MASK: - return errSecUnsupportedKeyUsageMask; - case CSSMERR_CSP_INVALID_KEYATTR_MASK: - return errSecInvalidKeyAttributeMask; - case CSSMERR_CSP_UNSUPPORTED_KEYATTR_MASK: - return errSecUnsupportedKeyAttributeMask; - case CSSMERR_CSP_INVALID_KEY_LABEL: - return errSecInvalidKeyLabel; - case CSSMERR_CSP_UNSUPPORTED_KEY_LABEL: - return errSecUnsupportedKeyLabel; - case CSSMERR_CSP_INVALID_KEY_FORMAT: - return errSecInvalidKeyFormat; - case CSSMERR_CSP_VECTOR_OF_BUFS_UNSUPPORTED: - return errSecUnsupportedVectorOfBuffers; - case CSSMERR_CSP_INVALID_INPUT_VECTOR: - return errSecInvalidInputVector; - case CSSMERR_CSP_INVALID_OUTPUT_VECTOR: - return errSecInvalidOutputVector; - case CSSMERR_CSP_INVALID_CONTEXT: - return errSecInvalidContext; - case CSSMERR_CSP_INVALID_ALGORITHM: - return errSecInvalidAlgorithm; - case CSSMERR_CSP_INVALID_ATTR_KEY: - return errSecInvalidAttributeKey; - case CSSMERR_CSP_MISSING_ATTR_KEY: - return errSecMissingAttributeKey; - case CSSMERR_CSP_INVALID_ATTR_INIT_VECTOR: - return errSecInvalidAttributeInitVector; - case CSSMERR_CSP_MISSING_ATTR_INIT_VECTOR: - return errSecMissingAttributeInitVector; - case CSSMERR_CSP_INVALID_ATTR_SALT: - return errSecInvalidAttributeSalt; - case CSSMERR_CSP_MISSING_ATTR_SALT: - return errSecMissingAttributeSalt; - case CSSMERR_CSP_INVALID_ATTR_PADDING: - return errSecInvalidAttributePadding; - case CSSMERR_CSP_MISSING_ATTR_PADDING: - return errSecMissingAttributePadding; - case CSSMERR_CSP_INVALID_ATTR_RANDOM: - return errSecInvalidAttributeRandom; - case CSSMERR_CSP_MISSING_ATTR_RANDOM: - return errSecMissingAttributeRandom; - case CSSMERR_CSP_INVALID_ATTR_SEED: - return errSecInvalidAttributeSeed; - case CSSMERR_CSP_MISSING_ATTR_SEED: - return errSecMissingAttributeSeed; - case CSSMERR_CSP_INVALID_ATTR_PASSPHRASE: - return errSecInvalidAttributePassphrase; - case CSSMERR_CSP_MISSING_ATTR_PASSPHRASE: - return errSecMissingAttributePassphrase; - case CSSMERR_CSP_INVALID_ATTR_KEY_LENGTH: - return errSecInvalidAttributeKeyLength; - case CSSMERR_CSP_MISSING_ATTR_KEY_LENGTH: - return errSecMissingAttributeKeyLength; - case CSSMERR_CSP_INVALID_ATTR_BLOCK_SIZE: - return errSecInvalidAttributeBlockSize; - case CSSMERR_CSP_MISSING_ATTR_BLOCK_SIZE: - return errSecMissingAttributeBlockSize; - case CSSMERR_CSP_INVALID_ATTR_OUTPUT_SIZE: - return errSecInvalidAttributeOutputSize; - case CSSMERR_CSP_MISSING_ATTR_OUTPUT_SIZE: - return errSecMissingAttributeOutputSize; - case CSSMERR_CSP_INVALID_ATTR_ROUNDS: - return errSecInvalidAttributeRounds; - case CSSMERR_CSP_MISSING_ATTR_ROUNDS: - return errSecMissingAttributeRounds; - case CSSMERR_CSP_INVALID_ATTR_ALG_PARAMS: - return errSecInvalidAlgorithmParms; - case CSSMERR_CSP_MISSING_ATTR_ALG_PARAMS: - return errSecMissingAlgorithmParms; - case CSSMERR_CSP_INVALID_ATTR_LABEL: - return errSecInvalidAttributeLabel; - case CSSMERR_CSP_MISSING_ATTR_LABEL: - return errSecMissingAttributeLabel; - case CSSMERR_CSP_INVALID_ATTR_KEY_TYPE: - return errSecInvalidAttributeKeyType; - case CSSMERR_CSP_MISSING_ATTR_KEY_TYPE: - return errSecMissingAttributeKeyType; - case CSSMERR_CSP_INVALID_ATTR_MODE: - return errSecInvalidAttributeMode; - case CSSMERR_CSP_MISSING_ATTR_MODE: - return errSecMissingAttributeMode; - case CSSMERR_CSP_INVALID_ATTR_EFFECTIVE_BITS: - return errSecInvalidAttributeEffectiveBits; - case CSSMERR_CSP_MISSING_ATTR_EFFECTIVE_BITS: - return errSecMissingAttributeEffectiveBits; - case CSSMERR_CSP_INVALID_ATTR_START_DATE: - return errSecInvalidAttributeStartDate; - case CSSMERR_CSP_MISSING_ATTR_START_DATE: - return errSecMissingAttributeStartDate; - case CSSMERR_CSP_INVALID_ATTR_END_DATE: - return errSecInvalidAttributeEndDate; - case CSSMERR_CSP_MISSING_ATTR_END_DATE: - return errSecMissingAttributeEndDate; - case CSSMERR_CSP_INVALID_ATTR_VERSION: - return errSecInvalidAttributeVersion; - case CSSMERR_CSP_MISSING_ATTR_VERSION: - return errSecMissingAttributeVersion; - case CSSMERR_CSP_INVALID_ATTR_PRIME: - return errSecInvalidAttributePrime; - case CSSMERR_CSP_MISSING_ATTR_PRIME: - return errSecMissingAttributePrime; - case CSSMERR_CSP_INVALID_ATTR_BASE: - return errSecInvalidAttributeBase; - case CSSMERR_CSP_MISSING_ATTR_BASE: - return errSecMissingAttributeBase; - case CSSMERR_CSP_INVALID_ATTR_SUBPRIME: - return errSecInvalidAttributeSubprime; - case CSSMERR_CSP_MISSING_ATTR_SUBPRIME: - return errSecMissingAttributeSubprime; - case CSSMERR_CSP_INVALID_ATTR_ITERATION_COUNT: - return errSecInvalidAttributeIterationCount; - case CSSMERR_CSP_MISSING_ATTR_ITERATION_COUNT: - return errSecMissingAttributeIterationCount; - case CSSMERR_CSP_INVALID_ATTR_DL_DB_HANDLE: - return errSecInvalidAttributeDLDBHandle; - case CSSMERR_CSP_MISSING_ATTR_DL_DB_HANDLE: - return errSecMissingAttributeDLDBHandle; - case CSSMERR_CSP_INVALID_ATTR_ACCESS_CREDENTIALS: - return errSecInvalidAttributeAccessCredentials; - case CSSMERR_CSP_MISSING_ATTR_ACCESS_CREDENTIALS: - return errSecMissingAttributeAccessCredentials; - case CSSMERR_CSP_INVALID_ATTR_PUBLIC_KEY_FORMAT: - return errSecInvalidAttributePublicKeyFormat; - case CSSMERR_CSP_MISSING_ATTR_PUBLIC_KEY_FORMAT: - return errSecMissingAttributePublicKeyFormat; - case CSSMERR_CSP_INVALID_ATTR_PRIVATE_KEY_FORMAT: - return errSecInvalidAttributePrivateKeyFormat; - case CSSMERR_CSP_MISSING_ATTR_PRIVATE_KEY_FORMAT: - return errSecMissingAttributePrivateKeyFormat; - case CSSMERR_CSP_INVALID_ATTR_SYMMETRIC_KEY_FORMAT: - return errSecInvalidAttributeSymmetricKeyFormat; - case CSSMERR_CSP_MISSING_ATTR_SYMMETRIC_KEY_FORMAT: - return errSecMissingAttributeSymmetricKeyFormat; - case CSSMERR_CSP_INVALID_ATTR_WRAPPED_KEY_FORMAT: - return errSecInvalidAttributeWrappedKeyFormat; - case CSSMERR_CSP_MISSING_ATTR_WRAPPED_KEY_FORMAT: - return errSecMissingAttributeWrappedKeyFormat; - case CSSMERR_CSP_STAGED_OPERATION_IN_PROGRESS: - return errSecStagedOperationInProgress; - case CSSMERR_CSP_STAGED_OPERATION_NOT_STARTED: - return errSecStagedOperationNotStarted; - case CSSMERR_CSP_VERIFY_FAILED: - return errSecVerifyFailed; - case CSSMERR_CSP_QUERY_SIZE_UNKNOWN: - return errSecQuerySizeUnknown; - case CSSMERR_CSP_BLOCK_SIZE_MISMATCH: - return errSecBlockSizeMismatch; - case CSSMERR_CSP_PUBLIC_KEY_INCONSISTENT: - return errSecPublicKeyInconsistent; - case CSSMERR_CSP_DEVICE_VERIFY_FAILED: - return errSecDeviceVerifyFailed; - case CSSMERR_CSP_INVALID_LOGIN_NAME: - return errSecInvalidLoginName; - case CSSMERR_CSP_ALREADY_LOGGED_IN: - return errSecAlreadyLoggedIn; - case CSSMERR_CSP_INVALID_DIGEST_ALGORITHM: - return errSecInvalidDigestAlgorithm; - case CSSMERR_TP_INVALID_CRLGROUP: - return errSecInvalidCRLGroup; - case CSSMERR_TP_CERTIFICATE_CANT_OPERATE: - return errSecCertificateCannotOperate; - case CSSMERR_TP_CERT_EXPIRED: - return errSecCertificateExpired; - case CSSMERR_TP_CERT_NOT_VALID_YET: - return errSecCertificateNotValidYet; - case CSSMERR_TP_CERT_REVOKED: - return errSecCertificateRevoked; - case CSSMERR_TP_CERT_SUSPENDED: - return errSecCertificateSuspended; - case CSSMERR_TP_INSUFFICIENT_CREDENTIALS: - return errSecInsufficientCredentials; - case CSSMERR_TP_INVALID_ACTION: - return errSecInvalidAction; - case CSSMERR_TP_INVALID_AUTHORITY: - return errSecInvalidAuthority; - case CSSMERR_TP_VERIFY_ACTION_FAILED: - return errSecVerifyActionFailed; - case CSSMERR_TP_INVALID_CERT_AUTHORITY: - case CSSMERR_APPLETP_INVALID_CA: - return errSecInvalidCertAuthority; - case CSSMERR_TP_INVALID_CRL_AUTHORITY: - return errSecInvaldCRLAuthority; - case CSSMERR_TP_INVALID_CRL_ENCODING: - return errSecInvalidCRLEncoding; - case CSSMERR_TP_INVALID_CRL_TYPE: - return errSecInvalidCRLType; - case CSSMERR_TP_INVALID_CRL: - return errSecInvalidCRL; - case CSSMERR_TP_INVALID_FORM_TYPE: - return errSecInvalidFormType; - case CSSMERR_TP_INVALID_ID: - return errSecInvalidID; - case CSSMERR_TP_INVALID_IDENTIFIER: - return errSecInvalidIdentifier; - case CSSMERR_TP_INVALID_INDEX: - return errSecInvalidIndex; - case CSSMERR_TP_INVALID_POLICY_IDENTIFIERS: - return errSecInvalidPolicyIdentifiers; - case CSSMERR_TP_INVALID_TIMESTRING: - return errSecInvalidTimeString; - case CSSMERR_TP_INVALID_REASON: - return errSecInvalidReason; - case CSSMERR_TP_INVALID_REQUEST_INPUTS: - return errSecInvalidRequestInputs; - case CSSMERR_TP_INVALID_RESPONSE_VECTOR: - return errSecInvalidResponseVector; - case CSSMERR_TP_INVALID_STOP_ON_POLICY: - return errSecInvalidStopOnPolicy; - case CSSMERR_TP_INVALID_TUPLE: - return errSecInvalidTuple; - case CSSMERR_TP_NOT_SIGNER: - return errSecNotSigner; - case CSSMERR_TP_NOT_TRUSTED: - return errSecNotTrusted; - case CSSMERR_TP_NO_DEFAULT_AUTHORITY: - return errSecNoDefaultAuthority; - case CSSMERR_TP_REJECTED_FORM: - return errSecRejectedForm; - case CSSMERR_TP_REQUEST_LOST: - return errSecRequestLost; - case CSSMERR_TP_REQUEST_REJECTED: - return errSecRequestRejected; - case CSSMERR_TP_UNSUPPORTED_ADDR_TYPE: - return errSecUnsupportedAddressType; - case CSSMERR_TP_UNSUPPORTED_SERVICE: - return errSecUnsupportedService; - case CSSMERR_TP_INVALID_TUPLEGROUP: - return errSecInvalidTupleGroup; - case CSSMERR_AC_INVALID_BASE_ACLS: - return errSecInvalidBaseACLs; - case CSSMERR_AC_INVALID_TUPLE_CREDENTIALS: - return errSecInvalidTupleCredendtials; - case CSSMERR_AC_INVALID_ENCODING: - return errSecInvalidEncoding; - case CSSMERR_AC_INVALID_VALIDITY_PERIOD: - return errSecInvalidValidityPeriod; - case CSSMERR_AC_INVALID_REQUESTOR: - return errSecInvalidRequestor; - case CSSMERR_AC_INVALID_REQUEST_DESCRIPTOR: - return errSecRequestDescriptor; - case CSSMERR_CL_INVALID_BUNDLE_INFO: - return errSecInvalidBundleInfo; - case CSSMERR_CL_INVALID_CRL_INDEX: - return errSecInvalidCRLIndex; - case CSSMERR_CL_NO_FIELD_VALUES: - return errSecNoFieldValues; - case CSSMERR_DL_UNSUPPORTED_FIELD_FORMAT: - return errSecUnsupportedFieldFormat; - case CSSMERR_DL_UNSUPPORTED_INDEX_INFO: - return errSecUnsupportedIndexInfo; - case CSSMERR_DL_UNSUPPORTED_LOCALITY: - return errSecUnsupportedLocality; - case CSSMERR_DL_UNSUPPORTED_NUM_ATTRIBUTES: - return errSecUnsupportedNumAttributes; - case CSSMERR_DL_UNSUPPORTED_NUM_INDEXES: - return errSecUnsupportedNumIndexes; - case CSSMERR_DL_UNSUPPORTED_NUM_RECORDTYPES: - return errSecUnsupportedNumRecordTypes; - case CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE: - return errSecFieldSpecifiedMultiple; - case CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT: - return errSecIncompatibleFieldFormat; - case CSSMERR_DL_INVALID_PARSING_MODULE: - return errSecInvalidParsingModule; - case CSSMERR_DL_DB_LOCKED: - return errSecDatabaseLocked; - case CSSMERR_DL_DATASTORE_IS_OPEN: - return errSecDatastoreIsOpen; - case CSSMERR_DL_MISSING_VALUE: - return errSecMissingValue; - case CSSMERR_DL_UNSUPPORTED_QUERY_LIMITS: - return errSecUnsupportedQueryLimits; - case CSSMERR_DL_UNSUPPORTED_NUM_SELECTION_PREDS: - return errSecUnsupportedNumSelectionPreds; - case CSSMERR_DL_UNSUPPORTED_OPERATOR: - return errSecUnsupportedOperator; - case CSSMERR_DL_INVALID_DB_LOCATION: - return errSecInvalidDBLocation; - case CSSMERR_DL_INVALID_ACCESS_REQUEST: - return errSecInvalidAccessRequest; - case CSSMERR_DL_INVALID_INDEX_INFO: - return errSecInvalidIndexInfo; - case CSSMERR_DL_INVALID_NEW_OWNER: - return errSecInvalidNewOwner; - case CSSMERR_DL_INVALID_MODIFY_MODE: - return errSecInvalidModifyMode; - case CSSMERR_DL_RECORD_MODIFIED: - return errSecRecordModified; - case CSSMERR_DL_ENDOFDATA: - return errSecEndOfData; - case CSSMERR_DL_INVALID_VALUE: - return errSecInvalidValue; - case CSSMERR_DL_MULTIPLE_VALUES_UNSUPPORTED: - return errSecMultipleValuesUnsupported; - default: - return osStatus; - } -} diff --git a/OSX/include/security_keychain/SecBase.h b/OSX/include/security_keychain/SecBase.h deleted file mode 100644 index 7a0cb546..00000000 --- a/OSX/include/security_keychain/SecBase.h +++ /dev/null @@ -1,655 +0,0 @@ -/* - * Copyright (c) 2000-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecBase - SecBase contains common declarations for the Security functions. -*/ - -#ifndef _SECURITY_SECBASE_H_ -#define _SECURITY_SECBASE_H_ - -#include -#include - -#if defined(__clang__) -#define SEC_DEPRECATED_ATTRIBUTE DEPRECATED_ATTRIBUTE -#else -#define SEC_DEPRECATED_ATTRIBUTE -#endif - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN -CF_IMPLICIT_BRIDGING_ENABLED - -#ifndef __SEC_TYPES__ -#define __SEC_TYPES__ - -/*! - @typedef SecKeychainRef - @abstract Contains information about a keychain. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecKeychainRef *SecKeychainRef; - -/*! - @typedef SecKeychainItemRef - @abstract Contains information about a keychain item. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecKeychainItemRef *SecKeychainItemRef; - -/*! - @typedef SecKeychainSearchRef - @abstract Contains information about a keychain search. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecKeychainSearchRef *SecKeychainSearchRef; - -/*! - @typedef SecKeychainAttrType - @abstract Represents a keychain attribute type. -*/ -typedef OSType SecKeychainAttrType; - -/*! - @struct SecKeychainAttribute - @abstract Contains keychain attributes. - @field tag A 4-byte attribute tag. - @field length The length of the buffer pointed to by data. - @field data A pointer to the attribute data. -*/ -struct SecKeychainAttribute -{ - SecKeychainAttrType tag; - UInt32 length; - void *data; -}; -typedef struct SecKeychainAttribute SecKeychainAttribute; - -/*! - @typedef SecKeychainAttributePtr - @abstract Represents a pointer to a keychain attribute structure. -*/ -typedef SecKeychainAttribute *SecKeychainAttributePtr; - -/*! - @typedef SecKeychainAttributeList - @abstract Represents a list of keychain attributes. - @field count An unsigned 32-bit integer that represents the number of keychain attributes in the array. - @field attr A pointer to the first keychain attribute in the array. -*/ -struct SecKeychainAttributeList -{ - UInt32 count; - SecKeychainAttribute *attr; -}; -typedef struct SecKeychainAttributeList SecKeychainAttributeList; - -/*! - @typedef SecKeychainStatus - @abstract Represents the status of a keychain. -*/ -typedef UInt32 SecKeychainStatus; -#endif - -/*! - @typedef SecTrustedApplicationRef - @abstract Contains information about a trusted application. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecTrustedApplicationRef *SecTrustedApplicationRef; - -/*! - @typedef SecPolicyRef - @abstract Contains information about a policy. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecPolicyRef *SecPolicyRef; - -/*! - @typedef SecCertificateRef - @abstract Contains information about a certificate. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecCertificateRef *SecCertificateRef; - -/*! - @typedef SecAccessRef - @abstract Contains information about an access. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecAccessRef *SecAccessRef; - -/*! - @typedef SecIdentityRef - @abstract Contains information about an identity. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecIdentityRef *SecIdentityRef; - -/*! - @typedef SecKeyRef - @abstract Contains information about a key. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecKeyRef *SecKeyRef; - -/*! - @typedef SecACLRef - @abstract Contains information about an access control list (ACL) entry. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecTrustRef *SecACLRef; - -/*! - @typedef SecAccessControlRef - @abstract CFType representing access control for an item. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecAccessControl *SecAccessControlRef; - -/*! - @typedef SecPasswordRef - @abstract Contains information about a password. -*/ -typedef struct CF_BRIDGED_TYPE(id) OpaqueSecPasswordRef *SecPasswordRef; - -/*! - @typedef SecKeychainAttributeInfo - @abstract Represents an attribute. - @field count The number of tag-format pairs in the respective arrays. - @field tag A pointer to the first attribute tag in the array. - @field format A pointer to the first CSSM_DB_ATTRIBUTE_FORMAT in the array. - @discussion Each tag and format item form a pair. -*/ -struct SecKeychainAttributeInfo -{ - UInt32 count; - UInt32 *tag; - UInt32 *format; -}; -typedef struct SecKeychainAttributeInfo SecKeychainAttributeInfo; - -/*! - @function SecCopyErrorMessageString - @abstract Returns a string describing the specified error result code. - @param status An error result code of type OSStatus or CSSM_RETURN, as returned by a Security or CSSM function. - @reserved Reserved for future use. Your code should pass NULL in this parameter. - @result A reference to an error string, or NULL if no error string is available for the specified result code. Your code must release this reference by calling the CFRelease function. -*/ -__nullable -CFStringRef SecCopyErrorMessageString(OSStatus status, void * __nullable reserved) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); -/*! -@enum Security Error Codes -@abstract Result codes returned from Security framework functions. -@constant errSecSuccess No error. -@constant errSecUnimplemented Function or operation not implemented. -@constant errSecDskFull Disk Full error. -@constant errSecIO I/O error. -@constant errSecParam One or more parameters passed to a function were not valid. -@constant errSecWrPerm Write permissions error. -@constant errSecAllocate Failed to allocate memory. -@constant errSecUserCanceled User canceled the operation. -@constant errSecBadReq Bad parameter or invalid state for operation. -@constant errSecInternalComponent -@constant errSecCoreFoundationUnknown -@constant errSecNotAvailable No keychain is available. -@constant errSecReadOnly Read only error. -@constant errSecAuthFailed Authorization/Authentication failed. -@constant errSecNoSuchKeychain The keychain does not exist. -@constant errSecInvalidKeychain The keychain is not valid. -@constant errSecDuplicateKeychain A keychain with the same name already exists. -@constant errSecDuplicateCallback The specified callback is already installed. -@constant errSecInvalidCallback The specified callback is not valid. -@constant errSecDuplicateItem The item already exists. -@constant errSecItemNotFound The item cannot be found. -@constant errSecBufferTooSmall The buffer is too small. -@constant errSecDataTooLarge The data is too large. -@constant errSecNoSuchAttr The attribute does not exist. -@constant errSecInvalidItemRef The item reference is invalid. -@constant errSecInvalidSearchRef The search reference is invalid. -@constant errSecNoSuchClass The keychain item class does not exist. -@constant errSecNoDefaultKeychain A default keychain does not exist. -@constant errSecInteractionNotAllowed User interaction is not allowed. -@constant errSecReadOnlyAttr The attribute is read only. -@constant errSecWrongSecVersion The version is incorrect. -@constant errSecKeySizeNotAllowed The key size is not allowed. -@constant errSecNoStorageModule There is no storage module available. -@constant errSecNoCertificateModule There is no certificate module available. -@constant errSecNoPolicyModule There is no policy module available. -@constant errSecInteractionRequired User interaction is required. -@constant errSecDataNotAvailable The data is not available. -@constant errSecDataNotModifiable The data is not modifiable. -@constant errSecCreateChainFailed The attempt to create a certificate chain failed. -@constant errSecACLNotSimple The access control list is not in standard simple form. -@constant errSecPolicyNotFound The policy specified cannot be found. -@constant errSecInvalidTrustSetting The specified trust setting is invalid. -@constant errSecNoAccessForItem The specified item has no access control. -@constant errSecInvalidOwnerEdit Invalid attempt to change the owner of this item. -@constant errSecTrustNotAvailable No trust results are available. -@constant errSecUnsupportedFormat Import/Export format unsupported. -@constant errSecUnknownFormat Unknown format in import. -@constant errSecKeyIsSensitive Key material must be wrapped for export. -@constant errSecMultiplePrivKeys An attempt was made to import multiple private keys. -@constant errSecPassphraseRequired Passphrase is required for import/export. -@constant errSecInvalidPasswordRef The password reference was invalid. -@constant errSecInvalidTrustSettings The Trust Settings Record was corrupted. -@constant errSecNoTrustSettings No Trust Settings were found. -@constant errSecPkcs12VerifyFailure MAC verification failed during PKCS12 Import. -@constant errSecDecode Unable to decode the provided data. - -@discussion The assigned error space is discontinuous: e.g. -25240..-25279, -25290..-25329, -68608..-67585, and so on. -*/ - -/* - Note: the comments that appear after these errors are used to create SecErrorMessages.strings. - The comments must not be multi-line, and should be in a form meaningful to an end user. If - a different or additional comment is needed, it can be put in the header doc format, or on a - line that does not start with errZZZ. -*/ - -CF_ENUM(OSStatus) -{ - errSecSuccess = 0, /* No error. */ - errSecUnimplemented = -4, /* Function or operation not implemented. */ - errSecDskFull = -34, - errSecIO = -36, /*I/O error (bummers)*/ - - errSecParam = -50, /* One or more parameters passed to a function were not valid. */ - errSecWrPerm = -61, /* write permissions error*/ - errSecAllocate = -108, /* Failed to allocate memory. */ - errSecUserCanceled = -128, /* User canceled the operation. */ - errSecBadReq = -909, /* Bad parameter or invalid state for operation. */ - - errSecInternalComponent = -2070, - errSecCoreFoundationUnknown = -4960, - - errSecNotAvailable = -25291, /* No keychain is available. You may need to restart your computer. */ - errSecReadOnly = -25292, /* This keychain cannot be modified. */ - errSecAuthFailed = -25293, /* The user name or passphrase you entered is not correct. */ - errSecNoSuchKeychain = -25294, /* The specified keychain could not be found. */ - errSecInvalidKeychain = -25295, /* The specified keychain is not a valid keychain file. */ - errSecDuplicateKeychain = -25296, /* A keychain with the same name already exists. */ - errSecDuplicateCallback = -25297, /* The specified callback function is already installed. */ - errSecInvalidCallback = -25298, /* The specified callback function is not valid. */ - errSecDuplicateItem = -25299, /* The specified item already exists in the keychain. */ - errSecItemNotFound = -25300, /* The specified item could not be found in the keychain. */ - errSecBufferTooSmall = -25301, /* There is not enough memory available to use the specified item. */ - errSecDataTooLarge = -25302, /* This item contains information which is too large or in a format that cannot be displayed. */ - errSecNoSuchAttr = -25303, /* The specified attribute does not exist. */ - errSecInvalidItemRef = -25304, /* The specified item is no longer valid. It may have been deleted from the keychain. */ - errSecInvalidSearchRef = -25305, /* Unable to search the current keychain. */ - errSecNoSuchClass = -25306, /* The specified item does not appear to be a valid keychain item. */ - errSecNoDefaultKeychain = -25307, /* A default keychain could not be found. */ - errSecInteractionNotAllowed = -25308, /* User interaction is not allowed. */ - errSecReadOnlyAttr = -25309, /* The specified attribute could not be modified. */ - errSecWrongSecVersion = -25310, /* This keychain was created by a different version of the system software and cannot be opened. */ - errSecKeySizeNotAllowed = -25311, /* This item specifies a key size which is too large. */ - errSecNoStorageModule = -25312, /* A required component (data storage module) could not be loaded. You may need to restart your computer. */ - errSecNoCertificateModule = -25313, /* A required component (certificate module) could not be loaded. You may need to restart your computer. */ - errSecNoPolicyModule = -25314, /* A required component (policy module) could not be loaded. You may need to restart your computer. */ - errSecInteractionRequired = -25315, /* User interaction is required, but is currently not allowed. */ - errSecDataNotAvailable = -25316, /* The contents of this item cannot be retrieved. */ - errSecDataNotModifiable = -25317, /* The contents of this item cannot be modified. */ - errSecCreateChainFailed = -25318, /* One or more certificates required to validate this certificate cannot be found. */ - errSecInvalidPrefsDomain = -25319, /* The specified preferences domain is not valid. */ - errSecInDarkWake = -25320, /* In dark wake, no UI possible */ - - errSecACLNotSimple = -25240, /* The specified access control list is not in standard (simple) form. */ - errSecPolicyNotFound = -25241, /* The specified policy cannot be found. */ - errSecInvalidTrustSetting = -25242, /* The specified trust setting is invalid. */ - errSecNoAccessForItem = -25243, /* The specified item has no access control. */ - errSecInvalidOwnerEdit = -25244, /* Invalid attempt to change the owner of this item. */ - errSecTrustNotAvailable = -25245, /* No trust results are available. */ - errSecUnsupportedFormat = -25256, /* Import/Export format unsupported. */ - errSecUnknownFormat = -25257, /* Unknown format in import. */ - errSecKeyIsSensitive = -25258, /* Key material must be wrapped for export. */ - errSecMultiplePrivKeys = -25259, /* An attempt was made to import multiple private keys. */ - errSecPassphraseRequired = -25260, /* Passphrase is required for import/export. */ - errSecInvalidPasswordRef = -25261, /* The password reference was invalid. */ - errSecInvalidTrustSettings = -25262, /* The Trust Settings Record was corrupted. */ - errSecNoTrustSettings = -25263, /* No Trust Settings were found. */ - errSecPkcs12VerifyFailure = -25264, /* MAC verification failed during PKCS12 import (wrong password?) */ - errSecNotSigner = -26267, /* A certificate was not signed by its proposed parent. */ - - errSecDecode = -26275, /* Unable to decode the provided data. */ - - errSecServiceNotAvailable = -67585, /* The required service is not available. */ - errSecInsufficientClientID = -67586, /* The client ID is not correct. */ - errSecDeviceReset = -67587, /* A device reset has occurred. */ - errSecDeviceFailed = -67588, /* A device failure has occurred. */ - errSecAppleAddAppACLSubject = -67589, /* Adding an application ACL subject failed. */ - errSecApplePublicKeyIncomplete = -67590, /* The public key is incomplete. */ - errSecAppleSignatureMismatch = -67591, /* A signature mismatch has occurred. */ - errSecAppleInvalidKeyStartDate = -67592, /* The specified key has an invalid start date. */ - errSecAppleInvalidKeyEndDate = -67593, /* The specified key has an invalid end date. */ - errSecConversionError = -67594, /* A conversion error has occurred. */ - errSecAppleSSLv2Rollback = -67595, /* A SSLv2 rollback error has occurred. */ - errSecDiskFull = -34, /* The disk is full. */ - errSecQuotaExceeded = -67596, /* The quota was exceeded. */ - errSecFileTooBig = -67597, /* The file is too big. */ - errSecInvalidDatabaseBlob = -67598, /* The specified database has an invalid blob. */ - errSecInvalidKeyBlob = -67599, /* The specified database has an invalid key blob. */ - errSecIncompatibleDatabaseBlob = -67600, /* The specified database has an incompatible blob. */ - errSecIncompatibleKeyBlob = -67601, /* The specified database has an incompatible key blob. */ - errSecHostNameMismatch = -67602, /* A host name mismatch has occurred. */ - errSecUnknownCriticalExtensionFlag = -67603, /* There is an unknown critical extension flag. */ - errSecNoBasicConstraints = -67604, /* No basic constraints were found. */ - errSecNoBasicConstraintsCA = -67605, /* No basic CA constraints were found. */ - errSecInvalidAuthorityKeyID = -67606, /* The authority key ID is not valid. */ - errSecInvalidSubjectKeyID = -67607, /* The subject key ID is not valid. */ - errSecInvalidKeyUsageForPolicy = -67608, /* The key usage is not valid for the specified policy. */ - errSecInvalidExtendedKeyUsage = -67609, /* The extended key usage is not valid. */ - errSecInvalidIDLinkage = -67610, /* The ID linkage is not valid. */ - errSecPathLengthConstraintExceeded = -67611, /* The path length constraint was exceeded. */ - errSecInvalidRoot = -67612, /* The root or anchor certificate is not valid. */ - errSecCRLExpired = -67613, /* The CRL has expired. */ - errSecCRLNotValidYet = -67614, /* The CRL is not yet valid. */ - errSecCRLNotFound = -67615, /* The CRL was not found. */ - errSecCRLServerDown = -67616, /* The CRL server is down. */ - errSecCRLBadURI = -67617, /* The CRL has a bad Uniform Resource Identifier. */ - errSecUnknownCertExtension = -67618, /* An unknown certificate extension was encountered. */ - errSecUnknownCRLExtension = -67619, /* An unknown CRL extension was encountered. */ - errSecCRLNotTrusted = -67620, /* The CRL is not trusted. */ - errSecCRLPolicyFailed = -67621, /* The CRL policy failed. */ - errSecIDPFailure = -67622, /* The issuing distribution point was not valid. */ - errSecSMIMEEmailAddressesNotFound = -67623, /* An email address mismatch was encountered. */ - errSecSMIMEBadExtendedKeyUsage = -67624, /* The appropriate extended key usage for SMIME was not found. */ - errSecSMIMEBadKeyUsage = -67625, /* The key usage is not compatible with SMIME. */ - errSecSMIMEKeyUsageNotCritical = -67626, /* The key usage extension is not marked as critical. */ - errSecSMIMENoEmailAddress = -67627, /* No email address was found in the certificate. */ - errSecSMIMESubjAltNameNotCritical = -67628, /* The subject alternative name extension is not marked as critical. */ - errSecSSLBadExtendedKeyUsage = -67629, /* The appropriate extended key usage for SSL was not found. */ - errSecOCSPBadResponse = -67630, /* The OCSP response was incorrect or could not be parsed. */ - errSecOCSPBadRequest = -67631, /* The OCSP request was incorrect or could not be parsed. */ - errSecOCSPUnavailable = -67632, /* OCSP service is unavailable. */ - errSecOCSPStatusUnrecognized = -67633, /* The OCSP server did not recognize this certificate. */ - errSecEndOfData = -67634, /* An end-of-data was detected. */ - errSecIncompleteCertRevocationCheck = -67635, /* An incomplete certificate revocation check occurred. */ - errSecNetworkFailure = -67636, /* A network failure occurred. */ - errSecOCSPNotTrustedToAnchor = -67637, /* The OCSP response was not trusted to a root or anchor certificate. */ - errSecRecordModified = -67638, /* The record was modified. */ - errSecOCSPSignatureError = -67639, /* The OCSP response had an invalid signature. */ - errSecOCSPNoSigner = -67640, /* The OCSP response had no signer. */ - errSecOCSPResponderMalformedReq = -67641, /* The OCSP responder was given a malformed request. */ - errSecOCSPResponderInternalError = -67642, /* The OCSP responder encountered an internal error. */ - errSecOCSPResponderTryLater = -67643, /* The OCSP responder is busy, try again later. */ - errSecOCSPResponderSignatureRequired = -67644, /* The OCSP responder requires a signature. */ - errSecOCSPResponderUnauthorized = -67645, /* The OCSP responder rejected this request as unauthorized. */ - errSecOCSPResponseNonceMismatch = -67646, /* The OCSP response nonce did not match the request. */ - errSecCodeSigningBadCertChainLength = -67647, /* Code signing encountered an incorrect certificate chain length. */ - errSecCodeSigningNoBasicConstraints = -67648, /* Code signing found no basic constraints. */ - errSecCodeSigningBadPathLengthConstraint= -67649, /* Code signing encountered an incorrect path length constraint. */ - errSecCodeSigningNoExtendedKeyUsage = -67650, /* Code signing found no extended key usage. */ - errSecCodeSigningDevelopment = -67651, /* Code signing indicated use of a development-only certificate. */ - errSecResourceSignBadCertChainLength = -67652, /* Resource signing has encountered an incorrect certificate chain length. */ - errSecResourceSignBadExtKeyUsage = -67653, /* Resource signing has encountered an error in the extended key usage. */ - errSecTrustSettingDeny = -67654, /* The trust setting for this policy was set to Deny. */ - errSecInvalidSubjectName = -67655, /* An invalid certificate subject name was encountered. */ - errSecUnknownQualifiedCertStatement = -67656, /* An unknown qualified certificate statement was encountered. */ - errSecMobileMeRequestQueued = -67657, /* The MobileMe request will be sent during the next connection. */ - errSecMobileMeRequestRedirected = -67658, /* The MobileMe request was redirected. */ - errSecMobileMeServerError = -67659, /* A MobileMe server error occurred. */ - errSecMobileMeServerNotAvailable = -67660, /* The MobileMe server is not available. */ - errSecMobileMeServerAlreadyExists = -67661, /* The MobileMe server reported that the item already exists. */ - errSecMobileMeServerServiceErr = -67662, /* A MobileMe service error has occurred. */ - errSecMobileMeRequestAlreadyPending = -67663, /* A MobileMe request is already pending. */ - errSecMobileMeNoRequestPending = -67664, /* MobileMe has no request pending. */ - errSecMobileMeCSRVerifyFailure = -67665, /* A MobileMe CSR verification failure has occurred. */ - errSecMobileMeFailedConsistencyCheck = -67666, /* MobileMe has found a failed consistency check. */ - errSecNotInitialized = -67667, /* A function was called without initializing CSSM. */ - errSecInvalidHandleUsage = -67668, /* The CSSM handle does not match with the service type. */ - errSecPVCReferentNotFound = -67669, /* A reference to the calling module was not found in the list of authorized callers. */ - errSecFunctionIntegrityFail = -67670, /* A function address was not within the verified module. */ - errSecInternalError = -67671, /* An internal error has occurred. */ - errSecMemoryError = -67672, /* A memory error has occurred. */ - errSecInvalidData = -67673, /* Invalid data was encountered. */ - errSecMDSError = -67674, /* A Module Directory Service error has occurred. */ - errSecInvalidPointer = -67675, /* An invalid pointer was encountered. */ - errSecSelfCheckFailed = -67676, /* Self-check has failed. */ - errSecFunctionFailed = -67677, /* A function has failed. */ - errSecModuleManifestVerifyFailed = -67678, /* A module manifest verification failure has occurred. */ - errSecInvalidGUID = -67679, /* An invalid GUID was encountered. */ - errSecInvalidHandle = -67680, /* An invalid handle was encountered. */ - errSecInvalidDBList = -67681, /* An invalid DB list was encountered. */ - errSecInvalidPassthroughID = -67682, /* An invalid passthrough ID was encountered. */ - errSecInvalidNetworkAddress = -67683, /* An invalid network address was encountered. */ - errSecCRLAlreadySigned = -67684, /* The certificate revocation list is already signed. */ - errSecInvalidNumberOfFields = -67685, /* An invalid number of fields were encountered. */ - errSecVerificationFailure = -67686, /* A verification failure occurred. */ - errSecUnknownTag = -67687, /* An unknown tag was encountered. */ - errSecInvalidSignature = -67688, /* An invalid signature was encountered. */ - errSecInvalidName = -67689, /* An invalid name was encountered. */ - errSecInvalidCertificateRef = -67690, /* An invalid certificate reference was encountered. */ - errSecInvalidCertificateGroup = -67691, /* An invalid certificate group was encountered. */ - errSecTagNotFound = -67692, /* The specified tag was not found. */ - errSecInvalidQuery = -67693, /* The specified query was not valid. */ - errSecInvalidValue = -67694, /* An invalid value was detected. */ - errSecCallbackFailed = -67695, /* A callback has failed. */ - errSecACLDeleteFailed = -67696, /* An ACL delete operation has failed. */ - errSecACLReplaceFailed = -67697, /* An ACL replace operation has failed. */ - errSecACLAddFailed = -67698, /* An ACL add operation has failed. */ - errSecACLChangeFailed = -67699, /* An ACL change operation has failed. */ - errSecInvalidAccessCredentials = -67700, /* Invalid access credentials were encountered. */ - errSecInvalidRecord = -67701, /* An invalid record was encountered. */ - errSecInvalidACL = -67702, /* An invalid ACL was encountered. */ - errSecInvalidSampleValue = -67703, /* An invalid sample value was encountered. */ - errSecIncompatibleVersion = -67704, /* An incompatible version was encountered. */ - errSecPrivilegeNotGranted = -67705, /* The privilege was not granted. */ - errSecInvalidScope = -67706, /* An invalid scope was encountered. */ - errSecPVCAlreadyConfigured = -67707, /* The PVC is already configured. */ - errSecInvalidPVC = -67708, /* An invalid PVC was encountered. */ - errSecEMMLoadFailed = -67709, /* The EMM load has failed. */ - errSecEMMUnloadFailed = -67710, /* The EMM unload has failed. */ - errSecAddinLoadFailed = -67711, /* The add-in load operation has failed. */ - errSecInvalidKeyRef = -67712, /* An invalid key was encountered. */ - errSecInvalidKeyHierarchy = -67713, /* An invalid key hierarchy was encountered. */ - errSecAddinUnloadFailed = -67714, /* The add-in unload operation has failed. */ - errSecLibraryReferenceNotFound = -67715, /* A library reference was not found. */ - errSecInvalidAddinFunctionTable = -67716, /* An invalid add-in function table was encountered. */ - errSecInvalidServiceMask = -67717, /* An invalid service mask was encountered. */ - errSecModuleNotLoaded = -67718, /* A module was not loaded. */ - errSecInvalidSubServiceID = -67719, /* An invalid subservice ID was encountered. */ - errSecAttributeNotInContext = -67720, /* An attribute was not in the context. */ - errSecModuleManagerInitializeFailed = -67721, /* A module failed to initialize. */ - errSecModuleManagerNotFound = -67722, /* A module was not found. */ - errSecEventNotificationCallbackNotFound = -67723, /* An event notification callback was not found. */ - errSecInputLengthError = -67724, /* An input length error was encountered. */ - errSecOutputLengthError = -67725, /* An output length error was encountered. */ - errSecPrivilegeNotSupported = -67726, /* The privilege is not supported. */ - errSecDeviceError = -67727, /* A device error was encountered. */ - errSecAttachHandleBusy = -67728, /* The CSP handle was busy. */ - errSecNotLoggedIn = -67729, /* You are not logged in. */ - errSecAlgorithmMismatch = -67730, /* An algorithm mismatch was encountered. */ - errSecKeyUsageIncorrect = -67731, /* The key usage is incorrect. */ - errSecKeyBlobTypeIncorrect = -67732, /* The key blob type is incorrect. */ - errSecKeyHeaderInconsistent = -67733, /* The key header is inconsistent. */ - errSecUnsupportedKeyFormat = -67734, /* The key header format is not supported. */ - errSecUnsupportedKeySize = -67735, /* The key size is not supported. */ - errSecInvalidKeyUsageMask = -67736, /* The key usage mask is not valid. */ - errSecUnsupportedKeyUsageMask = -67737, /* The key usage mask is not supported. */ - errSecInvalidKeyAttributeMask = -67738, /* The key attribute mask is not valid. */ - errSecUnsupportedKeyAttributeMask = -67739, /* The key attribute mask is not supported. */ - errSecInvalidKeyLabel = -67740, /* The key label is not valid. */ - errSecUnsupportedKeyLabel = -67741, /* The key label is not supported. */ - errSecInvalidKeyFormat = -67742, /* The key format is not valid. */ - errSecUnsupportedVectorOfBuffers = -67743, /* The vector of buffers is not supported. */ - errSecInvalidInputVector = -67744, /* The input vector is not valid. */ - errSecInvalidOutputVector = -67745, /* The output vector is not valid. */ - errSecInvalidContext = -67746, /* An invalid context was encountered. */ - errSecInvalidAlgorithm = -67747, /* An invalid algorithm was encountered. */ - errSecInvalidAttributeKey = -67748, /* A key attribute was not valid. */ - errSecMissingAttributeKey = -67749, /* A key attribute was missing. */ - errSecInvalidAttributeInitVector = -67750, /* An init vector attribute was not valid. */ - errSecMissingAttributeInitVector = -67751, /* An init vector attribute was missing. */ - errSecInvalidAttributeSalt = -67752, /* A salt attribute was not valid. */ - errSecMissingAttributeSalt = -67753, /* A salt attribute was missing. */ - errSecInvalidAttributePadding = -67754, /* A padding attribute was not valid. */ - errSecMissingAttributePadding = -67755, /* A padding attribute was missing. */ - errSecInvalidAttributeRandom = -67756, /* A random number attribute was not valid. */ - errSecMissingAttributeRandom = -67757, /* A random number attribute was missing. */ - errSecInvalidAttributeSeed = -67758, /* A seed attribute was not valid. */ - errSecMissingAttributeSeed = -67759, /* A seed attribute was missing. */ - errSecInvalidAttributePassphrase = -67760, /* A passphrase attribute was not valid. */ - errSecMissingAttributePassphrase = -67761, /* A passphrase attribute was missing. */ - errSecInvalidAttributeKeyLength = -67762, /* A key length attribute was not valid. */ - errSecMissingAttributeKeyLength = -67763, /* A key length attribute was missing. */ - errSecInvalidAttributeBlockSize = -67764, /* A block size attribute was not valid. */ - errSecMissingAttributeBlockSize = -67765, /* A block size attribute was missing. */ - errSecInvalidAttributeOutputSize = -67766, /* An output size attribute was not valid. */ - errSecMissingAttributeOutputSize = -67767, /* An output size attribute was missing. */ - errSecInvalidAttributeRounds = -67768, /* The number of rounds attribute was not valid. */ - errSecMissingAttributeRounds = -67769, /* The number of rounds attribute was missing. */ - errSecInvalidAlgorithmParms = -67770, /* An algorithm parameters attribute was not valid. */ - errSecMissingAlgorithmParms = -67771, /* An algorithm parameters attribute was missing. */ - errSecInvalidAttributeLabel = -67772, /* A label attribute was not valid. */ - errSecMissingAttributeLabel = -67773, /* A label attribute was missing. */ - errSecInvalidAttributeKeyType = -67774, /* A key type attribute was not valid. */ - errSecMissingAttributeKeyType = -67775, /* A key type attribute was missing. */ - errSecInvalidAttributeMode = -67776, /* A mode attribute was not valid. */ - errSecMissingAttributeMode = -67777, /* A mode attribute was missing. */ - errSecInvalidAttributeEffectiveBits = -67778, /* An effective bits attribute was not valid. */ - errSecMissingAttributeEffectiveBits = -67779, /* An effective bits attribute was missing. */ - errSecInvalidAttributeStartDate = -67780, /* A start date attribute was not valid. */ - errSecMissingAttributeStartDate = -67781, /* A start date attribute was missing. */ - errSecInvalidAttributeEndDate = -67782, /* An end date attribute was not valid. */ - errSecMissingAttributeEndDate = -67783, /* An end date attribute was missing. */ - errSecInvalidAttributeVersion = -67784, /* A version attribute was not valid. */ - errSecMissingAttributeVersion = -67785, /* A version attribute was missing. */ - errSecInvalidAttributePrime = -67786, /* A prime attribute was not valid. */ - errSecMissingAttributePrime = -67787, /* A prime attribute was missing. */ - errSecInvalidAttributeBase = -67788, /* A base attribute was not valid. */ - errSecMissingAttributeBase = -67789, /* A base attribute was missing. */ - errSecInvalidAttributeSubprime = -67790, /* A subprime attribute was not valid. */ - errSecMissingAttributeSubprime = -67791, /* A subprime attribute was missing. */ - errSecInvalidAttributeIterationCount = -67792, /* An iteration count attribute was not valid. */ - errSecMissingAttributeIterationCount = -67793, /* An iteration count attribute was missing. */ - errSecInvalidAttributeDLDBHandle = -67794, /* A database handle attribute was not valid. */ - errSecMissingAttributeDLDBHandle = -67795, /* A database handle attribute was missing. */ - errSecInvalidAttributeAccessCredentials = -67796, /* An access credentials attribute was not valid. */ - errSecMissingAttributeAccessCredentials = -67797, /* An access credentials attribute was missing. */ - errSecInvalidAttributePublicKeyFormat = -67798, /* A public key format attribute was not valid. */ - errSecMissingAttributePublicKeyFormat = -67799, /* A public key format attribute was missing. */ - errSecInvalidAttributePrivateKeyFormat = -67800, /* A private key format attribute was not valid. */ - errSecMissingAttributePrivateKeyFormat = -67801, /* A private key format attribute was missing. */ - errSecInvalidAttributeSymmetricKeyFormat = -67802, /* A symmetric key format attribute was not valid. */ - errSecMissingAttributeSymmetricKeyFormat = -67803, /* A symmetric key format attribute was missing. */ - errSecInvalidAttributeWrappedKeyFormat = -67804, /* A wrapped key format attribute was not valid. */ - errSecMissingAttributeWrappedKeyFormat = -67805, /* A wrapped key format attribute was missing. */ - errSecStagedOperationInProgress = -67806, /* A staged operation is in progress. */ - errSecStagedOperationNotStarted = -67807, /* A staged operation was not started. */ - errSecVerifyFailed = -67808, /* A cryptographic verification failure has occurred. */ - errSecQuerySizeUnknown = -67809, /* The query size is unknown. */ - errSecBlockSizeMismatch = -67810, /* A block size mismatch occurred. */ - errSecPublicKeyInconsistent = -67811, /* The public key was inconsistent. */ - errSecDeviceVerifyFailed = -67812, /* A device verification failure has occurred. */ - errSecInvalidLoginName = -67813, /* An invalid login name was detected. */ - errSecAlreadyLoggedIn = -67814, /* The user is already logged in. */ - errSecInvalidDigestAlgorithm = -67815, /* An invalid digest algorithm was detected. */ - errSecInvalidCRLGroup = -67816, /* An invalid CRL group was detected. */ - errSecCertificateCannotOperate = -67817, /* The certificate cannot operate. */ - errSecCertificateExpired = -67818, /* An expired certificate was detected. */ - errSecCertificateNotValidYet = -67819, /* The certificate is not yet valid. */ - errSecCertificateRevoked = -67820, /* The certificate was revoked. */ - errSecCertificateSuspended = -67821, /* The certificate was suspended. */ - errSecInsufficientCredentials = -67822, /* Insufficient credentials were detected. */ - errSecInvalidAction = -67823, /* The action was not valid. */ - errSecInvalidAuthority = -67824, /* The authority was not valid. */ - errSecVerifyActionFailed = -67825, /* A verify action has failed. */ - errSecInvalidCertAuthority = -67826, /* The certificate authority was not valid. */ - errSecInvaldCRLAuthority = -67827, /* The CRL authority was not valid. */ - errSecInvalidCRLEncoding = -67828, /* The CRL encoding was not valid. */ - errSecInvalidCRLType = -67829, /* The CRL type was not valid. */ - errSecInvalidCRL = -67830, /* The CRL was not valid. */ - errSecInvalidFormType = -67831, /* The form type was not valid. */ - errSecInvalidID = -67832, /* The ID was not valid. */ - errSecInvalidIdentifier = -67833, /* The identifier was not valid. */ - errSecInvalidIndex = -67834, /* The index was not valid. */ - errSecInvalidPolicyIdentifiers = -67835, /* The policy identifiers are not valid. */ - errSecInvalidTimeString = -67836, /* The time specified was not valid. */ - errSecInvalidReason = -67837, /* The trust policy reason was not valid. */ - errSecInvalidRequestInputs = -67838, /* The request inputs are not valid. */ - errSecInvalidResponseVector = -67839, /* The response vector was not valid. */ - errSecInvalidStopOnPolicy = -67840, /* The stop-on policy was not valid. */ - errSecInvalidTuple = -67841, /* The tuple was not valid. */ - errSecMultipleValuesUnsupported = -67842, /* Multiple values are not supported. */ - errSecNotTrusted = -67843, /* The trust policy was not trusted. */ - errSecNoDefaultAuthority = -67844, /* No default authority was detected. */ - errSecRejectedForm = -67845, /* The trust policy had a rejected form. */ - errSecRequestLost = -67846, /* The request was lost. */ - errSecRequestRejected = -67847, /* The request was rejected. */ - errSecUnsupportedAddressType = -67848, /* The address type is not supported. */ - errSecUnsupportedService = -67849, /* The service is not supported. */ - errSecInvalidTupleGroup = -67850, /* The tuple group was not valid. */ - errSecInvalidBaseACLs = -67851, /* The base ACLs are not valid. */ - errSecInvalidTupleCredendtials = -67852, /* The tuple credentials are not valid. */ - errSecInvalidEncoding = -67853, /* The encoding was not valid. */ - errSecInvalidValidityPeriod = -67854, /* The validity period was not valid. */ - errSecInvalidRequestor = -67855, /* The requestor was not valid. */ - errSecRequestDescriptor = -67856, /* The request descriptor was not valid. */ - errSecInvalidBundleInfo = -67857, /* The bundle information was not valid. */ - errSecInvalidCRLIndex = -67858, /* The CRL index was not valid. */ - errSecNoFieldValues = -67859, /* No field values were detected. */ - errSecUnsupportedFieldFormat = -67860, /* The field format is not supported. */ - errSecUnsupportedIndexInfo = -67861, /* The index information is not supported. */ - errSecUnsupportedLocality = -67862, /* The locality is not supported. */ - errSecUnsupportedNumAttributes = -67863, /* The number of attributes is not supported. */ - errSecUnsupportedNumIndexes = -67864, /* The number of indexes is not supported. */ - errSecUnsupportedNumRecordTypes = -67865, /* The number of record types is not supported. */ - errSecFieldSpecifiedMultiple = -67866, /* Too many fields were specified. */ - errSecIncompatibleFieldFormat = -67867, /* The field format was incompatible. */ - errSecInvalidParsingModule = -67868, /* The parsing module was not valid. */ - errSecDatabaseLocked = -67869, /* The database is locked. */ - errSecDatastoreIsOpen = -67870, /* The data store is open. */ - errSecMissingValue = -67871, /* A missing value was detected. */ - errSecUnsupportedQueryLimits = -67872, /* The query limits are not supported. */ - errSecUnsupportedNumSelectionPreds = -67873, /* The number of selection predicates is not supported. */ - errSecUnsupportedOperator = -67874, /* The operator is not supported. */ - errSecInvalidDBLocation = -67875, /* The database location is not valid. */ - errSecInvalidAccessRequest = -67876, /* The access request is not valid. */ - errSecInvalidIndexInfo = -67877, /* The index information is not valid. */ - errSecInvalidNewOwner = -67878, /* The new owner is not valid. */ - errSecInvalidModifyMode = -67879, /* The modify mode is not valid. */ - errSecMissingRequiredExtension = -67880, /* A required certificate extension is missing. */ - errSecExtendedKeyUsageNotCritical = -67881, /* The extended key usage extension was not marked critical. */ - errSecTimestampMissing = -67882, /* A timestamp was expected but was not found. */ - errSecTimestampInvalid = -67883, /* The timestamp was not valid. */ - errSecTimestampNotTrusted = -67884, /* The timestamp was not trusted. */ - errSecTimestampServiceNotAvailable = -67885, /* The timestamp service is not available. */ - errSecTimestampBadAlg = -67886, /* An unrecognized or unsupported Algorithm Identifier in timestamp. */ - errSecTimestampBadRequest = -67887, /* The timestamp transaction is not permitted or supported. */ - errSecTimestampBadDataFormat = -67888, /* The timestamp data submitted has the wrong format. */ - errSecTimestampTimeNotAvailable = -67889, /* The time source for the Timestamp Authority is not available. */ - errSecTimestampUnacceptedPolicy = -67890, /* The requested policy is not supported by the Timestamp Authority. */ - errSecTimestampUnacceptedExtension = -67891, /* The requested extension is not supported by the Timestamp Authority. */ - errSecTimestampAddInfoNotAvailable = -67892, /* The additional information requested is not available. */ - errSecTimestampSystemFailure = -67893, /* The timestamp request cannot be handled due to system failure. */ - errSecSigningTimeMissing = -67894, /* A signing time was expected but was not found. */ - errSecTimestampRejection = -67895, /* A timestamp transaction was rejected. */ - errSecTimestampWaiting = -67896, /* A timestamp transaction is waiting. */ - errSecTimestampRevocationWarning = -67897, /* A timestamp authority revocation warning was issued. */ - errSecTimestampRevocationNotification = -67898, /* A timestamp authority revocation notification was issued. */ -}; - -CF_IMPLICIT_BRIDGING_DISABLED -CF_ASSUME_NONNULL_END - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECBASE_H_ */ diff --git a/OSX/include/security_keychain/SecBase64P.c b/OSX/include/security_keychain/SecBase64P.c deleted file mode 100644 index c043906c..00000000 --- a/OSX/include/security_keychain/SecBase64P.c +++ /dev/null @@ -1,489 +0,0 @@ -/* ///////////////////////////////////////////////////////////////////////////// - * File: b64.c - * - * Purpose: Implementation file for the b64 library - * - * Created: 18th October 2004 - * Updated: 2nd August 2006 - * - * Home: http://synesis.com.au/software/ - * - * Copyright (c) 2004-2006, Matthew Wilson and Synesis Software - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of - * any contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - * ////////////////////////////////////////////////////////////////////////// */ - - -/** \file b64.c Implementation file for the b64 library - */ - -#include "SecBase64P.h" - -#include -#include - -/* ///////////////////////////////////////////////////////////////////////////// - * Constants and definitions - */ - -#ifndef B64_DOCUMENTATION_SKIP_SECTION -# define NUM_PLAIN_DATA_BYTES (3) -# define NUM_ENCODED_DATA_BYTES (4) -#endif /* !B64_DOCUMENTATION_SKIP_SECTION */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Warnings - */ - -#if defined(_MSC_VER) && \ - _MSC_VER < 1000 -# pragma warning(disable : 4705) -#endif /* _MSC_VER < 1000 */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Data - */ - -static const char b64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -static const signed char b64_indexes[] = -{ - /* 0 - 31 / 0x00 - 0x1f */ - -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - /* 32 - 63 / 0x20 - 0x3f */ - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, 62, -1, -1, -1, 63 /* ... , '+', ... '/' */ - , 52, 53, 54, 55, 56, 57, 58, 59 /* '0' - '7' */ - , 60, 61, -1, -1, -1, -1, -1, -1 /* '8', '9', ... */ - /* 64 - 95 / 0x40 - 0x5f */ - , -1, 0, 1, 2, 3, 4, 5, 6 /* ..., 'A' - 'G' */ - , 7, 8, 9, 10, 11, 12, 13, 14 /* 'H' - 'O' */ - , 15, 16, 17, 18, 19, 20, 21, 22 /* 'P' - 'W' */ - , 23, 24, 25, -1, -1, -1, -1, -1 /* 'X', 'Y', 'Z', ... */ - /* 96 - 127 / 0x60 - 0x7f */ - , -1, 26, 27, 28, 29, 30, 31, 32 /* ..., 'a' - 'g' */ - , 33, 34, 35, 36, 37, 38, 39, 40 /* 'h' - 'o' */ - , 41, 42, 43, 44, 45, 46, 47, 48 /* 'p' - 'w' */ - , 49, 50, 51, -1, -1, -1, -1, -1 /* 'x', 'y', 'z', ... */ - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1 -}; - -/* ///////////////////////////////////////////////////////////////////////////// - * Helper functions - */ - -/** This function reads in 3 bytes at a time, and translates them into 4 - * characters. - */ -static size_t SecBase64Encode_( unsigned char const *src - , size_t srcSize - , char *const dest - , size_t destLen - , unsigned lineLen - , SecBase64Result *rc) -{ - size_t total = ((srcSize + (NUM_PLAIN_DATA_BYTES - 1)) / NUM_PLAIN_DATA_BYTES) * NUM_ENCODED_DATA_BYTES; - - assert(NULL != rc); - *rc = kSecB64_R_OK; - - if(lineLen > 0) - { - size_t numLines = (total + (lineLen - 1)) / lineLen; - - total += 2 * (numLines - 1); - } - - if(NULL == dest) - { - return total; - } - else if(destLen < total) - { - *rc = kSecB64_R_INSUFFICIENT_BUFFER; - - return 0; - } - else - { - char *p = dest; - char *end = dest + destLen; - size_t len = 0; - - for(; NUM_PLAIN_DATA_BYTES <= srcSize; srcSize -= NUM_PLAIN_DATA_BYTES) - { - char characters[NUM_ENCODED_DATA_BYTES]; - - /* - * - * | 0 | 1 | 2 | - * - * | | | | - * | | | | | | | - * | | | | | | | | | | | | | - * | | | | | | | | | | | | | | | | | | | | | | | | | - * - * | 0 | 1 | 2 | 3 | - * - */ - - /* characters[0] is the 6 left-most bits of src[0] */ - characters[0] = (char)((src[0] & 0xfc) >> 2); - /* characters[0] is the right-most 2 bits of src[0] and the left-most 4 bits of src[1] */ - characters[1] = (char)(((src[0] & 0x03) << 4) + ((src[1] & 0xf0) >> 4)); - /* characters[0] is the right-most 4 bits of src[1] and the 2 left-most bits of src[2] */ - characters[2] = (char)(((src[1] & 0x0f) << 2) + ((src[2] & 0xc0) >> 6)); - /* characters[3] is the right-most 6 bits of src[2] */ - characters[3] = (char)(src[2] & 0x3f); - -#ifndef __WATCOMC__ - assert(characters[0] >= 0 && characters[0] < 64); - assert(characters[1] >= 0 && characters[1] < 64); - assert(characters[2] >= 0 && characters[2] < 64); - assert(characters[3] >= 0 && characters[3] < 64); -#endif /* __WATCOMC__ */ - - src += NUM_PLAIN_DATA_BYTES; - *p++ = b64_chars[(unsigned char)characters[0]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[(unsigned char)characters[1]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[(unsigned char)characters[2]]; - assert(NULL != strchr(b64_chars, *(p-1))); - ++len; - assert(len != lineLen); - - *p++ = b64_chars[(unsigned char)characters[3]]; - assert(NULL != strchr(b64_chars, *(p-1))); - - if( ++len == lineLen && - p != end) - { - *p++ = '\r'; - *p++ = '\n'; - len = 0; - } - } - - if(0 != srcSize) - { - /* Deal with the overspill, by boosting it up to three bytes (using 0s) - * and then appending '=' for any missing characters. - * - * This is done into a temporary buffer, so we can call ourselves and - * have the output continue to be written direct to the destination. - */ - - unsigned char dummy[NUM_PLAIN_DATA_BYTES]; - size_t i; - - for(i = 0; i < srcSize; ++i) - { - dummy[i] = *src++; - } - - for(; i < NUM_PLAIN_DATA_BYTES; ++i) - { - dummy[i] = '\0'; - } - - SecBase64Encode_(&dummy[0], NUM_PLAIN_DATA_BYTES, p, NUM_ENCODED_DATA_BYTES * (1 + 2), 0, rc); - - for(p += 1 + srcSize; srcSize++ < NUM_PLAIN_DATA_BYTES; ) - { - *p++ = '='; - } - } - - return total; - } -} - -/** This function reads in a character string in 4-character chunks, and writes - * out the converted form in 3-byte chunks to the destination. - */ -static size_t SecBase64Decode_( char const *src - , size_t srcLen - , unsigned char *dest - , size_t destSize - , unsigned flags - , char const **badChar - , SecBase64Result *rc) -{ - const size_t wholeChunks = (srcLen / NUM_ENCODED_DATA_BYTES); - const size_t remainderBytes = (srcLen % NUM_ENCODED_DATA_BYTES); - size_t maxTotal = (wholeChunks + (0 != remainderBytes)) * NUM_PLAIN_DATA_BYTES; - unsigned char *dest_ = dest; - - ((void)remainderBytes); - - assert(NULL != badChar); - assert(NULL != rc); - - *badChar = NULL; - *rc = kSecB64_R_OK; - - if(NULL == dest) - { - return maxTotal; - } - else if(destSize < maxTotal) - { - *rc = kSecB64_R_INSUFFICIENT_BUFFER; - - return 0; - } - else - { - /* Now we iterate through the src, collecting together four characters - * at a time from the Base-64 alphabet, until the end-point is reached. - * - * - */ - - char const *begin = src; - char const *const end = begin + srcLen; - size_t currIndex = 0; - size_t numPads = 0; - signed char indexes[NUM_ENCODED_DATA_BYTES]; /* 4 */ - - for(; begin != end; ++begin) - { - const char ch = *begin; - - if('=' == ch) - { - assert(currIndex < NUM_ENCODED_DATA_BYTES); - - indexes[currIndex++] = '\0'; - - ++numPads; - } - else - { - signed char ix = b64_indexes[(unsigned char)ch]; - - if(-1 == ix) - { - switch(ch) - { - case ' ': - case '\t': - case '\b': - case '\v': - if(kSecB64_F_STOP_ON_UNEXPECTED_WS & flags) - { - *rc = kSecB64_R_DATA_ERROR; - *badChar = begin; - return 0; - } - else - { - /* Fall through */ - } - case '\r': - case '\n': - continue; - default: - if(kSecB64_F_STOP_ON_UNKNOWN_CHAR & flags) - { - *rc = kSecB64_R_DATA_ERROR; - *badChar = begin; - return 0; - } - else - { - continue; - } - } - } - else - { - numPads = 0; - - assert(currIndex < NUM_ENCODED_DATA_BYTES); - - indexes[currIndex++] = ix; - } - } - - if(NUM_ENCODED_DATA_BYTES == currIndex) - { - unsigned char bytes[NUM_PLAIN_DATA_BYTES]; /* 3 */ - - bytes[0] = (unsigned char)((indexes[0] << 2) + ((indexes[1] & 0x30) >> 4)); - - currIndex = 0; - - *dest++ = bytes[0]; - if(2 != numPads) - { - bytes[1] = (unsigned char)(((indexes[1] & 0xf) << 4) + ((indexes[2] & 0x3c) >> 2)); - - *dest++ = bytes[1]; - - if(1 != numPads) - { - bytes[2] = (unsigned char)(((indexes[2] & 0x3) << 6) + indexes[3]); - - *dest++ = bytes[2]; - } - } - if(0 != numPads) - { - break; - } - } - } - - return (size_t)(dest - dest_); - } -} - -/* ///////////////////////////////////////////////////////////////////////////// - * API functions - */ - -size_t SecBase64Encode(void const *src, size_t srcSize, char *dest, size_t destLen) -{ - /* Use Null Object (Variable) here for rc, so do not need to check - * elsewhere. - */ - SecBase64Result rc_; - - return SecBase64Encode_((unsigned char const*)src, srcSize, dest, destLen, 0, &rc_); -} - -size_t SecBase64Encode2( void const *src - , size_t srcSize - , char *dest - , size_t destLen - , unsigned flags - , int lineLen /* = -1 */ - , SecBase64Result *rc /* = NULL */) -{ - /* Use Null Object (Variable) here for rc, so do not need to check - * elsewhere - */ - SecBase64Result rc_; - if(NULL == rc) - { - rc = &rc_; - } - - switch(kSecB64_F_LINE_LEN_MASK & flags) - { - case kSecB64_F_LINE_LEN_USE_PARAM: - if(lineLen >= 0) - { - break; - } - /* Fall through to 64 */ - case kSecB64_F_LINE_LEN_64: - lineLen = 64; - break; - case kSecB64_F_LINE_LEN_76: - lineLen = 76; - break; - default: - assert(!"Bad line length flag specified to SecBase64Encode2()"); - case kSecB64_F_LINE_LEN_INFINITE: - lineLen = 0; - break; - } - - assert(0 == (lineLen % 4)); - - return SecBase64Encode_((unsigned char const*)src, srcSize, dest, destLen, (unsigned)lineLen, rc); -} - -size_t SecBase64Decode(char const *src, size_t srcLen, void *dest, size_t destSize) -{ - /* Use Null Object (Variable) here for rc and badChar, so do not need to - * check elsewhere. - */ - char const *badChar_; - SecBase64Result rc_; - - return SecBase64Decode_(src, srcLen, (unsigned char*)dest, destSize, kSecB64_F_STOP_ON_NOTHING, &badChar_, &rc_); -} - -size_t SecBase64Decode2( char const *src - , size_t srcLen - , void *dest - , size_t destSize - , unsigned flags - , char const **badChar /* = NULL */ - , SecBase64Result *rc /* = NULL */) -{ - char const *badChar_; - SecBase64Result rc_; - - /* Use Null Object (Variable) here for rc and badChar, so do not need to - * check elsewhere. - */ - if(NULL == badChar) - { - badChar = &badChar_; - } - if(NULL == rc) - { - rc = &rc_; - } - - return SecBase64Decode_(src, srcLen, (unsigned char*)dest, destSize, flags, badChar, rc); -} - -/* ////////////////////////////////////////////////////////////////////////// */ diff --git a/OSX/include/security_keychain/SecBase64P.h b/OSX/include/security_keychain/SecBase64P.h deleted file mode 100644 index bfc0b797..00000000 --- a/OSX/include/security_keychain/SecBase64P.h +++ /dev/null @@ -1,247 +0,0 @@ -/* ///////////////////////////////////////////////////////////////////////////// - * File: b64/b64.h - * - * Purpose: Header file for the b64 library - * - * Created: 18th October 2004 - * Updated: 2nd August 2006 - * - * Thanks: To Adam McLaurin, for ideas regarding the SecBase64Decode2() and SecBase64Encode2(). - * - * Home: http://synesis.com.au/software/ - * - * Copyright (c) 2004-2006, Matthew Wilson and Synesis Software - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of - * any contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - * ////////////////////////////////////////////////////////////////////////// */ - - -/** \file b64/b64.h - * - * \brief [C/C++] Header file for the b64 library. - */ - -#ifndef _SEC_BASE64_H_ -#define _SEC_BASE64_H_ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* ///////////////////////////////////////////////////////////////////////////// - * Enumerations - */ - -/** \brief Return codes (from SecBase64Encode2() / SecBase64Decode2()) - */ -enum -{ - kSecB64_R_OK = 0, /*!< operation was successful. */ - kSecB64_R_INSUFFICIENT_BUFFER = 1, /*!< The given translation buffer was not of sufficient size. */ - kSecB64_R_TRUNCATED_INPUT = 2, /*!< The input did not represent a fully formed stream of octet couplings. */ - kSecB64_R_DATA_ERROR = 3 /*!< invalid data. */ -}; - -typedef uint32_t SecBase64Result; - -/** \brief Coding behaviour modification flags (for SecBase64Encode2() / SecBase64Decode2()) - */ -enum -{ - kSecB64_F_LINE_LEN_USE_PARAM = 0x0000 /*!< Uses the lineLen parameter to SecBase64Encode2(). Ignored by SecBase64Decode2(). */ - , kSecB64_F_LINE_LEN_INFINITE = 0x0001 /*!< Ignores the lineLen parameter to SecBase64Encode2(). Line length is infinite. Ignored by SecBase64Decode2(). */ - , kSecB64_F_LINE_LEN_64 = 0x0002 /*!< Ignores the lineLen parameter to SecBase64Encode2(). Line length is 64. Ignored by SecBase64Decode2(). */ - , kSecB64_F_LINE_LEN_76 = 0x0003 /*!< Ignores the lineLen parameter to SecBase64Encode2(). Line length is 76. Ignored by SecBase64Decode2(). */ - , kSecB64_F_LINE_LEN_MASK = 0x000f /*!< Mask for testing line length flags to SecBase64Encode2(). Ignored by SecBase64Encode2(). */ - , kSecB64_F_STOP_ON_NOTHING = 0x0000 /*!< Decoding ignores all invalid characters in the input data. Ignored by SecBase64Encode2(). */ - , kSecB64_F_STOP_ON_UNKNOWN_CHAR = 0x0100 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/], non-whitespace character is encountered. Ignored by SecBase64Encode2(). */ - , kSecB64_F_STOP_ON_UNEXPECTED_WS = 0x0200 /*!< Causes decoding to break if any unexpected whitespace is encountered. Ignored by SecBase64Encode2(). */ - , kSecB64_F_STOP_ON_BAD_CHAR = 0x0300 /*!< Causes decoding to break if any non-Base-64 [a-zA-Z0-9=+/] character is encountered. Ignored by SecBase64Encode2(). */ -}; - -typedef uint32_t SecBase64Flags; - -/* ///////////////////////////////////////////////////////////////////////////// - * Functions - */ - -#if 0 -static inline size_t SecBase64EncodedSize(size_t srcSize, size_t lineLen) { - size_t total = (((srcSize) + 2) / 3) * 4; - size_t lineLen = (lineLen); - if (lineLen > 0) { - size_t numLines = (total + (lineLen - 1)) / lineLen; - total += 2 * (numLines - 1); - } - return total; -} -#endif - -/** \brief Encodes a block of binary data into base64 - * - * \param src Pointer to the block to be encoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. - * \param srcSize Length of block to be encoded - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destLen Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \c SecBase64Encode()(NULL, srcSize, NULL, 0). - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destLen - * - * \note The function returns the required length if \c dest is NULL - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note Threading: The function is fully re-entrant. - */ -size_t SecBase64Encode(void const *src, size_t srcSize, char *dest, size_t destLen); - -/** \brief Encodes a block of binary data into base64 - * - * \param src Pointer to the block to be encoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. - * \param srcSize Length of block to be encoded - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destLen Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \c SecBase64Encode()(NULL, srcSize, NULL, 0). - * \param flags A combination of the SecBase64Flags enumeration, that moderate the - * behaviour of the function - * \param lineLen If the flags parameter contains kSecB64_F_LINE_LEN_USE_PARAM, then - * this parameter represents the length of the lines into which the encoded form is split, - * with a hard line break ('\\r\\n'). If this value is 0, then the line is not - * split. If it is <0, then the RFC-1113 recommended line length of 64 is used - * \param rc The return code representing the status of the operation. May be NULL. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destLen - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note Threading: The function is fully re-entrant. - */ -size_t SecBase64Encode2( void const *src - , size_t srcSize - , char *dest - , size_t destLen - , unsigned flags - , int lineLen /* = 0 */ - , SecBase64Result *rc /* = NULL */); - -/** \brief Decodes a sequence of base64 into a block of binary data - * - * \param src Pointer to the base64 block to be decoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. If \c dest is NULL, and \c src is - * not NULL, then the returned value is calculated exactly, otherwise a value - * is returned that is guaranteed to be large enough to hold the decoded block. - * - * \param srcLen Length of block to be encoded. Must be an integral of 4, the base64 - * encoding quantum, otherwise the base64 block is assumed to be invalid - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destSize Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \c SecBase64Decode(src, srcSize, NULL, 0), even in the case where the encoded form - * contains a number of characters that will be ignored, resulting in a lower total - * length of converted form. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destSize - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note \anchor anchor__4_characters The behaviour of both - * \link b64::SecBase64Encode2 SecBase64Encode2()\endlink - * and - * \link b64::SecBase64Decode2 SecBase64Decode2()\endlink - * are undefined if the line length is not a multiple of 4. - * - * \note Threading: The function is fully re-entrant. - */ -size_t SecBase64Decode(char const *src, size_t srcLen, void *dest, size_t destSize); - -/** \brief Decodes a sequence of base64 into a block of binary data - * - * \param src Pointer to the base64 block to be decoded. May not be NULL, except when - * \c dest is NULL, in which case it is ignored. If \c dest is NULL, and \c src is - * not NULL, then the returned value is calculated exactly, otherwise a value - * is returned that is guaranteed to be large enough to hold the decoded block. - * - * \param srcLen Length of block to be encoded. Must be an integral of 4, the base64 - * encoding quantum, otherwise the base64 block is assumed to be invalid - * \param dest Pointer to the buffer into which the result is to be written. May - * be NULL, in which case the function returns the required length - * \param destSize Length of the buffer into which the result is to be written. Must - * be at least as large as that indicated by the return value from - * \c SecBase64Decode(src, srcSize, NULL, 0), even in the case where the encoded form - * contains a number of characters that will be ignored, resulting in a lower total - * length of converted form. - * \param flags A combination of the SecBase64Flags enumeration, that moderate the - * behaviour of the function. - * \param rc The return code representing the status of the operation. May be NULL. - * \param badChar If the flags parameter does not contain kSecB64_F_STOP_ON_NOTHING, this - * parameter specifies the address of a pointer that will be set to point to any - * character in the sequence that stops the parsing, as dictated by the flags - * parameter. May be NULL. - * - * \return 0 if the size of the buffer was insufficient, or the length of the - * converted buffer was longer than \c destSize, or a bad character stopped parsing. - * - * \note The function returns the required length if \c dest is NULL. The returned size - * might be larger than the actual required size, but will never be smaller. - * - * \note The behaviour of both - * \link b64::SecBase64Encode2 SecBase64Encode2()\endlink - * and - * \link b64::SecBase64Decode2 SecBase64Decode2()\endlink - * are undefined if the line length is not a multiple of 4. - * - * \note Threading: The function is fully re-entrant. - */ -size_t SecBase64Decode2( char const *src - , size_t srcLen - , void *dest - , size_t destSize - , unsigned flags - , char const **badChar /* = NULL */ - , SecBase64Result *rc /* = NULL */); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* _SEC_BASE64_H_ */ diff --git a/OSX/include/security_keychain/SecBaseP.h b/OSX/include/security_keychain/SecBaseP.h deleted file mode 100644 index dc4f9cd1..00000000 --- a/OSX/include/security_keychain/SecBaseP.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2000-2009,2011 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecBase - SecBase contains common declarations for the Security functions. -*/ - -#ifndef _SECURITY_SECBASEP_H_ -#define _SECURITY_SECBASEP_H_ - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - @typedef SecCertificateRef - @abstract CFType representing a X.509 certificate, see - SecCertificate.h for details. -*/ -typedef struct __SecCertificate *SecCertificateRefP; - -/*! - @typedef SecIdentityRef - @abstract CFType representing an identity, which contains - a SecKeyRef and an ascociated SecCertificateRef, see - SecIdentity.h for details. -*/ -typedef struct __SecIdentity *SecIdentityRefP; - -/*! - @typedef SecKeyRef - @abstract CFType representing an asymetric key, see - SecKey.h for details. -*/ -typedef struct __SecKey *SecKeyRefP; - -/*********************************************** - *** OSStatus values unique to Security APIs *** - ***********************************************/ - -/* - Note: the comments that appear after these errors are used to create - SecErrorMessages.strings. The comments must not be multi-line, and - should be in a form meaningful to an end user. If a different or - additional comment is needed, it can be put in the header doc format, - or on a line that does not start with errZZZ. -*/ - -#if 0 -enum -{ - errSecSuccess = 0, /* No error. */ - errSecUnimplemented = -4, /* Function or operation not implemented. */ - errSecParam = -50, /* One or more parameters passed to a function where not valid. */ - errSecAllocate = -108, /* Failed to allocate memory. */ - errSecNotAvailable = -25291, /* No keychain is available. You may need to restart your computer. */ - errSecDuplicateItem = -25299, /* The specified item already exists in the keychain. */ - errSecItemNotFound = -25300, /* The specified item could not be found in the keychain. */ - errSecInteractionNotAllowed = -25308, /* User interaction is not allowed. */ - errSecDecode = -26275, /* Unable to decode the provided data. */ -}; -#endif - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECBASEP_H_ */ diff --git a/OSX/include/security_keychain/SecBasePriv.h b/OSX/include/security_keychain/SecBasePriv.h deleted file mode 100644 index 88721e24..00000000 --- a/OSX/include/security_keychain/SecBasePriv.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2003-2008,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecBasePriv - SecBasePriv contains private error codes for the Security framework. - */ -#ifndef _SECURITY_SECBASEPRIV_H_ -#define _SECURITY_SECBASEPRIV_H_ - -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -/******************************************************* - *** Private OSStatus values unique to Security APIs *** - *******************************************************/ - -/* - Note: the comments that appear after these errors are used to create SecErrorMessages.strings. - The comments must not be multi-line, and should be in a form meaningful to an end user. If - a different or additional comment is needed, it can be put in the header doc format, or on a - line that does not start with errZZZ. -*/ - -enum -{ - priv_errSecUnimplemented = -4, /* Private version of errSecUnimplemented constant. */ - priv_errSecParam = -50, /* Private version of errSecParam constant. */ - priv_errSecDecode = -26275, /* Private version of errSecDecode constant. */ -}; - -enum -{ - errSecInvalidCertificate = priv_errSecDecode, // -26265, /* This certificate could not be decoded. */ - errSecPolicyDenied = -26270, /* The certificate chain was not trusted due to a policy not accepting it. */ - errSecInvalidKey = priv_errSecDecode, // -26274, /* The provided key material was not valid. */ - errSecInternal = -26276, /* An internal error occured in the Security framework. */ - errSecUnsupportedAlgorithm = priv_errSecUnimplemented, // -26268, /* An unsupported algorithm was encountered. */ - errSecUnsupportedOperation = priv_errSecUnimplemented, // -26271, /* The operation you requested is not supported by this key. */ - errSecUnsupportedPadding = priv_errSecParam, // -26273, /* The padding you requested is not supported. */ - errSecItemInvalidKey = priv_errSecParam, // -34000, /* A string key in dictionary is not one of the supported keys. */ - errSecItemInvalidKeyType = priv_errSecParam, // -34001, /* A key in a dictionary is neither a CFStringRef nor a CFNumberRef. */ - errSecItemInvalidValue = priv_errSecParam, // -34002, /* A value in a dictionary is an invalid (or unsupported) CF type. */ - errSecItemClassMissing = priv_errSecParam, // -34003, /* No kSecItemClass key was specified in a dictionary. */ - errSecItemMatchUnsupported = priv_errSecParam, // -34004, /* The caller passed one or more kSecMatch keys to a function which does not support matches. */ - errSecUseItemListUnsupported = priv_errSecParam, // -34005, /* The caller passed in a kSecUseItemList key to a function which does not support it. */ - errSecUseKeychainUnsupported = priv_errSecParam, // -34006, /* The caller passed in a kSecUseKeychain key to a function which does not support it. */ - errSecUseKeychainListUnsupported = priv_errSecParam, // -34007, /* The caller passed in a kSecUseKeychainList key to a function which does not support it. */ - errSecReturnDataUnsupported = priv_errSecParam, // -34008, /* The caller passed in a kSecReturnData key to a function which does not support it. */ - errSecReturnAttributesUnsupported = priv_errSecParam, // -34009, /* The caller passed in a kSecReturnAttributes key to a function which does not support it. */ - errSecReturnRefUnsupported = priv_errSecParam, // -34010, /* The caller passed in a kSecReturnRef key to a function which does not support it. */ - errSecValueRefUnsupported = priv_errSecParam, // -34012, /* The caller passed in a kSecValueRef key to a function which does not support it. */ - errSecValuePersistentRefUnsupported = priv_errSecParam, // -34013, /* The caller passed in a kSecValuePersistentRef key to a function which does not support it. */ - errSecReturnMissingPointer = priv_errSecParam, // -34014, /* The caller passed asked for something to be returned but did not pass in a result pointer. */ - errSecMatchLimitUnsupported = priv_errSecParam, // -34015, /* The caller passed in a kSecMatchLimit key to a call which does not support limits. */ - errSecItemIllegalQuery = priv_errSecParam, // -34016, /* The caller passed in a query which contained too many keys. */ -}; - -const char *cssmErrorString(CSSM_RETURN error); - -OSStatus SecKeychainErrFromOSStatus(OSStatus osStatus) - __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA); - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECBASEPRIV_H_ */ diff --git a/OSX/include/security_keychain/SecBridge.h b/OSX/include/security_keychain/SecBridge.h deleted file mode 100644 index 2c541baf..00000000 --- a/OSX/include/security_keychain/SecBridge.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2000-2004,2011,2013-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#ifndef _SECURITY_SECBRIDGE_H_ -#define _SECURITY_SECBRIDGE_H_ - -#include -#include -#include "SecBasePriv.h" -#include -#include -#include - -using namespace KeychainCore; - -// -// API boilerplate macros. These provide a frame for C++ code that is impermeable to exceptions. -// Usage: -// BEGIN_API -// ... your C++ code here ... -// END_API // returns CSSM_RETURN on exception -// END_API0 // returns nothing (void) on exception -// END_API1(bad) // return (bad) on exception -// END_API2(name) // like END_API, with API name as debug scope for printing function result -// END_API3(name, bad) // like END_API1, with API name as debug scope for printing function result -// -#define BEGIN_SECAPI \ - OSStatus __secapiresult = errSecSuccess; \ - try { -#define END_SECAPI }\ - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } \ - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } \ - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } \ - catch (...) { __secapiresult=errSecInternalComponent; } \ - return __secapiresult; -#define END_SECAPI1(BAD_RETURN_VAL) \ - } \ - catch (...) \ - { \ - __secapiresult=BAD_RETURN_VAL; \ - } \ - return __secapiresult; -#define END_SECAPI1(BAD_RETURN_VAL) }\ - catch (...) { __secapiresult=BAD_RETURN_VAL; } \ - return __secapiresult; -#define END_SECAPI0 }\ - catch (...) { return; } - -#if SECTRUST_OSX -#define BEGIN_SECCERTAPI \ -OSStatus __secapiresult=errSecSuccess; \ -SecCertificateRef __itemImplRef=(SecCertificateRef)SecCertificateCopyKeychainItem(certificate); \ -if (!__itemImplRef) { __itemImplRef=SecCertificateCreateItemImplInstance(certificate); } \ -try { -#else -#define BEGIN_SECCERTAPI \ -OSStatus __secapiresult=errSecSuccess; \ -SecCertificateRef __itemImplRef=(SecCertificateRef)((certificate)?CFRetain(certificate):NULL); \ -try { -#endif -#define END_SECCERTAPI }\ -catch (const MacOSError &err) { __secapiresult=err.osStatus(); } \ -catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } \ -catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } \ -catch (...) { __secapiresult=errSecInternalComponent; } \ -if (__itemImplRef) { CFRelease(__itemImplRef); } \ -return __secapiresult; - - -#endif /* !_SECURITY_SECBRIDGE_H_ */ diff --git a/OSX/include/security_keychain/SecCFTypes.cpp b/OSX/include/security_keychain/SecCFTypes.cpp deleted file mode 100644 index 474d8206..00000000 --- a/OSX/include/security_keychain/SecCFTypes.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecCFTypes.cpp - CF runtime interface -// - -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -SecCFTypes & -gTypes() -{ - static ModuleNexus nexus; - - return nexus(); -} - -} // end namespace KeychainCore - -} // end namespace Security - -using namespace KeychainCore; - -SecCFTypes::SecCFTypes() : - Access("SecAccess"), - ACL("SecACL"), - Certificate("SecCertificate"), - CertificateRequest("SecCertificateRequest"), - Identity("SecIdentity"), - IdentityCursor("SecIdentitySearch"), - ItemImpl("SecKeychainItem"), - KCCursorImpl("SecKeychainSearch"), - KeychainImpl("SecKeychain"), - KeyItem("SecKey"), - PasswordImpl("SecPassword"), - Policy("SecPolicy"), - PolicyCursor("SecPolicySearch"), - Trust("SecTrust"), - TrustedApplication("SecTrustedApplication"), - ExtendedAttribute("SecKeychainItemExtendedAttributes") -{ -} - diff --git a/OSX/include/security_keychain/SecCFTypes.h b/OSX/include/security_keychain/SecCFTypes.h deleted file mode 100644 index 18935453..00000000 --- a/OSX/include/security_keychain/SecCFTypes.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -// -// SecCFTypes.h - CF runtime interface -// -#ifndef _SECURITY_SECCFTYPES_H_ -#define _SECURITY_SECCFTYPES_H_ - -#include -#include -#include - -namespace Security -{ - -namespace KeychainCore -{ - -/* Singleton that registers all the CFClass instances with the CFRuntime. - - To make something a CFTypeRef you need to make the actual object inheirit from SecCFObject and provide implementation of the virtual functions in that class. - - In addition to that you need to define an opque type for the C API like: - typedef struct __OpaqueYourObject *YourObjectRef; - - Add an instance of CFClass to the public section of SecCFTypes below to get it registered with the CFRuntime. - CFClass yourObject; - - XXX - In your C++ code you should use SecPointer to refer to instances of your class. SecPointers are just like autopointers and implement * and -> semantics. They refcount the underlying object. So to create an instance or your new object you would do something like: - - SecPointer instance(new YourObject()); - - SecPointers have copy semantics and if you subclass SecPointer and define a operator < on the subclass you can even safely store instances of your class in stl containers. - - Use then like this: - instance->somemethod(); - or if you want a reference to the underlying object: - YourObject &object = *instance; - if you want a pointer to the underlying object: - YourObject *object = instance.get(); - - In the API glue you will need to use: - SecPointer instance; - [...] get the instance somehow - return instance->handle(); - to return an opaque handle (the is a CFTypeRef) to your object. - - when you obtain an object as input use: - SecYourObjectRef ref; - SecPointer instance = YourObject::required(ref); - to get a SecPointer to an instance of your object from the external CFTypeRef. -*/ -class SecCFTypes -{ -public: - SecCFTypes(); - -public: - /* Add new instances of CFClass here that you want registered with the CF runtime. */ - CFClass Access; - CFClass ACL; - CFClass Certificate; - CFClass CertificateRequest; - CFClass Identity; - CFClass IdentityCursor; - CFClass ItemImpl; - CFClass KCCursorImpl; - CFClass KeychainImpl; - CFClass KeyItem; - CFClass PasswordImpl; - CFClass Policy; - CFClass PolicyCursor; - CFClass Trust; - CFClass TrustedApplication; - CFClass ExtendedAttribute; -}; - -extern SecCFTypes &gTypes(); - -} // end namespace KeychainCore - -} // end namespace Security - - -#endif // !_SECURITY_SECCFTYPES_H_ diff --git a/OSX/include/security_keychain/SecCertificate.cpp b/OSX/include/security_keychain/SecCertificate.cpp deleted file mode 100644 index 9950aa33..00000000 --- a/OSX/include/security_keychain/SecCertificate.cpp +++ /dev/null @@ -1,1538 +0,0 @@ -/* - * Copyright (c) 2002-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "SecBridge.h" - -// %%% used by SecCertificate{Copy,Set}Preference -#include -#include -#include -#include -#include -#include -#include -#include "CertificateValues.h" -#include "SecCertificateP.h" -#include "SecCertificatePrivP.h" - -#include "AppleBaselineEscrowCertificates.h" - - -SecCertificateRef SecCertificateCreateItemImplInstance(SecCertificateRef certificate); -OSStatus SecCertificateGetCLHandle_legacy(SecCertificateRef certificate, CSSM_CL_HANDLE *clHandle); -extern CSSM_KEYUSE ConvertArrayToKeyUsage(CFArrayRef usage); - -#define SEC_CONST_DECL(k,v) const CFStringRef k = CFSTR(v); - -SEC_CONST_DECL (kSecCertificateProductionEscrowKey, "ProductionEscrowKey"); -SEC_CONST_DECL (kSecCertificateProductionPCSEscrowKey, "ProductionPCSEscrowKey"); -SEC_CONST_DECL (kSecCertificateEscrowFileName, "AppleESCertificates"); - - -using namespace CssmClient; - -#if !SECTRUST_OSX -CFTypeID -SecCertificateGetTypeID(void) -{ - BEGIN_SECAPI - - return gTypes().Certificate.typeID; - - END_SECAPI1(_kCFRuntimeNotATypeID) -} -#endif - -/* convert a new-world SecCertificateRef to an old-world ItemImpl instance */ -SecCertificateRef -SecCertificateCreateItemImplInstance(SecCertificateRef certificate) -{ -#if !SECTRUST_OSX - return (SecCertificateRef)(certificate ? CFRetain(certificate) : NULL); -#else - if (!certificate) { - return NULL; - } - SecCertificateRef implCertRef = (SecCertificateRef) SecCertificateCopyKeychainItem(certificate); - if (implCertRef) { - return implCertRef; - } - CFDataRef data = SecCertificateCopyData(certificate); - if (!data) { - return NULL; - } - try { - CSSM_DATA cssmCertData; - cssmCertData.Length = (data) ? (CSSM_SIZE)CFDataGetLength(data) : 0; - cssmCertData.Data = (data) ? (uint8 *)CFDataGetBytePtr(data) : NULL; - - SecPointer certificatePtr(new Certificate(cssmCertData, CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER)); - implCertRef = certificatePtr->handle(); - } - catch (...) {} - CFRelease(data); - return implCertRef; -#endif -} - -/* convert an old-world ItemImpl instance to a new-world SecCertificateRef */ -SecCertificateRef -SecCertificateCreateFromItemImplInstance(SecCertificateRef certificate) -{ -#if !SECTRUST_OSX - return (SecCertificateRef)(certificate ? CFRetain(certificate) : NULL); -#else - if (!certificate) { - return NULL; - } - SecCertificateRef result = NULL; - CFDataRef data = NULL; - try { - CssmData certData = Certificate::required(certificate)->data(); - if (certData.Data && certData.Length) { - data = CFDataCreate(NULL, certData.Data, certData.Length); - } - if (!data) { - if (certData.Data && !certData.Length) { - /* zero-length certs can exist, so don't bother logging this */ - } - else { - syslog(LOG_ERR, "WARNING: SecKeychainSearchCopyNext failed to retrieve certificate data (length=%ld, data=0x%lX)", - (long)certData.Length, (uintptr_t)certData.Data); - } - return NULL; - } - } - catch (...) {} - - result = SecCertificateCreateWithKeychainItem(NULL, data, certificate); - if (data) - CFRelease(data); - return result; -#endif -} - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateCreateFromData(const CSSM_DATA *data, CSSM_CERT_TYPE type, CSSM_CERT_ENCODING encoding, SecCertificateRef *certificate) -{ -#if !SECTRUST_OSX - BEGIN_SECAPI - - SecPointer certificatePtr(new Certificate(Required(data), type, encoding)); - Required(certificate) = certificatePtr->handle(); - - END_SECAPI -#else - /* bridge to support old functionality */ - if (!data || !data->Data || !data->Length || !certificate) { - return errSecParam; - } - SecCertificateRef certRef = NULL; - CFDataRef dataRef = CFDataCreate(NULL, data->Data, data->Length); - if (dataRef) { - certRef = SecCertificateCreateWithData(NULL, dataRef); - CFRelease(dataRef); - } - *certificate = certRef; - return (certRef) ? errSecSuccess : errSecUnknownFormat; -#endif -} - -#if !SECTRUST_OSX -/* new in 10.6 */ -SecCertificateRef -SecCertificateCreateWithData(CFAllocatorRef allocator, CFDataRef data) -{ - SecCertificateRef certificate = NULL; - OSStatus __secapiresult; - try { - CSSM_DATA cssmCertData; - cssmCertData.Length = (data) ? (CSSM_SIZE)CFDataGetLength(data) : 0; - cssmCertData.Data = (data) ? (uint8 *)CFDataGetBytePtr(data) : NULL; - - //NOTE: there isn't yet a Certificate constructor which accepts a CFAllocatorRef - SecPointer certificatePtr(new Certificate(cssmCertData, CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER)); - certificate = certificatePtr->handle(); - - __secapiresult=errSecSuccess; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return certificate; -} -#endif - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA) */ -OSStatus -SecCertificateAddToKeychain(SecCertificateRef certificate, SecKeychainRef keychain) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Item item(Certificate::required(__itemImplRef)); - Keychain::optional(keychain)->add(item); - - END_SECCERTAPI -} - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateGetData(SecCertificateRef certificate, CSSM_DATA_PTR data) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(data) = Certificate::required(__itemImplRef)->data(); - - END_SECCERTAPI -} - -#if !SECTRUST_OSX -/* new in 10.6 */ -CFDataRef -SecCertificateCopyData(SecCertificateRef certificate) -{ - CFDataRef data = NULL; - OSStatus __secapiresult = errSecSuccess; - try { - CssmData output = Certificate::required(certificate)->data(); - CFIndex length = (CFIndex)output.length(); - const UInt8 *bytes = (const UInt8 *)output.data(); - if (length && bytes) { - data = CFDataCreate(NULL, bytes, length); - } - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return data; -} -#endif - -#if !SECTRUST_OSX -CFDataRef -SecCertificateGetSHA1Digest(SecCertificateRef certificate) -{ - CFDataRef data = NULL; - OSStatus __secapiresult = errSecSuccess; - try { - data = Certificate::required(certificate)->sha1Hash(); - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return data; -} -#endif - -#if !SECTRUST_OSX -CFDataRef -SecCertificateCopyPublicKeySHA1Digest(SecCertificateRef certificate) -{ - CFDataRef data = NULL; - OSStatus __secapiresult = errSecSuccess; - try { - CssmData output = Certificate::required(certificate)->publicKeyHash(); - CFIndex length = (CFIndex)output.length(); - const UInt8 *bytes = (const UInt8 *)output.data(); - if (length && bytes) { - data = CFDataCreate(NULL, bytes, length); - } - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return data; -} -#endif - -#if !SECTRUST_OSX -CFArrayRef -SecCertificateCopyDNSNames(SecCertificateRef certificate) -{ - CFArrayRef names = NULL; - OSStatus __secapiresult = errSecSuccess; - try { - names = Certificate::required(certificate)->copyDNSNames(); - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return names; -} -#endif - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateGetType(SecCertificateRef certificate, CSSM_CERT_TYPE *certificateType) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(certificateType) = Certificate::required(__itemImplRef)->type(); - - END_SECCERTAPI -} - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateGetSubject(SecCertificateRef certificate, const CSSM_X509_NAME **subject) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(subject) = Certificate::required(__itemImplRef)->subjectName(); - - END_SECCERTAPI -} - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateGetIssuer(SecCertificateRef certificate, const CSSM_X509_NAME **issuer) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(issuer) = Certificate::required(__itemImplRef)->issuerName(); - - END_SECCERTAPI -} - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateGetCLHandle(SecCertificateRef certificate, CSSM_CL_HANDLE *clHandle) -{ -#if !SECTRUST_OSX - BEGIN_SECAPI - - Required(clHandle) = Certificate::required(certificate)->clHandle(); - - END_SECAPI -#else -#if 0 - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(clHandle) = Certificate::required(__itemImplRef)->clHandle(); - - END_SECCERTAPI -#endif - /* bridge code to support deprecated functionality */ - OSStatus __secapiresult=errSecSuccess; - bool kcItem=true; - SecCertificateRef __itemImplRef=(SecCertificateRef)SecCertificateCopyKeychainItem(certificate); - if (!__itemImplRef) { __itemImplRef=SecCertificateCreateItemImplInstance(certificate); kcItem=false; } - try { - Required(clHandle) = Certificate::required(__itemImplRef)->clHandle(); - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - if (__itemImplRef) { - if (!kcItem) { - /* we can't release the temporary certificate, or the CL handle becomes invalid. - * for now, just stick the temporary certificate into an array. - * TBD: use a dictionary, indexed by hash of certificate. */ - static CFMutableArrayRef sLegacyCertArray = NULL; - if (!sLegacyCertArray) { - sLegacyCertArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); - if (!sLegacyCertArray) { - return errSecAllocate; - } - } - CFArrayAppendValue(sLegacyCertArray, __itemImplRef); -#ifndef NDEBUG - syslog(LOG_ERR, "WARNING: SecCertificateGetCLHandle called on certificate which is not in a keychain."); -#endif - } - CFRelease(__itemImplRef); - } - return __secapiresult; - -#endif -} - -/* private function; assumes input is old-style ItemImpl certificate reference, - and does not release that certificate reference! - */ -OSStatus -SecCertificateGetCLHandle_legacy(SecCertificateRef certificate, CSSM_CL_HANDLE *clHandle) -{ - BEGIN_SECAPI - - Required(clHandle) = Certificate::required(certificate)->clHandle(); - - END_SECAPI -} - - -/* - * Private API to infer a display name for a SecCertificateRef which - * may or may not be in a keychain. - * - * OS X only - */ -OSStatus -SecCertificateInferLabel(SecCertificateRef certificate, CFStringRef *label) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Certificate::required(__itemImplRef)->inferLabel(false, &Required(label)); - - END_SECCERTAPI -} - -/* OS X only (note: iOS version has different arguments and return value) */ -OSStatus -SecCertificateCopyPublicKey(SecCertificateRef certificate, SecKeyRef *key) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(key) = Certificate::required(__itemImplRef)->publicKey()->handle(); - - END_SECCERTAPI -} - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateGetAlgorithmID(SecCertificateRef certificate, const CSSM_X509_ALGORITHM_IDENTIFIER **algid) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(algid) = Certificate::required(__itemImplRef)->algorithmID(); - - END_SECCERTAPI -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA) */ -OSStatus -SecCertificateCopyCommonName(SecCertificateRef certificate, CFStringRef *commonName) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(commonName) = Certificate::required(__itemImplRef)->commonName(); - - END_SECCERTAPI -} - -#if !SECTRUST_OSX -/* new in 10.6 */ -CFStringRef -SecCertificateCopySubjectSummary(SecCertificateRef certificate) -{ - CFStringRef summary = NULL; - OSStatus __secapiresult; - try { - Certificate::required(certificate)->inferLabel(false, &summary); - - __secapiresult=errSecSuccess; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return summary; -} -#endif - -#if !SECTRUST_OSX -CFStringRef -SecCertificateCopyIssuerSummary(SecCertificateRef certificate) -{ - CFStringRef issuerStr = NULL; - SecCertificateRefP certP = NULL; - CFDataRef certData = SecCertificateCopyData(certificate); - if (certData) { - certP = SecCertificateCreateWithDataP(NULL, certData); - CFRelease(certData); - } - if (certP) { - issuerStr = SecCertificateCopyIssuerSummaryP(certP); - CFRelease(certP); - } - return issuerStr; -} -#endif - -/* OS X only */ -OSStatus -SecCertificateCopySubjectComponent(SecCertificateRef certificate, const CSSM_OID *component, CFStringRef *result) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(result) = Certificate::required(__itemImplRef)->distinguishedName(&CSSMOID_X509V1SubjectNameCStruct, component); - - END_SECCERTAPI -} - -/* OS X only; deprecated SPI */ -OSStatus -SecCertificateGetCommonName(SecCertificateRef certificate, CFStringRef *commonName) -{ - // deprecated SPI signature; replaced by SecCertificateCopyCommonName - return SecCertificateCopyCommonName(certificate, commonName); -} - -/* OS X only; deprecated SPI */ -OSStatus -SecCertificateGetEmailAddress(SecCertificateRef certificate, CFStringRef *emailAddress) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(emailAddress) = Certificate::required(__itemImplRef)->copyFirstEmailAddress(); - - END_SECCERTAPI -} - -/* OS X only */ -OSStatus -SecCertificateCopyEmailAddresses(SecCertificateRef certificate, CFArrayRef *emailAddresses) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(emailAddresses) = Certificate::required(__itemImplRef)->copyEmailAddresses(); - - END_SECCERTAPI -} - -/* Return a zero terminated list of CSSM_DATA_PTR's with the values of the field specified by field. - * Caller must call releaseFieldValues to free the storage allocated by this call. - * - * OS X only - */ -OSStatus -SecCertificateCopyFieldValues(SecCertificateRef certificate, const CSSM_OID *field, CSSM_DATA_PTR **fieldValues) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(fieldValues) = Certificate::required(__itemImplRef)->copyFieldValues(Required(field)); - - END_SECCERTAPI -} - -/* OS X only */ -OSStatus -SecCertificateReleaseFieldValues(SecCertificateRef certificate, const CSSM_OID *field, CSSM_DATA_PTR *fieldValues) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Certificate::required(__itemImplRef)->releaseFieldValues(Required(field), fieldValues); - - END_SECCERTAPI -} - -/* OS X only */ -OSStatus -SecCertificateCopyFirstFieldValue(SecCertificateRef certificate, const CSSM_OID *field, CSSM_DATA_PTR *fieldValue) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Required(fieldValue) = Certificate::required(__itemImplRef)->copyFirstFieldValue(Required(field)); - - END_SECCERTAPI -} - -/* OS X only */ -OSStatus -SecCertificateReleaseFirstFieldValue(SecCertificateRef certificate, const CSSM_OID *field, CSSM_DATA_PTR fieldValue) -{ - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - Certificate::required(__itemImplRef)->releaseFieldValue(Required(field), fieldValue); - - END_SECCERTAPI -} - -/* OS X only */ -OSStatus -SecCertificateFindByIssuerAndSN(CFTypeRef keychainOrArray,const CSSM_DATA *issuer, - const CSSM_DATA *serialNumber, SecCertificateRef *certificate) -{ - BEGIN_SECAPI - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - Required(certificate) = Certificate::findByIssuerAndSN(keychains, CssmData::required(issuer), CssmData::required(serialNumber))->handle(); - -#if SECTRUST_OSX - // convert ItemImpl-based SecCertificateRef to new-world version before returning - CssmData certData = Certificate::required(*certificate)->data(); - CFRef cfData(CFDataCreate(NULL, certData.Data, certData.Length)); - SecCertificateRef tmpRef = *certificate; - *certificate = SecCertificateCreateWithData(NULL, cfData); - CFRelease(tmpRef); -#endif - - END_SECAPI -} - -/* OS X only */ -OSStatus -SecCertificateFindBySubjectKeyID(CFTypeRef keychainOrArray, const CSSM_DATA *subjectKeyID, - SecCertificateRef *certificate) -{ - BEGIN_SECAPI - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - Required(certificate) = Certificate::findBySubjectKeyID(keychains, CssmData::required(subjectKeyID))->handle(); - -#if SECTRUST_OSX - // convert ItemImpl-based SecCertificateRef to new-world version before returning - CssmData certData = Certificate::required(*certificate)->data(); - CFRef cfData(CFDataCreate(NULL, certData.Data, certData.Length)); - SecCertificateRef tmpRef = *certificate; - *certificate = SecCertificateCreateWithData(NULL, cfData); - CFRelease(tmpRef); -#endif - - END_SECAPI -} - -/* OS X only */ -OSStatus -SecCertificateFindByEmail(CFTypeRef keychainOrArray, const char *emailAddress, SecCertificateRef *certificate) -{ - BEGIN_SECAPI - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - Required(certificate) = Certificate::findByEmail(keychains, emailAddress)->handle(); - -#if SECTRUST_OSX - // convert ItemImpl-based SecCertificateRef to new-world version before returning - CssmData certData = Certificate::required(*certificate)->data(); - CFRef cfData(CFDataCreate(NULL, certData.Data, certData.Length)); - SecCertificateRef tmpRef = *certificate; - *certificate = SecCertificateCreateWithData(NULL, cfData); - CFRelease(tmpRef); -#endif - - END_SECAPI -} - -/* OS X only */ -OSStatus -SecKeychainSearchCreateForCertificateByIssuerAndSN(CFTypeRef keychainOrArray, const CSSM_DATA *issuer, - const CSSM_DATA *serialNumber, SecKeychainSearchRef *searchRef) -{ - BEGIN_SECAPI - - Required(searchRef); - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - KCCursor cursor(Certificate::cursorForIssuerAndSN(keychains, CssmData::required(issuer), CssmData::required(serialNumber))); - *searchRef = cursor->handle(); - - END_SECAPI -} - -/* OS X only */ -OSStatus -SecKeychainSearchCreateForCertificateByIssuerAndSN_CF(CFTypeRef keychainOrArray, CFDataRef issuer, - CFDataRef serialNumber, SecKeychainSearchRef *searchRef) -{ - BEGIN_SECAPI - - Required(searchRef); - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - Required(issuer); - Required(serialNumber); - KCCursor cursor(Certificate::cursorForIssuerAndSN_CF(keychains, issuer, serialNumber)); - *searchRef = cursor->handle(); - - END_SECAPI -} - -/* OS X only */ -OSStatus -SecKeychainSearchCreateForCertificateBySubjectKeyID(CFTypeRef keychainOrArray, const CSSM_DATA *subjectKeyID, - SecKeychainSearchRef *searchRef) -{ - BEGIN_SECAPI - - Required(searchRef); - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - KCCursor cursor(Certificate::cursorForSubjectKeyID(keychains, CssmData::required(subjectKeyID))); - *searchRef = cursor->handle(); - - END_SECAPI -} - -/* OS X only */ -OSStatus -SecKeychainSearchCreateForCertificateByEmail(CFTypeRef keychainOrArray, const char *emailAddress, - SecKeychainSearchRef *searchRef) -{ - BEGIN_SECAPI - - Required(searchRef); - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - KCCursor cursor(Certificate::cursorForEmail(keychains, emailAddress)); - *searchRef = cursor->handle(); - - END_SECAPI -} - -/* OS X only */ -CSSM_RETURN -SecDigestGetData (CSSM_ALGORITHMS alg, CSSM_DATA* digest, const CSSM_DATA* data) -{ - BEGIN_SECAPI - // sanity checking - if (!digest || !digest->Data || !digest->Length || !data || !data->Data || !data->Length) - return errSecParam; - - CSP csp(gGuidAppleCSP); - Digest context(csp, alg); - CssmData input(data->Data, data->Length); - CssmData output(digest->Data, digest->Length); - - context.digest(input, output); - digest->Length = output.length(); - - return CSSM_OK; - END_SECAPI1(1); -} - -#if !SECTRUST_OSX -/* determine whether a cert is self-signed */ -OSStatus SecCertificateIsSelfSigned( - SecCertificateRef certificate, - Boolean *isSelfSigned) /* RETURNED */ -{ - BEGIN_SECAPI - - *isSelfSigned = Certificate::required(certificate)->isSelfSigned(); - - END_SECAPI -} -#endif - -/* OS X only: DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER */ -OSStatus -SecCertificateCopyPreference( - CFStringRef name, - CSSM_KEYUSE keyUsage, - SecCertificateRef *certificate) -{ - BEGIN_SECAPI - - Required(name); - Required(certificate); - StorageManager::KeychainList keychains; - globals().storageManager.getSearchList(keychains); - KCCursor cursor(keychains, kSecGenericPasswordItemClass, NULL); - - char idUTF8[MAXPATHLEN]; - if (!CFStringGetCString(name, idUTF8, sizeof(idUTF8)-1, kCFStringEncodingUTF8)) - idUTF8[0] = (char)'\0'; - CssmData service(const_cast(idUTF8), strlen(idUTF8)); - FourCharCode itemType = 'cprf'; - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecServiceItemAttr), service); - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecTypeItemAttr), itemType); - if (keyUsage) - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage); - - Item prefItem; - if (!cursor->next(prefItem)) - MacOSError::throwMe(errSecItemNotFound); - - // get persistent certificate reference - SecKeychainAttribute itemAttrs[] = { { kSecGenericItemAttr, 0, NULL } }; - SecKeychainAttributeList itemAttrList = { sizeof(itemAttrs) / sizeof(itemAttrs[0]), itemAttrs }; - prefItem->getContent(NULL, &itemAttrList, NULL, NULL); - - // find certificate, given persistent reference data - CFDataRef pItemRef = CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)itemAttrs[0].data, itemAttrs[0].length, kCFAllocatorNull); - SecKeychainItemRef certItemRef = nil; - OSStatus status = SecKeychainItemCopyFromPersistentReference(pItemRef, &certItemRef); //%%% need to make this a method of ItemImpl - prefItem->freeContent(&itemAttrList, NULL); - if (pItemRef) - CFRelease(pItemRef); - if (status) - return status; - - *certificate = (SecCertificateRef)certItemRef; - -#if SECTRUST_OSX - // convert ItemImpl-based SecCertificateRef to new-world version before returning - CssmData certData = Certificate::required(*certificate)->data(); - CFRef cfData(CFDataCreate(NULL, certData.Data, certData.Length)); - SecCertificateRef tmpRef = *certificate; - *certificate = SecCertificateCreateWithData(NULL, cfData); - CFRelease(tmpRef); -#endif - - END_SECAPI -} - -/* OS X only */ -SecCertificateRef -SecCertificateCopyPreferred( - CFStringRef name, - CFArrayRef keyUsage) -{ - // This function will look for a matching preference in the following order: - // - matches the name and the supplied key use - // - matches the name and the special 'ANY' key use - // - matches the name with no key usage constraint - - SecCertificateRef certRef = NULL; - CSSM_KEYUSE keyUse = ConvertArrayToKeyUsage(keyUsage); - OSStatus status = SecCertificateCopyPreference(name, keyUse, &certRef); - if (status != errSecSuccess && keyUse != CSSM_KEYUSE_ANY) - status = SecCertificateCopyPreference(name, CSSM_KEYUSE_ANY, &certRef); - if (status != errSecSuccess && keyUse != 0) - status = SecCertificateCopyPreference(name, 0, &certRef); - - return certRef; -} - -/* OS X only; not exported */ -static OSStatus -SecCertificateFindPreferenceItemWithNameAndKeyUsage( - CFTypeRef keychainOrArray, - CFStringRef name, - int32_t keyUsage, - SecKeychainItemRef *itemRef) -{ - BEGIN_SECAPI - - StorageManager::KeychainList keychains; - globals().storageManager.optionalSearchList(keychainOrArray, keychains); - KCCursor cursor(keychains, kSecGenericPasswordItemClass, NULL); - - char idUTF8[MAXPATHLEN]; - idUTF8[0] = (char)'\0'; - if (name) - { - if (!CFStringGetCString(name, idUTF8, sizeof(idUTF8)-1, kCFStringEncodingUTF8)) - idUTF8[0] = (char)'\0'; - } - size_t idUTF8Len = strlen(idUTF8); - if (!idUTF8Len) - MacOSError::throwMe(errSecParam); - - CssmData service(const_cast(idUTF8), idUTF8Len); - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecServiceItemAttr), service); - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecTypeItemAttr), (FourCharCode)'cprf'); - if (keyUsage) - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage); - - Item item; - if (!cursor->next(item)) - MacOSError::throwMe(errSecItemNotFound); - - if (itemRef) - *itemRef=item->handle(); - - END_SECAPI -} - -/* OS X only; not exported */ -static -OSStatus SecCertificateDeletePreferenceItemWithNameAndKeyUsage( - CFTypeRef keychainOrArray, - CFStringRef name, - int32_t keyUsage) -{ - // when a specific key usage is passed, we'll only match & delete that pref; - // when a key usage of 0 is passed, all matching prefs should be deleted. - // maxUsages represents the most matches there could theoretically be, so - // cut things off at that point if we're still finding items (if they can't - // be deleted for some reason, we'd never break out of the loop.) - - OSStatus status; - SecKeychainItemRef item = NULL; - int count = 0, maxUsages = 12; - while (++count <= maxUsages && - (status = SecCertificateFindPreferenceItemWithNameAndKeyUsage(keychainOrArray, name, keyUsage, &item)) == errSecSuccess) { - status = SecKeychainItemDelete(item); - CFRelease(item); - item = NULL; - } - - // it's not an error if the item isn't found - return (status == errSecItemNotFound) ? errSecSuccess : status; -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA) */ -OSStatus SecCertificateSetPreference( - SecCertificateRef certificate, - CFStringRef name, - CSSM_KEYUSE keyUsage, - CFDateRef date) -{ - if (!name) { - return errSecParam; - } - if (!certificate) { - // treat NULL certificate as a request to clear the preference - // (note: if keyUsage is 0, this clears all key usage prefs for name) - return SecCertificateDeletePreferenceItemWithNameAndKeyUsage(NULL, name, keyUsage); - } - - // This macro converts a new-style SecCertificateRef to an old-style ItemImpl - BEGIN_SECCERTAPI - - // determine the account attribute - // - // This attribute must be synthesized from certificate label + pref item type + key usage, - // as only the account and service attributes can make a generic keychain item unique. - // For 'iprf' type items (but not 'cprf'), we append a trailing space. This insures that - // we can save a certificate preference if an identity preference already exists for the - // given service name, and vice-versa. - // If the key usage is 0 (i.e. the normal case), we omit the appended key usage string. - // - CFStringRef labelStr = nil; - Certificate::required(__itemImplRef)->inferLabel(false, &labelStr); - if (!labelStr) { - MacOSError::throwMe(errSecDataTooLarge); // data is "in a format which cannot be displayed" - } - CFIndex accountUTF8Len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(labelStr), kCFStringEncodingUTF8) + 1; - const char *templateStr = "%s [key usage 0x%X]"; - const int keyUsageMaxStrLen = 8; - accountUTF8Len += strlen(templateStr) + keyUsageMaxStrLen; - char accountUTF8[accountUTF8Len]; - if (!CFStringGetCString(labelStr, accountUTF8, accountUTF8Len-1, kCFStringEncodingUTF8)) - accountUTF8[0] = (char)'\0'; - if (keyUsage) - snprintf(accountUTF8, accountUTF8Len-1, templateStr, accountUTF8, keyUsage); - CssmData account(const_cast(accountUTF8), strlen(accountUTF8)); - CFRelease(labelStr); - - // service attribute (name provided by the caller) - CFIndex serviceUTF8Len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(name), kCFStringEncodingUTF8) + 1;; - char serviceUTF8[serviceUTF8Len]; - if (!CFStringGetCString(name, serviceUTF8, serviceUTF8Len-1, kCFStringEncodingUTF8)) - serviceUTF8[0] = (char)'\0'; - CssmData service(const_cast(serviceUTF8), strlen(serviceUTF8)); - - // look for existing preference item, in case this is an update - StorageManager::KeychainList keychains; - globals().storageManager.getSearchList(keychains); - KCCursor cursor(keychains, kSecGenericPasswordItemClass, NULL); - FourCharCode itemType = 'cprf'; - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecServiceItemAttr), service); - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecTypeItemAttr), itemType); - if (keyUsage) - cursor->add(CSSM_DB_EQUAL, Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage); - if (date) - ; // %%%TBI - - Item item(kSecGenericPasswordItemClass, 'aapl', 0, NULL, false); - bool add = (!cursor->next(item)); - // at this point, we either have a new item to add or an existing item to update - - // set item attribute values - item->setAttribute(Schema::attributeInfo(kSecServiceItemAttr), service); - item->setAttribute(Schema::attributeInfo(kSecTypeItemAttr), itemType); - item->setAttribute(Schema::attributeInfo(kSecAccountItemAttr), account); - item->setAttribute(Schema::attributeInfo(kSecScriptCodeItemAttr), (sint32)keyUsage); - item->setAttribute(Schema::attributeInfo(kSecLabelItemAttr), service); - - // date - if (date) - ; // %%%TBI - - // generic attribute (store persistent certificate reference) - CFDataRef pItemRef = nil; - Certificate::required(__itemImplRef)->copyPersistentReference(pItemRef); - if (!pItemRef) { - MacOSError::throwMe(errSecInvalidItemRef); - } - const UInt8 *dataPtr = CFDataGetBytePtr(pItemRef); - CFIndex dataLen = CFDataGetLength(pItemRef); - CssmData pref(const_cast(reinterpret_cast(dataPtr)), dataLen); - item->setAttribute(Schema::attributeInfo(kSecGenericItemAttr), pref); - CFRelease(pItemRef); - - if (add) { - Keychain keychain = nil; - try { - keychain = globals().storageManager.defaultKeychain(); - if (!keychain->exists()) - MacOSError::throwMe(errSecNoSuchKeychain); // Might be deleted or not available at this time. - } - catch(...) { - keychain = globals().storageManager.defaultKeychainUI(item); - } - - try { - keychain->add(item); - } - catch (const MacOSError &err) { - if (err.osStatus() != errSecDuplicateItem) - throw; // if item already exists, fall through to update - } - } - item->update(); - - END_SECCERTAPI -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -OSStatus SecCertificateSetPreferred( - SecCertificateRef certificate, - CFStringRef name, - CFArrayRef keyUsage) -{ - CSSM_KEYUSE keyUse = ConvertArrayToKeyUsage(keyUsage); - return SecCertificateSetPreference(certificate, name, keyUse, NULL); -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -CFDictionaryRef SecCertificateCopyValues(SecCertificateRef certificate, CFArrayRef keys, CFErrorRef *error) -{ - CFDictionaryRef result = NULL; - OSStatus __secapiresult; - try - { - CertificateValues cv(certificate); - result = cv.copyFieldValues(keys,error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -CFStringRef SecCertificateCopyLongDescription(CFAllocatorRef alloc, SecCertificateRef certificate, CFErrorRef *error) -{ - return SecCertificateCopyShortDescription(alloc, certificate, error); -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -CFStringRef SecCertificateCopyShortDescription(CFAllocatorRef alloc, SecCertificateRef certificate, CFErrorRef *error) -{ - CFStringRef result = NULL; - OSStatus __secapiresult = SecCertificateInferLabel(certificate, &result); - if (error!=NULL && __secapiresult!=errSecSuccess) - { - *error = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, - __secapiresult ? __secapiresult : CSSM_ERRCODE_INTERNAL_ERROR, NULL); - } - return result; -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -CFDataRef SecCertificateCopySerialNumber(SecCertificateRef certificate, CFErrorRef *error) -{ - CFDataRef result = NULL; - OSStatus __secapiresult; - try - { - CertificateValues cv(certificate); - result = cv.copySerialNumber(error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -CFDataRef SecCertificateCopyNormalizedIssuerContent(SecCertificateRef certificate, CFErrorRef *error) -{ - CFDataRef result = NULL; - OSStatus __secapiresult; - try - { - CertificateValues cv(certificate); - result = cv.copyNormalizedIssuerContent(error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} - -/* OS X only: __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA) */ -CFDataRef SecCertificateCopyNormalizedSubjectContent(SecCertificateRef certificate, CFErrorRef *error) -{ - CFDataRef result = NULL; - OSStatus __secapiresult; - try - { - CertificateValues cv(certificate); - result = cv.copyNormalizedSubjectContent(error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} - -#if !SECTRUST_OSX -CFDataRef SecCertificateCopyIssuerSequence(SecCertificateRef certificate) -{ - CFDataRef result = NULL; - OSStatus __secapiresult; - try - { - CertificateValues cv(certificate); - result = cv.copyIssuerSequence(NULL); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} -#endif - -#if !SECTRUST_OSX -CFDataRef SecCertificateCopySubjectSequence(SecCertificateRef certificate) -{ - CFDataRef result = NULL; - OSStatus __secapiresult; - try - { - CertificateValues cv(certificate); - result = cv.copySubjectSequence(NULL); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} -#endif - -#if !SECTRUST_OSX -bool SecCertificateIsValid(SecCertificateRef certificate, CFAbsoluteTime verifyTime) -{ - bool result = NULL; - OSStatus __secapiresult; - try - { - CFErrorRef error = NULL; - CertificateValues cv(certificate); - result = cv.isValid(verifyTime, &error); - if (error) CFRelease(error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} -#endif - -/* OS X only: __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_7, __MAC_10_9, __IPHONE_NA, __IPHONE_NA) */ -bool SecCertificateIsValidX(SecCertificateRef certificate, CFAbsoluteTime verifyTime) -{ - /* - * deprecated function name - */ - return SecCertificateIsValid(certificate, verifyTime); -} - -#if !SECTRUST_OSX -CFAbsoluteTime SecCertificateNotValidBefore(SecCertificateRef certificate) -{ - CFAbsoluteTime result = 0; - OSStatus __secapiresult; - try - { - CFErrorRef error = NULL; - CertificateValues cv(certificate); - result = cv.notValidBefore(&error); - if (error) CFRelease(error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} -#endif - -#if !SECTRUST_OSX -CFAbsoluteTime SecCertificateNotValidAfter(SecCertificateRef certificate) -{ - CFAbsoluteTime result = 0; - OSStatus __secapiresult; - try - { - CFErrorRef error = NULL; - CertificateValues cv(certificate); - result = cv.notValidAfter(&error); - if (error) CFRelease(error); - __secapiresult=0; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return result; -} -#endif - -#if !SECTRUST_OSX -/* new in 10.8 */ -SecCertificateRef SecCertificateCreateWithBytes(CFAllocatorRef allocator, - const UInt8 *bytes, CFIndex length) -{ - SecCertificateRef certificate = NULL; - OSStatus __secapiresult; - try { - CSSM_DATA cssmCertData = { (CSSM_SIZE)length, (uint8 *)bytes }; - - //NOTE: there isn't yet a Certificate constructor which accepts a CFAllocatorRef - SecPointer certificatePtr(new Certificate(cssmCertData, CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER)); - certificate = certificatePtr->handle(); - - __secapiresult=errSecSuccess; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return certificate; -} -#endif - -#if !SECTRUST_OSX -/* new in 10.8 */ -CFIndex SecCertificateGetLength(SecCertificateRef certificate) -{ - CFIndex length = 0; - OSStatus __secapiresult; - try { - CssmData output = Certificate::required(certificate)->data(); - length = (CFIndex)output.length(); - __secapiresult=errSecSuccess; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return length; -} -#endif - -#if !SECTRUST_OSX -/* new in 10.8 */ -const UInt8 *SecCertificateGetBytePtr(SecCertificateRef certificate) -{ - const UInt8 *bytes = NULL; - OSStatus __secapiresult; - try { - CssmData output = Certificate::required(certificate)->data(); - bytes = (const UInt8 *)output.data(); - __secapiresult=errSecSuccess; - } - catch (const MacOSError &err) { __secapiresult=err.osStatus(); } - catch (const CommonError &err) { __secapiresult=SecKeychainErrFromOSStatus(err.osStatus()); } - catch (const std::bad_alloc &) { __secapiresult=errSecAllocate; } - catch (...) { __secapiresult=errSecInternalComponent; } - return bytes; -} -#endif - -#if !SECTRUST_OSX -/* not exported */ -static CFArrayRef CopyEscrowCertificates(SecCertificateEscrowRootType escrowRootType, CFErrorRef *error) -{ - // Return array of CFDataRef certificates. - CFArrayRef result = NULL; - int iCnt; - int numRoots = 0; - - // Get the hard coded set of production roots - // static struct RootRecord* kProductionEscrowRoots[] = {&kOldEscrowRootRecord, &kProductionEscrowRootRecord}; - - struct RootRecord** pEscrowRoots = NULL; - switch (escrowRootType) { - case kSecCertificateBaselineEscrowRoot: - numRoots = kNumberOfBaseLineEscrowRoots; - pEscrowRoots = kBaseLineEscrowRoots; - break; - case kSecCertificateProductionEscrowRoot: - numRoots = kNumberOfBaseLineEscrowRoots; //%%% currently, production == baseline on OS X - pEscrowRoots = kBaseLineEscrowRoots; - break; - case kSecCertificateBaselinePCSEscrowRoot: - numRoots = kNumberOfBaseLinePCSEscrowRoots; - pEscrowRoots = kBaseLinePCSEscrowRoots; - break; - case kSecCertificateProductionPCSEscrowRoot: - numRoots = kNumberOfBaseLinePCSEscrowRoots; //%%% currently, production == baseline on OS X - pEscrowRoots = kBaseLinePCSEscrowRoots; - break; - default: - break; - } - - CFDataRef productionCerts[numRoots]; - struct RootRecord* pRootRecord = NULL; - - for (iCnt = 0; pEscrowRoots != NULL && iCnt < numRoots; iCnt++) - { - pRootRecord = pEscrowRoots[iCnt]; - if (NULL != pRootRecord && pRootRecord->_length > 0 && NULL != pRootRecord->_bytes) - { - productionCerts[iCnt] = CFDataCreate(kCFAllocatorDefault, pRootRecord->_bytes, pRootRecord->_length); - } - } - result = CFArrayCreate(kCFAllocatorDefault, (const void **)productionCerts, numRoots, &kCFTypeArrayCallBacks); - for (iCnt = 0; iCnt < numRoots; iCnt++) - { - if (NULL != productionCerts[iCnt]) - { - CFRelease(productionCerts[iCnt]); - } - } - - return result; -} -#endif - -#if !SECTRUST_OSX -/* new in 10.9 */ -CFArrayRef SecCertificateCopyEscrowRoots(SecCertificateEscrowRootType escrowRootType) -{ - CFArrayRef result = NULL; - int iCnt; - int numRoots = 0; - CFDataRef certData = NULL; - - // The request is for the base line certificates. - // Use the hard coded data to generate the return array - if (kSecCertificateBaselineEscrowRoot == escrowRootType) - { - // Get the hard coded set of roots - numRoots = kNumberOfBaseLineEscrowRoots; - SecCertificateRef baseLineCerts[numRoots]; - struct RootRecord* pRootRecord = NULL; - - for (iCnt = 0; iCnt < numRoots; iCnt++) - { - pRootRecord = kBaseLineEscrowRoots[iCnt]; - if (NULL != pRootRecord && pRootRecord->_length > 0 && NULL != pRootRecord->_bytes) - { - certData = CFDataCreate(kCFAllocatorDefault, pRootRecord->_bytes, pRootRecord->_length); - if (NULL != certData) - { - baseLineCerts[iCnt] = SecCertificateCreateWithData(kCFAllocatorDefault, certData); - CFRelease(certData); - } - } - } - result = CFArrayCreate(kCFAllocatorDefault, (const void **)baseLineCerts, numRoots, &kCFTypeArrayCallBacks); - for (iCnt = 0; iCnt < numRoots; iCnt++) - { - if (NULL != baseLineCerts[iCnt]) - { - CFRelease(baseLineCerts[iCnt]); - } - } - } - // The request is for the current certificates. - else - { - CFErrorRef error = NULL; - CFArrayRef cert_datas = CopyEscrowCertificates(escrowRootType, &error); - if (NULL != error || NULL == cert_datas || 0 == (numRoots = (int)CFArrayGetCount(cert_datas))) - { - if (NULL != error) - { - CFRelease(error); - } - - if (NULL != cert_datas) - { - CFRelease(cert_datas); - } - return result; - } - - SecCertificateRef assetCerts[numRoots]; - for (iCnt = 0; iCnt < numRoots; iCnt++) - { - certData = (CFDataRef)CFArrayGetValueAtIndex(cert_datas, iCnt); - if (NULL != certData) - { - SecCertificateRef aCertRef = SecCertificateCreateWithData(kCFAllocatorDefault, certData); - assetCerts[iCnt] = aCertRef; - } - else - { - assetCerts[iCnt] = NULL; - } - } - - if (numRoots > 0) - { - result = CFArrayCreate(kCFAllocatorDefault, (const void **)assetCerts, numRoots, &kCFTypeArrayCallBacks); - for (iCnt = 0; iCnt < numRoots; iCnt++) - { - if (NULL != assetCerts[iCnt]) - { - CFRelease(assetCerts[iCnt]); - } - } - } - CFRelease(cert_datas); - } - - return result; -} -#endif - -#if !SECTRUST_OSX -/* new in 10.11 */ -SecSignatureHashAlgorithm SecCertificateGetSignatureHashAlgorithm(SecCertificateRef certificate) -{ - SecSignatureHashAlgorithm result = kSecSignatureHashAlgorithmUnknown; - CSSM_X509_ALGORITHM_IDENTIFIER_PTR algId = NULL; - CSSM_DATA_PTR fieldValue = NULL; - CSSM_OID_PTR algOID = NULL; - const CSSM_OID *sigAlgOID = &CSSMOID_X509V1SignatureAlgorithm; - OSStatus status; - - status = SecCertificateCopyFirstFieldValue(certificate, sigAlgOID, &fieldValue); - if (status || !fieldValue) { - return result; - } - algId = (CSSM_X509_ALGORITHM_IDENTIFIER_PTR)fieldValue->Data; - algOID = (algId) ? &algId->algorithm : NULL; - - while (algOID) { - if (!algOID->Data || !algOID->Length) { - break; - } - /* classify the signature algorithm OID into one of our known types */ - if (cuCompareCssmData(algOID, &CSSMOID_ECDSA_WithSHA512) || - cuCompareCssmData(algOID, &CSSMOID_SHA512WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_SHA512)) { - result = kSecSignatureHashAlgorithmSHA512; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_ECDSA_WithSHA384) || - cuCompareCssmData(algOID, &CSSMOID_SHA384WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_SHA384)) { - result = kSecSignatureHashAlgorithmSHA384; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_ECDSA_WithSHA256) || - cuCompareCssmData(algOID, &CSSMOID_SHA256WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_SHA256)) { - result = kSecSignatureHashAlgorithmSHA256; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_ECDSA_WithSHA224) || - cuCompareCssmData(algOID, &CSSMOID_SHA224WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_SHA224)) { - result = kSecSignatureHashAlgorithmSHA224; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_ECDSA_WithSHA1) || - cuCompareCssmData(algOID, &CSSMOID_SHA1WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_SHA1WithDSA) || - cuCompareCssmData(algOID, &CSSMOID_SHA1WithDSA_CMS) || - cuCompareCssmData(algOID, &CSSMOID_SHA1WithDSA_JDK) || - cuCompareCssmData(algOID, &CSSMOID_SHA1WithRSA_OIW) || - cuCompareCssmData(algOID, &CSSMOID_APPLE_FEE_SHA1) || - cuCompareCssmData(algOID, &CSSMOID_SHA1)) { - result = kSecSignatureHashAlgorithmSHA1; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_MD5WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_APPLE_FEE_MD5) || - cuCompareCssmData(algOID, &CSSMOID_MD5)) { - result = kSecSignatureHashAlgorithmMD5; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_MD4WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_MD4)) { - result = kSecSignatureHashAlgorithmMD4; - break; - } - if (cuCompareCssmData(algOID, &CSSMOID_MD2WithRSA) || - cuCompareCssmData(algOID, &CSSMOID_MD2)) { - result = kSecSignatureHashAlgorithmMD2; - break; - } - break; - } - - (void)SecCertificateReleaseFirstFieldValue(certificate, sigAlgOID, fieldValue); - - return result; -} -#endif - diff --git a/OSX/include/security_keychain/SecCertificate.h b/OSX/include/security_keychain/SecCertificate.h deleted file mode 100644 index 7eb01b64..00000000 --- a/OSX/include/security_keychain/SecCertificate.h +++ /dev/null @@ -1,480 +0,0 @@ -/* - * Copyright (c) 2002-2011,2013 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCertificate - The functions provided in SecCertificate implement and manage a particular type of keychain item that represents a certificate. You can store a certificate in a keychain, but a certificate can also be a transient object. - - You can use a certificate as a keychain item in most functions. -*/ - -#ifndef _SECURITY_SECCERTIFICATE_H_ -#define _SECURITY_SECCERTIFICATE_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -/* -#include -#include -*/ - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN -CF_IMPLICIT_BRIDGING_ENABLED - -/*! - @enum CertificateItemAttributes - @abstract Indicates the type of a certificate item attribute. - @constant kSecSubjectItemAttr Indicates a DER-encoded subject distinguished name. - @constant kSecIssuerItemAttr Indicates a DER-encoded issuer distinguished name. - @constant kSecSerialNumberItemAttr Indicates a DER-encoded certificate serial number (without the tag and length). - @constant kSecPublicKeyHashItemAttr Indicates a public key hash. - @constant kSecSubjectKeyIdentifierItemAttr Indicates a subject key identifier. - @constant kSecCertTypeItemAttr Indicates a certificate type. - @constant kSecCertEncodingItemAttr Indicates a certificate encoding. -*/ -enum -{ - kSecSubjectItemAttr = 'subj', - kSecIssuerItemAttr = 'issu', - kSecSerialNumberItemAttr = 'snbr', - kSecPublicKeyHashItemAttr = 'hpky', - kSecSubjectKeyIdentifierItemAttr = 'skid', - kSecCertTypeItemAttr = 'ctyp', - kSecCertEncodingItemAttr = 'cenc' -} /*DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER*/; - -/*! - @function SecCertificateGetTypeID - @abstract Returns the type identifier of SecCertificate instances. - @result The CFTypeID of SecCertificate instances. -*/ -CFTypeID SecCertificateGetTypeID(void) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_2_0); - -#pragma mark ---- Certificate Operations ---- - -/*! - @function SecCertificateCreateFromData - @abstract Creates a certificate based on the input data, type, and encoding. - @param data A pointer to the certificate data. - @param type The certificate type as defined in cssmtype.h. - @param encoding The certificate encoding as defined in cssmtype.h. - @param certificate On return, a reference to the newly created certificate. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This API is deprecated in 10.7 Please use the SecCertificateCreateWithData API instead. -*/ -OSStatus SecCertificateCreateFromData(const CSSM_DATA *data, CSSM_CERT_TYPE type, CSSM_CERT_ENCODING encoding, SecCertificateRef * __nonnull CF_RETURNS_RETAINED certificate) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateCreateWithData - @abstract Create a certificate reference given its DER representation as a CFData. - @param allocator CFAllocator to allocate the certificate data. Pass NULL to use the default allocator. - @param certificate DER encoded X.509 certificate. - @result On return, a reference to the certificate. Returns NULL if the passed-in data is not a valid DER-encoded X.509 certificate. -*/ -__nullable -SecCertificateRef SecCertificateCreateWithData(CFAllocatorRef __nullable allocator, CFDataRef data) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0); - -/*! - @function SecCertificateAddToKeychain - @abstract Adds a certificate to the specified keychain. - @param certificate A reference to a certificate. - @param keychain A reference to the keychain in which to add the certificate. Pass NULL to add the certificate to the default keychain. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function is successful only if the certificate was created using the SecCertificateCreateFromData or - SecCertificateCreateWithData functions, and the certificate has not yet been added to the specified keychain. -*/ -OSStatus SecCertificateAddToKeychain(SecCertificateRef certificate, SecKeychainRef __nullable keychain) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - -/*! - @function SecCertificateGetData - @abstract Retrieves the data for a given certificate. - @param certificate A reference to the certificate from which to retrieve the data. - @param data On return, the CSSM_DATA structure pointed to by data is filled in. You must allocate the space for a CSSM_DATA structure before calling this function. This data pointer is only guaranteed to remain valid as long as the certificate remains unchanged and valid. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This API is deprecated in 10.7. Please use the SecCertificateCopyData API instead. -*/ -OSStatus SecCertificateGetData(SecCertificateRef certificate, CSSM_DATA_PTR data) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateCopyData - @abstract Returns the DER representation of an X.509 certificate. - @param certificate A reference to a certificate. - @result On return, a data reference containing the DER encoded representation of the X.509 certificate. - */ -CFDataRef SecCertificateCopyData(SecCertificateRef certificate) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0); - -/*! - @function SecCertificateGetType - @abstract Retrieves the type for a given certificate. - @param certificate A reference to the certificate from which to obtain the type. - @param certificateType On return, the certificate type of the certificate. Certificate types are defined in cssmtype.h. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This API is deprecated in 10.7. Please use the SecCertificateCopyValues API instead. -*/ -OSStatus SecCertificateGetType(SecCertificateRef certificate, CSSM_CERT_TYPE *certificateType) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateGetSubject - @abstract Retrieves the subject name for a given certificate. - @param certificate A reference to the certificate from which to obtain the subject name. - @param subject On return, a pointer to a CSSM_X509_NAME struct which contains the subject's X.509 name (x509defs.h). This pointer remains valid until the certificate reference is released. The caller should not attempt to free this pointer. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion Prior to Mac OS X 10.5, this function did not return any output in the subject parameter. Your code should check the returned pointer value (in addition to the function result) before attempting to use it. - For example: - const CSSM_X509_NAME *subject = NULL; - OSStatus status = SecCertificateGetSubject(certificate, &subject); - if ( (status == errSecSuccess) && (subject != NULL) ) { - // subject is valid - } - This API is deprecated in 10.7. Please use the SecCertificateCopyValues API instead. -*/ -OSStatus SecCertificateGetSubject(SecCertificateRef certificate, const CSSM_X509_NAME * __nullable * __nonnull subject) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateGetIssuer - @abstract Retrieves the issuer name for a given certificate. - @param certificate A reference to the certificate from which to obtain the issuer name. - @param issuer On return, a pointer to a CSSM_X509_NAME struct which contains the issuer's X.509 name (x509defs.h). This pointer remains valid until the certificate reference is released. The caller should not attempt to free this pointer. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion Prior to Mac OS X 10.5, this function did not return any output in the issuer parameter. Your code should check the returned pointer value (in addition to the function result) before attempting to use it. - For example: - const CSSM_X509_NAME *issuer = NULL; - OSStatus status = SecCertificateGetIssuer(certificate, &issuer); - if ( (status == errSecSuccess) && (issuer != NULL) ) { - // issuer is valid - } - This API is deprecated in 10.7. Please use the SecCertificateCopyValues API instead. -*/ -OSStatus SecCertificateGetIssuer(SecCertificateRef certificate, const CSSM_X509_NAME * __nullable * __nonnull issuer) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateGetCLHandle - @abstract Retrieves the certificate library handle for a given certificate. - @param certificate A reference to the certificate from which to obtain the certificate library handle. - @param clHandle On return, the certificate library handle of the given certificate. This handle remains valid at least as long as the certificate does. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This API is deprecated in 10.7. Please use the SecCertificateCopyValues API instead. -*/ -OSStatus SecCertificateGetCLHandle(SecCertificateRef certificate, CSSM_CL_HANDLE *clHandle) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateGetAlgorithmID - @abstract Retrieves the algorithm identifier for a given certificate. - @param certificate A reference to the certificate from which to retrieve the algorithm identifier. - @param algid On return, a pointer to a CSSM_X509_ALGORITHM_IDENTIFIER struct which identifies the algorithm for this certificate (x509defs.h). This pointer remains valid until the certificate reference is released. The caller should not attempt to free this pointer. - @result A result code. See "Security Error Codes" (SecBase.h). - discussion This API is deprecated in 10.7. Please use the SecCertificateCopyValues API instead. -*/ -OSStatus SecCertificateGetAlgorithmID(SecCertificateRef certificate, const CSSM_X509_ALGORITHM_IDENTIFIER * __nullable * __nonnull algid) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateCopyPublicKey - @abstract Retrieves the public key for a given certificate. - @param certificate A reference to the certificate from which to retrieve the public key. - @param key On return, a reference to the public key for the specified certificate. Your code must release this reference by calling the CFRelease function. - @result A result code. See "Security Error Codes" (SecBase.h). -*/ -OSStatus SecCertificateCopyPublicKey(SecCertificateRef certificate, SecKeyRef * __nonnull CF_RETURNS_RETAINED key) - __OSX_AVAILABLE_STARTING(__MAC_10_3, __IPHONE_NA); - -/*! - @function SecCertificateCopyCommonName - @abstract Retrieves the common name of the subject of a given certificate. - @param certificate A reference to the certificate from which to retrieve the common name. - @param commonName On return, a reference to the common name. Your code must release this reference by calling the CFRelease function. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion All the data in this string comes from the certificate itself, and thus it's in whatever language the certificate itself is in. - Note that the certificate's common name field may not be present, or may be inadequate to describe the certificate; for display purposes, - you should consider using SecCertificateCopySubjectSummary instead of this function. -*/ -OSStatus SecCertificateCopyCommonName(SecCertificateRef certificate, CFStringRef * __nonnull CF_RETURNS_RETAINED commonName) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -/*! - @function SecCertificateCopySubjectSummary - @abstract Returns a simple string which hopefully represents a human understandable summary. - @param certificate A reference to the certificate from which to derive the subject summary string. - @result On return, a reference to the subject summary string. Your code must release this reference by calling the CFRelease function. - @discussion All the data in this string comes from the certificate itself, and thus it's in whatever language the certificate itself is in. -*/ -CFStringRef SecCertificateCopySubjectSummary(SecCertificateRef certificate) - __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0); - -/*! - @function SecCertificateCopyEmailAddresses - @abstract Returns an array of zero or more email addresses for the subject of a given certificate. - @param certificate A reference to the certificate from which to retrieve the email addresses. - @param emailAddresses On return, an array of zero or more CFStringRef elements corresponding to each email address found. - Your code must release this array reference by calling the CFRelease function. - @result A result code. See "Security Error Codes" (SecBase.h). -*/ -OSStatus SecCertificateCopyEmailAddresses(SecCertificateRef certificate, CFArrayRef * __nonnull CF_RETURNS_RETAINED emailAddresses) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -/*! - @function SecCertificateCopyPreference - @abstract Returns the preferred certificate for the specified name and key usage. If a preferred certificate does not exist for the specified name and key usage, NULL is returned. - @param name A string containing an email address (RFC822) or other name for which a preferred certificate is requested. - @param keyUsage A CSSM_KEYUSE key usage value, as defined in cssmtype.h. Pass 0 to ignore this parameter. - @param certificate On return, a reference to the preferred certificate, or NULL if none was found. You are responsible for releasing this reference by calling the CFRelease function. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function will typically be used to obtain the preferred encryption certificate for an email recipient. - This API is deprecated in 10.7. Please use the SecCertificateCopyPreferred API instead. -*/ -OSStatus SecCertificateCopyPreference(CFStringRef name, uint32 keyUsage, SecCertificateRef * __nonnull CF_RETURNS_RETAINED certificate) - DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER; - -/*! - @function SecCertificateCopyPreferred - @abstract Returns the preferred certificate for the specified name and key usage. If a preferred certificate does not exist for the specified name and key usage, NULL is returned. - @param name A string containing an email address (RFC822) or other name for which a preferred certificate is requested. - @param keyUsage A CFArrayRef value, containing items defined in SecItem.h Pass NULL to ignore this parameter. (kSecAttrCanEncrypt, kSecAttrCanDecrypt, kSecAttrCanDerive, kSecAttrCanSign, kSecAttrCanVerify, kSecAttrCanWrap, kSecAttrCanUnwrap) - @result On return, a reference to the preferred certificate, or NULL if none was found. You are responsible for releasing this reference by calling the CFRelease function. - @discussion This function will typically be used to obtain the preferred encryption certificate for an email recipient. If a preferred certificate has not been set - for the supplied name, the returned reference will be NULL. Your code should then perform a search for possible certificates, using the SecItemCopyMatching API. - */ -__nullable -SecCertificateRef SecCertificateCopyPreferred(CFStringRef name, CFArrayRef __nullable keyUsage) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateSetPreference - @abstract Sets the preferred certificate for a specified name, key usage, and date. - @param certificate A reference to the certificate which will be preferred. - @param name A string containing an email address (RFC822) or other name for which a preferred certificate will be associated. - @param keyUsage A CSSM_KEYUSE key usage value, as defined in cssmtype.h. Pass 0 to avoid specifying a particular key usage. - @param date (optional) A date reference. If supplied, the preferred certificate will be changed only if this date is later than the currently saved setting. Pass NULL if this preference should not be restricted by date. - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function will typically be used to set the preferred encryption certificate for an email recipient, either manually (when encrypting email to a recipient) or automatically upon receipt of encrypted email. - This API is deprecated in 10.7. Plese use the SecCertificateSetPreferred API instead. -*/ -OSStatus SecCertificateSetPreference(SecCertificateRef certificate, CFStringRef name, uint32 keyUsage, CFDateRef __nullable date) - __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_NA); - -/*! - @function SecCertificateSetPreferred - @abstract Sets the preferred certificate for a specified name and optional key usage. - @param certificate A reference to the preferred certificate. If NULL is passed, any existing preference for the specified name is cleared instead. - @param name A string containing an email address (RFC822) or other name for which a preferred certificate will be associated. - @param keyUsage A CFArrayRef value, containing items defined in SecItem.h Pass NULL to ignore this parameter. (kSecAttrCanEncrypt, kSecAttrCanDecrypt, kSecAttrCanDerive, kSecAttrCanSign, kSecAttrCanVerify, kSecAttrCanWrap, kSecAttrCanUnwrap) - @result A result code. See "Security Error Codes" (SecBase.h). - @discussion This function will typically be used to set the preferred encryption certificate for an email recipient, either manually (when encrypting email to a recipient) - or automatically upon receipt of encrypted email. -*/ -OSStatus SecCertificateSetPreferred(SecCertificateRef __nullable certificate, CFStringRef name, CFArrayRef __nullable keyUsage) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @enum kSecPropertyKey - @abstract Constants used to access dictionary entries returned by SecCertificateCopyValues - @constant kSecPropertyKeyType The type of the entry - @constant kSecPropertyKeyLabel The label of the entry - @constant kSecPropertyKeyLocalizedLabel The localized label of the entry - @constant kSecPropertyKeyValue The value of the entry - */ - -extern const CFStringRef kSecPropertyKeyType __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyKeyLabel __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyKeyLocalizedLabel __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyKeyValue __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @enum kSecPropertyType - @abstract Public Constants for property list values returned by SecCertificateCopyValues - @discussion Note that kSecPropertyTypeTitle and kSecPropertyTypeError are defined in SecTrust.h -*/ -extern const CFStringRef kSecPropertyTypeWarning __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyTypeSuccess __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyTypeSection __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyTypeData __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyTypeString __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyTypeURL __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecPropertyTypeDate __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateCopyValues - @abstract Creates a dictionary that represents a certificate's contents. - @param certificate The certificate from which to get values - @param keys An array of string OID values, or NULL. If present, this is - the subset of values from the certificate to return. If NULL, - all values will be returned. Only OIDs that are top level keys - in the returned dictionary can be specified. Unknown OIDs are - ignored. - @param error An optional pointer to a CFErrorRef. This value is - set if an error occurred. If not NULL the caller is - responsible for releasing the CFErrorRef. - @discussion The keys array will contain all of the keys used in the - returned dictionary. The top level keys in the returned - dictionary are OIDs, many of which are found in SecCertificateOIDs.h. - Each entry that is returned is itself a dictionary with four - entries, whose keys are kSecPropertyKeyType, kSecPropertyKeyLabel, - kSecPropertyKeyLocalizedLabel, kSecPropertyKeyValue. The label - entries may contain a descriptive (localized) string, or an - OID string. The kSecPropertyKeyType describes the type in the - value entry. The value entry may be any CFType, although it - is usually a CFStringRef, CFArrayRef or a CFDictionaryRef. -*/ -__nullable -CFDictionaryRef SecCertificateCopyValues(SecCertificateRef certificate, CFArrayRef __nullable keys, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @enum Transform Key Value Constants - @discussion Predefined values for the kSecTransformAttrCertificateUsage attribute. - - - kSecCertificateUsageSigning - kSecCertificateUsageSigningAndEncrypting - kSecCertificateUsageDeriveAndSign - -*/ - -extern const CFStringRef kSecCertificateUsageSigning __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecCertificateUsageSigningAndEncrypting __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecCertificateUsageDeriveAndSign __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateCopyLongDescription - @abstract Return the long description of a certificate - @param alloc The CFAllocator which should be used to allocate - memory for the dictionary and its storage for values. This - parameter may be NULL in which case the current default - CFAllocator is used. If this reference is not a valid - CFAllocator, the behavior is undefined. - @param certificate The certificate from which to retrieve the long description - @param error An optional pointer to a CFErrorRef. This value is - set if an error occurred. If not NULL the caller is - responsible for releasing the CFErrorRef. - @result A CFStringRef of the long description or NULL. If NULL and the error - parameter is supplied the error will be returned in the error parameter - @discussion Note that the format of this string may change in the future -*/ - -__nullable -CFStringRef SecCertificateCopyLongDescription(CFAllocatorRef __nullable alloc, SecCertificateRef certificate, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateCopyShortDescription - @abstract Return the short description of a certificate - @param alloc The CFAllocator which should be used to allocate - memory for the dictionary and its storage for values. This - parameter may be NULL in which case the current default - CFAllocator is used. If this reference is not a valid - CFAllocator, the behavior is undefined. - @param certificate The certificate from which to retrieve the short description - @param error An optional pointer to a CFErrorRef. This value is - set if an error occurred. If not NULL the caller is - responsible for releasing the CFErrorRef. - @result A CFStringRef of the short description or NULL. If NULL and the error - parameter is supplied the error will be returned in the error parameter - @discussion Note that the format of this string may change in the future -*/ - -__nullable -CFStringRef SecCertificateCopyShortDescription(CFAllocatorRef __nullable alloc, SecCertificateRef certificate, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateCopySerialNumber - @abstract Return the certificate's serial number. - @param certificate The certificate from which to get values - @param error An optional pointer to a CFErrorRef. This value is - set if an error occurred. If not NULL the caller is - responsible for releasing the CFErrorRef. - @discussion Return the content of a DER-encoded integer (without the - tag and length fields) for this certificate's serial - number. The caller must CFRelease the value returned. -*/ - -__nullable -CFDataRef SecCertificateCopySerialNumber(SecCertificateRef certificate, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateCopyNormalizedIssuerContent - @abstract Return the certificate's normalized issuer - @param certificate The certificate from which to get values - @param error An optional pointer to a CFErrorRef. This value is - set if an error occurred. If not NULL the caller is - responsible for releasing the CFErrorRef. - @discussion The issuer is a sequence in the format used by - SecItemCopyMatching. The content returned is a DER-encoded - X.509 distinguished name. For a display version of the issuer, - call SecCertificateCopyValues. The caller must CFRelease - the value returned. -*/ - -__nullable -CFDataRef SecCertificateCopyNormalizedIssuerContent(SecCertificateRef certificate, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -/*! - @function SecCertificateCopyNormalizedSubjectContent - @abstract Return the certificate's normalized subject - @param certificate The certificate from which to get values - @param error An optional pointer to a CFErrorRef. This value is - set if an error occurred. If not NULL the caller is - responsible for releasing the CFErrorRef. - @discussion The subject is a sequence in the format used by - SecItemCopyMatching. The content returned is a DER-encoded - X.509 distinguished name. For a display version of the subject, - call SecCertificateCopyValues. The caller must CFRelease - the value returned. -*/ - -__nullable -CFDataRef SecCertificateCopyNormalizedSubjectContent(SecCertificateRef certificate, CFErrorRef *error) - __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); - -CF_IMPLICIT_BRIDGING_DISABLED -CF_ASSUME_NONNULL_END - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECCERTIFICATE_H_ */ diff --git a/OSX/include/security_keychain/SecCertificateBundle.cpp b/OSX/include/security_keychain/SecCertificateBundle.cpp deleted file mode 100644 index 5e60033d..00000000 --- a/OSX/include/security_keychain/SecCertificateBundle.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2013-2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -#include - -#include "SecBridge.h" - -#if defined(__cplusplus) -extern "C" { -#endif -// misspelled function name is declared here so symbol won't be stripped -OSStatus SecCertifcateBundleExport( - CFArrayRef itemList, - CSSM_CERT_BUNDLE_TYPE type, - CSSM_CERT_BUNDLE_ENCODING encodingType, - CSSM_DATA* data); -#if defined(__cplusplus) -} -#endif - - -OSStatus -SecCertificateBundleImport( - SecKeychainRef keychain, - const CSSM_CERT_BUNDLE* bundle, - CSSM_CERT_BUNDLE_TYPE type, - CSSM_CERT_BUNDLE_ENCODING encodingType, - CFArrayRef keychainListToSkipDuplicates) -{ - BEGIN_SECAPI - - MacOSError::throwMe(errSecUnimplemented);//%%%for now - - END_SECAPI -} - - -OSStatus -SecCertificateBundleExport( - CFArrayRef certificates, - CSSM_CERT_BUNDLE_TYPE type, - CSSM_CERT_BUNDLE_ENCODING encodingType, - CSSM_DATA* data) -{ - BEGIN_SECAPI - - MacOSError::throwMe(errSecUnimplemented);//%%%for now - - END_SECAPI -} - -// note: misspelled function name is still exported as a precaution; -// can remove this after deprecation -OSStatus -SecCertifcateBundleExport( - CFArrayRef itemList, - CSSM_CERT_BUNDLE_TYPE type, - CSSM_CERT_BUNDLE_ENCODING encodingType, - CSSM_DATA* data) -{ - return SecCertificateBundleExport(itemList, type, encodingType, data); -} diff --git a/OSX/include/security_keychain/SecCertificateBundle.h b/OSX/include/security_keychain/SecCertificateBundle.h deleted file mode 100644 index f63160e0..00000000 --- a/OSX/include/security_keychain/SecCertificateBundle.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2002-2004,2011,2014 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCertificateBundle - The functions provided in SecCertificateBundle implement a way to issue a certificate request to a - certificate authority. -*/ - -#ifndef _SECURITY_SECCERTIFICATEBUNDLE_H_ -#define _SECURITY_SECCERTIFICATEBUNDLE_H_ - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -/*! - @function SecCertificateBundleImport - @abstract Imports one or more certificates into a keychain with the specified encoding and bundle type. - @param keychain The destination keychain for the import. Specify NULL for the default keychain. - @param bundle A pointer to the bundle data. - @param type The bundle type as defined in cssmtype.h. - @param encodingType The bundle encoding type as defined in cssmtype.h. - @param keychainListToSkipDuplicates A reference to an array of keychains. These keychains contain certificates that shouldn't be duplicated during the import. - @result A result code. See "Security Error Codes" (SecBase.h). -*/ -OSStatus SecCertificateBundleImport( - SecKeychainRef keychain, - const CSSM_CERT_BUNDLE* bundle, - CSSM_CERT_BUNDLE_TYPE type, - CSSM_CERT_BUNDLE_ENCODING encodingType, - CFArrayRef keychainListToSkipDuplicates); - -/*! - @function SecCertificateBundleExport - @abstract Exports one or more certificates into a bundle with the specified encoding and bundle type. - @param certificates An array of certificate and keychain items used to help build the bundle. - @param type The bundle type as defined in cssmtype.h. If the bundle type is unknown, an attempt will be made to determine the type for you. - @param encodingType The encoding type as defined in cssmtype.h. - @param data A pointer to data. On return, this points to the bundle data. - @result A result code. See "Security Error Codes" (SecBase.h). -*/ -OSStatus SecCertificateBundleExport( - CFArrayRef certificates, - CSSM_CERT_BUNDLE_TYPE type, - CSSM_CERT_BUNDLE_ENCODING encodingType, - CSSM_DATA* data); - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECCERTIFICATEBUNDLE_H_ */ diff --git a/OSX/include/security_keychain/SecCertificateInternalP.h b/OSX/include/security_keychain/SecCertificateInternalP.h deleted file mode 100644 index b8303e42..00000000 --- a/OSX/include/security_keychain/SecCertificateInternalP.h +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (c) 2007-2011,2013-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/* - SecCertificateInternal.h -*/ - -#ifndef _SECURITY_SECCERTIFICATEINTERNAL_H_ -#define _SECURITY_SECCERTIFICATEINTERNAL_H_ - -//#include -#include "SecCertificatePrivP.h" -#include "certextensionsP.h" -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -CFDataRef SecCertificateGetAuthorityKeyIDP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetSubjectKeyIDP(SecCertificateRefP certificate); - -/* Return an array of CFURLRefs each of which is an crl distribution point for - this certificate. */ -CFArrayRef SecCertificateGetCRLDistributionPointsP(SecCertificateRefP certificate); - -/* Return an array of CFURLRefs each of which is an ocspResponder for this - certificate. */ -CFArrayRef SecCertificateGetOCSPRespondersP(SecCertificateRefP certificate); - -/* Return an array of CFURLRefs each of which is an caIssuer for this - certificate. */ -CFArrayRef SecCertificateGetCAIssuersP(SecCertificateRefP certificate); - -/* Dump certificate for debugging. */ -void SecCertificateShowP(SecCertificateRefP certificate); - -/* Return the DER encoded issuer sequence for the receiving certificates issuer. */ -CFDataRef SecCertificateCopyIssuerSequenceP(SecCertificateRefP certificate); - -/* Return the DER encoded subject sequence for the receiving certificates subject. */ -CFDataRef SecCertificateCopySubjectSequenceP(SecCertificateRefP certificate); - -/* Return the content of a DER encoded X.501 name (without the tag and length - fields) for the receiving certificates issuer. */ -CFDataRef SecCertificateGetNormalizedIssuerContentP(SecCertificateRefP certificate); - -/* Return the content of a DER encoded X.501 name (without the tag and length - fields) for the receiving certificates subject. */ -CFDataRef SecCertificateGetNormalizedSubjectContentP(SecCertificateRefP certificate); - -CFDataRef SecDERItemCopySequenceP(DERItem *content); - -/* Return true iff the certificate has a subject. */ -bool SecCertificateHasSubjectP(SecCertificateRefP certificate); - -/* Return true iff the certificate has a critical subject alt name. */ -bool SecCertificateHasCriticalSubjectAltNameP(SecCertificateRefP certificate); - -/* Return true if certificate contains one or more critical extensions we - are unable to parse. */ -bool SecCertificateHasUnknownCriticalExtensionP(SecCertificateRefP certificate); - -/* Return true iff certificate is valid as of verifyTime. */ -bool SecCertificateIsValidP(SecCertificateRefP certificate, - CFAbsoluteTime verifyTime); - -/* Return an attribute dictionary used to store this item in a keychain. */ -CFDictionaryRef SecCertificateCopyAttributeDictionaryP( - SecCertificateRefP certificate); - -/* Return a certificate from the attribute dictionary that was used to store - this item in a keychain. */ -SecCertificateRefP SecCertificateCreateFromAttributeDictionaryP( - CFDictionaryRef refAttributes); - -/* Return a SecKeyRef for the public key embedded in the cert. */ -SecKeyRefP SecCertificateCopyPublicKeyP(SecCertificateRefP certificate); - -/* Return the SecCEBasicConstraints extension for this certificate if it - has one. */ -const SecCEBasicConstraints * -SecCertificateGetBasicConstraintsP(SecCertificateRefP certificate); - -/* Return the SecCEPolicyConstraints extension for this certificate if it - has one. */ -const SecCEPolicyConstraints * -SecCertificateGetPolicyConstraintsP(SecCertificateRefP certificate); - -/* Return a dictionary from CFDataRef to CFArrayRef of CFDataRef - representing the policyMapping extension of this certificate. */ -CFDictionaryRef -SecCertificateGetPolicyMappingsP(SecCertificateRefP certificate); - -/* Return the SecCECertificatePolicies extension for this certificate if it - has one. */ -const SecCECertificatePolicies * -SecCertificateGetCertificatePoliciesP(SecCertificateRefP certificate); - -/* Returns UINT32_MAX if InhibitAnyPolicy extension is not present or invalid, - returns the value of the SkipCerts field of the InhibitAnyPolicy extension - otherwise. */ -uint32_t -SecCertificateGetInhibitAnyPolicySkipCertsP(SecCertificateRefP certificate); - -/* Return the public key algorithm and parameters for certificate. */ -const DERAlgorithmId *SecCertificateGetPublicKeyAlgorithmP( - SecCertificateRefP certificate); - -/* Return the raw public key data for certificate. */ -const DERItem *SecCertificateGetPublicKeyDataP(SecCertificateRefP certificate); - -#pragma mark - -#pragma mark Certificate Operations - -OSStatus SecCertificateIsSignedByP(SecCertificateRefP certificate, - SecKeyRefP issuerKey); - -#pragma mark - -#pragma mark Certificate Creation - -#ifdef OPTIONAL_METHODS -/* Return a certificate for the PEM representation of this certificate. - Return NULL the passed in der_certificate is not a valid DER encoded X.509 - certificate, and return a CFError by reference. It is the - responsibility of the caller to release the CFError. */ -SecCertificateRefP SecCertificateCreateWithPEMP(CFAllocatorRef allocator, - CFStringRef pem_certificate); - -/* Return a CFStringRef containing the the pem representation of this - certificate. */ -CFStringRef SecCertificateGetPEMP(SecCertificateRefP der_certificate); - -#endif /* OPTIONAL_METHODS */ - -#if 0 -/* Complete the certificate chain of this certificate, setting the parent - certificate for each certificate along they way. Return 0 if the - system is able to find all the certificates to complete the certificate - chain either in the passed in other_certificates array or in the user or - the systems keychain(s). - If the certificate's issuer chain can not be completed, this function - will return an error status code. - NOTE: This function does not verify whether the certificate is trusted it's - main use is just to ensure that anyone using this certificate upstream will - have access to a complete (or as complete as possible in the case of - something going wrong) certificate chain. */ -OSStatus SecCertificateCompleteChainP(SecCertificateRefP certificate, - CFArrayRef other_certificates); -#endif - -#if 0 - -/*! - @function SecCertificateGetVersionNumberP - @abstract Retrieves the version of a given certificate as a CFNumberRef. - @param certificate A reference to the certificate from which to obtain the certificate version. - @result A CFNumberRef representing the certificate version. The following values are currently known to be returned, but more may be added in the future: - 1: X509v1 - 2: X509v2 - 3: X509v3 -*/ -CFNumberRef SecCertificateGetVersionNumberP(SecCertificateRefP certificate); - -/*! - @function SecCertificateGetSerialDERP - @abstract Retrieves the serial number of a given certificate in DER encoding. - @param certificate A reference to the certificate from which to obtain the serial number. - @result A CFDataRef containing the DER encoded serial number of the certificate, minus the tag and length fields. -*/ -CFDataRef SecCertificateGetSerialDERP(SecCertificateRefP certificate); - - -/*! - @function SecCertificateGetSerialStringP - @abstract Retrieves the serial number of a given certificate in human readable form. - @param certificate A reference to the certificate from which to obtain the serial number. - @result A CFStringRef containing the human readable serial number of the certificate in decimal form. -*/ -CFStringRef SecCertificateGetSerialStringP(SecCertificateRefP certificate); - - - -CFDataRef SecCertificateGetPublicKeyDERP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetPublicKeySHA1FingerPrintP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetPublicKeyMD5FingerPrintP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetSignatureAlgorithmDERP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetSignatureAlgorithmNameP(SecCertificateRefP certificate); -CFStringRef SecCertificateGetSignatureAlgorithmOIDP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetSignatureDERP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetSignatureAlgorithmParametersDERP(SecCertificateRefP certificate); - -/* plist top level array is orderd list of key/value pairs */ -CFArrayRef SecCertificateGetSignatureAlgorithmParametersArrayP(SecCertificateRefP certificate); - -#if 0 -/* This cert is signed by its parent? */ -bool SecCertificateIsSignatureValidP(SecCertificateRefP certificate); - -/* This cert is signed by its parent and so on until no parent certificate can be found? */ -bool SecCertificateIsIssuerChainValidP(SecCertificateRefP certificate, CFArrayRef additionalCertificatesToSearch); - -/* This cert is signed by its parent and so on until no parent certificate can be found? */ -bool SecCertificateIsSignatureChainValidP(SecCertificateRefP certificate); - -/* This cert is signed by its parent and so on until a certiicate in anchors can be found. */ -bool SecCertificateIssuerChainHasAnchorInP(SecCertificateRefP certificate, CFArrayRef anchors); - -/* This cert is signed by its parent and so on until a certiicate in anchors can be found. */ -bool SecCertificateSignatureChainHasAnchorInP(SecCertificateRefP certificate, CFArrayRef anchors); - -bool SecCertificateIsSelfSignedP(SecCertificateRefP certificate); -#endif - - -/* The entire certificate in DER encoding including the outer tag and length fields. */ -CFDataRef SecCertificateGetDERP(SecCertificateRefP certificate); - -/* Returns the status code of the last failed call for this certificate on this thread. */ -OSStatus SecCertificateGetStatusP(SecCertificateRefP certificate); - -CFDataRef SecCertificateGetIssuerDERP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetNormalizedIssuerDERP(SecCertificateRefP certificate); - -/* Return the issuer as an X509 name encoded in an array. Each element in this array is an array. Each inner array has en even number of elements. Each pair of elements in the inner array represents a key and a value. The key is a string and the value is also a string. Elements in the outer array should be considered ordered while pairs in the inner array should not. */ -CFArrayRef SecCertificateGetIssuerArrayP(SecCertificateRefP certificate); - - -CFDataRef SecCertificateGetSubjectDERP(SecCertificateRefP certificate); -CFDataRef SecCertificateGetNormalizedSubjectDERP(SecCertificateRefP certificate); -/* See SecCertificateGetIssuerArray for a description of the returned array. */ -CFArrayRef SecCertificateGetSubjectArrayP(SecCertificateRefP certificate); - -CFDateRef SecCertificateGetNotValidBeforeDateP(SecCertificateRefP certificate); -CFDateRef SecCertificateGetNotValidDateP(SecCertificateRefP certificate); - - -#if 0 - -CFIndex SecCertificateGetExtensionCountP(SecCertificateRefP certificate, index); -CFDataRef SecCertificateGetExtensionAtIndexDERP(SecCertificateRefP certificate, CFIndex index); -bool SecCertificateIsExtensionAtIndexCriticalP(SecCertificateRefP certificate, CFIndex index); - -/* array see email example. */ -CFArrayRef SecCertificateGetExtensionAtIndexParamsArrayP(SecCertificateRefP certificate, CFIndex index); - -CFStringRef SecCertificateGetExtensionAtIndexNameP(SecCertificateRefP certificate, CFIndex index); -CFStringRef SecCertificateGetExtensionAtIndexOIDP(SecCertificateRefP certificate, CFIndex index); - -#else - -/* Return an array with all of this certificates SecCertificateExtensionRefs. */ -CFArrayRef SecCertificateGetExtensionsP(SecCertificateRefP certificate); - -/* Return the SecCertificateExtensionRef for the extension with the given oid. Return NULL if it does not exist or if an error occours call SecCertificateGetStatus() to see if an error occured or not. */ -SecCertificateExtensionRef SecCertificateGetExtensionWithOIDP(SecCertificateRefP certificate, CFDataRef oid); - -CFDataRef SecCertificateExtensionGetDERP(SecCertificateExtensionRef extension, CFDataRef oid); -CFStringRef SecCertificateExtensionNameP(SecCertificateExtensionRef extension); -CFDataRef SecCertificateExtensionGetOIDDERP(SecCertificateExtensionRef extension, CFDataRef oid); -CFStringRef SecCertificateExtensionGetOIDStringP(SecCertificateExtensionRef extension, CFDataRef oid); -bool SecCertificateExtensionIsCriticalP(SecCertificateExtensionRef extension); -CFArrayRef SecCertificateExtensionGetContentDERP(SecCertificateExtensionRef extension); - -/* Return the content of extension as an array. The array has en even number of elements. Each pair of elements in the array represents a key and a value. The key is a string and the value is either a string, or dictionary or an array of key value pairs like the outer array. */ -CFArrayRef SecCertificateExtensionGetContentArrayP(SecCertificateExtensionRef extension); - -#endif /* 0 */ - -#endif /* 0 */ - - -void appendPropertyP(CFMutableArrayRef properties, - CFStringRef propertyType, CFStringRef label, CFTypeRef value); - -/* Utility functions. */ -CFStringRef SecDERItemCopyOIDDecimalRepresentation(CFAllocatorRef allocator, - const DERItem *oid); -CFDataRef createNormalizedX501Name(CFAllocatorRef allocator, - const DERItem *x501name); - -/* Decode a choice of UTCTime or GeneralizedTime to a CFAbsoluteTime. Return - an absoluteTime if the date was valid and properly decoded. Return - NULL_TIME otherwise. */ -CFAbsoluteTime SecAbsoluteTimeFromDateContent(DERTag tag, const uint8_t *bytes, - size_t length); - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECCERTIFICATEINTERNAL_H_ */ diff --git a/OSX/include/security_keychain/SecCertificateOIDs.h b/OSX/include/security_keychain/SecCertificateOIDs.h deleted file mode 100644 index 2fb8901d..00000000 --- a/OSX/include/security_keychain/SecCertificateOIDs.h +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2002-2012 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/*! - @header SecCertificateOIDs - These constants are used to access entries in the dictionary returned by - SecCertificateCopyValues, which are the parsed field from a certificate. -*/ - -#ifndef _SECURITY_SECCERTIFICATEOIDS_H_ -#define _SECURITY_SECCERTIFICATEOIDS_H_ - -#include -#include -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -CF_ASSUME_NONNULL_BEGIN - -extern const CFStringRef kSecOIDADC_CERT_POLICY __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_CERT_POLICY __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EKU_CODE_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EKU_CODE_SIGNING_DEV __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EKU_ICHAT_ENCRYPTION __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EKU_ICHAT_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EKU_RESOURCE_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EKU_SYSTEM_IDENTITY __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_ADC_APPLE_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_ADC_DEV_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_APPLE_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_CODE_SIGNING __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_INTERMEDIATE_MARKER __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_WWDR_INTERMEDIATE __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_ITMS_INTERMEDIATE __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_AAI_INTERMEDIATE __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAPPLE_EXTENSION_APPLEID_INTERMEDIATE __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAuthorityInfoAccess __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDAuthorityKeyIdentifier __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDBasicConstraints __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDBiometricInfo __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCSSMKeyStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCertIssuer __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCertificatePolicies __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDClientAuth __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCollectiveStateProvinceName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCollectiveStreetAddress __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCommonName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCountryName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCrlDistributionPoints __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCrlNumber __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDCrlReason __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDOTMAC_CERT_EMAIL_ENCRYPT __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDOTMAC_CERT_EMAIL_SIGN __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDOTMAC_CERT_EXTENSION __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDOTMAC_CERT_IDENTITY __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDOTMAC_CERT_POLICY __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDeltaCrlIndicator __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDDescription __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDEKU_IPSec __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDEmailAddress __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDEmailProtection __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDExtendedKeyUsage __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDExtendedKeyUsageAny __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDExtendedUseCodeSigning __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDGivenName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDHoldInstructionCode __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDInvalidityDate __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDIssuerAltName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDIssuingDistributionPoint __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDIssuingDistributionPoints __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDKERBv5_PKINIT_KP_CLIENT_AUTH __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDKERBv5_PKINIT_KP_KDC __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDKeyUsage __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDLocalityName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDMS_NTPrincipalName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDMicrosoftSGC __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDNameConstraints __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDNetscapeCertSequence __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDNetscapeCertType __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDNetscapeSGC __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDOCSPSigning __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDOrganizationName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDOrganizationalUnitName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDPolicyConstraints __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDPolicyMappings __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDPrivateKeyUsagePeriod __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDQC_Statements __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSerialNumber __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDServerAuth __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDStateProvinceName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDStreetAddress __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectAltName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectDirectoryAttributes __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectEmailAddress __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectInfoAccess __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectKeyIdentifier __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectPicture __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSubjectSignatureBitmap __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSurname __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDTimeStamping __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDTitle __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDUseExemptions __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1CertificateIssuerUniqueId __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1CertificateSubjectUniqueId __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1IssuerName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1IssuerNameCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1IssuerNameLDAP __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1IssuerNameStd __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SerialNumber __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1Signature __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SignatureAlgorithm __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SignatureAlgorithmParameters __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SignatureAlgorithmTBS __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SignatureCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SignatureStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectName __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectNameCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectNameLDAP __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectNameStd __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectPublicKey __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectPublicKeyAlgorithm __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectPublicKeyAlgorithmParameters __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1SubjectPublicKeyCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1ValidityNotAfter __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1ValidityNotBefore __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V1Version __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3Certificate __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionCritical __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionId __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionType __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionValue __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionsCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateExtensionsStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3CertificateNumberOfExtensions __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3SignedCertificate __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDX509V3SignedCertificateCStruct __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA); -extern const CFStringRef kSecOIDSRVName __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_NA); - -CF_ASSUME_NONNULL_END - -#if defined(__cplusplus) -} -#endif - -#endif /* !_SECURITY_SECCERTIFICATEOIDS_H_ */ diff --git a/OSX/include/security_keychain/SecCertificateP.c b/OSX/include/security_keychain/SecCertificateP.c deleted file mode 100644 index fc6403c9..00000000 --- a/OSX/include/security_keychain/SecCertificateP.c +++ /dev/null @@ -1,4743 +0,0 @@ -/* - * Copyright (c) 2006-2015 Apple Inc. All Rights Reserved. - * - * @APPLE_LICENSE_HEADER_START@ - * - * This file contains Original Code and/or Modifications of Original Code - * as defined in and that are subject to the Apple Public Source License - * Version 2.0 (the 'License'). You may not use this file except in - * compliance with the License. Please obtain a copy of the License at - * http://www.opensource.apple.com/apsl/ and read it before using this - * file. - * - * The Original Code and all software distributed under the License are - * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER - * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, - * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. - * Please see the License for the specific language governing rights and - * limitations under the License. - * - * @APPLE_LICENSE_HEADER_END@ - */ - -/* - * SecCertificate.c - CoreFoundation based certificate object - */ - - -#include "SecCertificateInternalP.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "SecBasePriv.h" - -#include "SecRSAKeyP.h" -#include "SecFrameworkP.h" -#include "SecItem.h" -#include "SecItemPriv.h" -#include -#include -#include -#include -#include "SecInternalP.h" -#include "SecBase64P.h" - -#include - -typedef struct SecCertificateExtension { - DERItem extnID; - bool critical; - DERItem extnValue; -} SecCertificateExtension; - -#if 0 -typedef struct KnownExtension { - bool critical; - DERItem extnValue; -} KnownExtension; - -enum { - kSecSelfSignedUnknown = 0, - kSecSelfSignedFalse, - kSecSelfSignedTrue, -}; -#endif - -struct __SecCertificate { - CFRuntimeBase _base; - - DERItem _der; /* Entire certificate in DER form. */ - DERItem _tbs; /* To Be Signed cert DER bytes. */ - DERAlgorithmId _sigAlg; /* Top level signature algorithm. */ - DERItem _signature; /* The content of the sig bit string. */ - - UInt8 _version; - DERItem _serialNum; /* Integer. */ - DERAlgorithmId _tbsSigAlg; /* sig alg MUST be same as _sigAlg. */ - DERItem _issuer; /* Sequence of RDN. */ - CFAbsoluteTime _notBefore; - CFAbsoluteTime _notAfter; - DERItem _subject; /* Sequence of RDN. */ - DERAlgorithmId _algId; /* oid and params of _pubKeyDER. */ - DERItem _pubKeyDER; /* contents of bit string */ - DERItem _issuerUniqueID; /* bit string, optional */ - DERItem _subjectUniqueID; /* bit string, optional */ - -#if 0 - /* Known extensions if the certificate contains them, - extnValue.length will be > 0. */ - KnownExtension _authorityKeyID; - - /* This extension is used to uniquely identify a certificate from among - several that have the same subject name. If the extension is not - present, its value is calculated by performing a SHA-1 hash of the - certificate's DER encoded subjectPublicKeyInfo, as recommended by - PKIX. */ - KnownExtension _subjectKeyID; - KnownExtension _keyUsage; - KnownExtension _extendedKeyUsage; - KnownExtension _basicConstraints; - KnownExtension _netscapeCertType; - KnownExtension _subjectAltName; - KnownExtension _qualCertStatements; - -#endif - bool _foundUnknownCriticalExtension; - - /* Well known certificate extensions. */ - SecCEBasicConstraints _basicConstraints; - SecCEPolicyConstraints _policyConstraints; - CFDictionaryRef _policyMappings; - SecCECertificatePolicies _certificatePolicies; - - /* If InhibitAnyPolicy extension is not present or invalid UINT32_MAX, - value of the SkipCerts field of the InhibitAnyPolicy extension - otherwise. */ - uint32_t _inhibitAnyPolicySkipCerts; - - /* If KeyUsage extension is not present this is 0, otherwise it's - the value of the extension. */ - SecKeyUsage _keyUsage; - - /* OCTECTS of SubjectKeyIdentifier extensions KeyIdentifier. - Length = 0 if not present. */ - DERItem _subjectKeyIdentifier; - - /* OCTECTS of AuthorityKeyIdentifier extensions KeyIdentifier. - Length = 0 if not present. */ - DERItem _authorityKeyIdentifier; - /* AuthorityKeyIdentifier extension _authorityKeyIdentifierIssuer and - _authorityKeyIdentifierSerialNumber have non zero length if present. - Both are either present or absent together. */ - DERItem _authorityKeyIdentifierIssuer; - DERItem _authorityKeyIdentifierSerialNumber; - - /* Subject alt name extension, if present. Not malloced, it's just a - pointer to an element in the _extensions array. */ - const SecCertificateExtension *_subjectAltName; - - /* Parsed extension values. */ - - /* Array of CFURLRefs containing the URI values of crlDistributionPoints. */ - CFMutableArrayRef _crlDistributionPoints; - - /* Array of CFURLRefs containing the URI values of accessLocations of each - id-ad-ocsp AccessDescription in the Authority Information Access - extension. */ - CFMutableArrayRef _ocspResponders; - - /* Array of CFURLRefs containing the URI values of accessLocations of each - id-ad-caIssuers AccessDescription in the Authority Information Access - extension. */ - CFMutableArrayRef _caIssuers; - - /* All other (non known) extensions. The _extensions array is malloced. */ - CFIndex _extensionCount; - SecCertificateExtension *_extensions; - - /* Optional cached fields. */ - SecKeyRef _pubKey; - CFDataRef _der_data; - CFArrayRef _properties; - CFDataRef _serialNumber; - CFDataRef _normalizedIssuer; - CFDataRef _normalizedSubject; - CFDataRef _authorityKeyID; - CFDataRef _subjectKeyID; - - CFDataRef _sha1Digest; - uint8_t _isSelfSigned; - -}; - -/* Public Constants for property list keys. */ -CFStringRef kSecPropertyKeyType = CFSTR("type"); -CFStringRef kSecPropertyKeyLabel = CFSTR("label"); -CFStringRef kSecPropertyKeyLocalizedLabel = CFSTR("localized label"); -CFStringRef kSecPropertyKeyValue = CFSTR("value"); - -/* Public Constants for property list values. */ -CFStringRef kSecPropertyTypeWarning = CFSTR("warning"); -CFStringRef kSecPropertyTypeError = CFSTR("error"); -CFStringRef kSecPropertyTypeSuccess = CFSTR("success"); -CFStringRef kSecPropertyTypeTitle = CFSTR("title"); -CFStringRef kSecPropertyTypeSection = CFSTR("section"); -CFStringRef kSecPropertyTypeData = CFSTR("data"); -CFStringRef kSecPropertyTypeString = CFSTR("string"); -CFStringRef kSecPropertyTypeURL = CFSTR("url"); -CFStringRef kSecPropertyTypeDate = CFSTR("date"); - -/* Extension parsing routine. */ -typedef void (*SecCertificateExtensionParser)(SecCertificateRefP certificate, - const SecCertificateExtension *extn); - -/* CFRuntime regsitration data. */ -static pthread_once_t kSecCertificateRegisterClass = PTHREAD_ONCE_INIT; -static CFTypeID kSecCertificateTypeID = _kCFRuntimeNotATypeID; - -/* Mapping from extension OIDs (as a DERItem *) to - SecCertificateExtensionParser extension parsing routines. */ -static CFDictionaryRef gExtensionParsers; - -/* Forward declartions of static functions. */ -static CFStringRef SecCertificateDescribe(CFTypeRef cf); -static void SecCertificateDestroy(CFTypeRef cf); -static bool derDateGetAbsoluteTime(const DERItem *dateChoice, - CFAbsoluteTime *absTime); - -/* Static functions. */ -static CFStringRef SecCertificateDescribe(CFTypeRef cf) { - SecCertificateRefP certificate = (SecCertificateRefP)cf; - return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR(""), certificate, - SecCertificateCopySubjectSummaryP(certificate), - SecCertificateCopyIssuerSummaryP(certificate)); -} - -static void SecCertificateDestroy(CFTypeRef cf) { - SecCertificateRefP certificate = (SecCertificateRefP)cf; - if (certificate->_certificatePolicies.policies) - free(certificate->_certificatePolicies.policies); - CFReleaseSafe(certificate->_policyMappings); - CFReleaseSafe(certificate->_crlDistributionPoints); - CFReleaseSafe(certificate->_ocspResponders); - CFReleaseSafe(certificate->_caIssuers); - if (certificate->_extensions) { - free(certificate->_extensions); - } - CFReleaseSafe(certificate->_pubKey); - CFReleaseSafe(certificate->_der_data); - CFReleaseSafe(certificate->_properties); - CFReleaseSafe(certificate->_serialNumber); - CFReleaseSafe(certificate->_normalizedIssuer); - CFReleaseSafe(certificate->_normalizedSubject); - CFReleaseSafe(certificate->_authorityKeyID); - CFReleaseSafe(certificate->_subjectKeyID); - CFReleaseSafe(certificate->_sha1Digest); -} - -static Boolean SecCertificateEqual(CFTypeRef cf1, CFTypeRef cf2) { - SecCertificateRefP cert1 = (SecCertificateRefP)cf1; - SecCertificateRefP cert2 = (SecCertificateRefP)cf2; - if (cert1 == cert2) - return true; - if (!cert2 || cert1->_der.length != cert2->_der.length) - return false; - return !memcmp(cert1->_der.data, cert2->_der.data, cert1->_der.length); -} - -/* Hash of the certificate is der length + signature length + last 4 bytes - of signature. */ -static CFHashCode SecCertificateHash(CFTypeRef cf) { - SecCertificateRefP certificate = (SecCertificateRefP)cf; - DERSize der_length = certificate->_der.length; - DERSize sig_length = certificate->_signature.length; - DERSize ix = (sig_length > 4) ? sig_length - 4 : 0; - CFHashCode hashCode = 0; - for (; ix < sig_length; ++ix) - hashCode = (hashCode << 8) + certificate->_signature.data[ix]; - - return (hashCode + der_length + sig_length); -} - -#if 1 - -/************************************************************************/ -/************************* General Name Parsing *************************/ -/************************************************************************/ - -typedef OSStatus (*parseGeneralNameCallback)(void *context, - SecCEGeneralNameType type, const DERItem *value); - - -/* - GeneralName ::= CHOICE { - otherName [0] OtherName, - rfc822Name [1] IA5String, - dNSName [2] IA5String, - x400Address [3] ORAddress, - directoryName [4] Name, - ediPartyName [5] EDIPartyName, - uniformResourceIdentifier [6] IA5String, - iPAddress [7] OCTET STRING, - registeredID [8] OBJECT IDENTIFIER} - - OtherName ::= SEQUENCE { - type-id OBJECT IDENTIFIER, - value [0] EXPLICIT ANY DEFINED BY type-id } - - EDIPartyName ::= SEQUENCE { - nameAssigner [0] DirectoryString OPTIONAL, - partyName [1] DirectoryString } - */ -static OSStatus parseGeneralNameContentProperty(DERTag tag, - const DERItem *generalNameContent, - void *context, parseGeneralNameCallback callback) { - switch (tag) { - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0: - return callback(context, GNT_OtherName, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | 1: - return callback(context, GNT_RFC822Name, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | 2: - return callback(context, GNT_DNSName, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 3: - return callback(context, GNT_X400Address, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 4: - return callback(context, GNT_DirectoryName, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 5: - return callback(context, GNT_EdiPartyName, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 6: - { - /* Technically I don't think this is valid, but there are certs out - in the wild that use a constructed IA5String. In particular the - VeriSign Time Stamping Authority CA.cer does this. */ - DERDecodedInfo uriContent; - require_noerr(DERDecodeItem(generalNameContent, &uriContent), badDER); - require(uriContent.tag == ASN1_IA5_STRING, badDER); - return callback(context, GNT_URI, &uriContent.content); - } - case ASN1_CONTEXT_SPECIFIC | 6: - return callback(context, GNT_URI, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | 7: - return callback(context, GNT_IPAddress, generalNameContent); - case ASN1_CONTEXT_SPECIFIC | 8: - return callback(context, GNT_RegisteredID, generalNameContent); - default: - goto badDER; - } -badDER: - return errSecInvalidCertificate; -} - -static OSStatus parseGeneralNamesContent(const DERItem *generalNamesContent, - void *context, parseGeneralNameCallback callback) { - DERSequence gnSeq; - DERReturn drtn = DERDecodeSeqContentInit(generalNamesContent, &gnSeq); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo generalNameContent; - while ((drtn = DERDecodeSeqNext(&gnSeq, &generalNameContent)) == - DR_Success) { - OSStatus status = parseGeneralNameContentProperty( - generalNameContent.tag, &generalNameContent.content, context, - callback); - if (status) - return status; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return errSecSuccess; - -badDER: - return errSecInvalidCertificate; -} - -static OSStatus parseGeneralNames(const DERItem *generalNames, void *context, - parseGeneralNameCallback callback) { - DERDecodedInfo generalNamesContent; - DERReturn drtn = DERDecodeItem(generalNames, &generalNamesContent); - require_noerr_quiet(drtn, badDER); - require_quiet(generalNamesContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - return parseGeneralNamesContent(&generalNamesContent.content, context, - callback); -badDER: - return errSecInvalidCertificate; -} - -#else - -/* - GeneralName ::= CHOICE { - otherName [0] OtherName, - rfc822Name [1] IA5String, - dNSName [2] IA5String, - x400Address [3] ORAddress, - directoryName [4] Name, - ediPartyName [5] EDIPartyName, - uniformResourceIdentifier [6] IA5String, - iPAddress [7] OCTET STRING, - registeredID [8] OBJECT IDENTIFIER} - - EDIPartyName ::= SEQUENCE { - nameAssigner [0] DirectoryString OPTIONAL, - partyName [1] DirectoryString } - */ -static OSStatus parseGeneralNameContentProperty(DERTag tag, - const DERItem *generalNameContent, SecCEGeneralName *generalName) { - switch (tag) { - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0: - generalName->nameType = GNT_OtherName; - generalName->berEncoded = true; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | 1: - /* IA5String. */ - generalName->nameType = GNT_RFC822Name; - generalName->berEncoded = false; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | 2: - /* IA5String. */ - generalName->nameType = GNT_DNSName; - generalName->berEncoded = false; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 3: - generalName->nameType = GNT_X400Address; - generalName->berEncoded = true; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 4: - generalName->nameType = GNT_DirectoryName; - generalName->berEncoded = true; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 5: - generalName->nameType = GNT_EdiPartyName; - generalName->berEncoded = true; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 6: - { - /* Technically I don't think this is valid, but there are certs out - in the wild that use a constructed IA5String. In particular the - VeriSign Time Stamping Authority CA.cer does this. */ - DERDecodedInfo decoded; - require_noerr(DERDecodeItem(generalNameContent, &decoded), badDER); - require(decoded.tag == ASN1_IA5_STRING, badDER); - generalName->nameType = GNT_URI; - generalName->berEncoded = false; - generalName->name = decoded.content; - break; - } - case ASN1_CONTEXT_SPECIFIC | 6: - generalName->nameType = GNT_URI; - generalName->berEncoded = false; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | 7: - /* @@@ This is the IP Address as an OCTECT STRING. For IPv4 it's - 8 octects, addr/mask for ipv6 it's 32. */ - generalName->nameType = GNT_IPAddress; - generalName->berEncoded = false; - generalName->name = *generalNameContent; - break; - case ASN1_CONTEXT_SPECIFIC | 8: - /* name is the content of an OID. */ - generalName->nameType = GNT_RegisteredID; - generalName->berEncoded = false; - generalName->name = *generalNameContent; - break; - default: - goto badDER; - break; - } - return errSecSuccess; -badDER: - return errSecInvalidCertificate; -} - -/* - GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName - */ -static OSStatus parseGeneralNamesContent(const DERItem *generalNamesContent, - CFIndex *count, SecCEGeneralName **name) { - SecCEGeneralName *generalNames = NULL; - DERSequence gnSeq; - DERReturn drtn = DERDecodeSeqContentInit(generalNamesContent, &gnSeq); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo generalNameContent; - CFIndex generalNamesCount = 0; - while ((drtn = DERDecodeSeqNext(&gnSeq, &generalNameContent)) == - DR_Success) { - ++generalNamesCount; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - - require(generalNames = calloc(generalNamesCount, sizeof(SecCEGeneralName)), - badDER); - DERDecodeSeqContentInit(generalNamesContent, &gnSeq); - CFIndex ix = 0; - while ((drtn = DERDecodeSeqNext(&gnSeq, &generalNameContent)) == - DR_Success) { - if (!parseGeneralNameContentProperty(generalNameContent.tag, - &generalNameContent.content, &generalNames[ix])) { - goto badDER; - } - ++ix; - } - *count = generalNamesCount; - *name = generalNames; - return errSecSuccess; - -badDER: - if (generalNames) - free(generalNames); - return errSecInvalidCertificate; -} - -static OSStatus parseGeneralNames(const DERItem *generalNames, - CFIndex *count, SecCEGeneralName **name) { - DERDecodedInfo generalNamesContent; - DERReturn drtn = DERDecodeItem(generalNames, &generalNamesContent); - require_noerr_quiet(drtn, badDER); - require_quiet(generalNamesContent.tag == ASN1_CONSTR_SEQUENCE, - badDER); - parseGeneralNamesContent(&generalNamesContent.content, count, name); - return errSecSuccess; -badDER: - return errSecInvalidCertificate; -} -#endif - -/************************************************************************/ -/************************** X.509 Name Parsing **************************/ -/************************************************************************/ - -typedef OSStatus (*parseX501NameCallback)(void *context, const DERItem *type, - const DERItem *value, CFIndex rdnIX); - -static OSStatus parseRDNContent(const DERItem *rdnSetContent, void *context, - parseX501NameCallback callback) { - DERSequence rdn; - DERReturn drtn = DERDecodeSeqContentInit(rdnSetContent, &rdn); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo atvContent; - CFIndex rdnIX = 0; - while ((drtn = DERDecodeSeqNext(&rdn, &atvContent)) == DR_Success) { - require_quiet(atvContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERAttributeTypeAndValue atv; - drtn = DERParseSequenceContent(&atvContent.content, - DERNumAttributeTypeAndValueItemSpecs, - DERAttributeTypeAndValueItemSpecs, - &atv, sizeof(atv)); - require_noerr_quiet(drtn, badDER); - require_quiet(atv.type.length != 0, badDER); - OSStatus status = callback(context, &atv.type, &atv.value, rdnIX++); - if (status) - return status; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - - return errSecSuccess; -badDER: - return errSecInvalidCertificate; -} - -static OSStatus parseX501NameContent(const DERItem *x501NameContent, void *context, - parseX501NameCallback callback) { - DERSequence derSeq; - DERReturn drtn = DERDecodeSeqContentInit(x501NameContent, &derSeq); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo currDecoded; - while ((drtn = DERDecodeSeqNext(&derSeq, &currDecoded)) == DR_Success) { - require_quiet(currDecoded.tag == ASN1_CONSTR_SET, badDER); - OSStatus status = parseRDNContent(&currDecoded.content, context, - callback); - if (status) - return status; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - - return errSecSuccess; - -badDER: - return errSecInvalidCertificate; -} - -static OSStatus parseX501Name(const DERItem *x501Name, void *context, - parseX501NameCallback callback) { - DERDecodedInfo x501NameContent; - if (DERDecodeItem(x501Name, &x501NameContent) || - x501NameContent.tag != ASN1_CONSTR_SEQUENCE) { - return errSecInvalidCertificate; - } else { - return parseX501NameContent(&x501NameContent.content, context, - callback); - } -} - -/************************************************************************/ -/********************** Extension Parsing Routines **********************/ -/************************************************************************/ - -static void SecCEPSubjectKeyIdentifier(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERDecodedInfo keyIdentifier; - DERReturn drtn = DERDecodeItem(&extn->extnValue, &keyIdentifier); - require_noerr_quiet(drtn, badDER); - require_quiet(keyIdentifier.tag == ASN1_OCTET_STRING, badDER); - certificate->_subjectKeyIdentifier = keyIdentifier.content; - - return; -badDER: - secdebug("cert", "Invalid SubjectKeyIdentifier Extension"); -} - -static void SecCEPKeyUsage(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - SecKeyUsage keyUsage = extn->critical ? kSecKeyUsageCritical : 0; - DERDecodedInfo bitStringContent; - DERReturn drtn = DERDecodeItem(&extn->extnValue, &bitStringContent); - require_noerr_quiet(drtn, badDER); - require_quiet(bitStringContent.tag == ASN1_BIT_STRING, badDER); - DERSize len = bitStringContent.content.length - 1; - require_quiet(len == 1 || len == 2, badDER); - DERByte numUnusedBits = bitStringContent.content.data[0]; - require_quiet(numUnusedBits < 8, badDER); - /* Flip the bits in the bit string so the first bit in the lsb. */ - uint_fast16_t bits = 8 * len - numUnusedBits; - uint_fast16_t value = bitStringContent.content.data[1]; - uint_fast16_t mask; - if (len > 1) { - value = (value << 8) + bitStringContent.content.data[2]; - mask = 0x8000; - } else { - mask = 0x80; - } - uint_fast16_t ix; - for (ix = 0; ix < bits; ++ix) { - if (value & mask) { - keyUsage |= 1 << ix; - } - mask >>= 1; - } - certificate->_keyUsage = keyUsage; - return; -badDER: - certificate->_keyUsage = kSecKeyUsageUnspecified; -} - -static void SecCEPPrivateKeyUsagePeriod(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -static void SecCEPSubjectAltName(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - certificate->_subjectAltName = extn; -} - -static void SecCEPIssuerAltName(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -static void SecCEPBasicConstraints(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERBasicConstraints basicConstraints; - require_noerr_quiet(DERParseSequence(&extn->extnValue, - DERNumBasicConstraintsItemSpecs, DERBasicConstraintsItemSpecs, - &basicConstraints, sizeof(basicConstraints)), badDER); - require_noerr_quiet(DERParseBoolean(&basicConstraints.cA, false, - &certificate->_basicConstraints.isCA), badDER); - if (basicConstraints.pathLenConstraint.length != 0) { - require_noerr_quiet(DERParseInteger( - &basicConstraints.pathLenConstraint, - &certificate->_basicConstraints.pathLenConstraint), badDER); - certificate->_basicConstraints.pathLenConstraintPresent = true; - } - certificate->_basicConstraints.present = true; - certificate->_basicConstraints.critical = extn->critical; - return; -badDER: - certificate->_basicConstraints.present = false; - secdebug("cert", "Invalid BasicConstraints Extension"); -} - -static void SecCEPCrlDistributionPoints(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -/* - certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation - - PolicyInformation ::= SEQUENCE { - policyIdentifier CertPolicyId, - policyQualifiers SEQUENCE SIZE (1..MAX) OF - PolicyQualifierInfo OPTIONAL } - - CertPolicyId ::= OBJECT IDENTIFIER - - PolicyQualifierInfo ::= SEQUENCE { - policyQualifierId PolicyQualifierId, - qualifier ANY DEFINED BY policyQualifierId } -*/ -static void SecCEPCertificatePolicies(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERTag tag; - DERSequence piSeq; - SecCEPolicyInformation *policies = NULL; - DERReturn drtn = DERDecodeSeqInit(&extn->extnValue, &tag, &piSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo piContent; - DERSize policy_count = 0; - while ((drtn = DERDecodeSeqNext(&piSeq, &piContent)) == DR_Success) { - require_quiet(piContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - policy_count++; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - policies = (SecCEPolicyInformation *)malloc(sizeof(SecCEPolicyInformation) - * policy_count); - DERDecodeSeqInit(&extn->extnValue, &tag, &piSeq); - DERSize policy_ix = 0; - while ((drtn = DERDecodeSeqNext(&piSeq, &piContent)) == DR_Success) { - DERPolicyInformation pi; - drtn = DERParseSequenceContent(&piContent.content, - DERNumPolicyInformationItemSpecs, - DERPolicyInformationItemSpecs, - &pi, sizeof(pi)); - require_noerr_quiet(drtn, badDER); - policies[policy_ix].policyIdentifier = pi.policyIdentifier; - policies[policy_ix++].policyQualifiers = pi.policyQualifiers; - } - certificate->_certificatePolicies.present = true; - certificate->_certificatePolicies.critical = extn->critical; - certificate->_certificatePolicies.numPolicies = (uint32_t)policy_count; - certificate->_certificatePolicies.policies = policies; - return; -badDER: - if (policies) - free(policies); - certificate->_certificatePolicies.present = false; - secdebug("cert", "Invalid CertificatePolicies Extension"); -} - -/* - id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } - - PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE { - issuerDomainPolicy CertPolicyId, - subjectDomainPolicy CertPolicyId } -*/ -#if 0 -static void SecCEPPolicyMappings(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERTag tag; - DERSequence pmSeq; - SecCEPolicyMapping *mappings = NULL; - DERReturn drtn = DERDecodeSeqInit(&extn->extnValue, &tag, &pmSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo pmContent; - DERSize mapping_count = 0; - while ((drtn = DERDecodeSeqNext(&pmSeq, &pmContent)) == DR_Success) { - require_quiet(pmContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - mapping_count++; - } - mappings = (SecCEPolicyMapping *)malloc(sizeof(SecCEPolicyMapping) - * mapping_count); - DERDecodeSeqInit(&extn->extnValue, &tag, &pmSeq); - DERSize mapping_ix = 0; - while ((drtn = DERDecodeSeqNext(&pmSeq, &pmContent)) == DR_Success) { - DERPolicyMapping pm; - drtn = DERParseSequenceContent(&pmContent.content, - DERNumPolicyMappingItemSpecs, - DERPolicyMappingItemSpecs, - &pm, sizeof(pm)); - require_noerr_quiet(drtn, badDER); - mappings[mapping_ix].issuerDomainPolicy = pm.issuerDomainPolicy; - mappings[mapping_ix++].subjectDomainPolicy = pm.subjectDomainPolicy; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - certificate->_policyMappings.present = true; - certificate->_policyMappings.critical = extn->critical; - certificate->_policyMappings.numMappings = mapping_count; - certificate->_policyMappings.mappings = mappings; - return; -badDER: - if (mappings) - free(mappings); - CFReleaseSafe(mappings); - certificate->_policyMappings.present = false; - secdebug("cert", "Invalid CertificatePolicies Extension"); -} -#else -static void SecCEPPolicyMappings(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERTag tag; - DERSequence pmSeq; - CFMutableDictionaryRef mappings = NULL; - DERReturn drtn = DERDecodeSeqInit(&extn->extnValue, &tag, &pmSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo pmContent; - require_quiet(mappings = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks), - badDER);; - while ((drtn = DERDecodeSeqNext(&pmSeq, &pmContent)) == DR_Success) { - require_quiet(pmContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERPolicyMapping pm; - drtn = DERParseSequenceContent(&pmContent.content, - DERNumPolicyMappingItemSpecs, - DERPolicyMappingItemSpecs, - &pm, sizeof(pm)); - require_noerr_quiet(drtn, badDER); - CFDataRef idp, sdp; - require_quiet(idp = CFDataCreate(kCFAllocatorDefault, - pm.issuerDomainPolicy.data, pm.issuerDomainPolicy.length), badDER); - require_quiet(sdp = CFDataCreate(kCFAllocatorDefault, - pm.subjectDomainPolicy.data, pm.subjectDomainPolicy.length), badDER); - CFMutableArrayRef sdps = - (CFMutableArrayRef)CFDictionaryGetValue(mappings, idp); - if (sdps) { - CFArrayAppendValue(sdps, sdp); - } else { - require_quiet(sdps = CFArrayCreateMutable(kCFAllocatorDefault, 0, - &kCFTypeArrayCallBacks), badDER); - CFDictionarySetValue(mappings, idp, sdps); - CFRelease(sdps); - } - } - require_quiet(drtn == DR_EndOfSequence, badDER); - certificate->_policyMappings = mappings; - return; -badDER: - CFReleaseSafe(mappings); - certificate->_policyMappings = NULL; - secdebug("cert", "Invalid CertificatePolicies Extension"); -} -#endif - -/* -AuthorityKeyIdentifier ::= SEQUENCE { - keyIdentifier [0] KeyIdentifier OPTIONAL, - authorityCertIssuer [1] GeneralNames OPTIONAL, - authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } - -- authorityCertIssuer and authorityCertSerialNumber MUST both - -- be present or both be absent - -KeyIdentifier ::= OCTET STRING -*/ -static void SecCEPAuthorityKeyIdentifier(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERAuthorityKeyIdentifier akid; - DERReturn drtn; - drtn = DERParseSequence(&extn->extnValue, - DERNumAuthorityKeyIdentifierItemSpecs, - DERAuthorityKeyIdentifierItemSpecs, - &akid, sizeof(akid)); - require_noerr_quiet(drtn, badDER); - if (akid.keyIdentifier.length) { - certificate->_authorityKeyIdentifier = akid.keyIdentifier; - } - if (akid.authorityCertIssuer.length || - akid.authorityCertSerialNumber.length) { - require_quiet(akid.authorityCertIssuer.length && - akid.authorityCertSerialNumber.length, badDER); - /* Perhaps put in a subsection called Authority Certificate Issuer. */ - certificate->_authorityKeyIdentifierIssuer = akid.authorityCertIssuer; - certificate->_authorityKeyIdentifierSerialNumber = akid.authorityCertSerialNumber; - } - - return; -badDER: - secdebug("cert", "Invalid AuthorityKeyIdentifier Extension"); -} - -static void SecCEPPolicyConstraints(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERPolicyConstraints pc; - DERReturn drtn; - drtn = DERParseSequence(&extn->extnValue, - DERNumPolicyConstraintsItemSpecs, - DERPolicyConstraintsItemSpecs, - &pc, sizeof(pc)); - require_noerr_quiet(drtn, badDER); - if (pc.requireExplicitPolicy.length) { - require_noerr_quiet(DERParseInteger( - &pc.requireExplicitPolicy, - &certificate->_policyConstraints.requireExplicitPolicy), badDER); - certificate->_policyConstraints.requireExplicitPolicyPresent = true; - } - if (pc.inhibitPolicyMapping.length) { - require_noerr_quiet(DERParseInteger( - &pc.inhibitPolicyMapping, - &certificate->_policyConstraints.inhibitPolicyMapping), badDER); - certificate->_policyConstraints.inhibitPolicyMappingPresent = true; - } - - certificate->_policyConstraints.present = true; - certificate->_policyConstraints.critical = extn->critical; - - return; -badDER: - certificate->_policyConstraints.present = false; - secdebug("cert", "Invalid PolicyConstraints Extension"); -} - -static void SecCEPExtendedKeyUsage(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -/* - InhibitAnyPolicy ::= SkipCerts - - SkipCerts ::= INTEGER (0..MAX) -*/ -static void SecCEPInhibitAnyPolicy(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - require_noerr_quiet(DERParseInteger( - &extn->extnValue, - &certificate->_inhibitAnyPolicySkipCerts), badDER); - return; -badDER: - certificate->_inhibitAnyPolicySkipCerts = UINT32_MAX; - secdebug("cert", "Invalid InhibitAnyPolicy Extension"); -} - -/* - id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 } - - AuthorityInfoAccessSyntax ::= - SEQUENCE SIZE (1..MAX) OF AccessDescription - - AccessDescription ::= SEQUENCE { - accessMethod OBJECT IDENTIFIER, - accessLocation GeneralName } - - id-ad OBJECT IDENTIFIER ::= { id-pkix 48 } - - id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 } - - id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 } - */ -static void SecCEPAuthorityInfoAccess(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); - DERTag tag; - DERSequence adSeq; - DERReturn drtn = DERDecodeSeqInit(&extn->extnValue, &tag, &adSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo adContent; - while ((drtn = DERDecodeSeqNext(&adSeq, &adContent)) == DR_Success) { - require_quiet(adContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERAccessDescription ad; - drtn = DERParseSequenceContent(&adContent.content, - DERNumAccessDescriptionItemSpecs, - DERAccessDescriptionItemSpecs, - &ad, sizeof(ad)); - require_noerr_quiet(drtn, badDER); - CFMutableArrayRef *urls; - if (DEROidCompare(&ad.accessMethod, &oidAdOCSP)) - urls = &certificate->_ocspResponders; - else if (DEROidCompare(&ad.accessMethod, &oidAdCAIssuer)) - urls = &certificate->_caIssuers; - else - continue; - - DERDecodedInfo generalNameContent; - drtn = DERDecodeItem(&ad.accessLocation, &generalNameContent); - require_noerr_quiet(drtn, badDER); - switch (generalNameContent.tag) { -#if 0 - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 6: - /* Technically I don't think this is valid, but there are certs out - in the wild that use a constructed IA5String. In particular the - VeriSign Time Stamping Authority CA.cer does this. */ -#endif - case ASN1_CONTEXT_SPECIFIC | 6: - { - CFURLRef url = CFURLCreateWithBytes(kCFAllocatorDefault, - generalNameContent.content.data, generalNameContent.content.length, - kCFStringEncodingASCII, NULL); - if (url) { - if (!*urls) - *urls = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); - CFArrayAppendValue(*urls, url); - CFRelease(url); - } - break; - } - default: - secdebug("cert", "bad general name for id-ad-ocsp AccessDescription t: 0x%02x v: %.*s", - generalNameContent.tag, (int)generalNameContent.content.length, generalNameContent.content.data); - goto badDER; - break; - } - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return; -badDER: - secdebug("cert", "failed to parse Authority Information Access extension"); -} - -static void SecCEPSubjectInfoAccess(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -static void SecCEPNetscapeCertType(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -static void SecCEPEntrustVersInfo(SecCertificateRefP certificate, - const SecCertificateExtension *extn) { - secdebug("cert", "critical: %s", extn->critical ? "yes" : "no"); -} - -/* Dictionary key callback for comparing to DERItems. */ -static Boolean SecDERItemEqual(const void *value1, const void *value2) { - return DEROidCompare((const DERItem *)value1, (const DERItem *)value2); -} - -/* Dictionary key callback calculating the hash of a DERItem. */ -static CFHashCode SecDERItemHash(const void *value) { - const DERItem *derItem = (const DERItem *)value; - CFHashCode hash = derItem->length; - DERSize ix = derItem->length > 8 ? derItem->length - 8 : 0; - for (; ix < derItem->length; ++ix) { - hash = (hash << 9) + (hash >> 23) + derItem->data[ix]; - } - - return hash; -} - -/* Dictionary key callbacks using the above 2 functions. */ -static const CFDictionaryKeyCallBacks SecDERItemKeyCallBacks = { - 0, /* version */ - NULL, /* retain */ - NULL, /* release */ - NULL, /* copyDescription */ - SecDERItemEqual, /* equal */ - SecDERItemHash /* hash */ -}; - -static void SecCertificateRegisterClass(void) { - static const CFRuntimeClass kSecCertificateClass = { - 0, /* version */ - "SecCertificate", /* class name */ - NULL, /* init */ - NULL, /* copy */ - SecCertificateDestroy, /* dealloc */ - SecCertificateEqual, /* equal */ - SecCertificateHash, /* hash */ - NULL, /* copyFormattingDesc */ - SecCertificateDescribe /* copyDebugDesc */ - }; - - kSecCertificateTypeID = _CFRuntimeRegisterClass(&kSecCertificateClass); - - /* Build a dictionary that maps from extension OIDs to callback functions - which can parse the extension of the type given. */ - static const void *extnOIDs[] = { - &oidSubjectKeyIdentifier, - &oidKeyUsage, - &oidPrivateKeyUsagePeriod, - &oidSubjectAltName, - &oidIssuerAltName, - &oidBasicConstraints, - &oidCrlDistributionPoints, - &oidCertificatePolicies, - &oidPolicyMappings, - &oidAuthorityKeyIdentifier, - &oidPolicyConstraints, - &oidExtendedKeyUsage, - &oidInhibitAnyPolicy, - &oidAuthorityInfoAccess, - &oidSubjectInfoAccess, - &oidNetscapeCertType, - &oidEntrustVersInfo - }; - static const void *extnParsers[] = { - SecCEPSubjectKeyIdentifier, - SecCEPKeyUsage, - SecCEPPrivateKeyUsagePeriod, - SecCEPSubjectAltName, - SecCEPIssuerAltName, - SecCEPBasicConstraints, - SecCEPCrlDistributionPoints, - SecCEPCertificatePolicies, - SecCEPPolicyMappings, - SecCEPAuthorityKeyIdentifier, - SecCEPPolicyConstraints, - SecCEPExtendedKeyUsage, - SecCEPInhibitAnyPolicy, - SecCEPAuthorityInfoAccess, - SecCEPSubjectInfoAccess, - SecCEPNetscapeCertType, - SecCEPEntrustVersInfo - }; - gExtensionParsers = CFDictionaryCreate(kCFAllocatorDefault, extnOIDs, - extnParsers, sizeof(extnOIDs) / sizeof(*extnOIDs), - &SecDERItemKeyCallBacks, NULL); -} - -/* Given the contents of an X.501 Name return the contents of a normalized - X.501 name. */ -CFDataRef createNormalizedX501Name(CFAllocatorRef allocator, - const DERItem *x501name) { - CFMutableDataRef result = CFDataCreateMutable(allocator, x501name->length); - CFIndex length = x501name->length; - CFDataSetLength(result, length); - UInt8 *base = CFDataGetMutableBytePtr(result); - - DERSequence rdnSeq; - DERReturn drtn = DERDecodeSeqContentInit(x501name, &rdnSeq); - - require_noerr_quiet(drtn, badDER); - DERDecodedInfo rdn; - - /* Always points to last rdn tag. */ - const DERByte *rdnTag = rdnSeq.nextItem; - /* Offset relative to base of current rdn set tag. */ - CFIndex rdnTagLocation = 0; - while ((drtn = DERDecodeSeqNext(&rdnSeq, &rdn)) == DR_Success) { - require_quiet(rdn.tag == ASN1_CONSTR_SET, badDER); - /* We don't allow empty RDNs. */ - require_quiet(rdn.content.length != 0, badDER); - /* Length of the tag and length of the current rdn. */ - CFIndex rdnTLLength = rdn.content.data - rdnTag; - CFIndex rdnContentLength = rdn.content.length; - /* Copy the tag and length of the RDN. */ - memcpy(base + rdnTagLocation, rdnTag, rdnTLLength); - - DERSequence atvSeq; - drtn = DERDecodeSeqContentInit(&rdn.content, &atvSeq); - DERDecodedInfo atv; - /* Always points to tag of current atv sequence. */ - const DERByte *atvTag = atvSeq.nextItem; - /* Offset relative to base of current atv sequence tag. */ - CFIndex atvTagLocation = rdnTagLocation + rdnTLLength; - while ((drtn = DERDecodeSeqNext(&atvSeq, &atv)) == DR_Success) { - require_quiet(atv.tag == ASN1_CONSTR_SEQUENCE, badDER); - /* Length of the tag and length of the current atv. */ - CFIndex atvTLLength = atv.content.data - atvTag; - CFIndex atvContentLength = atv.content.length; - /* Copy the tag and length of the atv and the atv itself. */ - memcpy(base + atvTagLocation, atvTag, - atvTLLength + atv.content.length); - - /* Now decode the atv sequence. */ - DERAttributeTypeAndValue atvPair; - drtn = DERParseSequenceContent(&atv.content, - DERNumAttributeTypeAndValueItemSpecs, - DERAttributeTypeAndValueItemSpecs, - &atvPair, sizeof(atvPair)); - require_noerr_quiet(drtn, badDER); - require_quiet(atvPair.type.length != 0, badDER); - DERDecodedInfo value; - drtn = DERDecodeItem(&atvPair.value, &value); - require_noerr_quiet(drtn, badDER); - - /* (c) attribute values in PrintableString are not case sensitive - (e.g., "Marianne Swanson" is the same as "MARIANNE SWANSON"); and - - (d) attribute values in PrintableString are compared after - removing leading and trailing white space and converting internal - substrings of one or more consecutive white space characters to a - single space. */ - if (value.tag == ASN1_PRINTABLE_STRING) { - /* Offset relative to base of current value tag. */ - CFIndex valueTagLocation = atvTagLocation + atvPair.value.data - atvTag; - CFIndex valueTLLength = value.content.data - atvPair.value.data; - CFIndex valueContentLength = value.content.length; - - /* Now copy all the bytes, but convert to upper case while - doing so and convert multiple whitespace chars into a - single space. */ - bool lastWasBlank = false; - CFIndex valueLocation = valueTagLocation + valueTLLength; - CFIndex valueCurrentLocation = valueLocation; - CFIndex ix; - for (ix = 0; ix < valueContentLength; ++ix) { - UInt8 ch = value.content.data[ix]; - if (isblank(ch)) { - if (lastWasBlank) { - continue; - } else { - /* Don't insert a space for first character - we encounter. */ - if (valueCurrentLocation > valueLocation) { - base[valueCurrentLocation++] = ' '; - } - lastWasBlank = true; - } - } else { - lastWasBlank = false; - if ('a' <= ch && ch <= 'z') { - base[valueCurrentLocation++] = ch + 'A' - 'a'; - } else { - base[valueCurrentLocation++] = ch; - } - } - } - /* Finally if lastWasBlank remove the trailing space. */ - if (lastWasBlank && valueCurrentLocation > valueLocation) { - valueCurrentLocation--; - } - /* Adjust content length to normalized length. */ - valueContentLength = valueCurrentLocation - valueLocation; - - /* Number of bytes by which the length should be shorted. */ - CFIndex lengthDiff = value.content.length - valueContentLength; - if (lengthDiff == 0) { - /* Easy case no need to adjust lengths. */ - } else { - /* Hard work we need to go back and fix up length fields - for: - 1) The value itself. - 2) The ATV Sequence containing type/value - 3) The RDN Set containing one or more atv pairs. - 4) The result. - */ - - /* Step 1 fix up length of value. */ - /* Length of value tag and length minus the tag. */ - DERSize newValueTLLength = valueTLLength - 1; - drtn = DEREncodeLength(valueContentLength, - base + valueTagLocation + 1, &newValueTLLength); - /* Add the length of the tag back in. */ - newValueTLLength++; - CFIndex valueLLDiff = valueTLLength - newValueTLLength; - if (valueLLDiff) { - /* The size of the length field changed, let's slide - the value back by valueLLDiff bytes. */ - memmove(base + valueTagLocation + newValueTLLength, - base + valueTagLocation + valueTLLength, - valueContentLength); - /* The length diff for the enclosing object. */ - lengthDiff += valueLLDiff; - } - - /* Step 2 fix up length of the enclosing ATV Sequence. */ - atvContentLength -= lengthDiff; - DERSize newATVTLLength = atvTLLength - 1; - drtn = DEREncodeLength(atvContentLength, - base + atvTagLocation + 1, &newATVTLLength); - /* Add the length of the tag back in. */ - newATVTLLength++; - CFIndex atvLLDiff = atvTLLength - newATVTLLength; - if (atvLLDiff) { - /* The size of the length field changed, let's slide - the value back by valueLLDiff bytes. */ - memmove(base + atvTagLocation + newATVTLLength, - base + atvTagLocation + atvTLLength, - atvContentLength); - /* The length diff for the enclosing object. */ - lengthDiff += atvLLDiff; - atvTLLength = newATVTLLength; - } - - /* Step 3 fix up length of enclosing RDN Set. */ - rdnContentLength -= lengthDiff; - DERSize newRDNTLLength = rdnTLLength - 1; - drtn = DEREncodeLength(rdnContentLength, - base + rdnTagLocation + 1, &newRDNTLLength); - /* Add the length of the tag back in. */ - newRDNTLLength++; - CFIndex rdnLLDiff = rdnTLLength - newRDNTLLength; - if (rdnLLDiff) { - /* The size of the length field changed, let's slide - the value back by valueLLDiff bytes. */ - memmove(base + rdnTagLocation + newRDNTLLength, - base + rdnTagLocation + rdnTLLength, - rdnContentLength); - /* The length diff for the enclosing object. */ - lengthDiff += rdnLLDiff; - rdnTLLength = newRDNTLLength; - - /* Adjust the locations that might have changed due to - this slide. */ - atvTagLocation -= rdnLLDiff; - } - } - } - atvTagLocation += atvTLLength + atvContentLength; - atvTag = atvSeq.nextItem; - } - rdnTagLocation += rdnTLLength + rdnContentLength; - rdnTag = rdnSeq.nextItem; - } - require_quiet(drtn == DR_EndOfSequence, badDER); - /* Truncate the result to the proper length. */ - CFDataSetLength(result, rdnTagLocation); - - return result; - -badDER: - CFRelease(result); - return NULL; -} - -/* AUDIT[securityd]: - certificate->_der is a caller provided data of any length (might be 0). - - Top level certificate decode. - */ -static bool SecCertificateParse(SecCertificateRefP certificate) -{ - DERReturn drtn; - - check(certificate); - CFAllocatorRef allocator = CFGetAllocator(certificate); - - /* top level decode */ - DERSignedCertCrl signedCert; - drtn = DERParseSequence(&certificate->_der, DERNumSignedCertCrlItemSpecs, - DERSignedCertCrlItemSpecs, &signedCert, - sizeof(signedCert)); - require_noerr_quiet(drtn, badCert); - /* Store tbs since we need to digest it for verification later on. */ - certificate->_tbs = signedCert.tbs; - - /* decode the TBSCert - it was saved in full DER form */ - DERTBSCert tbsCert; - drtn = DERParseSequence(&signedCert.tbs, - DERNumTBSCertItemSpecs, DERTBSCertItemSpecs, - &tbsCert, sizeof(tbsCert)); - require_noerr_quiet(drtn, badCert); - - /* sequence we're given: decode the signedCerts Signature Algorithm. */ - /* This MUST be the same as the certificate->_tbsSigAlg with the exception - of the params field. */ - drtn = DERParseSequenceContent(&signedCert.sigAlg, - DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, - &certificate->_sigAlg, sizeof(certificate->_sigAlg)); - require_noerr_quiet(drtn, badCert); - - /* The contents of signedCert.sig is a bit string whose contents - are the signature itself. */ - DERByte numUnusedBits; - drtn = DERParseBitString(&signedCert.sig, - &certificate->_signature, &numUnusedBits); - require_noerr_quiet(drtn, badCert); - - /* Now decode the tbsCert. */ - - /* First we turn the optional version into an int. */ - if (tbsCert.version.length) { - DERDecodedInfo decoded; - drtn = DERDecodeItem(&tbsCert.version, &decoded); - require_noerr_quiet(drtn, badCert); - require_quiet(decoded.tag == ASN1_INTEGER, badCert); - require_quiet(decoded.content.length == 1, badCert); - certificate->_version = decoded.content.data[0]; - require_quiet(certificate->_version > 0, badCert); - require_quiet(certificate->_version < 3, badCert); - } else { - certificate->_version = 0; - } - - /* The serial number is in the tbsCert.serialNum - it was saved in - INTEGER form without the tag and length. */ - certificate->_serialNum = tbsCert.serialNum; - certificate->_serialNumber = CFDataCreate(allocator, - tbsCert.serialNum.data, tbsCert.serialNum.length); - - /* sequence we're given: decode the tbsCerts TBS Signature Algorithm. */ - drtn = DERParseSequenceContent(&tbsCert.tbsSigAlg, - DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, - &certificate->_tbsSigAlg, sizeof(certificate->_tbsSigAlg)); - require_noerr_quiet(drtn, badCert); - - /* The issuer is in the tbsCert.issuer - it's a sequence without the tag - and length fields. */ - certificate->_issuer = tbsCert.issuer; - certificate->_normalizedIssuer = createNormalizedX501Name(allocator, - &tbsCert.issuer); - - /* sequence we're given: decode the tbsCerts Validity sequence. */ - DERValidity validity; - drtn = DERParseSequenceContent(&tbsCert.validity, - DERNumValidityItemSpecs, DERValidityItemSpecs, - &validity, sizeof(validity)); - require_noerr_quiet(drtn, badCert); - require_quiet(derDateGetAbsoluteTime(&validity.notBefore, - &certificate->_notBefore), badCert); - require_quiet(derDateGetAbsoluteTime(&validity.notAfter, - &certificate->_notAfter), badCert); - - /* The subject is in the tbsCert.subject - it's a sequence without the tag - and length fields. */ - certificate->_subject = tbsCert.subject; - certificate->_normalizedSubject = createNormalizedX501Name(allocator, - &tbsCert.subject); - - /* sequence we're given: encoded DERSubjPubKeyInfo - it was saved in full DER form */ - DERSubjPubKeyInfo pubKeyInfo; - drtn = DERParseSequence(&tbsCert.subjectPubKey, - DERNumSubjPubKeyInfoItemSpecs, DERSubjPubKeyInfoItemSpecs, - &pubKeyInfo, sizeof(pubKeyInfo)); - require_noerr_quiet(drtn, badCert); - - /* sequence we're given: decode the pubKeyInfos DERAlgorithmId */ - drtn = DERParseSequenceContent(&pubKeyInfo.algId, - DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, - &certificate->_algId, sizeof(certificate->_algId)); - require_noerr_quiet(drtn, badCert); - - /* Now we can figure out the key's algorithm id and params based on - certificate->_algId.oid. */ - - /* The contents of pubKeyInfo.pubKey is a bit string whose contents - are a PKCS1 format RSA key. */ - drtn = DERParseBitString(&pubKeyInfo.pubKey, - &certificate->_pubKeyDER, &numUnusedBits); - require_noerr_quiet(drtn, badCert); - - /* The contents of tbsCert.issuerID is a bit string. */ - certificate->_issuerUniqueID = tbsCert.issuerID; - - /* The contents of tbsCert.subjectID is a bit string. */ - certificate->_subjectUniqueID = tbsCert.subjectID; - - /* Extensions. */ - if (tbsCert.extensions.length) { - CFIndex extensionCount = 0; - DERSequence derSeq; - DERTag tag; - drtn = DERDecodeSeqInit(&tbsCert.extensions, &tag, - &derSeq); - require_noerr_quiet(drtn, badCert); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badCert); - DERDecodedInfo currDecoded; - while ((drtn = DERDecodeSeqNext(&derSeq, &currDecoded)) == DR_Success) { -#if 0 -/* ! = MUST recognize ? = SHOULD recognize -*/ - - KnownExtension _subjectKeyID; /* ?SubjectKeyIdentifier id-ce 14 */ - KnownExtension _keyUsage; /* !KeyUsage id-ce 15 */ - KnownExtension _subjectAltName; /* !SubjectAltName id-ce 17 */ - KnownExtension _basicConstraints; /* !BasicConstraints id-ce 19 */ - KnownExtension _authorityKeyID; /* ?AuthorityKeyIdentifier id-ce 35 */ - KnownExtension _extKeyUsage; /* !ExtKeyUsage id-ce 37 */ - KnownExtension _netscapeCertType; /* 2.16.840.1.113730.1.1 netscape 1 1 */ - KnownExtension _qualCertStatements; /* QCStatements id-pe 3 */ - - KnownExtension _issuerAltName; /* IssuerAltName id-ce 18 */ - KnownExtension _nameConstraints; /* !NameConstraints id-ce 30 */ - KnownExtension _cRLDistributionPoints; /* CRLDistributionPoints id-ce 31 */ - KnownExtension _certificatePolicies; /* !CertificatePolicies id-ce 32 */ - KnownExtension _policyMappings; /* ?PolicyMappings id-ce 33 */ - KnownExtension _policyConstraints; /* !PolicyConstraints id-ce 36 */ - KnownExtension _freshestCRL; /* FreshestCRL id-ce 46 */ - KnownExtension _inhibitAnyPolicy; /* !InhibitAnyPolicy id-ce 54 */ - - KnownExtension _authorityInfoAccess; /* AuthorityInfoAccess id-pe 1 */ - KnownExtension _subjectInfoAccess; /* SubjectInfoAccess id-pe 11 */ -#endif - - extensionCount++; - } - require_quiet(drtn == DR_EndOfSequence, badCert); - - /* Put some upper limit on the number of extentions allowed. */ - require_quiet(extensionCount < 10000, badCert); - certificate->_extensionCount = extensionCount; - certificate->_extensions = - malloc(sizeof(SecCertificateExtension) * extensionCount); - - CFIndex ix = 0; - drtn = DERDecodeSeqInit(&tbsCert.extensions, &tag, &derSeq); - require_noerr_quiet(drtn, badCert); - for (ix = 0; ix < extensionCount; ++ix) { - drtn = DERDecodeSeqNext(&derSeq, &currDecoded); - require_quiet(drtn == DR_Success || - (ix == extensionCount - 1 && drtn == DR_EndOfSequence), badCert); - require_quiet(currDecoded.tag == ASN1_CONSTR_SEQUENCE, badCert); - DERExtension extn; - drtn = DERParseSequenceContent(&currDecoded.content, - DERNumExtensionItemSpecs, DERExtensionItemSpecs, - &extn, sizeof(extn)); - require_noerr_quiet(drtn, badCert); - /* Copy stuff into certificate->extensions[ix]. */ - certificate->_extensions[ix].extnID = extn.extnID; - require_noerr_quiet(drtn = DERParseBoolean(&extn.critical, false, - &certificate->_extensions[ix].critical), badCert); - certificate->_extensions[ix].extnValue = extn.extnValue; - - SecCertificateExtensionParser parser = - (SecCertificateExtensionParser)CFDictionaryGetValue( - gExtensionParsers, &certificate->_extensions[ix].extnID); - if (parser) { - /* Invoke the parser. */ - parser(certificate, &certificate->_extensions[ix]); - } else if (certificate->_extensions[ix].critical) { - secdebug("cert", "Found unknown critical extension"); - certificate->_foundUnknownCriticalExtension = true; - } else { - secdebug("cert", "Found unknown non critical extension"); - } - } - } - - return true; - -badCert: - return false; -} - - -/* Public API functions. */ -CFTypeID SecCertificateGetTypeIDP(void) { - pthread_once(&kSecCertificateRegisterClass, SecCertificateRegisterClass); - return kSecCertificateTypeID; -} - -SecCertificateRefP SecCertificateCreateWithBytesP(CFAllocatorRef allocator, - const UInt8 *der_bytes, CFIndex der_length) { - check(der_bytes); - check(der_length); - CFIndex size = sizeof(struct __SecCertificate) + der_length; - SecCertificateRefP result = (SecCertificateRefP)_CFRuntimeCreateInstance( - allocator, SecCertificateGetTypeIDP(), size - sizeof(CFRuntimeBase), 0); - if (result) { - memset((char*)result + sizeof(result->_base), 0, - sizeof(*result) - sizeof(result->_base)); - result->_der.data = ((DERByte *)result + sizeof(*result)); - result->_der.length = der_length; - memcpy(result->_der.data, der_bytes, der_length); - if (!SecCertificateParse(result)) { - CFRelease(result); - return NULL; - } - } - return result; -} - -/* @@@ Placeholder until iap submits a binary is fixed. */ -SecCertificateRefP SecCertificateCreate(CFAllocatorRef allocator, - const UInt8 *der_bytes, CFIndex der_length); - -SecCertificateRefP SecCertificateCreate(CFAllocatorRef allocator, - const UInt8 *der_bytes, CFIndex der_length) { - return SecCertificateCreateWithBytesP(allocator, der_bytes, der_length); -} -/* @@@ End of placeholder. */ - -/* AUDIT[securityd](done): - der_certificate is a caller provided data of any length (might be 0), only - its cf type has been checked. - */ -SecCertificateRefP SecCertificateCreateWithDataP(CFAllocatorRef allocator, - CFDataRef der_certificate) { - check(der_certificate); - CFIndex size = sizeof(struct __SecCertificate); - SecCertificateRefP result = (SecCertificateRefP)_CFRuntimeCreateInstance( - allocator, SecCertificateGetTypeIDP(), size - sizeof(CFRuntimeBase), 0); - if (result) { - memset((char*)result + sizeof(result->_base), 0, size - sizeof(result->_base)); - result->_der_data = CFDataCreateCopy(allocator, der_certificate); - result->_der.data = (DERByte *)CFDataGetBytePtr(result->_der_data); - result->_der.length = CFDataGetLength(result->_der_data); - if (!SecCertificateParse(result)) { - CFRelease(result); - return NULL; - } - } - return result; -} - -CFDataRef SecCertificateCopyDataP(SecCertificateRefP certificate) { - check(certificate); - CFDataRef result; - if (certificate->_der_data) { - CFRetain(certificate->_der_data); - result = certificate->_der_data; - } else { - result = CFDataCreate(CFGetAllocator(certificate), - certificate->_der.data, certificate->_der.length); -#if 0 - /* FIXME: If we wish to cache result we need to lock the certificate. - Also this create 2 copies of the certificate data which is somewhat - suboptimal. */ - CFRetain(result); - certificate->_der_data = result; -#endif - } - - return result; -} - -CFIndex SecCertificateGetLengthP(SecCertificateRefP certificate) { - return certificate->_der.length; -} - -const UInt8 *SecCertificateGetBytePtrP(SecCertificateRefP certificate) { - return certificate->_der.data; -} - -/* From rfc3280 - Appendix B. ASN.1 Notes - - Object Identifiers (OIDs) are used throughout this specification to - identify certificate policies, public key and signature algorithms, - certificate extensions, etc. There is no maximum size for OIDs. - This specification mandates support for OIDs which have arc elements - with values that are less than 2^28, that is, they MUST be between 0 - and 268,435,455, inclusive. This allows each arc element to be - represented within a single 32 bit word. Implementations MUST also - support OIDs where the length of the dotted decimal (see [RFC 2252], - section 4.1) string representation can be up to 100 bytes - (inclusive). Implementations MUST be able to handle OIDs with up to - 20 elements (inclusive). CAs SHOULD NOT issue certificates which - contain OIDs that exceed these requirements. Likewise, CRL issuers - SHOULD NOT issue CRLs which contain OIDs that exceed these - requirements. -*/ - -/* Oids longer than this are considered invalid. */ -#define MAX_OID_SIZE 32 - -CFStringRef SecDERItemCopyOIDDecimalRepresentation(CFAllocatorRef allocator, - const DERItem *oid) { - - if (oid->length == 0) { - return SecFrameworkCopyLocalizedString(CFSTR(""), - CFSTR("SecCertificate")); - } - if (oid->length > MAX_OID_SIZE) { - return SecFrameworkCopyLocalizedString(CFSTR("Oid too long"), - CFSTR("SecCertificate")); - } - - CFMutableStringRef result = CFStringCreateMutable(allocator, 0); - - // The first two levels are encoded into one byte, since the root level - // has only 3 nodes (40*x + y). However if x = joint-iso-itu-t(2) then - // y may be > 39, so we have to add special-case handling for this. - uint32_t x = oid->data[0] / 40; - uint32_t y = oid->data[0] % 40; - if (x > 2) - { - // Handle special case for large y if x = 2 - y += (x - 2) * 40; - x = 2; - } - CFStringAppendFormat(result, NULL, CFSTR("%u.%u"), x, y); - - uint32_t value = 0; - for (x = 1; x < oid->length; ++x) - { - value = (value << 7) | (oid->data[x] & 0x7F); - /* @@@ value may not span more than 4 bytes. */ - /* A max number of 20 values is allowed. */ - if (!(oid->data[x] & 0x80)) - { - CFStringAppendFormat(result, NULL, CFSTR(".%lu"), (unsigned long)value); - value = 0; - } - } - return result; -} - -static CFStringRef copyLocalizedOidDescription(CFAllocatorRef allocator, - const DERItem *oid) { - if (oid->length == 0) { - return SecFrameworkCopyLocalizedString(CFSTR(""), - CFSTR("SecCertificate")); - } - - /* Build the key we use to lookup the localized OID description. */ - CFMutableStringRef oidKey = CFStringCreateMutable(allocator, - oid->length * 3 + 5); - CFStringAppendFormat(oidKey, NULL, CFSTR("06 %02lX"), (unsigned long)oid->length); - DERSize ix; - for (ix = 0; ix < oid->length; ++ix) - CFStringAppendFormat(oidKey, NULL, CFSTR(" %02X"), oid->data[ix]); - - CFStringRef name = SecFrameworkCopyLocalizedString(oidKey, CFSTR("OID")); - if (CFEqual(oidKey, name)) { - CFRelease(name); - name = SecDERItemCopyOIDDecimalRepresentation(allocator, oid); - } - CFRelease(oidKey); - - return name; -} - -/* Return the ipAddress as a dotted quad for ipv4 or as 8 colon separated - 4 digit hex strings for ipv6. Return NULL if the passed in IP doesn't - have a length of exactly 4 or 16 octects. */ -static CFStringRef copyIPAddressContentDescription(CFAllocatorRef allocator, - const DERItem *ip) { - /* @@@ This is the IP Address as an OCTECT STRING. For IPv4 it's - 4 octects addr, or 8 octects, addr/mask for ipv6 it's - 16 octects addr, or 32 octects addr/mask. */ - CFStringRef value = NULL; - if (ip->length == 4) { - value = CFStringCreateWithFormat(allocator, NULL, - CFSTR("%u.%u.%u.%u"), - ip->data[0], ip->data[1], ip->data[2], ip->data[3]); - } else if (ip->length == 16) { - value = CFStringCreateWithFormat(allocator, NULL, - CFSTR("%02x%02x:%02x%02x:%02x%02x:%02x%02x:" - "%02x%02x:%02x%02x:%02x%02x:%02x%02x"), - ip->data[0], ip->data[1], ip->data[2], ip->data[3], - ip->data[4], ip->data[5], ip->data[6], ip->data[7], - ip->data[8], ip->data[9], ip->data[10], ip->data[11], - ip->data[12], ip->data[13], ip->data[14], ip->data[15]); - } - - return value; -} - -#if 0 -static CFStringRef copyFullOidDescription(CFAllocatorRef allocator, - const DERItem *oid) { - CFStringRef decimal = SecDERItemCopyOIDDecimalRepresentation(allocator, oid); - CFStringRef name = copyLocalizedOidDescription(allocator, oid); - CFStringRef oid_string = CFStringCreateWithFormat(allocator, NULL, - CFSTR("%@ (%@)"), name, decimal); - CFRelease(name); - CFRelease(decimal); - return oid_string; -} -#endif - -void appendPropertyP(CFMutableArrayRef properties, - CFStringRef propertyType, CFStringRef label, CFTypeRef value) { - CFDictionaryRef property; - if (label) { - CFStringRef localizedLabel = SecFrameworkCopyLocalizedString(label, - CFSTR("SecCertificate")); - const void *all_keys[4]; - all_keys[0] = kSecPropertyKeyType; - all_keys[1] = kSecPropertyKeyLabel; - all_keys[2] = kSecPropertyKeyLocalizedLabel; - all_keys[3] = kSecPropertyKeyValue; - const void *property_values[] = { - propertyType, - label, - localizedLabel, - value, - }; - property = CFDictionaryCreate(CFGetAllocator(properties), - all_keys, property_values, value ? 4 : 3, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFRelease(localizedLabel); - } else { - const void *nolabel_keys[2]; - nolabel_keys[0] = kSecPropertyKeyType; - nolabel_keys[1] = kSecPropertyKeyValue; - const void *property_values[] = { - propertyType, - value, - }; - property = CFDictionaryCreate(CFGetAllocator(properties), - nolabel_keys, property_values, 2, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - } - - CFArrayAppendValue(properties, property); - CFRelease(property); -} - -/* YYMMDDhhmmZ */ -#define UTC_TIME_NOSEC_ZULU_LEN 11 -/* YYMMDDhhmmssZ */ -#define UTC_TIME_ZULU_LEN 13 -/* YYMMDDhhmmssThhmm */ -#define UTC_TIME_LOCALIZED_LEN 17 -/* YYYYMMDDhhmmssZ */ -#define GENERALIZED_TIME_ZULU_LEN 15 -/* YYYYMMDDhhmmssThhmm */ -#define GENERALIZED_TIME_LOCALIZED_LEN 19 - -/* Parse 2 digits at (*p)[0] and (*p)[1] and return the result. Also - advance *p by 2. */ -static inline SInt32 parseDecimalPair(const DERByte **p) { - const DERByte *cp = *p; - *p += 2; - return 10 * (cp[0] - '0') + cp[1] - '0'; -} - -/* Decode a choice of UTCTime or GeneralizedTime to a CFAbsoluteTime. Return - true if the date was valid and properly decoded, also return the result in - absTime. Return false otherwise. */ -CFAbsoluteTime SecAbsoluteTimeFromDateContent(DERTag tag, const uint8_t *bytes, - size_t length) { - check(bytes); - if (length == 0) - return NULL_TIME; - - bool isUtcLength = false; - bool isLocalized = false; - bool noSeconds = false; - switch (length) { - case UTC_TIME_NOSEC_ZULU_LEN: /* YYMMDDhhmmZ */ - isUtcLength = true; - noSeconds = true; - break; - case UTC_TIME_ZULU_LEN: /* YYMMDDhhmmssZ */ - isUtcLength = true; - break; - case GENERALIZED_TIME_ZULU_LEN: /* YYYYMMDDhhmmssZ */ - break; - case UTC_TIME_LOCALIZED_LEN: /* YYMMDDhhmmssThhmm (where T=[+,-]) */ - isUtcLength = true; - /*DROPTHROUGH*/ - case GENERALIZED_TIME_LOCALIZED_LEN:/* YYYYMMDDhhmmssThhmm (where T=[+,-]) */ - isLocalized = true; - break; - default: /* unknown format */ - return NULL_TIME; - } - - /* Make sure the der tag fits the thing inside it. */ - if (tag == ASN1_UTC_TIME) { - if (!isUtcLength) - return NULL_TIME; - } else if (tag == ASN1_GENERALIZED_TIME) { - if (isUtcLength) - return NULL_TIME; - } else { - return NULL_TIME; - } - - const DERByte *cp = bytes; - /* Check that all characters are digits, except if localized the timezone - indicator or if not localized the 'Z' at the end. */ - DERSize ix; - for (ix = 0; ix < length; ++ix) { - if (!(isdigit(cp[ix]))) { - if ((isLocalized && ix == length - 5 && - (cp[ix] == '+' || cp[ix] == '-')) || - (!isLocalized && ix == length - 1 && cp[ix] == 'Z')) { - continue; - } - return NULL_TIME; - } - } - - /* Initialize the fields in a gregorian date struct. */ - CFGregorianDate gdate; - if (isUtcLength) { - SInt32 year = parseDecimalPair(&cp); - if (year < 50) { - /* 0 <= year < 50 : assume century 21 */ - gdate.year = 2000 + year; - } else if (year < 70) { - /* 50 <= year < 70 : illegal per PKIX */ - return false; - } else { - /* 70 < year <= 99 : assume century 20 */ - gdate.year = 1900 + year; - } - } else { - gdate.year = 100 * parseDecimalPair(&cp) + parseDecimalPair(&cp); - } - gdate.month = parseDecimalPair(&cp); - gdate.day = parseDecimalPair(&cp); - gdate.hour = parseDecimalPair(&cp); - gdate.minute = parseDecimalPair(&cp); - if (noSeconds) { - gdate.second = 0; - } else { - gdate.second = parseDecimalPair(&cp); - } - - CFTimeInterval timeZoneOffset = 0; - if (isLocalized) { - /* ZONE INDICATOR */ - SInt32 multiplier = *cp++ == '+' ? 60 : -60; - timeZoneOffset = multiplier * - (parseDecimalPair(&cp) + 60 * parseDecimalPair(&cp)); - } else { - timeZoneOffset = 0; - } - - secdebug("dateparse", - "date %.*s year: %04d-%02d-%02d %02d:%02d:%02.f %+05.f", - (int)length, bytes, (int)gdate.year, gdate.month, - gdate.day, gdate.hour, gdate.minute, gdate.second, - timeZoneOffset / 60); - - if (!CFGregorianDateIsValid(gdate, kCFGregorianAllUnits)) - return false; - CFTimeZoneRef timeZone = CFTimeZoneCreateWithTimeIntervalFromGMT(NULL, - timeZoneOffset); - if (!timeZone) - return NULL_TIME; - CFAbsoluteTime absTime = CFGregorianDateGetAbsoluteTime(gdate, timeZone); - CFRelease(timeZone); - return absTime; -} - -static bool derDateContentGetAbsoluteTime(DERTag tag, const DERItem *date, - CFAbsoluteTime *pabsTime) { - CFAbsoluteTime absTime = SecAbsoluteTimeFromDateContent(tag, date->data, - date->length); - if (absTime == NULL_TIME) - return false; - - *pabsTime = absTime; - return true; -} - -/* Decode a choice of UTCTime or GeneralizedTime to a CFAbsoluteTime. Return - true if the date was valid and properly decoded, also return the result in - absTime. Return false otherwise. */ -static bool derDateGetAbsoluteTime(const DERItem *dateChoice, - CFAbsoluteTime *absTime) { - check(dateChoice); - check(absTime); - if (dateChoice->length == 0) - return false; - - DERDecodedInfo decoded; - if (DERDecodeItem(dateChoice, &decoded)) - return false; - - return derDateContentGetAbsoluteTime(decoded.tag, &decoded.content, - absTime); -} - -static void appendDataProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *der_data) { - CFDataRef data = CFDataCreate(CFGetAllocator(properties), - der_data->data, der_data->length); - appendPropertyP(properties, kSecPropertyTypeData, label, data); - CFRelease(data); -} - -static void appendUnparsedProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *der_data) { - CFStringRef newLabel = CFStringCreateWithFormat(CFGetAllocator(properties), - NULL, CFSTR("Unparsed %@"), label); - appendDataProperty(properties, newLabel, der_data); - CFRelease(newLabel); -} - -static void appendInvalidProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *der_data) { - CFStringRef newLabel = CFStringCreateWithFormat(CFGetAllocator(properties), - NULL, CFSTR("Invalid %@"), label); - appendDataProperty(properties, newLabel, der_data); - CFRelease(newLabel); -} - -static void appendDateContentProperty(CFMutableArrayRef properties, - CFStringRef label, DERTag tag, const DERItem *dateContent) { - CFAbsoluteTime absTime; - if (!derDateContentGetAbsoluteTime(tag, dateContent, &absTime)) { - /* Date decode failure insert hex bytes instead. */ - return appendInvalidProperty(properties, label, dateContent); - } - CFDateRef date = CFDateCreate(CFGetAllocator(properties), absTime); - appendPropertyP(properties, kSecPropertyTypeDate, label, date); - CFRelease(date); -} - -static void appendDateProperty(CFMutableArrayRef properties, - CFStringRef label, CFAbsoluteTime absTime) { - CFDateRef date = CFDateCreate(CFGetAllocator(properties), absTime); - appendPropertyP(properties, kSecPropertyTypeDate, label, date); - CFRelease(date); -} - -static void appendIPAddressContentProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *ip) { - CFStringRef value = - copyIPAddressContentDescription(CFGetAllocator(properties), ip); - if (value) { - appendPropertyP(properties, kSecPropertyTypeString, label, value); - CFRelease(value); - } else { - appendUnparsedProperty(properties, label, ip); - } -} - -static void appendURLContentProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *urlContent) { - CFURLRef url = CFURLCreateWithBytes(CFGetAllocator(properties), - urlContent->data, urlContent->length, kCFStringEncodingASCII, NULL); - if (url) { - appendPropertyP(properties, kSecPropertyTypeURL, label, url); - CFRelease(url); - } else { - appendInvalidProperty(properties, label, urlContent); - } -} - -static void appendURLProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *url) { - DERDecodedInfo decoded; - DERReturn drtn; - - drtn = DERDecodeItem(url, &decoded); - if (drtn || decoded.tag != ASN1_IA5_STRING) { - appendInvalidProperty(properties, label, url); - } else { - appendURLContentProperty(properties, label, &decoded.content); - } -} - -static void appendOIDProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *oid) { - CFStringRef oid_string = copyLocalizedOidDescription(CFGetAllocator(properties), - oid); - appendPropertyP(properties, kSecPropertyTypeString, label, oid_string); - CFRelease(oid_string); -} - -static void appendAlgorithmProperty(CFMutableArrayRef properties, - CFStringRef label, const DERAlgorithmId *algorithm) { - CFMutableArrayRef alg_props = - CFArrayCreateMutable(CFGetAllocator(properties), 0, - &kCFTypeArrayCallBacks); - appendOIDProperty(alg_props, CFSTR("Algorithm"), &algorithm->oid); - if (algorithm->params.length) { - if (algorithm->params.length == 2 && - algorithm->params.data[0] == ASN1_NULL && - algorithm->params.data[1] == 0) { - /* @@@ Localize or perhaps skip it? */ - appendPropertyP(alg_props, kSecPropertyTypeString, - CFSTR("Parameters"), CFSTR("none")); - } else { - appendUnparsedProperty(alg_props, CFSTR("Parameters"), - &algorithm->params); - } - } - appendPropertyP(properties, kSecPropertyTypeSection, label, alg_props); - CFRelease(alg_props); -} - -static CFStringRef copyHexDescription(CFAllocatorRef allocator, - const DERItem *blob) { - CFIndex ix, length = blob->length /* < 24 ? blob->length : 24 */; - CFMutableStringRef string = CFStringCreateMutable(allocator, - blob->length * 3 - 1); - for (ix = 0; ix < length; ++ix) - if (ix == 0) - CFStringAppendFormat(string, NULL, CFSTR("%02X"), blob->data[ix]); - else - CFStringAppendFormat(string, NULL, CFSTR(" %02X"), blob->data[ix]); - - return string; -} - -static CFStringRef copyBlobString(CFAllocatorRef allocator, - CFStringRef blobType, CFStringRef quanta, const DERItem *blob) { - CFStringRef blobFormat = SecFrameworkCopyLocalizedString( - CFSTR("%@; %d %@; data = %@"), CFSTR("SecCertificate") - /*, "format string for encoded field data (e.g. Sequence; 128 bytes; " - "data = 00 00 ...)" */); - CFStringRef hex = copyHexDescription(allocator, blob); - CFStringRef result = CFStringCreateWithFormat(allocator, NULL, - blobFormat, blobType, blob->length, quanta, hex); - CFRelease(hex); - CFRelease(blobFormat); - - return result; -} - -static CFStringRef copyContentString(CFAllocatorRef allocator, - const DERItem *string, CFStringEncoding encoding, - bool printableOnly) { - /* Strip potential bogus trailing zero from printable strings. */ - DERSize length = string->length; - if (length && string->data[length - 1] == 0) { - /* Don't mess with the length of UTF16 strings though. */ - if (encoding != kCFStringEncodingUTF16) - length--; - } - /* A zero length string isn't considered printable. */ - if (!length && printableOnly) - return NULL; - - /* Passing true for the 5th paramater to CFStringCreateWithBytes() makes - it treat kCFStringEncodingUTF16 as big endian by default, whereas - passing false makes it treat it as native endian by default. */ - CFStringRef result = CFStringCreateWithBytes(allocator, string->data, - length, encoding, encoding == kCFStringEncodingUTF16); - if (result) - return result; - - return printableOnly ? NULL : copyHexDescription(allocator, string); -} - -/* From rfc3280 - Appendix B. ASN.1 Notes - - CAs MUST force the serialNumber to be a non-negative integer, that - is, the sign bit in the DER encoding of the INTEGER value MUST be - zero - this can be done by adding a leading (leftmost) `00'H octet if - necessary. This removes a potential ambiguity in mapping between a - string of octets and an integer value. - - As noted in section 4.1.2.2, serial numbers can be expected to - contain long integers. Certificate users MUST be able to handle - serialNumber values up to 20 octets in length. Conformant CAs MUST - NOT use serialNumber values longer than 20 octets. -*/ - -/* Return the given numeric data as a string: decimal up to 64 bits, - hex otherwise. */ -static CFStringRef copyIntegerContentDescription(CFAllocatorRef allocator, - const DERItem *integer) { - uint64_t value = 0; - CFIndex ix, length = integer->length; - - if (length == 0 || length > 8) - return copyHexDescription(allocator, integer); - - for(ix = 0; ix < length; ++ix) { - value <<= 8; - value += integer->data[ix]; - } - - return CFStringCreateWithFormat(allocator, NULL, CFSTR("%llu"), value); -} - -static CFStringRef copyDERThingContentDescription(CFAllocatorRef allocator, - DERTag tag, const DERItem *derThing, bool printableOnly) { - switch(tag) { - case ASN1_INTEGER: - case ASN1_BOOLEAN: - return printableOnly ? NULL : copyIntegerContentDescription(allocator, derThing); - case ASN1_PRINTABLE_STRING: - case ASN1_IA5_STRING: - return copyContentString(allocator, derThing, kCFStringEncodingASCII, printableOnly); - case ASN1_UTF8_STRING: - case ASN1_GENERAL_STRING: - case ASN1_UNIVERSAL_STRING: - return copyContentString(allocator, derThing, kCFStringEncodingUTF8, printableOnly); - case ASN1_T61_STRING: // 20, also BER_TAG_TELETEX_STRING - case ASN1_VIDEOTEX_STRING: // 21 - case ASN1_VISIBLE_STRING: // 26 - return copyContentString(allocator, derThing, kCFStringEncodingISOLatin1, printableOnly); - case ASN1_BMP_STRING: // 30 - return copyContentString(allocator, derThing, kCFStringEncodingUTF16, printableOnly); - case ASN1_OCTET_STRING: - return printableOnly ? NULL : copyBlobString(allocator, CFSTR("Byte string"), CFSTR("bytes"), - derThing); - //return copyBlobString(BYTE_STRING_STR, BYTES_STR, derThing); - case ASN1_BIT_STRING: - return printableOnly ? NULL : copyBlobString(allocator, CFSTR("Bit string"), CFSTR("bits"), - derThing); - case (DERByte)ASN1_CONSTR_SEQUENCE: - return printableOnly ? NULL : copyBlobString(allocator, CFSTR("Sequence"), CFSTR("bytes"), - derThing); - case (DERByte)ASN1_CONSTR_SET: - return printableOnly ? NULL : copyBlobString(allocator, CFSTR("Set"), CFSTR("bytes"), - derThing); - case ASN1_OBJECT_ID: - return printableOnly ? NULL : copyLocalizedOidDescription(allocator, derThing); - default: - /* @@@ Localize. */ - /* "format string for undisplayed field data with a given DER tag" */ - return printableOnly ? NULL : CFStringCreateWithFormat(allocator, NULL, - CFSTR("not displayed (tag = %d; length %d)"), - tag, (int)derThing->length); - } -} - -static CFStringRef copyDERThingDescription(CFAllocatorRef allocator, - const DERItem *derThing, bool printableOnly) { - DERDecodedInfo decoded; - DERReturn drtn; - - drtn = DERDecodeItem(derThing, &decoded); - if (drtn) { - return printableOnly ? NULL : copyHexDescription(allocator, derThing); - } else { - return copyDERThingContentDescription(allocator, decoded.tag, - &decoded.content, false); - } -} - -static void appendDERThingProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *derThing) { - CFStringRef value = copyDERThingDescription(CFGetAllocator(properties), - derThing, false); - appendPropertyP(properties, kSecPropertyTypeString, label, value); - CFRelease(value); -} - -static OSStatus appendRDNProperty(void *context, const DERItem *rdnType, - const DERItem *rdnValue, CFIndex rdnIX) { - CFMutableArrayRef properties = (CFMutableArrayRef)context; - if (rdnIX > 0) { - /* If there is more than one value pair we create a subsection for the - second pair, and append things to the subsection for subsequent - pairs. */ - CFIndex lastIX = CFArrayGetCount(properties) - 1; - CFTypeRef lastValue = CFArrayGetValueAtIndex(properties, lastIX); - if (rdnIX == 1) { - /* Since this is the second rdn pair for a given rdn, we setup a - new subsection for this rdn. We remove the first property - from the properties array and make it the first element in the - subsection instead. */ - CFMutableArrayRef rdn_props = CFArrayCreateMutable( - CFGetAllocator(properties), 0, &kCFTypeArrayCallBacks); - CFArrayAppendValue(rdn_props, lastValue); - CFArrayRemoveValueAtIndex(properties, lastIX); - appendPropertyP(properties, kSecPropertyTypeSection, NULL, rdn_props); - properties = rdn_props; - } else { - /* Since this is the third or later rdn pair we have already - created a subsection in the top level properties array. Instead - of appending to that directly we append to the array inside the - subsection. */ - properties = (CFMutableArrayRef)CFDictionaryGetValue( - (CFDictionaryRef)lastValue, kSecPropertyKeyValue); - } - } - - /* Finally we append the new rdn value to the property array. */ - CFStringRef label = copyLocalizedOidDescription(CFGetAllocator(properties), - rdnType); - if (label) { - appendDERThingProperty(properties, label, rdnValue); - CFRelease(label); - return errSecSuccess; - } else { - return errSecInvalidCertificate; - } -} - -static CFArrayRef createPropertiesForRDNContent(CFAllocatorRef allocator, - const DERItem *rdnSetContent) { - CFMutableArrayRef properties = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - OSStatus status = parseRDNContent(rdnSetContent, properties, - appendRDNProperty); - if (status) { - CFArrayRemoveAllValues(properties); - appendInvalidProperty(properties, CFSTR("RDN"), rdnSetContent); - } - - return properties; -} - -/* - From rfc3739 - 3.1.2. Subject - - When parsing the subject here are some tips for a short name of the cert. - Choice I: commonName - Choice II: givenName - Choice III: pseudonym - - The commonName attribute value SHALL, when present, contain a name - of the subject. This MAY be in the subject's preferred - presentation format, or a format preferred by the CA, or some - other format. Pseudonyms, nicknames, and names with spelling - other than defined by the registered name MAY be used. To - understand the nature of the name presented in commonName, - complying applications MAY have to examine present values of the - givenName and surname attributes, or the pseudonym attribute. - -*/ -static CFArrayRef createPropertiesForX501NameContent(CFAllocatorRef allocator, - const DERItem *x501NameContent) { - CFMutableArrayRef properties = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - OSStatus status = parseX501NameContent(x501NameContent, properties, - appendRDNProperty); - if (status) { - CFArrayRemoveAllValues(properties); - appendInvalidProperty(properties, CFSTR("X.501 Name"), x501NameContent); - } - - return properties; -} - -static CFArrayRef createPropertiesForX501Name(CFAllocatorRef allocator, - const DERItem *x501Name) { - CFMutableArrayRef properties = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - OSStatus status = parseX501Name(x501Name, properties, appendRDNProperty); - if (status) { - CFArrayRemoveAllValues(properties); - appendInvalidProperty(properties, CFSTR("X.501 Name"), x501Name); - } - - return properties; -} - -static void appendIntegerProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *integer) { - CFStringRef string = copyIntegerContentDescription( - CFGetAllocator(properties), integer); - appendPropertyP(properties, kSecPropertyTypeString, label, string); - CFRelease(string); -} - -static void appendBoolProperty(CFMutableArrayRef properties, - CFStringRef label, bool boolean) { - appendPropertyP(properties, kSecPropertyTypeString, - label, boolean ? CFSTR("Yes") : CFSTR("No")); -} - -static void appendBooleanProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *boolean, bool defaultValue) { - bool result; - DERReturn drtn = DERParseBoolean(boolean, defaultValue, &result); - if (drtn) { - /* Couldn't parse boolean; dump the raw unparsed data as hex. */ - appendInvalidProperty(properties, label, boolean); - } else { - appendBoolProperty(properties, label, result); - } -} - -static void appendBitStringContentNames(CFMutableArrayRef properties, - CFStringRef label, const DERItem *bitStringContent, - const CFStringRef *names, CFIndex namesCount) { - DERSize len = bitStringContent->length - 1; - require_quiet(len == 1 || len == 2, badDER); - DERByte numUnusedBits = bitStringContent->data[0]; - require_quiet(numUnusedBits < 8, badDER); - uint_fast16_t bits = 8 * len - numUnusedBits; - require_quiet(bits <= (uint_fast16_t)namesCount, badDER); - uint_fast16_t value = bitStringContent->data[1]; - uint_fast16_t mask; - if (len > 1) { - value = (value << 8) + bitStringContent->data[2]; - mask = 0x8000; - } else { - mask = 0x80; - } - uint_fast16_t ix; - bool didOne = false; - CFMutableStringRef string = - CFStringCreateMutable(CFGetAllocator(properties), 0); - for (ix = 0; ix < bits; ++ix) { - if (value & mask) { - if (didOne) { - CFStringAppend(string, CFSTR(", ")); - } else { - didOne = true; - } - CFStringAppend(string, names[ix]); - } - mask >>= 1; - } - appendPropertyP(properties, kSecPropertyTypeString, label, string); - CFRelease(string); - return; -badDER: - appendInvalidProperty(properties, label, bitStringContent); -} - -static void appendBitStringNames(CFMutableArrayRef properties, - CFStringRef label, const DERItem *bitString, - const CFStringRef *names, CFIndex namesCount) { - DERDecodedInfo bitStringContent; - DERReturn drtn = DERDecodeItem(bitString, &bitStringContent); - require_noerr_quiet(drtn, badDER); - require_quiet(bitStringContent.tag == ASN1_BIT_STRING, badDER); - appendBitStringContentNames(properties, label, &bitStringContent.content, - names, namesCount); - return; -badDER: - appendInvalidProperty(properties, label, bitString); -} - -#if 0 -typedef uint16_t SecKeyUsage; - -#define kSecKeyUsageDigitalSignature 0x8000 -#define kSecKeyUsageNonRepudiation 0x4000 -#define kSecKeyUsageKeyEncipherment 0x2000 -#define kSecKeyUsageDataEncipherment 0x1000 -#define kSecKeyUsageKeyAgreement 0x0800 -#define kSecKeyUsageKeyCertSign 0x0400 -#define kSecKeyUsageCRLSign 0x0200 -#define kSecKeyUsageEncipherOnly 0x0100 -#define kSecKeyUsageDecipherOnly 0x0080 - -/* - KeyUsage ::= BIT STRING { - digitalSignature (0), - nonRepudiation (1), - keyEncipherment (2), - dataEncipherment (3), - keyAgreement (4), - keyCertSign (5), - cRLSign (6), - encipherOnly (7), - decipherOnly (8) } - */ -static void appendKeyUsage(CFMutableArrayRef properties, - const DERItem *extnValue) { - if ((extnValue->length != 4 && extnValue->length != 5) || - extnValue->data[0] != ASN1_BIT_STRING || - extnValue->data[1] < 2 || extnValue->data[1] > 3 || - extnValue->data[2] > 7) { - appendInvalidProperty(properties, CFSTR("KeyUsage Extension"), - extnValue); - } else { - CFMutableStringRef string = - CFStringCreateMutable(CFGetAllocator(properties), 0); - SecKeyUsage usage = (extnValue->data[3] << 8); - if (extnValue->length == 5) - usage += extnValue->data[4]; - secdebug("keyusage", "keyusage: %04X", usage); - static const CFStringRef usageNames[] = { - CFSTR("Digital Signature"), - CFSTR("Non-Repudiation"), - CFSTR("Key Encipherment"), - CFSTR("Data Encipherment"), - CFSTR("Key Agreement"), - CFSTR("Cert Sign"), - CFSTR("CRL Sign"), - CFSTR("Encipher"), - CFSTR("Decipher"), - }; - bool didOne = false; - SecKeyUsage mask = kSecKeyUsageDigitalSignature; - CFIndex ix, bits = (extnValue->data[1] - 1) * 8 - extnValue->data[2]; - for (ix = 0; ix < bits; ++ix) { - if (usage & mask) { - if (didOne) { - CFStringAppend(string, CFSTR(", ")); - } else { - didOne = true; - } - /* @@@ Localize usageNames[ix]. */ - CFStringAppend(string, usageNames[ix]); - } - mask >>= 1; - } - appendPropertyP(properties, kSecPropertyTypeString, CFSTR("Usage"), - string); - CFRelease(string); - } -} -#else -static void appendKeyUsage(CFMutableArrayRef properties, - const DERItem *extnValue) { - static const CFStringRef usageNames[] = { - CFSTR("Digital Signature"), - CFSTR("Non-Repudiation"), - CFSTR("Key Encipherment"), - CFSTR("Data Encipherment"), - CFSTR("Key Agreement"), - CFSTR("Cert Sign"), - CFSTR("CRL Sign"), - CFSTR("Encipher Only"), - CFSTR("Decipher Only") - }; - appendBitStringNames(properties, CFSTR("Usage"), extnValue, - usageNames, sizeof(usageNames) / sizeof(*usageNames)); -} -#endif - -static void appendPrivateKeyUsagePeriod(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERPrivateKeyUsagePeriod pkup; - DERReturn drtn = DERParseSequence(extnValue, - DERNumPrivateKeyUsagePeriodItemSpecs, DERPrivateKeyUsagePeriodItemSpecs, - &pkup, sizeof(pkup)); - require_noerr_quiet(drtn, badDER); - if (pkup.notBefore.length) { - appendDateContentProperty(properties, CFSTR("Not Valid Before"), - ASN1_GENERALIZED_TIME, &pkup.notBefore); - } - if (pkup.notAfter.length) { - appendDateContentProperty(properties, CFSTR("Not Valid After"), - ASN1_GENERALIZED_TIME, &pkup.notAfter); - } - return; -badDER: - appendInvalidProperty(properties, CFSTR("Private Key Usage Period"), - extnValue); -} - -static void appendStringContentProperty(CFMutableArrayRef properties, - CFStringRef label, const DERItem *stringContent, - CFStringEncoding encoding) { - CFStringRef string = CFStringCreateWithBytes(CFGetAllocator(properties), - stringContent->data, stringContent->length, encoding, FALSE); - if (string) { - appendPropertyP(properties, kSecPropertyTypeString, label, string); - CFRelease(string); - } else { - appendInvalidProperty(properties, label, stringContent); - } -} - -/* - OtherName ::= SEQUENCE { - type-id OBJECT IDENTIFIER, - value [0] EXPLICIT ANY DEFINED BY type-id } -*/ -static void appendOtherNameContentProperty(CFMutableArrayRef properties, - const DERItem *otherNameContent) { - DEROtherName on; - DERReturn drtn = DERParseSequenceContent(otherNameContent, - DERNumOtherNameItemSpecs, DEROtherNameItemSpecs, - &on, sizeof(on)); - require_noerr_quiet(drtn, badDER); - CFAllocatorRef allocator = CFGetAllocator(properties); - CFStringRef oid_string = copyLocalizedOidDescription(allocator, - &on.typeIdentifier); - CFStringRef value_string = copyDERThingDescription(allocator, &on.value, false); - if (value_string) - appendPropertyP(properties, kSecPropertyTypeString, oid_string, - value_string); - else - appendUnparsedProperty(properties, oid_string, &on.value); - - return; -badDER: - appendInvalidProperty(properties, CFSTR("Other Name"), otherNameContent); -} - -/* - GeneralName ::= CHOICE { - otherName [0] OtherName, - rfc822Name [1] IA5String, - dNSName [2] IA5String, - x400Address [3] ORAddress, - directoryName [4] Name, - ediPartyName [5] EDIPartyName, - uniformResourceIdentifier [6] IA5String, - iPAddress [7] OCTET STRING, - registeredID [8] OBJECT IDENTIFIER} - - EDIPartyName ::= SEQUENCE { - nameAssigner [0] DirectoryString OPTIONAL, - partyName [1] DirectoryString } - */ -static bool appendGeneralNameContentProperty(CFMutableArrayRef properties, - DERTag tag, const DERItem *generalName) { - switch (tag) { - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0: - appendOtherNameContentProperty(properties, generalName); - break; - case ASN1_CONTEXT_SPECIFIC | 1: - /* IA5String. */ - appendStringContentProperty(properties, CFSTR("Email Address"), - generalName, kCFStringEncodingASCII); - break; - case ASN1_CONTEXT_SPECIFIC | 2: - /* IA5String. */ - appendStringContentProperty(properties, CFSTR("DNS Name"), generalName, - kCFStringEncodingASCII); - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 3: - appendUnparsedProperty(properties, CFSTR("X.400 Address"), - generalName); - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 4: - { - CFArrayRef directory_plist = - createPropertiesForX501Name(CFGetAllocator(properties), - generalName); - appendPropertyP(properties, kSecPropertyTypeSection, - CFSTR("Directory Name"), directory_plist); - CFRelease(directory_plist); - break; - } - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 5: - appendUnparsedProperty(properties, CFSTR("EDI Party Name"), - generalName); - break; - case ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 6: - /* Technically I don't think this is valid, but there are certs out - in the wild that use a constructed IA5String. In particular the - VeriSign Time Stamping Authority CA.cer does this. */ - appendURLProperty(properties, CFSTR("URI"), generalName); - break; - case ASN1_CONTEXT_SPECIFIC | 6: - appendURLContentProperty(properties, CFSTR("URI"), generalName); - break; - case ASN1_CONTEXT_SPECIFIC | 7: - appendIPAddressContentProperty(properties, CFSTR("IP Address"), - generalName); - break; - case ASN1_CONTEXT_SPECIFIC | 8: - appendOIDProperty(properties, CFSTR("Registered ID"), generalName); - break; - default: - goto badDER; - break; - } - return true; -badDER: - return false; -} - -static void appendGeneralNameProperty(CFMutableArrayRef properties, - const DERItem *generalName) { - DERDecodedInfo generalNameContent; - DERReturn drtn = DERDecodeItem(generalName, &generalNameContent); - require_noerr_quiet(drtn, badDER); - if (appendGeneralNameContentProperty(properties, generalNameContent.tag, - &generalNameContent.content)) - return; -badDER: - appendInvalidProperty(properties, CFSTR("General Name"), generalName); -} - - -/* - GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName - */ -static void appendGeneralNamesContent(CFMutableArrayRef properties, - const DERItem *generalNamesContent) { - DERSequence gnSeq; - DERReturn drtn = DERDecodeSeqContentInit(generalNamesContent, &gnSeq); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo generalNameContent; - while ((drtn = DERDecodeSeqNext(&gnSeq, &generalNameContent)) == - DR_Success) { - if (!appendGeneralNameContentProperty(properties, - generalNameContent.tag, &generalNameContent.content)) { - goto badDER; - } - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return; -badDER: - appendInvalidProperty(properties, CFSTR("General Names"), - generalNamesContent); -} - -static void appendGeneralNames(CFMutableArrayRef properties, - const DERItem *generalNames) { - DERDecodedInfo generalNamesContent; - DERReturn drtn = DERDecodeItem(generalNames, &generalNamesContent); - require_noerr_quiet(drtn, badDER); - require_quiet(generalNamesContent.tag == ASN1_CONSTR_SEQUENCE, - badDER); - appendGeneralNamesContent(properties, &generalNamesContent.content); - return; -badDER: - appendInvalidProperty(properties, CFSTR("General Names"), generalNames); -} - -/* -BasicConstraints ::= SEQUENCE { - cA BOOLEAN DEFAULT FALSE, - pathLenConstraint INTEGER (0..MAX) OPTIONAL } -*/ -static void appendBasicConstraints(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERBasicConstraints basicConstraints; - DERReturn drtn = DERParseSequence(extnValue, - DERNumBasicConstraintsItemSpecs, DERBasicConstraintsItemSpecs, - &basicConstraints, sizeof(basicConstraints)); - require_noerr_quiet(drtn, badDER); - - appendBooleanProperty(properties, CFSTR("Certificate Authority"), - &basicConstraints.cA, false); - - if (basicConstraints.pathLenConstraint.length != 0) { - appendIntegerProperty(properties, CFSTR("Path Length Constraint"), - &basicConstraints.pathLenConstraint); - } - return; -badDER: - appendInvalidProperty(properties, CFSTR("Basic Constraints"), extnValue); -} - -/* - CRLDistPointsSyntax ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint - - DistributionPoint ::= SEQUENCE { - distributionPoint [0] DistributionPointName OPTIONAL, - reasons [1] ReasonFlags OPTIONAL, - cRLIssuer [2] GeneralNames OPTIONAL } - - DistributionPointName ::= CHOICE { - fullName [0] GeneralNames, - nameRelativeToCRLIssuer [1] RelativeDistinguishedName } - - ReasonFlags ::= BIT STRING { - unused (0), - keyCompromise (1), - cACompromise (2), - affiliationChanged (3), - superseded (4), - cessationOfOperation (5), - certificateHold (6), - privilegeWithdrawn (7), - aACompromise (8) } -*/ -static void appendCrlDistributionPoints(CFMutableArrayRef properties, - const DERItem *extnValue) { - CFAllocatorRef allocator = CFGetAllocator(properties); - DERTag tag; - DERSequence dpSeq; - DERReturn drtn = DERDecodeSeqInit(extnValue, &tag, &dpSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo dpSeqContent; - while ((drtn = DERDecodeSeqNext(&dpSeq, &dpSeqContent)) == DR_Success) { - require_quiet(dpSeqContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDistributionPoint dp; - drtn = DERParseSequenceContent(&dpSeqContent.content, - DERNumDistributionPointItemSpecs, - DERDistributionPointItemSpecs, - &dp, sizeof(dp)); - require_noerr_quiet(drtn, badDER); - if (dp.distributionPoint.length) { - DERDecodedInfo distributionPointName; - drtn = DERDecodeItem(&dp.distributionPoint, &distributionPointName); - require_noerr_quiet(drtn, badDER); - if (distributionPointName.tag == - (ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0)) { - /* Full Name */ - appendGeneralNamesContent(properties, - &distributionPointName.content); - } else if (distributionPointName.tag == - (ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 1)) { - CFArrayRef rdn_props = createPropertiesForRDNContent(allocator, - &dp.reasons); - appendPropertyP(properties, kSecPropertyTypeSection, - CFSTR("Name Relative To CRL Issuer"), rdn_props); - CFRelease(rdn_props); - } else { - goto badDER; - } - } - if (dp.reasons.length) { - static const CFStringRef reasonNames[] = { - CFSTR("Unused"), - CFSTR("Key Compromise"), - CFSTR("CA Compromise"), - CFSTR("Affiliation Changed"), - CFSTR("Superseded"), - CFSTR("Cessation Of Operation"), - CFSTR("Certificate Hold"), - CFSTR("Priviledge Withdrawn"), - CFSTR("AA Compromise") - }; - appendBitStringContentNames(properties, CFSTR("Reasons"), - &dp.reasons, - reasonNames, sizeof(reasonNames) / sizeof(*reasonNames)); - } - if (dp.cRLIssuer.length) { - CFMutableArrayRef crlIssuer = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - appendPropertyP(properties, kSecPropertyTypeSection, - CFSTR("CRL Issuer"), crlIssuer); - CFRelease(crlIssuer); - appendGeneralNames(crlIssuer, &dp.cRLIssuer); - } - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return; -badDER: - appendInvalidProperty(properties, CFSTR("Crl Distribution Points"), - extnValue); -} - -/* Decode a sequence of integers into a comma separated list of ints. */ -static void appendIntegerSequenceContent(CFMutableArrayRef properties, - CFStringRef label, const DERItem *intSequenceContent) { - CFAllocatorRef allocator = CFGetAllocator(properties); - DERSequence intSeq; - DERReturn drtn = DERDecodeSeqContentInit(intSequenceContent, &intSeq); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo intContent; - CFMutableStringRef value = NULL; - while ((drtn = DERDecodeSeqNext(&intSeq, &intContent)) - == DR_Success) { - require_quiet(intContent.tag == ASN1_INTEGER, badDER); - CFStringRef intDesc = copyIntegerContentDescription( - allocator, &intContent.content); - if (value) { - CFStringAppendFormat(value, NULL, CFSTR(", %@"), intDesc); - } else { - value = CFStringCreateMutableCopy(allocator, 0, intDesc); - } - CFRelease(intDesc); - } - require_quiet(drtn == DR_EndOfSequence, badDER); - if (value) { - appendPropertyP(properties, kSecPropertyTypeString, - CFSTR("Notice Numbers"), value); - CFRelease(value); - return; - } - /* DROPTHOUGH if !value. */ -badDER: - appendInvalidProperty(properties, label, intSequenceContent); -} - -static void appendCertificatePolicies(CFMutableArrayRef properties, - const DERItem *extnValue) { - CFAllocatorRef allocator = CFGetAllocator(properties); - DERTag tag; - DERSequence piSeq; - DERReturn drtn = DERDecodeSeqInit(extnValue, &tag, &piSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo piContent; - int pin = 1; - while ((drtn = DERDecodeSeqNext(&piSeq, &piContent)) == DR_Success) { - require_quiet(piContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERPolicyInformation pi; - drtn = DERParseSequenceContent(&piContent.content, - DERNumPolicyInformationItemSpecs, - DERPolicyInformationItemSpecs, - &pi, sizeof(pi)); - require_noerr_quiet(drtn, badDER); - CFStringRef piLabel = CFStringCreateWithFormat(allocator, NULL, - CFSTR("Policy Identifier #%d"), pin++); - appendOIDProperty(properties, piLabel, &pi.policyIdentifier); - CFRelease(piLabel); - if (pi.policyQualifiers.length == 0) - continue; - - DERSequence pqSeq; - drtn = DERDecodeSeqContentInit(&pi.policyQualifiers, &pqSeq); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo pqContent; - int pqn = 1; - while ((drtn = DERDecodeSeqNext(&pqSeq, &pqContent)) == DR_Success) { - DERPolicyQualifierInfo pqi; - drtn = DERParseSequenceContent(&pqContent.content, - DERNumPolicyQualifierInfoItemSpecs, - DERPolicyQualifierInfoItemSpecs, - &pqi, sizeof(pqi)); - require_noerr_quiet(drtn, badDER); - DERDecodedInfo qualifierContent; - drtn = DERDecodeItem(&pqi.qualifier, &qualifierContent); - require_noerr_quiet(drtn, badDER); - CFStringRef pqLabel = CFStringCreateWithFormat(allocator, NULL, - CFSTR("Policy Qualifier #%d"), pqn++); - appendOIDProperty(properties, pqLabel, &pqi.policyQualifierID); - CFRelease(pqLabel); - if (DEROidCompare(&oidQtCps, &pqi.policyQualifierID)) { - require_quiet(qualifierContent.tag == ASN1_IA5_STRING, badDER); - appendURLContentProperty(properties, - CFSTR("CPS URI"), - &qualifierContent.content); - } else if (DEROidCompare(&oidQtUNotice, &pqi.policyQualifierID)) { - require_quiet(qualifierContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERUserNotice un; - drtn = DERParseSequenceContent(&qualifierContent.content, - DERNumUserNoticeItemSpecs, - DERUserNoticeItemSpecs, - &un, sizeof(un)); - require_noerr_quiet(drtn, badDER); - if (un.noticeRef.length) { - DERNoticeReference nr; - drtn = DERParseSequenceContent(&un.noticeRef, - DERNumNoticeReferenceItemSpecs, - DERNoticeReferenceItemSpecs, - &nr, sizeof(nr)); - require_noerr_quiet(drtn, badDER); - appendDERThingProperty(properties, - CFSTR("Organization"), - &nr.organization); - appendIntegerSequenceContent(properties, - CFSTR("Notice Numbers"), &nr.noticeNumbers); - } - if (un.explicitText.length) { - appendDERThingProperty(properties, CFSTR("Explicit Text"), - &un.explicitText); - } - } else { - appendUnparsedProperty(properties, CFSTR("Qualifier"), - &pqi.qualifier); - } - } - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return; -badDER: - appendInvalidProperty(properties, CFSTR("Certificate Policies"), - extnValue); -} - -static void appendSubjectKeyIdentifier(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERReturn drtn; - DERDecodedInfo keyIdentifier; - drtn = DERDecodeItem(extnValue, &keyIdentifier); - require_noerr_quiet(drtn, badDER); - require_quiet(keyIdentifier.tag == ASN1_OCTET_STRING, badDER); - appendDataProperty(properties, CFSTR("Key Identifier"), - &keyIdentifier.content); - - return; -badDER: - appendInvalidProperty(properties, CFSTR("Invalid Subject Key Identifier"), - extnValue); -} - -/* -AuthorityKeyIdentifier ::= SEQUENCE { - keyIdentifier [0] KeyIdentifier OPTIONAL, - authorityCertIssuer [1] GeneralNames OPTIONAL, - authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL } - -- authorityCertIssuer and authorityCertSerialNumber MUST both - -- be present or both be absent - -KeyIdentifier ::= OCTET STRING -*/ -static void appendAuthorityKeyIdentifier(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERAuthorityKeyIdentifier akid; - DERReturn drtn; - drtn = DERParseSequence(extnValue, - DERNumAuthorityKeyIdentifierItemSpecs, - DERAuthorityKeyIdentifierItemSpecs, - &akid, sizeof(akid)); - require_noerr_quiet(drtn, badDER); - if (akid.keyIdentifier.length) { - appendDataProperty(properties, CFSTR("Key Identifier"), - &akid.keyIdentifier); - } - if (akid.authorityCertIssuer.length || - akid.authorityCertSerialNumber.length) { - require_quiet(akid.authorityCertIssuer.length && - akid.authorityCertSerialNumber.length, badDER); - /* Perhaps put in a subsection called Authority Certificate Issuer. */ - appendGeneralNamesContent(properties, - &akid.authorityCertIssuer); - appendIntegerProperty(properties, - CFSTR("Authority Certificate Serial Number"), - &akid.authorityCertSerialNumber); - } - - return; -badDER: - appendInvalidProperty(properties, CFSTR("Authority Key Identifier"), - extnValue); -} - -/* - PolicyConstraints ::= SEQUENCE { - requireExplicitPolicy [0] SkipCerts OPTIONAL, - inhibitPolicyMapping [1] SkipCerts OPTIONAL } - - SkipCerts ::= INTEGER (0..MAX) -*/ -static void appendPolicyConstraints(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERPolicyConstraints pc; - DERReturn drtn; - drtn = DERParseSequence(extnValue, - DERNumPolicyConstraintsItemSpecs, - DERPolicyConstraintsItemSpecs, - &pc, sizeof(pc)); - require_noerr_quiet(drtn, badDER); - if (pc.requireExplicitPolicy.length) { - appendIntegerProperty(properties, - CFSTR("Require Explicit Policy"), &pc.requireExplicitPolicy); - } - if (pc.inhibitPolicyMapping.length) { - appendIntegerProperty(properties, - CFSTR("Inhibit Policy Mapping"), &pc.inhibitPolicyMapping); - } - - return; - -badDER: - appendInvalidProperty(properties, CFSTR("Policy Constraints"), extnValue); -} - -/* -extendedKeyUsage EXTENSION ::= { - SYNTAX SEQUENCE SIZE (1..MAX) OF KeyPurposeId - IDENTIFIED BY id-ce-extKeyUsage } - -KeyPurposeId ::= OBJECT IDENTIFIER -*/ -static void appendExtendedKeyUsage(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERTag tag; - DERSequence derSeq; - DERReturn drtn = DERDecodeSeqInit(extnValue, &tag, &derSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo currDecoded; - while ((drtn = DERDecodeSeqNext(&derSeq, &currDecoded)) == DR_Success) { - require_quiet(currDecoded.tag == ASN1_OBJECT_ID, badDER); - appendOIDProperty(properties, CFSTR("Purpose"), - &currDecoded.content); - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return; -badDER: - appendInvalidProperty(properties, CFSTR("Extended Key Usage"), extnValue); -} - -/* - id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 } - - AuthorityInfoAccessSyntax ::= - SEQUENCE SIZE (1..MAX) OF AccessDescription - - AccessDescription ::= SEQUENCE { - accessMethod OBJECT IDENTIFIER, - accessLocation GeneralName } - - id-ad OBJECT IDENTIFIER ::= { id-pkix 48 } - - id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 } - - id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 } -*/ -static void appendInfoAccess(CFMutableArrayRef properties, - const DERItem *extnValue) { - DERTag tag; - DERSequence adSeq; - DERReturn drtn = DERDecodeSeqInit(extnValue, &tag, &adSeq); - require_noerr_quiet(drtn, badDER); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badDER); - DERDecodedInfo adContent; - while ((drtn = DERDecodeSeqNext(&adSeq, &adContent)) == DR_Success) { - require_quiet(adContent.tag == ASN1_CONSTR_SEQUENCE, badDER); - DERAccessDescription ad; - drtn = DERParseSequenceContent(&adContent.content, - DERNumAccessDescriptionItemSpecs, - DERAccessDescriptionItemSpecs, - &ad, sizeof(ad)); - require_noerr_quiet(drtn, badDER); - appendOIDProperty(properties, CFSTR("Access Method"), - &ad.accessMethod); - //CFSTR("Access Location"); - appendGeneralNameProperty(properties, &ad.accessLocation); - } - require_quiet(drtn == DR_EndOfSequence, badDER); - return; -badDER: - appendInvalidProperty(properties, CFSTR("Authority Information Access"), - extnValue); -} - -static void appendNetscapeCertType(CFMutableArrayRef properties, - const DERItem *extnValue) { - static const CFStringRef certTypes[] = { - CFSTR("SSL client"), - CFSTR("SSL server"), - CFSTR("S/MIME"), - CFSTR("Object Signing"), - CFSTR("Reserved"), - CFSTR("SSL CA"), - CFSTR("S/MIME CA"), - CFSTR("Object Signing CA") - }; - appendBitStringNames(properties, CFSTR("Usage"), extnValue, - certTypes, sizeof(certTypes) / sizeof(*certTypes)); -} - -#if 0 -static void appendEntrustVersInfo(CFMutableArrayRef properties, - const DERItem *extnValue) { -} - -/* - * The list of Qualified Cert Statement statementIds we understand, even though - * we don't actually do anything with them; if these are found in a Qualified - * Cert Statement that's critical, we can truthfully say "yes we understand this". - */ -static const CSSM_OID_PTR knownQualifiedCertStatements[] = -{ - /* id-qcs := { id-pkix 11 } */ - (const CSSM_OID_PTR)&CSSMOID_OID_QCS_SYNTAX_V1, /* id-qcs 1 */ - (const CSSM_OID_PTR)&CSSMOID_OID_QCS_SYNTAX_V2, /* id-qcs 2 */ - (const CSSM_OID_PTR)&CSSMOID_ETSI_QCS_QC_COMPLIANCE, - (const CSSM_OID_PTR)&CSSMOID_ETSI_QCS_QC_LIMIT_VALUE, - (const CSSM_OID_PTR)&CSSMOID_ETSI_QCS_QC_RETENTION, - (const CSSM_OID_PTR)&CSSMOID_ETSI_QCS_QC_SSCD -}; -#define NUM_KNOWN_QUAL_CERT_STATEMENTS (sizeof(knownQualifiedCertStatements) / sizeof(CSSM_OID_PTR)) -*/ -static void appendQCCertStatements(CFMutableArrayRef properties, - const DERItem *extnValue) { -} - -#endif - -static bool appendPrintableDERSequenceP(CFMutableArrayRef properties, - CFStringRef label, const DERItem *sequence) { - DERTag tag; - DERSequence derSeq; - DERReturn drtn = DERDecodeSeqInit(sequence, &tag, &derSeq); - require_noerr_quiet(drtn, badSequence); - require_quiet(tag == ASN1_CONSTR_SEQUENCE, badSequence); - DERDecodedInfo currDecoded; - bool appendedSomething = false; - while ((drtn = DERDecodeSeqNext(&derSeq, &currDecoded)) == DR_Success) { - switch (currDecoded.tag) - { - case 0: // 0 - case ASN1_SEQUENCE: // 16 - case ASN1_SET: // 17 - // skip constructed object lengths - break; - - case ASN1_UTF8_STRING: // 12 - case ASN1_NUMERIC_STRING: // 18 - case ASN1_PRINTABLE_STRING: // 19 - case ASN1_T61_STRING: // 20, also ASN1_TELETEX_STRING - case ASN1_VIDEOTEX_STRING: // 21 - case ASN1_IA5_STRING: // 22 - case ASN1_GRAPHIC_STRING: // 25 - case ASN1_VISIBLE_STRING: // 26, also ASN1_ISO646_STRING - case ASN1_GENERAL_STRING: // 27 - case ASN1_UNIVERSAL_STRING: // 28 - { - CFStringRef string = - copyDERThingContentDescription(CFGetAllocator(properties), - currDecoded.tag, &currDecoded.content, false); - //CFStringRef cleanString = copyStringRemovingPercentEscapes(string); - - appendPropertyP(properties, kSecPropertyTypeString, label, - string); - CFRelease(string); - appendedSomething = true; - break; - } - default: - break; - } - } - require_quiet(drtn == DR_EndOfSequence, badSequence); - return appendedSomething; -badSequence: - return false; -} - -static void appendExtension(CFMutableArrayRef parent, - const SecCertificateExtension *extn) { - CFAllocatorRef allocator = CFGetAllocator(parent); - CFMutableArrayRef properties = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - const DERItem - *extnID = &extn->extnID, - *extnValue = &extn->extnValue; - - appendBoolProperty(properties, CFSTR("Critical"), extn->critical); - -#if 1 - bool handled = true; - /* Extensions that we know how to handle ourselves... */ - if (extnID->length == oidSubjectKeyIdentifier.length && - !memcmp(extnID->data, oidSubjectKeyIdentifier.data, extnID->length - 1)) - { - switch (extnID->data[extnID->length - 1]) { - case 14: /* SubjectKeyIdentifier id-ce 14 */ - appendSubjectKeyIdentifier(properties, extnValue); - break; - case 15: /* KeyUsage id-ce 15 */ - appendKeyUsage(properties, extnValue); - break; - case 16: /* PrivateKeyUsagePeriod id-ce 16 */ - appendPrivateKeyUsagePeriod(properties, extnValue); - break; - case 17: /* SubjectAltName id-ce 17 */ - case 18: /* IssuerAltName id-ce 18 */ - appendGeneralNames(properties, extnValue); - break; - case 19: /* BasicConstraints id-ce 19 */ - appendBasicConstraints(properties, extnValue); - break; - case 30: /* NameConstraints id-ce 30 */ - handled = false; - break; - case 31: /* CRLDistributionPoints id-ce 31 */ - appendCrlDistributionPoints(properties, extnValue); - break; - case 32: /* CertificatePolicies id-ce 32 */ - appendCertificatePolicies(properties, extnValue); - break; - case 33: /* PolicyMappings id-ce 33 */ - handled = false; - break; - case 35: /* AuthorityKeyIdentifier id-ce 35 */ - appendAuthorityKeyIdentifier(properties, extnValue); - break; - case 36: /* PolicyConstraints id-ce 36 */ - appendPolicyConstraints(properties, extnValue); - break; - case 37: /* ExtKeyUsage id-ce 37 */ - appendExtendedKeyUsage(properties, extnValue); - break; - case 46: /* FreshestCRL id-ce 46 */ - handled = false; - break; - case 54: /* InhibitAnyPolicy id-ce 54 */ - handled = false; - break; - default: - handled = false; - break; - } - } else if (extnID->length == oidAuthorityInfoAccess.length && - !memcmp(extnID->data, oidAuthorityInfoAccess.data, extnID->length - 1)) - { - switch (extnID->data[extnID->length - 1]) { - case 1: /* AuthorityInfoAccess id-pe 1 */ - appendInfoAccess(properties, extnValue); - break; - case 3: /* QCStatements id-pe 3 */ - handled = false; - break; - case 11: /* SubjectInfoAccess id-pe 11 */ - appendInfoAccess(properties, extnValue); - break; - default: - handled = false; - break; - } - } else if (DEROidCompare(extnID, &oidNetscapeCertType)) { - /* 2.16.840.1.113730.1.1 netscape 1 1 */ - appendNetscapeCertType(properties, extnValue); - } else { - handled = false; - } - - if (!handled) { - /* Try to parse and display printable string(s). */ - if (appendPrintableDERSequenceP(properties, CFSTR("Data"), extnValue)) { - /* Nothing to do here appendPrintableDERSequenceP did the work. */ - } else { - /* Couldn't parse extension; dump the raw unparsed data as hex. */ - appendUnparsedProperty(properties, CFSTR("Data"), extnValue); - } - } -#else - /* Extensions that we know how to handle ourselves... */ - if (DEROidCompare(extnID, &oidSubjectKeyIdentifier)) { - appendSubjectKeyIdentifier(properties, extnValue); - } else if (DEROidCompare(extnID, &oidKeyUsage)) { - appendKeyUsage(properties, extnValue); - } else if (DEROidCompare(extnID, &oidPrivateKeyUsagePeriod)) { - appendPrivateKeyUsagePeriod(properties, extnValue); - } else if (DEROidCompare(extnID, &oidSubjectAltName)) { - appendGeneralNames(properties, extnValue); - } else if (DEROidCompare(extnID, &oidIssuerAltName)) { - appendGeneralNames(properties, extnValue); - } else if (DEROidCompare(extnID, &oidBasicConstraints)) { - appendBasicConstraints(properties, extnValue); - } else if (DEROidCompare(extnID, &oidCrlDistributionPoints)) { - appendCrlDistributionPoints(properties, extnValue); - } else if (DEROidCompare(extnID, &oidCertificatePolicies)) { - appendCertificatePolicies(properties, extnValue); - } else if (DEROidCompare(extnID, &oidAuthorityKeyIdentifier)) { - appendAuthorityKeyIdentifier(properties, extnValue); - } else if (DEROidCompare(extnID, &oidPolicyConstraints)) { - appendPolicyConstraints(properties, extnValue); - } else if (DEROidCompare(extnID, &oidExtendedKeyUsage)) { - appendExtendedKeyUsage(properties, extnValue); - } else if (DEROidCompare(extnID, &oidAuthorityInfoAccess)) { - appendInfoAccess(properties, extnValue); - } else if (DEROidCompare(extnID, &oidSubjectInfoAccess)) { - appendInfoAccess(properties, extnValue); - } else if (DEROidCompare(extnID, &oidNetscapeCertType)) { - appendNetscapeCertType(properties, extnValue); -#if 0 - } else if (DEROidCompare(extnID, &oidEntrustVersInfo)) { - appendEntrustVersInfo(properties, extnValue); -#endif - } else - /* Try to parse and display printable string(s). */ - if (appendPrintableDERSequenceP(properties, CFSTR("Data"), extnValue)) { - /* Nothing to do here appendPrintableDERSequenceP did the work. */ - } else { - /* Couldn't parse extension; dump the raw unparsed data as hex. */ - appendUnparsedProperty(properties, CFSTR("Data"), extnValue); - } -#endif - CFStringRef oid_string = copyLocalizedOidDescription(allocator, extnID); - appendPropertyP(parent, kSecPropertyTypeSection, oid_string, properties); - CFRelease(oid_string); - CFRelease(properties); -} - -/* Different types of summary types from least desired to most desired. */ -enum SummaryType { - kSummaryTypeNone, - kSummaryTypePrintable, - kSummaryTypeOrganizationName, - kSummaryTypeOrganizationalUnitName, - kSummaryTypeCommonName, -}; - -struct Summary { - enum SummaryType type; - CFStringRef summary; - CFStringRef description; -}; - -static OSStatus obtainSummaryFromX501Name(void *context, - const DERItem *type, const DERItem *value, CFIndex rdnIX) { - struct Summary *summary = (struct Summary *)context; - enum SummaryType stype = kSummaryTypeNone; - CFStringRef string = NULL; - if (DEROidCompare(type, &oidCommonName)) { - /* We skip Common Names that have generic values. */ - const char tfm[] = "Thawte Freemail Member"; - if ((value->length == sizeof(tfm) + 1) && - !memcmp(value->data + 2, tfm, sizeof(tfm) - 1)) { - return errSecSuccess; - } - stype = kSummaryTypeCommonName; - } else if (DEROidCompare(type, &oidOrganizationalUnitName)) { - stype = kSummaryTypeOrganizationalUnitName; - } else if (DEROidCompare(type, &oidOrganizationName)) { - stype = kSummaryTypeOrganizationName; - } else if (DEROidCompare(type, &oidDescription)) { - if (!summary->description) { - summary->description = string = copyDERThingDescription(kCFAllocatorDefault, value, true); - CFRetain(string); - } - stype = kSummaryTypePrintable; - } else { - stype = kSummaryTypePrintable; - } - - /* Use the first field we encounter of the highest priority type. */ - if (summary->type < stype) { - if (!string) { - string = copyDERThingDescription(kCFAllocatorDefault, value, true); - } - - if (string) { - CFReleaseSafe(summary->summary); - summary->summary = string; - summary->type = stype; - } - } else { - CFReleaseSafe(string); - } - - return errSecSuccess; -} - -CFStringRef SecCertificateCopySubjectSummaryP(SecCertificateRefP certificate) { - struct Summary summary = {}; - parseX501NameContent(&certificate->_subject, &summary, obtainSummaryFromX501Name); - /* If we found a description and a common name we change the summary to - CommonName (Description). */ - if (summary.description) { - if (summary.type == kSummaryTypeCommonName) { - CFStringRef newSummary = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR("%@ (%@)"), summary.summary, summary.description); - CFRelease(summary.summary); - summary.summary = newSummary; - } - CFRelease(summary.description); - } - - if (!summary.summary) { - /* If we didn't find a suitable printable string in the subject at all, we try - the first email address in the certificate instead. */ - CFArrayRef names = SecCertificateCopyRFC822NamesP(certificate); - if (!names) { - /* If we didn't find any email addresses in the certificate, we try finding - a DNS name instead. */ - names = SecCertificateCopyDNSNamesP(certificate); - } - if (names) { - summary.summary = CFArrayGetValueAtIndex(names, 0); - CFRetain(summary.summary); - CFRelease(names); - } - } - - return summary.summary; -} - -CFStringRef SecCertificateCopyIssuerSummaryP(SecCertificateRefP certificate) { - struct Summary summary = {}; - parseX501NameContent(&certificate->_issuer, &summary, obtainSummaryFromX501Name); - /* If we found a description and a common name we change the summary to - CommonName (Description). */ - if (summary.description) { - if (summary.type == kSummaryTypeCommonName) { - CFStringRef newSummary = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, - CFSTR("%@ (%@)"), summary.summary, summary.description); - CFRelease(summary.summary); - summary.summary = newSummary; - } - CFRelease(summary.description); - } - - return summary.summary; -} - -/* Return the earliest date on which all certificates in this chain are still - valid. */ -static CFAbsoluteTime SecCertificateGetChainsLastValidity( - SecCertificateRefP certificate) { - CFAbsoluteTime earliest = certificate->_notAfter; -#if 0 - while (certificate->_parent) { - certificate = certificate->_parent; - if (earliest > certificate->_notAfter) - earliest = certificate->_notAfter; - } -#endif - - return earliest; -} - -/* Return the latest date on which all certificates in this chain will be - valid. */ -static CFAbsoluteTime SecCertificateGetChainsFirstValidity( - SecCertificateRefP certificate) { - CFAbsoluteTime latest = certificate->_notBefore; -#if 0 - while (certificate->_parent) { - certificate = certificate->_parent; - if (latest < certificate->_notBefore) - latest = certificate->_notBefore; - } -#endif - - return latest; -} - -bool SecCertificateIsValidP(SecCertificateRefP certificate, - CFAbsoluteTime verifyTime) { - check(certificate); - return certificate->_notBefore <= verifyTime && - verifyTime <= certificate->_notAfter; -} - -CFIndex SecCertificateVersionP(SecCertificateRefP certificate) { - return certificate->_version + 1; -} - -CFAbsoluteTime SecCertificateNotValidBeforeP(SecCertificateRefP certificate) { - return certificate->_notBefore; -} - -CFAbsoluteTime SecCertificateNotValidAfterP(SecCertificateRefP certificate) { - return certificate->_notAfter; -} - -CFMutableArrayRef SecCertificateCopySummaryPropertiesP( - SecCertificateRefP certificate, CFAbsoluteTime verifyTime) { - CFAllocatorRef allocator = CFGetAllocator(certificate); - CFMutableArrayRef summary = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - - /* First we put the subject summary name. */ - CFStringRef ssummary = SecCertificateCopySubjectSummaryP(certificate); - if (ssummary) { - appendPropertyP(summary, kSecPropertyTypeTitle, - NULL, ssummary); - CFRelease(ssummary); - } -#if 0 - CFStringRef isummary = CFSTR("Issuer Summary"); - appendPropertyP(summary, kSecPropertyTypeString, - CFSTR("Issued By"), isummary); - CFRelease(isummary); -#endif - - /* Let see if this certificate is currently valid. */ - CFStringRef label; - CFAbsoluteTime when; - CFStringRef message; - CFStringRef ptype; - if (verifyTime > certificate->_notAfter) { - label = CFSTR("Expired"); - when = certificate->_notAfter; - ptype = kSecPropertyTypeError; - message = CFSTR("This certificate has expired"); - } else if (certificate->_notBefore > verifyTime) { - label = CFSTR("Valid from"); - when = certificate->_notBefore; - ptype = kSecPropertyTypeError; - message = CFSTR("This certificate is not yet valid"); - } else { - CFAbsoluteTime last = SecCertificateGetChainsLastValidity(certificate); - CFAbsoluteTime first = SecCertificateGetChainsFirstValidity(certificate); - if (verifyTime > last) { - label = CFSTR("Expired"); - when = last; - ptype = kSecPropertyTypeError; - message = CFSTR("This certificate has an issuer that has expired"); - } else if (verifyTime < first) { - label = CFSTR("Valid from"); - when = first; - ptype = kSecPropertyTypeError; - message = CFSTR("This certificate has an issuer that is not yet valid"); - } else { - label = CFSTR("Expires"); - when = certificate->_notAfter; - ptype = kSecPropertyTypeSuccess; - message = CFSTR("This certificate is valid"); - } - } - - appendDateProperty(summary, label, when); - appendPropertyP(summary, ptype, NULL, message); - - return summary; -} - -CFArrayRef SecCertificateCopyPropertiesP(SecCertificateRefP certificate) { - if (!certificate->_properties) { - CFAllocatorRef allocator = CFGetAllocator(certificate); - CFMutableArrayRef properties = CFArrayCreateMutable(allocator, 0, - &kCFTypeArrayCallBacks); - - /* First we put the Subject Name in the property list. */ - CFArrayRef subject_plist = createPropertiesForX501NameContent(allocator, - &certificate->_subject); - appendPropertyP(properties, kSecPropertyTypeSection, - CFSTR("Subject Name"), subject_plist); - CFRelease(subject_plist); - -#if 0 - /* Put Normalized subject in for testing. */ - if (certificate->_normalizedSubject) { - DERItem nsubject = { - (DERByte *)CFDataGetBytePtr(certificate->_normalizedSubject), - CFDataGetLength(certificate->_normalizedSubject) - }; - CFArrayRef nsubject_plist = createPropertiesForX501NameContent(allocator, - &nsubject); - appendPropertyP(properties, kSecPropertyTypeSection, - CFSTR("Normalized Subject Name"), nsubject_plist); - CFRelease(nsubject_plist); - } -#endif - - /* Next we put the Issuer Name in the property list. */ - CFArrayRef issuer_plist = createPropertiesForX501NameContent(allocator, - &certificate->_issuer); - appendPropertyP(properties, kSecPropertyTypeSection, - CFSTR("Issuer Name"), issuer_plist); - CFRelease(issuer_plist); - -#if 0 - /* Certificate version/type. */ - bool isRoot = false; - CFStringRef typeString = CFStringCreateWithFormat(allocator, NULL, - CFSTR("X.509 version %d %scertificate"), - certificate->_version + 1, isRoot ? "root " : ""); - appendPropertyP(properties, kSecPropertyTypeString, - CFSTR("Certificate Type"), typeString); - CFRelease(typeString); -#endif - - /* Version */ - CFStringRef versionString = CFStringCreateWithFormat(allocator, - NULL, CFSTR("%d"), certificate->_version + 1); - appendPropertyP(properties, kSecPropertyTypeString, - CFSTR("Version"), versionString); - CFRelease(versionString); - - /* Serial Number */ - if (certificate->_serialNum.length) { - appendIntegerProperty(properties, CFSTR("Serial Number"), - &certificate->_serialNum); - } - - /* Signature algorithm. */ -#if 0 - appendAlgorithmProperty(properties, CFSTR("Signature Algorithm"), - &certificate->_sigAlg); -#endif - appendAlgorithmProperty(properties, CFSTR("Signature Algorithm"), - &certificate->_tbsSigAlg); - - - /* Validity dates. */ - appendDateProperty(properties, CFSTR("Not Valid Before"), - certificate->_notBefore); - appendDateProperty(properties, CFSTR("Not Valid After"), - certificate->_notAfter); - - if (certificate->_subjectUniqueID.length) { - appendDataProperty(properties, CFSTR("Subject Unique ID"), - &certificate->_subjectUniqueID); - } - if (certificate->_issuerUniqueID.length) { - appendDataProperty(properties, CFSTR("Issuer Unique ID"), - &certificate->_issuerUniqueID); - } - - /* Public key algorithm. */ - appendAlgorithmProperty(properties, CFSTR("Public Key Algorithm"), - &certificate->_algId); - - /* Consider breaking down an RSA public key into modulus and - exponent? */ - appendDataProperty(properties, CFSTR("Public Key Data"), - &certificate->_pubKeyDER); - /* @@@ Key Size. */ - /* @@@ Key Usage. */ - - appendDataProperty(properties, CFSTR("Signature"), - &certificate->_signature); - - CFIndex ix; - for (ix = 0; ix < certificate->_extensionCount; ++ix) { - appendExtension(properties, &certificate->_extensions[ix]); - } - - /* @@@ Key Fingerprints. */ - - certificate->_properties = properties; - } - - CFRetain(certificate->_properties); - return certificate->_properties; -} - -CFDataRef SecCertificateCopySerialNumberP( - SecCertificateRefP certificate) { - if (certificate->_serialNumber) { - CFRetain(certificate->_serialNumber); - } - return certificate->_serialNumber; -} - -/* - * Accessor for normalized issuer content - */ -CFDataRef SecCertificateGetNormalizedIssuerContentP( - SecCertificateRefP certificate) { - return certificate->_normalizedIssuer; -} - -/* - * Accessor for normalized subject content - */ -CFDataRef SecCertificateGetNormalizedSubjectContentP( - SecCertificateRefP certificate) { - return certificate->_normalizedSubject; -} - -/* - * Returns DER-encoded normalized issuer sequence - * for use with SecItemCopyMatching; caller must release - */ -CFDataRef SecCertificateCopyNormalizedIssuerSequenceP( - SecCertificateRefP certificate) { - DERItem tmpdi; - tmpdi.data = (DERByte *)CFDataGetBytePtr(certificate->_normalizedIssuer); - tmpdi.length = CFDataGetLength(certificate->_normalizedIssuer); - - return SecDERItemCopySequenceP(&tmpdi); -} - -/* - * Returns DER-encoded normalized subject sequence - * for use with SecItemCopyMatching; caller must release - */ -CFDataRef SecCertificateCopyNormalizedSubjectSequenceP( - SecCertificateRefP certificate) { - DERItem tmpdi; - tmpdi.data = (DERByte *)CFDataGetBytePtr(certificate->_normalizedSubject); - tmpdi.length = CFDataGetLength(certificate->_normalizedSubject); - - return SecDERItemCopySequenceP(&tmpdi); -} - -/* Verify that certificate was signed by issuerKey. */ -OSStatus SecCertificateIsSignedByP(SecCertificateRefP certificate, - SecKeyRefP issuerKey) { - /* Setup algId in SecAsn1AlgId format. */ - SecAsn1AlgId algId; - algId.algorithm.Length = certificate->_tbsSigAlg.oid.length; - algId.algorithm.Data = certificate->_tbsSigAlg.oid.data; - algId.parameters.Length = certificate->_tbsSigAlg.params.length; - algId.parameters.Data = certificate->_tbsSigAlg.params.data; - -#warning implementation empty -#if 0 - OSStatus status = SecKeyDigestAndVerify(issuerKey, &algId, - certificate->_tbs.data, certificate->_tbs.length, - certificate->_signature.data, certificate->_signature.length); - if (status) { - secdebug("verify", "signature verify failed: %d", status); - return errSecNotSigner; - } -#endif - - return errSecSuccess; -} - -#if 0 -static OSStatus SecCertificateIsIssuedBy(SecCertificateRefP certificate, - SecCertificateRefP issuer, bool signatureCheckOnly) { - if (!signatureCheckOnly) { - /* It turns out we don't actually need to use normalized subject and - issuer according to rfc2459. */ - - /* If present we should check issuerID against the issuer subjectID. */ - - /* If we have an AuthorityKeyIdentifier extension that has a keyIdentifier - then we should look for a SubjectKeyIdentifier in the issuer - certificate. - If we have a authorityCertSerialNumber we can use that for chaining. - If we have a authorityCertIssuer we can use that? (or not) */ - - /* Verify that this cert was issued by issuer. Do so by chaining - either issuerID to subjectID or normalized issuer to normalized - subject. */ - CFDataRef normalizedIssuer = - SecCertificateGetNormalizedIssuerContentP(certificate); - CFDataRef normalizedIssuerSubject = - SecCertificateGetNormalizedSubjectContentP(issuer); - if (normalizedIssuer && normalizedIssuerSubject && - !CFEqual(normalizedIssuer, normalizedIssuerSubject)) - return errSecIssuerMismatch; - } - - /* Next verify that this cert was signed by issuer. */ - SecKeyRef issuerKey = SecCertificateGetPublicKey(issuer); - - /* Get the encodedDigestInfo from the digest of the subject's TBSCert */ - /* FIXME: We sould cache this (or at least the digest) until we find - a suitable issuer. */ - uint8_t signedData[DER_SHA1_DIGEST_INFO_LEN]; - CFIndex signedDataLength; - CertVerifyReturn crtn; - if (DEROidCompare(&certificate->_tbsSigAlg.oid, &oidSha1Rsa)) { - signedDataLength = DER_SHA1_DIGEST_INFO_LEN; - crtn = sha1DigestInfo(&certificate->_tbs, signedData); - } else if(DEROidCompare(&certificate->_tbsSigAlg.oid, &oidMd5Rsa)) { - signedDataLength = DER_MD_DIGEST_INFO_LEN; - crtn = mdDigestInfo(WD_MD5, &certificate->_tbs, signedData); - } else if(DEROidCompare(&certificate->_tbsSigAlg.oid, &oidMd2Rsa)) { - signedDataLength = DER_MD_DIGEST_INFO_LEN; - crtn = mdDigestInfo(WD_MD2, &certificate->_tbs, signedData); - } else { - secdebug("verify", "unsupported algorithm"); - return errSecUnsupportedAlgorithm; - } - if (crtn) { - secdebug("verify", "*DigestInfo returned: %d", crtn); - /* FIXME: Do proper error code translation. */ - return errSecUnsupportedAlgorithm; - } - - OSStatus status = SecKeyRawVerify(issuerKey, kSecPaddingPKCS1, - signedData, signedDataLength, - certificate->_signature.data, certificate->_signature.length); - if (status) { - secdebug("verify", "signature verify failed: %d", status); - return errSecNotSigner; - } - - return errSecSuccess; -} - -static OSStatus _SecCertificateSetParent(SecCertificateRefP certificate, - SecCertificateRefP issuer, bool signatureCheckOnly) { - check(issuer); - if (certificate->_parent) { - /* Setting a certificates issuer twice is only allowed if the new - issuer is equal to the current one. */ - return issuer && CFEqual(certificate->_parent, issuer); - } - -#if 0 - OSStatus status = SecCertificateIsIssuedBy(certificate, issuer, - signatureCheckOnly); -#else - OSStatus status = errSecSuccess; -#endif - if (!status) { - if (CFEqual(certificate, issuer)) { - /* We don't retain ourselves cause that would be bad mojo, - however we do record that we are properly self signed. */ - certificate->_isSelfSigned = kSecSelfSignedTrue; - secdebug("cert", "set self as parent"); - return errSecSuccess; - } - - CFRetain(issuer); - certificate->_parent = issuer; - certificate->_isSelfSigned = kSecSelfSignedFalse; - } - - return status; -} - -static bool SecCertificateIsSelfSignedP(SecCertificateRefP certificate) { - if (certificate->_isSelfSigned == kSecSelfSignedUnknown) { - certificate->_isSelfSigned = - (SecCertificateIsIssuedBy(certificate, certificate, false) ? - kSecSelfSignedTrue : kSecSelfSignedFalse); - } - - return certificate->_isSelfSigned == kSecSelfSignedTrue; -} - -/* Return true iff we were able to set our own parent from one of the - certificates in other_certificates, return false otherwise. If - signatureCheckOnly is true, we can skip the subject == issuer or - authorityKeyIdentifier tests. */ -static bool SecCertificateSetParentFrom(SecCertificateRefP certificate, - CFArrayRef other_certificates, bool signatureCheckOnly) { - CFIndex count = CFArrayGetCount(other_certificates); - CFIndex ix; - for (ix = 0; ix < count; ++ix) { - SecCertificateRefP candidate = (SecCertificateRefP) - CFArrayGetValueAtIndex(other_certificates, ix); - if (_SecCertificateSetParent(certificate, candidate, - signatureCheckOnly)) - return true; - } - return false; -} - -/* Lookup the parent of certificate in the keychain and set it. */ -static bool SecCertificateFindParent(SecCertificateRefP certificate) { - /* FIXME: Search for things other than just subject of our issuer if we - have a subjectID or authorityKeyIdentifier. */ - CFDataRef normalizedIssuer = - SecCertificateGetNormalizedIssuerContentP(certificate); - const void *keys[] = { - kSecClass, - kSecReturnRef, - kSecMatchLimit, - kSecAttrSubject - }, - *values[] = { - kSecClassCertificate, - kCFBooleanTrue, - kSecMatchLimitAll, - normalizedIssuer - }; - CFDictionaryRef query = CFDictionaryCreate(NULL, keys, values, 4, - &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFTypeRef results; - OSStatus status = SecItemCopyMatching(query, &results); - CFRelease(query); - if (status) { - secdebug("cert", "SecCertificateFindParent: SecItemCopyMatching: %d", - status); - return false; - } - CFArrayRef certs = (CFArrayRef)results; - /* Since we already know the certificates we are providing as candidates - have been checked for subject matching, we can ask - SecCertificateSetParentFrom to skip everything except the signature - checks. */ - bool result = SecCertificateSetParentFrom(certificate, certs, true); - CFRelease(certs); - return result; -} - -OSStatus SecCertificateCompleteChainP(SecCertificateRefP certificate, - CFArrayRef other_certificates) { - for (;;) { - if (certificate->_parent == NULL) { - if (SecCertificateIsSelfSignedP(certificate)) - return errSecSuccess; - if (!other_certificates || - !SecCertificateSetParentFrom(certificate, other_certificates,\ - false)) { - if (!SecCertificateFindParent(certificate)) - return errSecIssuerNotFound; - } - } - certificate = certificate->_parent; - } -} -#endif - -static OSStatus appendIPAddressesFromGeneralNames(void *context, - SecCEGeneralNameType gnType, const DERItem *generalName) { - CFMutableArrayRef ipAddresses = (CFMutableArrayRef)context; - if (gnType == GNT_IPAddress) { - CFStringRef string = copyIPAddressContentDescription( - kCFAllocatorDefault, generalName); - if (string) { - CFArrayAppendValue(ipAddresses, string); - CFRelease(string); - } else { - return errSecInvalidCertificate; - } - } - return errSecSuccess; -} - -CFArrayRef SecCertificateCopyIPAddressesP(SecCertificateRefP certificate) { - /* These can only exist in the subject alt name. */ - if (!certificate->_subjectAltName) - return NULL; - - CFMutableArrayRef ipAddresses = CFArrayCreateMutable(kCFAllocatorDefault, - 0, &kCFTypeArrayCallBacks); - OSStatus status = parseGeneralNames(&certificate->_subjectAltName->extnValue, - ipAddresses, appendIPAddressesFromGeneralNames); - if (status || CFArrayGetCount(ipAddresses) == 0) { - CFRelease(ipAddresses); - ipAddresses = NULL; - } - return ipAddresses; -} - -static OSStatus appendDNSNamesFromGeneralNames(void *context, SecCEGeneralNameType gnType, - const DERItem *generalName) { - CFMutableArrayRef dnsNames = (CFMutableArrayRef)context; - if (gnType == GNT_DNSName) { - CFStringRef string = CFStringCreateWithBytes(kCFAllocatorDefault, - generalName->data, generalName->length, - kCFStringEncodingUTF8, FALSE); - if (string) { - CFArrayAppendValue(dnsNames, string); - CFRelease(string); - } else { - return errSecInvalidCertificate; - } - } - return errSecSuccess; -} - -/* Return true if the passed in string matches the - Preferred name syntax from sections 2.3.1. in RFC 1035. - With the added check that we disallow empty dns names. - Also in order to support wildcard DNSNames we allow for the '*' - character anywhere in a dns component where we currently allow - a letter. - - ::= | " " - - ::=