Files
palemoon27/toolkit/identity/IdentityCryptoService.cpp
roytam1 4c9d88c9a4 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1246051 - have MediaQueue<T>::Peek/PeekFront return a RefPtr<> to avoid dangling pointers per comment 0. r=gerald. (00f334efb1)
- Bug 1264199: P1. Perform audio conversion in the MSDM taskqueue and ahead of use. r=kinetik (001936e3ea)
- Bug 1267983 - include MediaQueue.h; r=jwwang (036107d765)
- Bug 1264199: P0. Fix nsDequeue/MediaQueue methods constness. r=jwwang (9aa33dfcb5)
- Bug 1264199: P0.1. Export SaferMultDiv method. r=gerald (0b7a35ae4d)
- Bug 1264199: P2. Ensure the AudioStream only ever receive the same content format. r=kinetik (a180d09279)
- Bug 1264199: P3. Attempt to minimize audio quality loss and unnecessary processing. r=kinetik (29d57b5a33)
- Bug 1264199: P4. Add mono to stereo upmix to AudioConverter. r=rillian (49c029bd86)
- Bug 1264199: P5. Perform all downmixing operations in DecodedAudioDataSink. r=kinetik (05a479f095)
- Bug 1264199: P6. Drain resampler when changing format or reaching the end. r=kinetik (8639102a94)
- Bug 1264199: P8. Handle potential resampling errors. r=kinetik (1267e4e73d)
- Bug 1264199: P9. Include pending frames in HasUnplayedFrames calculation. r=jwwang (ce7097fc90)
- Bug 1263496 - Part 1: fix for @mozilla.org/nullprincipal;1 r=bholley (c4c462a1bc)
- Bug 1263496 - Part 2: fix for NS_NULLPRINCIPAL_CONTRACTID. r=bholley (c1504240ec)
- Bug 1263496 - Part 3: fix for nsNullPrincipal::Create (0196a5a3ce)
- Bug 1261009 - Remove the Data Store API, r=fabrice (b22e580107)
- Bug 1261405 - Rename PushPermissionDescriptor.userVisible to `userVisibleOnly`. r=baku (4de70267cc)
- Bug 1266821 - Remove PushPermissionDescriptor from the Permissions API. r=baku (196cd83442)
- Bug 1268393 - Some compilation issues in ServiceWorker code, r=ehsan (d9c2f2554b)
- Merge branch 'dev' of https://github.com/rmottola/Arctic-Fox into dev (6f6c606911)
- Bug 1267733 P1 Treat last-update-time as infinitely in the past when checking for service worker update after restart. r=jdm (255da0a9e2)
- Bug 1209095 - Accept opaqueredirection fetch results if the request redirection type is manual. r=bkelly (6fe92d1368)
- Bug 1267733 P2 Pass ServiceWorkerRegistrationInfo down to CancelChannelRunnable. r=jdm (0ec51f09ef)
- Bug 1267733 P3 Trigger service worker update after failed interception. r=jdm (f89a7998d4)
- Bug 1267733 P4 Add a wpt test that verifies a service worker update can recover from a broken navigation interception. r=jdm (9dc0ce97bd)
- Bug 1267691: Assert on failed attempts to shutdown a thread from itself r=froyd (0cbd1e458c)
- Bug 1180533 - Disable BackgroundHangMonitor on gonk (a2d666e741)
- Bug 1121216 - disable BackgroundHangMonitor for TSan builds; r=jchen (ef15d1016f)
- Bug 1265621 - Use StaticRefPtr in Omnijar.cpp; r=froydnj (81bc32836e)
- Bug 1265621 - Expose outer zip readers in Omnijar::GetReader; r=froydnj (ce3f82929e)
- Bug 1267021 - Use fallible allocation and move semantics for Push events. r=wchen (3a1ae23d8d)
- Bug 1222899 - Handle geolocation-device-events callback. r=kchen (a33bcf4297)
- Bug 1237831 - Update GonkGPSGeolocationProvider.cpp to use B2G-style. r=jst (d389eedf47)
- Bug 1245033 - Build break in dom/system/gonk/GonkGPSGeolocationProvider.cpp:541:126: error: format '%d' expects argument of type 'int', but argument 5 has type 'nsresult'. r=fabrice (ecde789edf)
- Bug 1264287: Convert Wifi to use |UniquePtr|, r=nfroyd (9bad7792bf)
- Bug 1267577 - Move nsRunnable to mozilla::Runnable. r=gsvelto (f58e2161f2)
- Bug 1210370 - Close wpa_supplicant before we shutdown nsIWifiProxyService. r=mrbkap (5cd4dce58f)
- Bug 1218629 - Save audio volume for each device to setting db r=alwu (2f1847dd6f)
- Bug 1249437 - Remove workaround of volume control r=alwu (13cd144a89)
- Bug 1268432: Replace |Task| with |Runnable| in B2G code r=fabrice (bcc768e9cb)
- Bug 1226483 - Add ASSERT check to AudioManager::SelectDeviceFromDevices() r=alwu (446e8f634e)
- Bug 1229234 - Enable audio_is_output_device() on ICS r=alwu (84aae07f23)
- Bug 1267369 - Only generate typelib data for scriptable interfaces; r=khuey (e49b44c9ce)
- Bug 1155969 - Make runtests.py flake8 compliant. r=ted (1de456b206)
- Bug 1266569 - Avoid including the ChromeUtils binding in Base64.h. r=froydnj (7ba39a7687)
- Bug 1267568 part 1 - Add a weak ptr to nsGlobalChromeWindow to remember the pres shell we set the fullscreen change flag. r=smaug (83995d5296)
- Bug 1267568 part 2 - Add helper method to nsIPresShell to get the RefreshDriver. r=smaug (c60589fb40)
- Bug 1267568 part 3 - Use an individual method for check whether resize should be delayed. r=smaug (f0ab5156d1)
- Bug 1267568 part 4 - Replace InFullscreenChange flag of PresShell with IsResizeSuppressed flag in RefreshDriver. r=smaug (0a54f5a08b)
- Bug 1267568 part 5 - Replace the old FullscreenChangePrepare class with a single function. r=smaug (4196e82852)
- Bug 1267568 part 6 - Send fullscreen message before triggering any potential reflow. r=dao (fe9133ca2d)
- Bug 1243352 - attribute a value for ProxyHandlerInfo::mPrefAction in ProxyHandlerInfo::SetPreferredAction. r=blassey (577c23e4cb)
- Bug 1266433 - Send Push observer notifications to parent and content processes. f=janx r=dragana (768c173c2c)
- Bug 1267493 - Replace isURIPotentiallyTrustworthy usage in Push with a testing pref. r=dragana (96434b90d9)
- Bug 1266433 - Send an observer notification when a push subscription is lost. f=janx r=dragana (a7c7277e02)
- Bug 1247685 - Send subscription keys to the Push server. r=mt (651fc0cad3)
- Bug 1266540 - Stub out Push error reporting for the GCM and H2 backends. r=wchen (fd00c311aa)
- Bug 1266623 - Up/down mix WASAPI capture streams when stream formats don't match. r=padenot (ca92ec20ab)
- Bug 1267930 - When the wasapi rendering loop is stuck and we're shuttin down, leak the thread and continue the shutdown process. r=kinetik (04419ad94d)
- Bug 1269692 - Update cubeb to revision 17e3048d0afa1152776fb1867cdb61c49fae69e4. (3de098f4bb)
- Bug 1251502 - Update cubeb's udpate.sh script to account for new files. r=kinetik (a3ae5f27c1)
- Bug 1243234 - Hide MP4Metadata behind an impl pointer. r=giles (1543bedf28)
- Bug 1243234 - Update rust mp4parse telemetry reporting. r=kinetik (bb5c999c06)
- Bug 1242807 - Fix mp4parse-rust's error reporting via telemetry. r=giles (a3ca1b133b)
- Bug 1243234 - Move mp4parse-rust code into MP4MetadataRust impl. r=giles (ec4d6bcf0e)
- Bug 1243234 - Remove now-unnecessary StagefrightPrivate wrapper. r=giles (1e2c54232b)
- Bug 1243234 - Move mp4parse-rust initialization into constructor and clean up try_rust. r=giles (291c01f45a)
- Bug 1243234 - Update rust mp4parse to v0.2.1. r=kinetik (d2774346cd)
- Bug 1264622: [MP4] Resync stagefright's updateAudioTrackInfoFromESDS_MPEG4Audio with upstream. r=kentuckyfriedtakahe (b4b596507b)
- Bug 1254721: Ensure consistency between Cenc offsets and sizes table. r=gerald (59bd7122d1)
- Bug 1151202 - libstagefright: Fix compilation for systems without <sys/cdefs.h>. r=cpearce (e219658c31)
- Bug 1255866 - stagefright: Fix unused variable warnings. r=ajones (62afc26384)
- Bug 1251821: increase UDP socket send buffer on Win 7 r=jdm,jesup (e0d6e545f4)
- Bug 929977: Add support for RFC 7675 ICE consent freshness. r=bwc,mt (ea8a565a65)
- Bug 1231981 - Part 1: Very basic test TURN server for running in CI. r=ahal,drno (c98a79810b)
- Bug 1231981 - Part 2: A websocket-to-process bridge script that can be used by JS to launch an ICE server for testing. r=ahal (5bdb00dfd1)
- Bug 1231981 - Part 2.1: Only run the websocket/process bridge for media tests. r=ahal (86f97e2eb6)
- Bug 1225729: Whitelist specific bad RTCP timestamp value r=drno (f0c8402fd0)
- Bug 1193045 - Check selected attribute for all calls. r=bwc (7eb4095c34)
- Bug 1213056 - update tests to use maplike getStats. r=bwc (d27f997290)
- Bug 1231981 - Part 3: Set up TURN server for webrtc mochitests, when configured to. r=drno (38e4455eec)
- Bug 1231975 - Part 1: Basic audio mochitests for NAT scenarios. r=drno (16efaf581e)
- Bug 1231975 - Part 2: Break a reference cycle between NrTcpSocketIpc and TCPSocketChild, in the same manner as the UDP case. r=mcmanus (1fa55e3e5f)
2024-08-28 22:57:14 +08:00

