From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../projects/nss/nss_sample_code/index.html | 33 +++ .../index.html | 255 +++++++++++++++++++++ .../projects/nss/reference/fc_login/index.html | 53 +++++ files/ru/mozilla/projects/nss/reference/index.html | 161 +++++++++++++ 4 files changed, 502 insertions(+) create mode 100644 files/ru/mozilla/projects/nss/nss_sample_code/index.html create mode 100644 files/ru/mozilla/projects/nss/nss_sample_code/nss_sample_code_sample_2_initialization_of_nss/index.html create mode 100644 files/ru/mozilla/projects/nss/reference/fc_login/index.html create mode 100644 files/ru/mozilla/projects/nss/reference/index.html (limited to 'files/ru/mozilla/projects/nss') diff --git a/files/ru/mozilla/projects/nss/nss_sample_code/index.html b/files/ru/mozilla/projects/nss/nss_sample_code/index.html new file mode 100644 index 0000000000..2bc6d0e4fc --- /dev/null +++ b/files/ru/mozilla/projects/nss/nss_sample_code/index.html @@ -0,0 +1,33 @@ +--- +title: NSS Sample Code +slug: Mozilla/Projects/NSS/NSS_Sample_Code +tags: + - Example + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Projects/NSS/NSS_Sample_Code +--- +

NSS Sample Code

+ +

The collection of sample code here demonstrates how NSS can be used for cryptographic operations, certificate handling, SSL, etc. It also demonstrates some best practices in the application of cryptography.

+ +

Old samples in the process of being replaced.

+ +
    +
  1. Sample Code 1: Key Generation and Transport Between Servers
  2. +
  3. Sample Code 2: Symmetric Encryption
  4. +
  5. Sample Code 3: Hashing, MAC
  6. +
  7. Sample Code 4: PKI Encryption
  8. +
  9. Sample Code 5: PKI Encryption with a raw public & private key in DER format
  10. +
  11. Sample Code 6: Persistent Symmetric Keys in NSS database
  12. +
+ +


+ These are very old examples in need of replacement. See https://bugzilla.mozilla.org/show_bug.cgi?id=490238

+ +

You are welcome to download the new samples via:

+ +
hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update SAMPLES_BRANCH
+
+ +

The new samples: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/New_NSS_Samples

diff --git a/files/ru/mozilla/projects/nss/nss_sample_code/nss_sample_code_sample_2_initialization_of_nss/index.html b/files/ru/mozilla/projects/nss/nss_sample_code/nss_sample_code_sample_2_initialization_of_nss/index.html new file mode 100644 index 0000000000..d3a5983c84 --- /dev/null +++ b/files/ru/mozilla/projects/nss/nss_sample_code/nss_sample_code_sample_2_initialization_of_nss/index.html @@ -0,0 +1,255 @@ +--- +title: NSS Sample Code Sample_2_Initialization of NSS +slug: >- + Mozilla/Projects/NSS/NSS_Sample_Code/NSS_Sample_Code_Sample_2_Initialization_of_NSS +tags: + - Example + - Mozilla firefox nss init + - NSS + - Security + - Инициализация NSS + - Пример +translation_of: >- + Mozilla/Projects/NSS/NSS_Sample_Code/NSS_Sample_Code_Sample_2_Initialization_of_NSS +--- +

NSS Sample Code 2: Initializing NSS

+ +

Эта программа демонстрирует как инициализировать NSS Database. Так же эта программа иллюстрирует обработку пароля.

+ +

Пример NSS инициализации и обработки пароля

