What is the right error code of C_DeriveKey if the derivation key has CKA_DERIVE=0 - pkcs#11

I am developer of the PKCS#11 library. I think that the function C_DeriveKey should fail with the error code
CKR_KEY_FUNCTION_NOT_PERMITTED
if the key has CKA_DERIVE=0.But this error code is not listed as a possible return value for C_DeriveKey in the specification document . What is the right error code to be returned by C_DeriveKey in this case?

I agree that the specification is not very clear on this case. There is a newer version of the specification available (v3.0 from March 2020, link), but it does not bring more clarity on this. I would make the following considerations:
General note on return values
The introduction on return values in section 5.1 gives the following disclaimer (link):
Because of the complexity of the Cryptoki specification, it is recommended that Cryptoki applications attempt to give some leeway when interpreting Cryptoki functions’ return values. We have attempted to specify the behavior of Cryptoki functions as completely as was feasible; nevertheless, there are presumably some gaps. For example, it is possible that a particular error code which might apply to a particular Cryptoki function is unfortunately not actually listed in the description of that function as a possible error code.
The last part directly acknowledges that the list of possible return values for each function may be incomplete. For that reason, C_DeriveKey not listing CKR_KEY_FUNCTION_NOT_PERMITTED as a possible return code may not be authoritative, if there are other reasons for why the function should return this value.
Definition of the return codes
Section 5.1.6 gives the following definitions (link):
CKR_KEY_FUNCTION_NOT_PERMITTED: An attempt has been made to use a key for a cryptographic purpose that the key’s attributes are not set to allow it to do. For example, to use a key for performing encryption, that key MUST have its CKA_ENCRYPT attribute set to CK_TRUE (the fact that the key MUST have a CKA_ENCRYPT attribute implies that the key cannot be a private key). This return value has lower priority than CKR_KEY_TYPE_INCONSISTENT.
CKR_KEY_TYPE_INCONSISTENT: The specified key is not the correct type of key to use with the specified mechanism. This return value has a higher priority than CKR_KEY_FUNCTION_NOT_PERMITTED.
From this definition I would conclude that CKR_KEY_TYPE_INCONSISTENT is not the right return code for the scenario we are discussing, because it relates the mechanism to the "type" of the key. If we understand "type" in the sense of CKA_KEY_TYPE, it is completely unrelated to the attribute CKA_DERIVE.
Moreover, the attribute CKA_ENCRYPT is given as an example in the definition of CKR_KEY_FUNCTION_NOT_PERMITTED. This attribute is very similar to CKA_DERIVE, i.e. CKA_ENCRYPT controlling whether the key can be used for encryption and CKA_DERIVE controlling whether the key can be used for deriving. Thus, if CKR_KEY_FUNCTION_NOT_PERMITTED is the right return code for the case when CKA_ENCRYPT is not set, it seems reasonable that it would also be the right return code for the case when CKA_DERIVE is not set.
Reference implementations
I looked at some PKCS#11 libraries to check how they handle the case that C_DeriveKey is called on a key with CKA_DERIVE set to CK_FALSE. Most of the implementations I found do not implement the C_DeriveKey function at all (i.e. they always return CKR_FUNCTION_NOT_SUPPORTED). For the libraries that do implement this function, I observed the following behaviors:
OpenSC returns CKR_KEY_TYPE_INCONSISTENT (reference):
CK_ATTRIBUTE derive_attribute = { CKA_DERIVE, &can_derive, sizeof(can_derive) };
...
rv = object->ops->get_attribute(session, object, &derive_attribute);
if (rv != CKR_OK || !can_derive) {
rv = CKR_KEY_TYPE_INCONSISTENT;
goto out;
}
I also checked how OpenSC handles the other attributes that are similar to CKA_DERIVE. It seems the C_EncryptInit function is not implemented in OpenSC (presumably because this is a public key operation?), but C_DecryptInit is. This function implements a check for CKA_DECRYPT (reference), but returns CKR_KEY_TYPE_INCONSISTENT, which goes against the example that was given in the specification of CKR_KEY_FUNCTION_NOT_PERMITTED.
SoftHSMv2 returns CKR_KEY_FUNCTION_NOT_PERMITTED (reference):
// Check if key can be used for derive
if (!key->getBooleanValue(CKA_DERIVE, false))
return CKR_KEY_FUNCTION_NOT_PERMITTED;
openCryptoki: I could not find any check for CKA_DERIVE. They do check CKF_DERIVE against the feature flags of the mechanism and return CKR_MECHANISM_INVALID if the flag is not set (reference), i.e. if the mechanism does not support derivation, but this is not the same as checking CKA_DERIVE against the flags of the key.
illumos-gate (IllumOS being a fork of the discontinued OpenSolaris) also returns CKR_KEY_FUNCTION_NOT_PERMITTED in their soft-key implementation (reference):
/* Check to see if key object allows for derivation. */
if (!(basekey_p->bool_attr_mask & DERIVE_BOOL_ON)) {
rv = CKR_KEY_FUNCTION_NOT_PERMITTED;
goto clean_exit1;
}
Interestingly, in older version of their code they returned CKR_KEY_TYPE_INCONSISTENT instead, and then changed it to CKR_KEY_FUNCTION_NOT_PERMITTED in this commit. The relevant part of the commit message seems to be 6177650 Wrong error code returned when key does not allow requested operation. The ID refers to a ticket in the OpenSolaris bug tracker, which is no longer online. There is an archive of the bug tracker here, but it does not contain any information on this ticket, unfortunately.
Of these reference implementations, I would consider OpenSC to be the most authoritative, in terms of how widely they are used.
Conclusion
Based on the above considerations, I would consider CKR_KEY_FUNCTION_NOT_PERMITTED to be the appropriate return code for the scenario we are discussing. This is supported by the following arguments:
The specification explicitly acknowledges that the list of possible return code for each function might be incomplete. Therefore, CKR_KEY_FUNCTION_NOT_PERMITTED not being listed for C_DeriveKey is not a strong counter-argument.
The specification explicitly lists CKA_ENCRYPT as an example for when CKR_KEY_FUNCTION_NOT_PERMITTED is an appropriate return code. The attribute CKA_ENCRYPT is similar to CKA_DERIVE, so it seems plausible that the return code is also appropriate for CKA_DERIVE.
The specification of CKR_KEY_TYPE_INCONSISTENT suggest that it is about the relation between the mechanism and the key type, not about other key attributes.
OpenSC uses CKR_KEY_TYPE_INCONSISTENT for the scenario we are discussing, but also uses this return code for C_DecryptInit in the case that CKA_DECRYPT is not set, which goes against the example given in the specification of CKR_KEY_FUNCTION_NOT_PERMITTED.
OpenSolaris/IllumOS deliberately switched from CKR_KEY_TYPE_INCONSISTENT to CKR_KEY_FUNCTION_NOT_PERMITTED as the return code for the scenario we are discussing. This suggests they also considered the latter the more fitting return code.