572 lines
16 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsIIdentityCryptoService.h"
#include "mozilla/ModuleUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsNSSShutDown.h"
#include "nsIThread.h"
#include "nsThreadUtils.h"
#include "nsCOMPtr.h"
#include "nsProxyRelease.h"
#include "nsString.h"
#include "mozilla/ArrayUtils.h" // ArrayLength
#include "mozilla/Base64.h"
#include "ScopedNSSTypes.h"
#include "NSSErrorsService.h"
#include "nss.h"
#include "pk11pub.h"
#include "secmod.h"
#include "secerr.h"
#include "keyhi.h"
#include "cryptohi.h"
#include <limits.h>
using namespace mozilla;
namespace {
void
HexEncode(const SECItem * it, nsACString & result)
{
const char * digits = "0123456789ABCDEF";
result.SetCapacity((it->len * 2) + 1);
result.SetLength(it->len * 2);
char * p = result.BeginWriting();
for (unsigned int i = 0; i < it->len; ++i) {
*p++ = digits[it->data[i] >> 4];
*p++ = digits[it->data[i] & 0x0f];
}
}
#define DSA_KEY_TYPE_STRING (NS_LITERAL_CSTRING("DS160"))
#define RSA_KEY_TYPE_STRING (NS_LITERAL_CSTRING("RS256"))
class KeyPair : public nsIIdentityKeyPair, public nsNSSShutDownObject
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIIDENTITYKEYPAIR
KeyPair(SECKEYPrivateKey* aPrivateKey, SECKEYPublicKey* aPublicKey,
nsIEventTarget* aOperationThread);
private:
~KeyPair()
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return;
}
destructorSafeDestroyNSSReference();
shutdown(calledFromObject);
}
void virtualDestroyNSSReference() override
{
destructorSafeDestroyNSSReference();
}
void destructorSafeDestroyNSSReference()
{
SECKEY_DestroyPrivateKey(mPrivateKey);
mPrivateKey = nullptr;
SECKEY_DestroyPublicKey(mPublicKey);
mPublicKey = nullptr;
}
SECKEYPrivateKey * mPrivateKey;
SECKEYPublicKey * mPublicKey;
nsCOMPtr<nsIEventTarget> mThread;
KeyPair(const KeyPair &) = delete;
void operator=(const KeyPair &) = delete;
};
NS_IMPL_ISUPPORTS(KeyPair, nsIIdentityKeyPair)
class KeyGenRunnable : public Runnable, public nsNSSShutDownObject
{
public:
NS_DECL_NSIRUNNABLE
KeyGenRunnable(KeyType keyType, nsIIdentityKeyGenCallback * aCallback,
nsIEventTarget* aOperationThread);
private:
~KeyGenRunnable()
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return;
}
destructorSafeDestroyNSSReference();
shutdown(calledFromObject);
}
virtual void virtualDestroyNSSReference() override
{
destructorSafeDestroyNSSReference();
}
void destructorSafeDestroyNSSReference()
{
}
const KeyType mKeyType; // in
nsMainThreadPtrHandle<nsIIdentityKeyGenCallback> mCallback; // in
nsresult mRv; // out
nsCOMPtr<nsIIdentityKeyPair> mKeyPair; // out
nsCOMPtr<nsIEventTarget> mThread;
KeyGenRunnable(const KeyGenRunnable &) = delete;
void operator=(const KeyGenRunnable &) = delete;
};
class SignRunnable : public Runnable, public nsNSSShutDownObject
{
public:
NS_DECL_NSIRUNNABLE
SignRunnable(const nsACString & textToSign, SECKEYPrivateKey * privateKey,
nsIIdentitySignCallback * aCallback);
private:
~SignRunnable()
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
return;
}
destructorSafeDestroyNSSReference();
shutdown(calledFromObject);
}
void virtualDestroyNSSReference() override
{
destructorSafeDestroyNSSReference();
}
void destructorSafeDestroyNSSReference()
{
SECKEY_DestroyPrivateKey(mPrivateKey);
mPrivateKey = nullptr;
}
const nsCString mTextToSign; // in
SECKEYPrivateKey* mPrivateKey; // in
nsMainThreadPtrHandle<nsIIdentitySignCallback> mCallback; // in
nsresult mRv; // out
nsCString mSignature; // out
private:
SignRunnable(const SignRunnable &) = delete;
void operator=(const SignRunnable &) = delete;
};
class IdentityCryptoService final : public nsIIdentityCryptoService
{
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIIDENTITYCRYPTOSERVICE
IdentityCryptoService() { }
nsresult Init()
{
nsresult rv;
nsCOMPtr<nsISupports> dummyUsedToEnsureNSSIsInitialized
= do_GetService("@mozilla.org/psm;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIThread> thread;
rv = NS_NewNamedThread("IdentityCrypto", getter_AddRefs(thread));
NS_ENSURE_SUCCESS(rv, rv);
mThread = thread.forget();
return NS_OK;
}
private:
~IdentityCryptoService() { }
IdentityCryptoService(const KeyPair &) = delete;
void operator=(const IdentityCryptoService &) = delete;
nsCOMPtr<nsIEventTarget> mThread;
};
NS_IMPL_ISUPPORTS(IdentityCryptoService, nsIIdentityCryptoService)
NS_IMETHODIMP
IdentityCryptoService::GenerateKeyPair(
const nsACString & keyTypeString, nsIIdentityKeyGenCallback * callback)
{
KeyType keyType;
if (keyTypeString.Equals(RSA_KEY_TYPE_STRING)) {
keyType = rsaKey;
} else if (keyTypeString.Equals(DSA_KEY_TYPE_STRING)) {
keyType = dsaKey;
} else {
return NS_ERROR_UNEXPECTED;
}
nsCOMPtr<nsIRunnable> r = new KeyGenRunnable(keyType, callback, mThread);
nsresult rv = mThread->Dispatch(r, NS_DISPATCH_NORMAL);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP
IdentityCryptoService::Base64UrlEncode(const nsACString & utf8Input,
nsACString & result)
{
return Base64URLEncode(utf8Input.Length(),
reinterpret_cast<const uint8_t*>(utf8Input.BeginReading()),
Base64URLEncodePaddingPolicy::Include, result);
}
KeyPair::KeyPair(SECKEYPrivateKey * privateKey, SECKEYPublicKey * publicKey,
nsIEventTarget* operationThread)
: mPrivateKey(privateKey)
, mPublicKey(publicKey)
, mThread(operationThread)
{
MOZ_ASSERT(!NS_IsMainThread());
}
NS_IMETHODIMP
KeyPair::GetHexRSAPublicKeyExponent(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(mPublicKey->keyType == rsaKey, NS_ERROR_NOT_AVAILABLE);
HexEncode(&mPublicKey->u.rsa.publicExponent, result);
return NS_OK;
}
NS_IMETHODIMP
KeyPair::GetHexRSAPublicKeyModulus(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(mPublicKey->keyType == rsaKey, NS_ERROR_NOT_AVAILABLE);
HexEncode(&mPublicKey->u.rsa.modulus, result);
return NS_OK;
}
NS_IMETHODIMP
KeyPair::GetHexDSAPrime(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(mPublicKey->keyType == dsaKey, NS_ERROR_NOT_AVAILABLE);
HexEncode(&mPublicKey->u.dsa.params.prime, result);
return NS_OK;
}
NS_IMETHODIMP
KeyPair::GetHexDSASubPrime(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(mPublicKey->keyType == dsaKey, NS_ERROR_NOT_AVAILABLE);
HexEncode(&mPublicKey->u.dsa.params.subPrime, result);
return NS_OK;
}
NS_IMETHODIMP
KeyPair::GetHexDSAGenerator(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(mPublicKey->keyType == dsaKey, NS_ERROR_NOT_AVAILABLE);
HexEncode(&mPublicKey->u.dsa.params.base, result);
return NS_OK;
}
NS_IMETHODIMP
KeyPair::GetHexDSAPublicValue(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
NS_ENSURE_TRUE(mPublicKey->keyType == dsaKey, NS_ERROR_NOT_AVAILABLE);
HexEncode(&mPublicKey->u.dsa.publicValue, result);
return NS_OK;
}
NS_IMETHODIMP
KeyPair::GetKeyType(nsACString & result)
{
MOZ_ASSERT(NS_IsMainThread());
NS_ENSURE_TRUE(mPublicKey, NS_ERROR_NOT_AVAILABLE);
switch (mPublicKey->keyType) {
case rsaKey: result = RSA_KEY_TYPE_STRING; return NS_OK;
case dsaKey: result = DSA_KEY_TYPE_STRING; return NS_OK;
default: return NS_ERROR_UNEXPECTED;
}
}
NS_IMETHODIMP
KeyPair::Sign(const nsACString & textToSign,
nsIIdentitySignCallback* callback)
{
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIRunnable> r = new SignRunnable(textToSign, mPrivateKey,
callback);
return mThread->Dispatch(r, NS_DISPATCH_NORMAL);
}
KeyGenRunnable::KeyGenRunnable(KeyType keyType,
nsIIdentityKeyGenCallback * callback,
nsIEventTarget* operationThread)
: mKeyType(keyType)
, mCallback(new nsMainThreadPtrHolder<nsIIdentityKeyGenCallback>(callback))
, mRv(NS_ERROR_NOT_INITIALIZED)
, mThread(operationThread)
{
}
MOZ_MUST_USE nsresult
GenerateKeyPair(PK11SlotInfo * slot,
SECKEYPrivateKey ** privateKey,
SECKEYPublicKey ** publicKey,
CK_MECHANISM_TYPE mechanism,
void * params)
{
*publicKey = nullptr;
*privateKey = PK11_GenerateKeyPair(slot, mechanism, params, publicKey,
PR_FALSE /*isPerm*/,
PR_TRUE /*isSensitive*/,
nullptr /*&pwdata*/);
if (!*privateKey) {
MOZ_ASSERT(!*publicKey);
return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
}
if (!*publicKey) {
SECKEY_DestroyPrivateKey(*privateKey);
*privateKey = nullptr;
MOZ_CRASH("PK11_GnerateKeyPair returned private key without public key");
}
return NS_OK;
}
MOZ_MUST_USE nsresult
GenerateRSAKeyPair(PK11SlotInfo * slot,
SECKEYPrivateKey ** privateKey,
SECKEYPublicKey ** publicKey)
{
MOZ_ASSERT(!NS_IsMainThread());
PK11RSAGenParams rsaParams;
rsaParams.keySizeInBits = 2048;
rsaParams.pe = 0x10001;
return GenerateKeyPair(slot, privateKey, publicKey, CKM_RSA_PKCS_KEY_PAIR_GEN,
&rsaParams);
}
MOZ_MUST_USE nsresult
GenerateDSAKeyPair(PK11SlotInfo * slot,
SECKEYPrivateKey ** privateKey,
SECKEYPublicKey ** publicKey)
{
MOZ_ASSERT(!NS_IsMainThread());
// XXX: These could probably be static const arrays, but this way we avoid
// compiler warnings and also we avoid having to worry much about whether the
// functions that take these inputs will (unexpectedly) modify them.
// Using NIST parameters. Some other BrowserID components require that these
// exact parameters are used.
uint8_t P[] = {
0xFF,0x60,0x04,0x83,0xDB,0x6A,0xBF,0xC5,0xB4,0x5E,0xAB,0x78,
0x59,0x4B,0x35,0x33,0xD5,0x50,0xD9,0xF1,0xBF,0x2A,0x99,0x2A,
0x7A,0x8D,0xAA,0x6D,0xC3,0x4F,0x80,0x45,0xAD,0x4E,0x6E,0x0C,
0x42,0x9D,0x33,0x4E,0xEE,0xAA,0xEF,0xD7,0xE2,0x3D,0x48,0x10,
0xBE,0x00,0xE4,0xCC,0x14,0x92,0xCB,0xA3,0x25,0xBA,0x81,0xFF,
0x2D,0x5A,0x5B,0x30,0x5A,0x8D,0x17,0xEB,0x3B,0xF4,0xA0,0x6A,
0x34,0x9D,0x39,0x2E,0x00,0xD3,0x29,0x74,0x4A,0x51,0x79,0x38,
0x03,0x44,0xE8,0x2A,0x18,0xC4,0x79,0x33,0x43,0x8F,0x89,0x1E,
0x22,0xAE,0xEF,0x81,0x2D,0x69,0xC8,0xF7,0x5E,0x32,0x6C,0xB7,
0x0E,0xA0,0x00,0xC3,0xF7,0x76,0xDF,0xDB,0xD6,0x04,0x63,0x8C,
0x2E,0xF7,0x17,0xFC,0x26,0xD0,0x2E,0x17
};
uint8_t Q[] = {
0xE2,0x1E,0x04,0xF9,0x11,0xD1,0xED,0x79,0x91,0x00,0x8E,0xCA,
0xAB,0x3B,0xF7,0x75,0x98,0x43,0x09,0xC3
};
uint8_t G[] = {
0xC5,0x2A,0x4A,0x0F,0xF3,0xB7,0xE6,0x1F,0xDF,0x18,0x67,0xCE,
0x84,0x13,0x83,0x69,0xA6,0x15,0x4F,0x4A,0xFA,0x92,0x96,0x6E,
0x3C,0x82,0x7E,0x25,0xCF,0xA6,0xCF,0x50,0x8B,0x90,0xE5,0xDE,
0x41,0x9E,0x13,0x37,0xE0,0x7A,0x2E,0x9E,0x2A,0x3C,0xD5,0xDE,
0xA7,0x04,0xD1,0x75,0xF8,0xEB,0xF6,0xAF,0x39,0x7D,0x69,0xE1,
0x10,0xB9,0x6A,0xFB,0x17,0xC7,0xA0,0x32,0x59,0x32,0x9E,0x48,
0x29,0xB0,0xD0,0x3B,0xBC,0x78,0x96,0xB1,0x5B,0x4A,0xDE,0x53,
0xE1,0x30,0x85,0x8C,0xC3,0x4D,0x96,0x26,0x9A,0xA8,0x90,0x41,
0xF4,0x09,0x13,0x6C,0x72,0x42,0xA3,0x88,0x95,0xC9,0xD5,0xBC,
0xCA,0xD4,0xF3,0x89,0xAF,0x1D,0x7A,0x4B,0xD1,0x39,0x8B,0xD0,
0x72,0xDF,0xFA,0x89,0x62,0x33,0x39,0x7A
};
static_assert(MOZ_ARRAY_LENGTH(P) == 1024 / CHAR_BIT, "bad DSA P");
static_assert(MOZ_ARRAY_LENGTH(Q) == 160 / CHAR_BIT, "bad DSA Q");
static_assert(MOZ_ARRAY_LENGTH(G) == 1024 / CHAR_BIT, "bad DSA G");
PQGParams pqgParams = {
nullptr /*arena*/,
{ siBuffer, P, static_cast<unsigned int>(mozilla::ArrayLength(P)) },
{ siBuffer, Q, static_cast<unsigned int>(mozilla::ArrayLength(Q)) },
{ siBuffer, G, static_cast<unsigned int>(mozilla::ArrayLength(G)) }
};
return GenerateKeyPair(slot, privateKey, publicKey, CKM_DSA_KEY_PAIR_GEN,
&pqgParams);
}
NS_IMETHODIMP
KeyGenRunnable::Run()
{
if (!NS_IsMainThread()) {
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
mRv = NS_ERROR_NOT_AVAILABLE;
} else {
// We always want to use the internal slot for BrowserID; in particular,
// we want to avoid smartcard slots.
PK11SlotInfo *slot = PK11_GetInternalSlot();
if (!slot) {
mRv = NS_ERROR_UNEXPECTED;
} else {
SECKEYPrivateKey *privk = nullptr;
SECKEYPublicKey *pubk = nullptr;
switch (mKeyType) {
case rsaKey:
mRv = GenerateRSAKeyPair(slot, &privk, &pubk);
break;
case dsaKey:
mRv = GenerateDSAKeyPair(slot, &privk, &pubk);
break;
default:
MOZ_CRASH("unknown key type");
}
PK11_FreeSlot(slot);
if (NS_SUCCEEDED(mRv)) {
MOZ_ASSERT(privk);
MOZ_ASSERT(pubk);
// mKeyPair will take over ownership of privk and pubk
mKeyPair = new KeyPair(privk, pubk, mThread);
}
}
}
NS_DispatchToMainThread(this);
} else {
// Back on Main Thread
(void) mCallback->GenerateKeyPairFinished(mRv, mKeyPair);
}
return NS_OK;
}
SignRunnable::SignRunnable(const nsACString & aText,
SECKEYPrivateKey * privateKey,
nsIIdentitySignCallback * aCallback)
: mTextToSign(aText)
, mPrivateKey(SECKEY_CopyPrivateKey(privateKey))
, mCallback(new nsMainThreadPtrHolder<nsIIdentitySignCallback>(aCallback))
, mRv(NS_ERROR_NOT_INITIALIZED)
{
}
NS_IMETHODIMP
SignRunnable::Run()
{
if (!NS_IsMainThread()) {
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
mRv = NS_ERROR_NOT_AVAILABLE;
} else {
// We need the output in PKCS#11 format, not DER encoding, so we must use
// PK11_HashBuf and PK11_Sign instead of SEC_SignData.
SECItem sig = { siBuffer, nullptr, 0 };
int sigLength = PK11_SignatureLen(mPrivateKey);
if (sigLength <= 0) {
mRv = mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
} else if (!SECITEM_AllocItem(nullptr, &sig, sigLength)) {
mRv = mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
} else {
uint8_t hash[32]; // big enough for SHA-1 or SHA-256
SECOidTag hashAlg = mPrivateKey->keyType == dsaKey ? SEC_OID_SHA1
: SEC_OID_SHA256;
SECItem hashItem = { siBuffer, hash,
hashAlg == SEC_OID_SHA1 ? 20u : 32u };
mRv = MapSECStatus(PK11_HashBuf(hashAlg, hash,
const_cast<uint8_t*>(reinterpret_cast<const uint8_t *>(
mTextToSign.get())),
mTextToSign.Length()));
if (NS_SUCCEEDED(mRv)) {
mRv = MapSECStatus(PK11_Sign(mPrivateKey, &sig, &hashItem));
}
if (NS_SUCCEEDED(mRv)) {
mRv = Base64URLEncode(sig.len, sig.data,
Base64URLEncodePaddingPolicy::Include,
mSignature);
}
SECITEM_FreeItem(&sig, false);
}
}
NS_DispatchToMainThread(this);
} else {
// Back on Main Thread
(void) mCallback->SignFinished(mRv, mSignature);
}
return NS_OK;
}
// XPCOM module registration
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(IdentityCryptoService, Init)
#define NS_IDENTITYCRYPTOSERVICE_CID \
{0xbea13a3a, 0x44e8, 0x4d7f, {0xa0, 0xa2, 0x2c, 0x67, 0xf8, 0x4e, 0x3a, 0x97}}
NS_DEFINE_NAMED_CID(NS_IDENTITYCRYPTOSERVICE_CID);
const mozilla::Module::CIDEntry kCIDs[] = {
{ &kNS_IDENTITYCRYPTOSERVICE_CID, false, nullptr, IdentityCryptoServiceConstructor },
{ nullptr }
};
const mozilla::Module::ContractIDEntry kContracts[] = {
{ "@mozilla.org/identity/crypto-service;1", &kNS_IDENTITYCRYPTOSERVICE_CID },
{ nullptr }
};
const mozilla::Module kModule = {
mozilla::Module::kVersion,
kCIDs,
kContracts
};
} // unnamed namespace
NSMODULE_DEFN(identity) = &kModule;