summaryrefslogtreecommitdiffstats
path: root/base/symkey/src/com/netscape/symkey/EncryptData.cpp
blob: 3963b50268147b01215a927d983152ae8ab9486b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

#ifdef __cplusplus
extern "C"
{
#endif
#include "pk11func.h"
#include "nspr.h"
#ifdef __cplusplus
#include <jni.h>
#include <assert.h>
#include <string.h>

}
#endif
#include <memory.h>
#include <assert.h>
#include <stdio.h>
#include <cstdarg>
#include <string>
#include <stdlib.h>
#include "Buffer.h"
#include "SymKey.h"

// AC: KDF SPEC CHANGE: Include headers for NIST SP800-108 KDF functions.
#include "NistSP800_108KDF.h"

#define DES2_WORKAROUND

PRFileDesc *d = NULL;

void GetKeyName(jbyte *keyVersion, char *keyname)
{
    int index=0;

    if( !keyname || !keyVersion || 
        (strlen(keyname) < KEYNAMELENGTH)) {
       return;
    }

    if(strlen(masterKeyPrefix)!=0)
    {
        index= strlen(masterKeyPrefix);
        strcpy(keyname,masterKeyPrefix);
    }

    if( (index + 3) >= KEYNAMELENGTH) {
        return;
    }
    
    keyname[index+0]='#';
    sprintf(keyname+index+1,"%.2d", keyVersion[0]);
    keyname[index+3]='#';
    sprintf(keyname+index+4,"%.2d", keyVersion[1]);
}

// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
extern "C"  JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_EncryptData
(JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyte, jboolean, jbyteArray, jbyteArray, jbyteArray, jstring, jstring);