+ +
/* NSPR Заголовки*/
+#include <prthread.h>
+#include <plgetopt.h>
+#include <prprf.h>
+
+/* NSS Заголовки */
+#include <nss.h>
+#include <pk11func.h>
+
+#include "util.h"
+
+// для того, чтобы русские буквы отображались корректно используйте setlocale(LC_ALL,"RUS") в main() :)
+
+/* Вывести сообщение о том, какая база данных используется и выйти */
+static void Usage(const char *progName)
+{
+    fprintf(stderr, "\nИспользуется:  %s -d <dbdirpath> [-p <plainpasswc>]"
+                    " [-f <passwdffile>]\n\n",
+                    progName);
+    fprintf(stderr, "%-15s Укажите путь к каталогу базы данных\n\n",
+             "-d <dbdirpath>");
+    fprintf(stderr, "%-15s Укажите незашифрованный пароль\n\n",
+             "-p <plainpasswc>");
+    fprintf(stderr, "%-15s Укажите файл с паролями\n\n",
+             "-f <plainpasswc>");
+    exit(-1);
+}
+
+/* Инициализация пароля слота*/
+char *InitSlotPassword(PK11SlotInfo *slot, PRBool retry, void *arg)
+{
+   FILE       *input;
+   FILE       *output;
+   char       *p0            = NULL;
+   char       *p1            = NULL;
+   secuPWData *pwdata        = (secuPWData *) arg;
+
+   if (pwdata->source == PW_FROMFILE) {
+       return FilePasswd(slot, retry, pwdata->data);
+   }
+   if (pwdata->source == PW_PLAINTEXT) {
+       return PL_strdup(pwdata->data);
+   }
+
+   /* Открыть терминал (linux)*/
+   input = fopen("/dev/tty", "r");
+   if (input == NULL) {
+       PR_fprintf(PR_STDERR, "Ошибка открытия терминала для чтения\n");
+       return NULL;
+   }
+
+   /* У нас нет паролей, давайте инициализируем базу данных*/
+   PR_fprintf(PR_STDERR,
+       "Введите пароль который будет закодирован вашим ключом.\n"
+       "Пароль должен быть длиннее восьми символов ,\n"
+       "И содержать хотя бы одну букву из алфавита.\n\n");
+
+   output = fopen("/dev/tty", "w");
+   if (output == NULL) {
+       PR_fprintf(PR_STDERR, "Ошибка открытия консоли для записи\n");
+       return NULL;
+   }
+
+   for (;;) {
+       if (p0)
+           PORT_Free(p0);
+       p0 = GetPassword(input, output, "Введите новый пароль: ",
+                                                CheckPassword);
+       if (p1)
+           PORT_Free(p1);
+       p1 = GetPassword(input, output, "Введите пароль повторно: ",
+                                                CheckPassword);
+       if (p0 && p1 && !PORT_Strcmp(p0, p1)) {
+           break;
+       }
+       PR_fprintf(PR_STDERR, "Пароли не совпадают. Попробуйте ещё раз.\n");
+   }
+
+   /* Убрать дубликат пароля из строки*/
+   if (p1) {
+       PORT_Memset(p1, 0, PORT_Strlen(p1));
+       PORT_Free(p1);
+   }
+   fclose(input);
+   fclose(output);
+
+   return p0;
+}
+
+/* Смена пароля */
+SECStatus ChangePW(PK11SlotInfo *slot, char *oldPass, char *newPass,
+                   char *oldPwFile, char *newPwFile)
+{
+    SECStatus rv;
+    secuPWData pwdata;
+    secuPWData newpwdata;
+    char      *oldpw = NULL;
+    char      *newpw = NULL;
+
+    if (oldPass) {
+        pwdata.source = PW_PLAINTEXT;
+        pwdata.data = oldPass;
+    } else if (oldPwFile) {
+        pwdata.source = PW_FROMFILE;
+        pwdata.data = oldPwFile;
+    } else {
+        pwdata.source = PW_NONE;
+        pwdata.data = NULL;
+    }
+
+    if (newPass) {
+        newpwdata.source = PW_PLAINTEXT;
+        newpwdata.data = newPass;
+    } else if (newPwFile) {
+        newpwdata.source = PW_FROMFILE;
+        newpwdata.data = NULL;
+    } else {
+        newpwdata.source = PW_NONE;
+        newpwdata.data = NULL;
+    }
+
+    if (PK11_NeedUserInit(slot)) {
+        newpw = InitSlotPassword(slot, PR_FALSE, &pwdata);
+        rv = PK11_InitPin(slot, (char*)NULL, newpw);
+    }
+    else {
+        for (;;) {
+            oldpw = GetModulePassword(slot, PR_FALSE, &pwdata);
+
+            if (PK11_CheckUserPassword(slot, oldpw) != SECSuccess) {
+                if (pwdata.source == PW_NONE) {
+                    PR_fprintf(PR_STDERR, "Invalid password.  Try again.\n");
+                } else {
+                    PR_fprintf(PR_STDERR, "Invalid password.\n");
+                    PORT_Memset(oldpw, 0, PL_strlen(oldpw));
+                    PORT_Free(oldpw);
+                    return SECFailure;
+                }
+            } else {
+                break;
+            }
+            PORT_Free(oldpw);
+        }
+        newpw = InitSlotPassword(slot, PR_FALSE, &newpwdata);
+
+        if (PK11_ChangePW(slot, oldpw, newpw) != SECSuccess) {
+            PR_fprintf(PR_STDERR, "Не получилось изменить пароль.\n");
+            return SECFailure;
+        }
+        PORT_Memset(oldpw, 0, PL_strlen(oldpw));
+        PORT_Free(oldpw);
+        PR_fprintf(PR_STDOUT, "Пароль изменён успешно!.\n");
+    }
+    PORT_Memset(newpw, 0, PL_strlen(newpw));
+    PORT_Free(newpw);
+    return SECSuccess;
+}
+
+/*
+ * Этот пример показывает как инициализировать nss базу данных.
+ * Он создаёт новую nss конфигурационную директорию с пустой базой данных
+ * и инициализирует базы данных. Так же он показывает методы
+ * для обработки пароля.
+ */
+int main(int argc, char **argv)
+{
+    PLOptState     *optstate;
+    PLOptStatus    status;
+    SECStatus      rv;
+    SECStatus      rvShutdown;
+    char           *slotname    = "internal";
+    PK11SlotInfo   *slot        = NULL;
+    char           *dbdir       = NULL;
+    char           *plainPass   = NULL;
+    char           *pwFile      = NULL;
+
+    char * progName = strrchr(argv[0], '/');
+    progName = progName ? progName + 1 : argv[0];
+
+    /* Копирование аргументов командной строки */
+    optstate = PL_CreateOptState(argc, argv, "d:p:q:f:g:");
+    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
+        switch (optstate->option) {
+        case 'd':
+             dbdir = strdup(optstate->value);
+             break;
+        case 'p':
+             plainPass = strdup(optstate->value);
+             break;
+        case 'f':
+             pwFile = strdup(optstate->value);
+             break;
+        default:
+             Usage(progName);
+             break;
+        }
+    }
+    PL_DestroyOptState(optstate);
+
+    if (!dbdir)
+        Usage(progName);
+
+    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
+
+    /* Создать базу данных */
+    rv = NSS_InitReadWrite(dbdir);
+    if (rv != SECSuccess) {
+        PR_fprintf(PR_STDERR, "NSS_Initialize Failed ( не получилось инициализировать nss )");
+        PR_Cleanup();
+        exit(rv);
+    }
+
+    if (PL_strcmp(slotname, "internal") == 0)
+        slot = PK11_GetInternalKeySlot();
+
+    /* Если создаётся новая база данных, инициализируем пароль.*/
+    rv = ChangePW(slot, plainPass, 0, pwFile, 0);
+    if (rv != SECSuccess) {
+        PR_fprintf(PR_STDERR, "Не получилось  сменить пароль\n");
+    }
+
+    if (slot) {
+        PK11_FreeSlot(slot);
+    }
+    rvShutdown = NSS_Shutdown();
+    if (rvShutdown != SECSuccess) {
+        PR_fprintf(PR_STDERR, "Failed : NSS_Shutdown() ( ошибка : выключение nss )\n");
+        rv = SECFailure;
+    }
+
+    PR_Cleanup();
+
+    return rv;
+}
+</plainpasswc></plainpasswc></dbdirpath></passwdffile></plainpasswc></dbdirpath></pk11func.h></nss.h></prprf.h></plgetopt.h></prthread.h>
diff --git a/files/ru/mozilla/projects/nss/reference/fc_login/index.html b/files/ru/mozilla/projects/nss/reference/fc_login/index.html new file mode 100644 index 0000000000..5842a77b23 --- /dev/null +++ b/files/ru/mozilla/projects/nss/reference/fc_login/index.html @@ -0,0 +1,53 @@ +--- +title: FC_Login +slug: Mozilla/Projects/NSS/Reference/FC_Login +translation_of: Mozilla/Projects/NSS/Reference/FC_Login +--- +