Related

how to understand mongoDB Api method requirements?

i was following along a youtube tutorial video for mongoDB.
the method used was deleteMany from the collection class
and the code was:
function deleteManyItems(MyMongoClient){
var mydb = MyMongoClient.db('school');
var myColl = mydb.collection('students');
myColl.deleteMany(function(error, result){
if(error){
console.log('Sorry unable to delete items');
}else{
console.log(result);
}
})
Although the above code worked,iam a bit confused becasue the official docs for the method say there should be a "filter". And my code worked without the filter:
deleteMany(filter, options, callback)
Delete multiple documents from a collection
lib/collection.js, line 945
My question is how do you know when reading the API documentations what is compulsory and what is not, as it doesn't say in the documentation. is it something you have to figure out by experimenting?
The docs should say which parameters are required. You shouldn't need to guess.
But, they don't as far as I can tell.
Thus, you have to figure out the proper usage the hard way (trial and error or referencing other resources).
Note that in JavaScript, in general:
The language syntax permits invoking any function with any number of parameters. Therefore, in the example you gave, the following invocations would be allowed by the language:
deleteMany()
deleteMany(filter)
deleteMany(filter, options)
deleteMany(filter, options, callback)
deleteMany(filter, options, callback, ignoredParameter)
Despite the language allowing all those invocations, the implementation of the particular method may not. For example, providing 4 parameters like the last example may work the same as providing 3 parameters or it might fail with various errors.
The callback is often the last parameter.
Parameters named options can often be omitted.
If a method accepts a callback, the callback is often allowed to be the last parameter even when it technically violates the documented invocation, for example:
deleteMany(filter, callback)
These conventions don't have to be obeyed by any particular library, therefore they should be documented in the documentation attached to the library.
The documentation for deleteMany states that options is optional but does not state that filter is optional. Therefore, it appears to incorrectly claim that filter is required whereas it really isn't.

How to handle jOOQ depreciation warning on procedure that returns a trigger?

I use the following stored procedure to maintain the edit time on a few tables via triggers on those tables:
CREATE OR REPLACE FUNCTION maintain_edit_time()
RETURNS TRIGGER AS $t_edit_time$
BEGIN
NEW.edit_timestamp = NOW();
RETURN NEW;
END;
$t_edit_time$ LANGUAGE plpgsql;
When generating jOOQ objects for the database in question, I get the following generated code:
/**
* #deprecated Unknown data type. Please define an explicit {#link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
*/
#java.lang.Deprecated
public static Object maintainEditTime(Configuration configuration) {
MaintainEditTime f = new MaintainEditTime();
f.execute(configuration);
return f.getReturnValue();
}
/**
* #deprecated Unknown data type. Please define an explicit {#link org.jooq.Binding} to specify how this type should be handled. Deprecation can be turned off using <deprecationOnUnknownTypes/> in your code generator configuration.
*/
#java.lang.Deprecated
public static Field<Object> maintainEditTime() {
MaintainEditTime f = new MaintainEditTime();
return f.asField();
}
I assume this is because I do not have a jOOQ binding between TRIGGER and a Java object. However, I do not have a clue what I would define this binding as, nor do I have any need for a binding to exist.
Left alone, though, this generates a compile warning. What's the cleanest, easiest way to resolve this?
Options seem to include turning off deprecation, using ignoreProcedureReturnValues, or creating a binding. Ideally, I'd like to simply not generate a Java object for this procedure, but I could not find a way to do that.
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.
Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.
You've already found the perfect solution, which you documented in your own answer. I'll answer your various other questions here, for completeness' sake
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.
That flag has been introduced because of a backwards incompatible change in the code generator that affected only SQL Server: https://github.com/jOOQ/jOOQ/issues/4106
In SQL Server, procedures always return an INT value, just like functions. This change allowed for fetching this INT value using jOOQ generated code. In some cases, it was desireable to not have this feature enabled when upgrading from jOOQ 3.5 to 3.6. Going forward, we'll always generate this INT return type on SQL Server stored procedures.
This is why the flag has been deprecated from the beginning, as we don't encourage its use, except for backwards compatibility usage. It probably won't help you here.
Stored procedure support is definitely not going to be deprecated.
Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.
Why not. A quick workaround. You don't have to use all the generated code. The deprecation is there to indicate that calling this generated procedure probably won't work out of the box, so its use is discouraged.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.
Indeed, that wouldn't really add much value to your use cases as you will never directly call the trigger function in PostgreSQL.
Again, your own solution using <exclude> is the ideal solution here. In the future, we might offer a new code generation configuration flag that allows for turning on/off the generation of trigger functions, with the default being off: https://github.com/jOOQ/jOOQ/issues/9270
Well, after noting that an ideal way to do this would be to ignore that procedure, I did find how to ignore the procedure by name in the generally excellent jOOQ website documentation. Don't know how I missed in on first pass. If I needed to call this procedure in Java, I'm unclear which of the above options I would have used.
Luckily, there was no need for this procedure to be referenced in code, and I excluded it as shown below in in the jOOQ XML configuration.
<excludes>
databasechangelog.*
| maintain_edit_time
</excludes>

Using Conditional Syntax (Overrides) in BitBake

Reading a book on Yocto. Got to the following page, which says:
BitBake provides a very easy-to-use way to write conditional metadata.
It is done by a mechanism called overrides.
The OVERRIDES variable contains values separated by colons (:), and
each value is an item we want to satisfy conditions. So, if we have a
variable that is conditional on arm, and arm is in OVERRIDES, then the
version of the variable that is specific to arm is used rather than
the non-conditional version, as shown:
OVERRIDES = "architecture:os:machine"
TEST = "defaultvalue"
TEST_os = "osspecificvalue"
TEST_other = "othercondvalue"
In this example, TEST will be osspecificvalue due to the condition
of os being in OVERRIDES.
I'm unclear from this explanation how did TEST become equal to osspecificvalue. Would someone be able to explain it?
Bitbake implements it's own dictionary data structure based on Python's MutableMapping in lib/bb/data_smart.py. The goal is to create a dictionary with more flexibility in that each value in the "key,value" pair can be overridden based on specific identifiers.
If you look at how the variables in this dictionary are set, you will see that the datastore allows "overrides" of variables based on a list of override identifiers. These identifiers are expected to be appended with an underscore, like in your example of "TEST_os".
In the case you are referencing, "other" identifier is not in the list of OVERRIDES, so this "smart dictionary" does not override the value of TEST with "othercondvalue". However, because the "os" identifier is in the list of OVERRIDES, the value of TEST is indeed overridden with the value "osspecificvalue".
I would highly recommend reading through the DataSmart class as this is a very simplified explanation, but hopefully it helps.
Also, see the BitBake manual entry for OVERRIDES for more information.

What will be the return value of C_CreateObject(in PKCS#11) if token not supported?

I am working on a library which follows PKCS#11 standard.
https://www.cryptsoft.com/pkcs11doc/v220/
The library can generate RSA Keypair in token by the function C_GenerateKeyPair and returns appropriate object handles with return value CKR_OK.
The token(applet) not supports load of private/public key except generate key pair. What will be the appropriate return value of create RSA private/public key using C_CreateObject?
Now I am returning CKR_GENERAL_ERROR, is it okay?
Allowed return values are
CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY,
CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID,
CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY,
CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_FAILED,
CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_PIN_EXPIRED,
CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY,
CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT,
CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Thanks for your help
Update
I have two types of applet, one supports load of RSA private/public key to token and another not supports. It can only possible to identify if the token supports load of key is the response of transmitted APDU. So I can't take decision only to check the class attribute of C_CreateObject.
If your library does not support C_CreateObject at all then the best choice IMO is CKR_FUNCTION_NOT_SUPPORTED.
Chapter 11 in PKCS#11 v2.20 states:
A Cryptoki library need not support every function in the Cryptoki API. However, even an unsupported function must have a "stub" in the library which simply returns the value CKR_FUNCTION_NOT_SUPPORTED.
If your library does support C_CreateObject for creation of other object types (e.g. certificates, data objects etc.) then the best choice IMO is CKR_ATTRIBUTE_VALUE_INVALID.
Chapter 10.1.1 in PKCS#11 v2.20 states:
If the supplied template specifies an invalid value for a valid attribute, then the attempt should fail with the error code CKR_ATTRIBUTE_VALUE_INVALID.
UPDATE
Now that you have shared more details about your library in the comments I can add more detailed explanation:
It seems I can call your implementation of C_CreateObject with template containing CKA_CLASS=CKO_CERTIFICATE and it will create certificate object on this particular token and return CKR_OK. If I call it with template containing CKA_CLASS=CKO_PRIVATE_KEY then your code will decide to return an error right after the evaluation of the supplied value of this attribute. IMO there is no doubt that chapter 10.1.1 of PKCS#11 v2.20 recommends you to return CKR_ATTRIBUTE_VALUE_INVALID in this case.
However if are not willing to follow behavior recommended by the specification and there is no predefined error code you like, you can introduce your own vendor defined code (see my older answer for more details):
#define CKR_TOKEN_OPERATION_NOT_SUPPORTED (CKR_VENDOR_DEFINED|0x0000001)
IMO confusion level for inexperienced developer will be the same regardless of error code you return. In the end he/she will need to consult your documentation or logs produced by your library to find out the real reason why he/she received the error.

What is to prefer in Restlet: handleGet, handlePost OR represent, acceptRepresetation?

IMHO, there are two techiques to handle a query for a resource:
For http GET you can override represent(Variant variant) or handleGet().
For http POST the same applies with acceptRepresentation(Representation entity) and handlePost().
The doc for handleGet says:
Handles a GET call by automatically returning the best representation available. The content negotiation is automatically supported based on the client's preferences available in the request. This feature can be turned off using the "negotiateContent" property.
and for represent:
Returns a full representation for a given variant previously returned via the getVariants() method. The default implementation directly returns the variant in case the variants are already full representations. In all other cases, you will need to override this method in order to provide your own implementation.
What are the main differences between these two types of implementations? In which case should I prefer one over the other? Is it right that I can achieve with e.g. handleGet() everything that would work with represent()?
I first started using handleGet setting the entity for the response. When I implemented another project I used represent. Looking back i can't really say one way is better or clearer than the other. What are your expirences for that?
I recommend using represent(Variant) because then you’ll be leveraging the content negotiation functionality provided by the default implementation of handleGet(Request, Response).
BTW, lately I've started using the annotation-based syntax instead of overriding superclass methods, and I like it. I find it clearer, simpler, and more flexible.
For example:
#Post('html')
Representation doSearch(Form form) throws ResourceException {
// get a field from the form
String query = form.getFirstValue("query");
// validate the form - primitive example of course
if (query == null || query.trim().length() == 0)
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Query is required.");
// do something
SearchResults searchResults = SearchEngine.doSearch(query);
// return a HTML representation
return new StringRepresentation(searchResults.asHtmlString(), MediaType.TEXT_HTML);
}
The advantages of using this approach include the incoming representation being automatically converted to a useful form, the method can be named whatever makes sense for your application, and just by scanning the class you can see which class methods handle which HTTP methods, for what kind of representations.