// AC: KDF SPEC CHANGE: function signature change - added jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, and jbyteArray KDD
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_netscape_symkey_SessionKey_EncryptData(JNIEnv * env, jclass this2, jstring j_tokenName, jstring j_keyName, jbyteArray  j_in, jbyteArray keyInfo, jbyte nistSP800_108KdfOnKeyVersion, jboolean nistSP800_108KdfUseCuidAsKdd, jbyteArray CUID, jbyteArray KDD, jbyteArray kekKeyArray, jstring useSoftToken_s,jstring keySet)
{
    jbyte * kek_key =  NULL;

    PK11SymKey *masterKey = NULL;

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Kek) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    // KDF output keys
    PK11SymKey* macKey = NULL;
    PK11SymKey* encKey = NULL;
    PK11SymKey* kekKey = NULL;

    Buffer out = Buffer(KEYLENGTH, (BYTE)0);
    BYTE kekData[KEYLENGTH];
    char keyname[KEYNAMELENGTH];

    int status = PR_FAILURE;

    jbyte *cc = NULL;
    int cc_len = 0;

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    jbyte* cuidValue = NULL;
    jsize cuidValue_len = -1;
    jbyte* kddValue = NULL;
    jsize kddValue_len = -1;

    if( kekKeyArray != NULL) {
        kek_key = (jbyte*)(env)->GetByteArrayElements(kekKeyArray, NULL);
    } else {
        return NULL;
    }

    PK11SlotInfo *slot = NULL;
    PK11SlotInfo *internal = PK11_GetInternalKeySlot();

    Buffer kek_buffer = Buffer((BYTE*)kek_key, KEYLENGTH);
    char *keySetStringChars = NULL;
    if( keySet != NULL) {
        keySetStringChars = (char *) (env)->GetStringUTFChars( keySet, NULL);
    }

    char *keySetString = keySetStringChars;

    if ( keySetString == NULL ) {
        keySetString = (char *) DEFKEYSET_NAME;
    }

    jbyte * keyVersion =  NULL; 
    int keyVersion_len = 0;
    if( keyInfo != NULL) {
        keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
        if( keyVersion) {
            keyVersion_len =  (env)->GetArrayLength(keyInfo);
        }
    }

    if( !keyVersion || (keyVersion_len < 2) ) {
        goto done;
    }


    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    //                       Also added "len" variable for CUID (for sanity check).
    if ( CUID != NULL ) {
        cuidValue =  (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
        cuidValue_len = env->GetArrayLength(CUID);
    }
    if( cuidValue == NULL) {
        goto done;
    }
    if ( cuidValue_len <= 0){  // check that CUID is at least 1 byte in length
        goto done;
    }
    if ( KDD != NULL ){
        kddValue = env->GetByteArrayElements(KDD, NULL);
        kddValue_len = env->GetArrayLength(KDD);
    }
    if ( kddValue == NULL ){
        goto done;
    }
    if ( kddValue_len != static_cast<jsize>(NistSP800_108KDF::KDD_SIZE_BYTES) ){   // check that KDD is expected size
        goto done;
    }


    if( j_in != NULL) {
        cc = (jbyte*)(env)->GetByteArrayElements( j_in, NULL);
        cc_len = (env)->GetArrayLength(j_in);
    }

    if( cc == NULL) {
        goto done;
    }

    // AC: KDF SPEC CHANGE: Moved this call down. (We don't necessarily need it anymore depending on the KDF we're going to use.)
    //GetDiversificationData(cuidValue,kekData,kek);

    PR_fprintf(PR_STDOUT,"In SessionKey: EncryptData! \n");

    if(j_tokenName != NULL) {
        char *tokenNameChars = (char *)(env)->GetStringUTFChars(j_tokenName, NULL);
        slot = ReturnSlot(tokenNameChars);
        (env)->ReleaseStringUTFChars(j_tokenName, (const char *)tokenNameChars);
        tokenNameChars = NULL;
    }

    if(j_keyName != NULL) {
        char *keyNameChars= (char *)(env)->GetStringUTFChars(j_keyName, NULL);
        strcpy(keyname,keyNameChars);
        env->ReleaseStringUTFChars(j_keyName, (const char *)keyNameChars);
        keyNameChars = NULL;
    }
    else {
        GetKeyName(keyVersion,keyname);
    }

    if ( (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 && strcmp( keyname, "#01#01") == 0) ||
        (keyVersion[0] == -1  && strstr(keyname, "#FF") ))
    {
        /* default development keyset */
        Buffer devInput = Buffer((BYTE*)cc, cc_len);
        Buffer empty = Buffer();
        
        kekKey = ReturnDeveloperSymKey( internal, (char *) "kek", keySetString, empty); 

        if ( kekKey ) {
            status = EncryptData(Buffer(),kekKey,devInput, out);
        } else { 
            status = EncryptData(kek_buffer, NULL, devInput, out);
        }
    }
    else
    {
        if (slot!=NULL)
        {
            masterKey = ReturnSymKey( slot,keyname);

            if (masterKey != NULL)
            {


                // ---------------------------------
                // AC KDF SPEC CHANGE: Determine which KDF to use.
                //
                // Convert to unsigned types
                BYTE nistSP800_108KdfOnKeyVersion_byte = static_cast<BYTE>(nistSP800_108KdfOnKeyVersion);
                BYTE requestedKeyVersion_byte = static_cast<BYTE>(keyVersion[0]);
                // if requested key version meets setting value, use NIST SP800-108 KDF
                if (NistSP800_108KDF::useNistSP800_108KDF(nistSP800_108KdfOnKeyVersion_byte, requestedKeyVersion_byte) == true){

                    PR_fprintf(PR_STDOUT,"EncryptData NistSP800_108KDF code: Using NIST SP800-108 KDF.\n");

                    // react to "UseCUIDAsKDD" setting value
                    jbyte* context_jbyte = NULL;
                    jsize context_len_jsize = 0;
                    if (nistSP800_108KdfUseCuidAsKdd == JNI_TRUE){
                        context_jbyte = cuidValue;
                        context_len_jsize = cuidValue_len;
                    }else{
                        context_jbyte = kddValue;
                        context_len_jsize = kddValue_len;
                    }

                    // Converting this way is safe since jbyte is guaranteed to be 8 bits
                    // Of course, this assumes that "char" is 8 bits (not guaranteed, but typical),
                    //            but it looks like this assumption is also made in GetDiversificationData
                    const BYTE* const context = reinterpret_cast<const BYTE*>(context_jbyte);

                    // Convert jsize to size_t
                    const size_t context_len = static_cast<size_t>(context_len_jsize);
                    if (context_len > 0x000000FF){  // sanity check (CUID should never be larger than 255 bytes)
                        PR_fprintf(PR_STDERR, "EncryptData NistSP800_108KDF code: Error; context_len larger than 255 bytes.\n");
                        goto done;
                    }

                    // call NIST SP800-108 KDF routine
                    try{
                        NistSP800_108KDF::ComputeCardKeys(masterKey, context, context_len, &encKey, &macKey, &kekKey);
                    }catch(std::runtime_error& ex){
                        PR_fprintf(PR_STDERR, "EncryptData NistSP800_108KDF code: Exception invoking NistSP800_108KDF::ComputeCardKeys: ");
                        PR_fprintf(PR_STDERR, "%s\n", ex.what() == NULL ? "null" : ex.what());
                        goto done;
                    }catch(...){
                        PR_fprintf(PR_STDERR, "EncryptData NistSP800_108KDF code: Unknown exception invoking NistSP800_108KDF::ComputeCardKeys.\n");
                        goto done;
                    }

                // if not a key version where we use the NIST SP800-108 KDF, use the original KDF
                }else{

                    PR_fprintf(PR_STDOUT,"EncryptData NistSP800_108KDF code: Using original KDF.\n");

                    // AC: KDF SPEC CHANGE: Moved this call down from the original location.
                    //                      (We don't always need to call it anymore; it depends on the KDF we're going to use.)
                    //
                    // Note the change from "cuidValue" to "kddValue".
                    //   This change is necessary due to the semantics change in the parameters passed between TPS and TKS.
                    GetDiversificationData(kddValue,kekData,kek);

                    // AC: Derives the Kek key for the token.
                    kekKey = ComputeCardKeyOnToken(masterKey,kekData);

                } // endif use original KDF
                // ---------------------------------


                if (kekKey != NULL)
                {
                    Buffer input = Buffer((BYTE*)cc, cc_len);
                    status = EncryptData(Buffer(), kekKey, input, out);
                }
            }
        }
    }

done:

    if (masterKey != NULL) {
        PK11_FreeSymKey( masterKey);
        masterKey = NULL;
    }

    if( slot != NULL ) {
        PK11_FreeSlot( slot);
        slot = NULL;
    }

    if( internal != NULL) {
       PK11_FreeSlot( internal);
       internal = NULL;
    }

    // AC: KDF SPEC CHANGE:  For the NIST SP800-108 KDF, we build all 3 keys despite only using one of them (Kek) in this function.
    //                       We do this because our NIST SP800-108 KDF outputs the data for all three keys simultaneously.
    if( macKey ) {
        PK11_FreeSymKey(macKey);
        macKey = NULL;
    }
    if ( encKey ) {
        PK11_FreeSymKey(encKey);
        encKey = NULL;
    }
    if ( kekKey != NULL) {
        PK11_FreeSymKey( kekKey);
        kekKey = NULL;
    }

    if( keySetStringChars ) {
        (env)->ReleaseStringUTFChars(keySet, (const char *)keySetStringChars);
        keySetStringChars = NULL;
    }

    jbyteArray handleBA=NULL;
    if (status != PR_FAILURE && (out.size()>0) ) {
        jbyte *handleBytes=NULL;
        handleBA = (env)->NewByteArray( out.size());
        handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
        BYTE* outp = (BYTE*)out;
        memcpy(handleBytes, outp,out.size());
        env->ReleaseByteArrayElements( handleBA, handleBytes, 0);
        handleBytes=NULL;
    }

    if( cc != NULL) {
        env->ReleaseByteArrayElements(j_in, cc, JNI_ABORT);
    }

    if( keyVersion != NULL) {
        env->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
    }

    if( cuidValue != NULL) {
        env->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
    }

    // AC: KDF SPEC CHANGE:  Need to retrieve KDD as well as CUID from JNI.
    if ( kddValue != NULL){
        env->ReleaseByteArrayElements(KDD, kddValue, JNI_ABORT);
        kddValue = NULL;
    }

    return handleBA;
}