+

+

Name

+

FC_Login() - log a user into a token. +

+

Syntax

+
CK_RV FC_Login(
+  CK_SESSION_HANDLE hSession,
+  CK_USER_TYPE userType,
+  CK_CHAR_PTR pPin,
+  CK_ULONG ulPinLen
+);
+
+

Parameters

+

FC_Login() takes four parameters: +

+
hSession +
{{ mediawiki.external('in') }} a session handle +
userType +
{{ mediawiki.external('in') }} the user type (CKU_SO or CKU_USER) +
pPin +
{{ mediawiki.external('in') }} a pointer that points to the user's PIN +
ulPinLen +
{{ mediawiki.external('in') }} the length of the PIN +
+

Description

+

FC_Login() logs a user into a token. +

The Security Officer (CKU_SO) only logs in to initialize the normal user's PIN. The SO PIN is the empty string. The NSS cryptographic module doesn't allow the SO to log in if the normal user's PIN is already initialized. +

+

Return value

+

FC_Login() returns the following return codes. +

+ +

See also

+ +{{ languages( { "ja": "ja/FC_Login" } ) }} diff --git a/files/ru/mozilla/projects/nss/reference/index.html b/files/ru/mozilla/projects/nss/reference/index.html new file mode 100644 index 0000000000..fefd88af2a --- /dev/null +++ b/files/ru/mozilla/projects/nss/reference/index.html @@ -0,0 +1,161 @@ +--- +title: NSS reference +slug: Mozilla/Projects/NSS/Reference +tags: + - NSS + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Projects/NSS/Reference +--- +

  

+

Initial Notes

+
+ + + +
+

  

+

Building and installing NSS

+

Overview of an NSS application

+

Based on "Overview of an SSL Application" in the SSL Reference.

+

Getting started with NSS

+

Based on "Getting Started With SSL" in the SSL Reference.

+

Data types

+

Based on "Selected SSL Types and Structures" in the SSL Reference.

+

NSS initialization and shutdown

+ +

Utility functions

+

Based on "Utility Functions" in NSS Public Functions.

+

Certificate functions

+

Based on Certificate Functions in the SSL Reference and "Certificate Functions" in NSS Public Functions.

+ +

Key functions

+

Key Functions

+ +

Digital signatures

+

This API consists of the routines used to perform signature generation and the routines used to perform signature verification.

+

Encryption/decryption

+

Hashing

+

Key generation

+

Generate keys, key pairs, and domain parameters.

+

Random number generation

+

This API consists of the two routines used for pseudorandom number generation -- PK11_GenerateRandomOnSlot and PK11_GenerateRandom -- and the two routines used for seeding pseudorandom number generation -- PK11_SeedRandom and PK11_RandomUpdate.

+

PKCS #11 functions

+

Based on PKCS #11 Functions in the SSL Reference and "Crypto Functions" in NSS Public Functions.

+ +

SSL Functions

+

Based on "SSL Functions" in the SSL Reference and "SSL Functions" and "Deprecated SSL Functions" in NSS Public Functions.

+ +

S/MIME

+

Based on the S/MIME Reference (which only has one written chapter) and "S/MIME Functions" in NSS Public Functions.

+

PKCS #7 functions

+

Based on "Archived PKCS #7 Functions documentation."

+

PKCS #5 functions

+

Password-based encryption

+ +

PKCS #12 functions

+

Based on "Archived PKCS #12 Functions documentation." Used to exchange data such as private keys and certificates between two parties.

+ +

NSPR functions

+

A small number of NSPR functions are required for using the certificate verification and SSL functions in NSS.  These functions are listed in this section.

+

Error codes

+

Based on "NSS and SSL Error Codes" in the SSL Reference.

+

NSS Environment variables

+

NSS cryptographic module

+

NSS Tech Notes

+

NSS Tech Notes NSS Memory allocation

+

Tools

+

Based on NSS Tools documentation.

+

Based on NSS Tools Man Pages : work in progress

+

{{ languages( { "ja": "ja/NSS_reference" } ) }}

-- cgit v1.2.3-54-g00ecf