WinVerifyTrust returns CERT_E_UNTRUSTEDROOT for a valid (loaded) driver - certificate

In the following code snippet, WinVerifyTrust returns CERT_E_UNTRUSTEDROOT for a kernel driver file (.sys) that is loaded and running on the system:
GUID guidAction = DRIVER_ACTION_VERIFY;
WINTRUST_FILE_INFO sWintrustFileInfo = { 0 };
WINTRUST_DATA sWintrustData = { 0 };
HRESULT hr = 0;
sWintrustFileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
sWintrustFileInfo.pcwszFilePath = argv[1];
sWintrustFileInfo.hFile = NULL;
sWintrustData.cbStruct = sizeof(WINTRUST_DATA);
sWintrustData.dwUIChoice = WTD_UI_NONE;
sWintrustData.fdwRevocationChecks = WTD_REVOKE_NONE;
sWintrustData.dwUnionChoice = WTD_CHOICE_FILE;
sWintrustData.pFile = &sWintrustFileInfo;
sWintrustData.dwStateAction = WTD_STATEACTION_VERIFY;
hr = WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &guidAction, &sWintrustData);
A few interesting points:
- The driver is signed with a valid (purchased) certificate using SHA-256.
- KB3033929 is installed on the system (Win7/32)
- When viewing the certificate from the file properties, the entire certification chain shows up as valid
Am I calling WinVerifyTrust wrong?
Alternative question: is there another way of knowing (by the presence of a registry key or something similar) that SHA-256 based code signing verification is available on the target system? (I need to verify this during installation...)
Thanks :)

DRIVER_ACTION works good for WHQL afaik. Try
GUID WINTRUST_ACTION_GENERIC_VERIFY_V2
Here is something else you can refer to
http://gnomicbits.blogspot.in/2016/03/how-to-verify-pe-digital-signature.html

Related

Generate digest/ binary blob for XRP raw transaction using rippled c++ library

I have an offline signing code to which I need to pass the digest or the binary blob to get the signature. Looks like the digest I have produced is not right as when I try to submit the serialized signature, it complains of "fails local checks: Invalid signature." Here are the steps, I am doing to generate the digest/binary blob
STTx noopTx(ttPAYMENT,
[&](auto& obj)
{
// General transaction fields
obj[sfAccount] = id;
obj[sfFee] = STAmount(XRPAmount(fee));
obj[sfFlags] = tfFullyCanonicalSig;
obj[sfSequence] = sequence;
obj[sfSigningPubKey] = pub_key.slice();
// Payment-specific fields
obj[sfAmount] = STAmount(XRPAmount(amount));
obj[sfDestination] = *to_account;
obj[sfSendMax] = STAmount(XRPAmount(amount));
});
ripple::uint256 hash256 = noopTx.getSigningHash();
output:
0861970E8AAC8539600E2FB9169774F303A29C3B8CA98FF9206C9B958C681ACF
Please can someone tell me if I am missing any field that is needed?.

Create WS security headers for REST web service in SoapUI Pro

We are developing a REST web service with the WS security headers to be passed through as header parameters in the REST request.
I am testing this in SoapUI Pro and want to create a groovy script to generate these and then use them in the REST request.
These parameters include the password digest, encoded nonce and created dateTime and password digest which is created from encoding the nonce, hashed password and created date and time, i.e. the code should be the same as that which generates these from using the Outgoing WS Security configurations in SoapUI Pro.
I have created a groovy test script in Soap UI Pro (below). However when I supply the created values to the headers I get authorisation errors.
I am able to hash the password correctly and get the same result a my python script.
Groovy code for this is ..
MessageDigest cript = MessageDigest.getInstance("SHA-1");
cript.reset();
cript.update(userPass.getBytes("UTF-8"));
hashedpw = new String(cript.digest());
This correctly hashes the text 'Password2451!' to í¦è~µ”t5Sl•Vž³t;$.
The next step is to create a password digest of the nonce the created time stamp and the hashed pasword. I have the following code for this ...
MessageDigest cript2 = MessageDigest.getInstance("SHA-1");
cript2.reset();
cript2.update((nonce+created+hashedpw).getBytes("UTF-8"));
PasswordDigest = new String(cript2.digest());
PasswordDigest = PasswordDigest.getBytes("UTF-8").encodeBase64()
This converts '69999998992017-03-06T16:19:28Zí¦è~µ”t5Sl•Vž³t;$' into w6YA4oCUw6nDicucw6RqxZMIbcKze+KAmsOvBA4oYu+/vQ==.
However the correct value should be 01hCcFQRjDKMT6daqncqhN2Vd2Y=.
The following python code correctly achieves this conversion ...
hashedpassword = sha.new(password).digest()
digest = sha.new(nonce + CREATIONDATE + hashedpassword).digest()
Can anyone tell me where I am going wrong with the groovy code?
Thanks.
changing my answer slightly as in original I was converting the pasword digest to a string value which caused the request to not validate some of the time as certain bytes did not get converted into the correct string value.
import java.security.MessageDigest;
int a = 9
nonce = ""
for(i = 0; i < 10; i++)
{
random = new Random()
randomInteger= random.nextInt(a)
nonce = nonce + randomInteger
}
Byte[] nonceBytes = nonce.getBytes()
def XRMGDateTime = new Date().format("yyyy-MM-dd'T'HH:mm:ss", TimeZone.getTimeZone( 'BTC' ));
Byte[] creationBytes = XRMGDateTime.getBytes()
def password = testRunner.testCase.testSuite.getPropertyValue( "XRMGPassword" )
EncodedNonce = nonce.getBytes("UTF-8").encodeBase64()
MessageDigest cript = MessageDigest.getInstance("SHA-1");
cript.reset();
cript.update(password.getBytes());
hashedpw = cript.digest();
MessageDigest cript2 = MessageDigest.getInstance("SHA-1");
cript2.update(nonce.getBytes());;
cript2.update(XRMGDateTime.getBytes());
cript2.update(hashedpw);
PasswordDigest = cript2.digest()
EncodedPasswordDigest = PasswordDigest.encodeBase64();
def StringPasswordDigest = EncodedPasswordDigest.toString()
def encodedNonceString = EncodedNonce.toString()
testRunner.testCase.setPropertyValue( "passwordDigest", StringPasswordDigest )
testRunner.testCase.setPropertyValue( "XRMGDateTime", XRMGDateTime )
testRunner.testCase.setPropertyValue( "XRMGNonce", encodedNonceString )
testRunner.testCase.setPropertyValue( "Nonce", nonce )

simulink - GetSet Custom Storage Class

I am having a model which takes two input & multiplies them & give the output.
output_1 = input_1 * input_2
I have declared my simulink signals as CustomStorageClass= GetSet
input_1 = Simulink.Signal;
input_1.CoderInfo.StorageClass = 'Custom';
input_1.CoderInfo.CustomStorageClass = 'GetSet';
input_1.CoderInfo.CustomAttributes.GetFunction = 'Get_input_1';
input_1.CoderInfo.CustomAttributes.SetFunction = 'Set_input_1';
input_1.CoderInfo.CustomAttributes.HeaderFile = 'signals.h';
input_2 = Simulink.Signal;
input_2.CoderInfo.StorageClass = 'Custom';
input_2.CoderInfo.CustomStorageClass = 'GetSet';
input_2.CoderInfo.CustomAttributes.GetFunction = 'Get_input_2';
input_2.CoderInfo.CustomAttributes.SetFunction = 'Set_input_2';
input_2.CoderInfo.CustomAttributes.HeaderFile = 'signals.h';
output_1 = Simulink.Signal;
output_1.CoderInfo.StorageClass = 'Custom';
output_1.CoderInfo.CustomStorageClass = 'GetSet';
output_1.CoderInfo.CustomAttributes.GetFunction = 'Get_output_1';
output_1.CoderInfo.CustomAttributes.SetFunction = 'Set_output_1';
output_1.CoderInfo.CustomAttributes.HeaderFile = 'signals.h';
Now I am trying to convert my model to code using simulink coder.
In code generation setting of the model i have selected ert.tlc file in the system target file settings.
But the generated code does not have a Get_input_1() or Get_input_2() call like shown in this link.
http://www.mathworks.com/help/ecoder/ug/getset-custom-storage-classes.html
What i have missed in the setting. Please suggest
I know you probably already solved this issue, but I have also seen this behavior before.
Sometimes MATLAB does not update the header files correctly. If you had set a different configuration for your variable and then made a change involving the header files, I would recommend erasing the *_ert_rtw and slprj folders (they will appear again). It is similar to doing a "Make clean" operation, to ensure that everything is brand new.

Problem reading Serial Port C#.net 2.0 to get Weighing machine output

I'm trying to read weight from Sartorius Weighing Scale model No BS2202S using the following code in C#.net 2.0 on a Windows XP machine:
public string readWeight()
{
string lastError = "";
string weightData = "";
SerialPort port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 9600;
port.Parity = Parity.Even;
port.DataBits = 7;
port.StopBits = StopBits.One;
port.Handshake = Handshake.RequestToSend;
try {
port.Open();
weightData = port.ReadExisting();
if(weightData == null || weightData.Length == 0) {
lastError = "Unable to read weight. The data returned form weighing machine is empty or null.";
return lastError;
}
}
catch(TimeoutException) {
lastError = "Operation timed out while reading weight";
return lastError;
}
catch(Exception ex) {
lastError = "The following exception occurred while reading data." + Environment.NewLine + ex.Message;
return lastError;
}
finally {
if(port.IsOpen == true) {
port.Close();
port.Dispose();
}
}
return weightData;
}
I'm able to read the weight using Hyperterminal application (supplied with Windows XP) with the same serial port parameters given above for opening the port. But from the above code snippet, I can open the port and each time it is returning empty data.
I tried opening port using the code given this Stack Overflow thread, still it returns empty data.
Kindly assist me.
I know this is probably old now ... but for future reference ...
Look at the handshaking. There is both hardware handshaking and software handshaking. Your problem could be either - so you need to try both.
For hardware handshaking you can try:
mySerialPort.DtrEnable = True
mySerialPort.RtsEnable = True
Note that
mySerialPort.Handshake = Handshake.RequestToSend
I do not think sets the DTR line which some serial devices might require
Software handshaking is also known as XON/XOFF and can be set with
mySerialPort.Handshake = Handshake.XOnXOff
OR
mySerialPort.Handshake = Handshake.RequestToSendXOnXOff
You may still need to enable DTR
When all else fails - dont forget to check all of these combinations of handshaking.
Since someone else will probably have trouble with this in the future, hand shaking is a selectable option.
In most of the balances you will see the options for Software, Hardware 2 char, Hardware 1 char. The default setting for the Sartorius balances is Hardware 2 Char. I usually recommend changing to Software.
Also if it stops working all together it can often be fixed by defaulting the unit using the 9 1 1 parameter. And then resetting the communication settings.
An example of how to change the settings can be found on the manual on this page:
http://www.dataweigh.com/products/sartorius/cpa-analytical-balances/

How to create chrome crx file programmatically (preferably in java)?

I want to create chrome extension crx file programatically (not using chrome.exe, because it opens new chrome window). So what are the alternatives for same ? My preference is java, but if its possible in other language then also I am okay.
As kylehuff stated, there are external tools that you could use. But you can always use the command line from Google Chrome to do that which is cross platform (Linux / Windows / Mac).
chrome.exe --pack-extension=[extension_path] --pack-extension-key=[extension_key]
--pack-extension is:
Package an extension to a .crx installable file from a given directory.
--pack-extension-key is:
Optional PEM private key is to use in signing packaged .crx.
The above does not run Google Chrome, it is just command line packing using Chromium's core crx algorithm that they use internally.
There is a variety of utilities to do this, in various languages (albeit; they are mostly shell/scripting languages)
I cannot post the links to all of them, because I am a new stackoverflow user - I can only post 1 link, so I created a page which lists them all - including the one C one I speak about below - http://curetheitch.com/projects/buildcrx/6/
Anyway, I spent a few hours and put together a version in C which runs on Windows or Linux, as the other solutions require installation of a scripting language or shell (i.e. python, ruby, bash, etc.) and OpenSSL. The utility I wrote has OpenSSL statically linked so there are no interpreter or library requirements.
The repository is hosted on github, but the link above has a list of my utility and other peoples solutions.
Nothing listed for Java, which was your preference, but hopefully that helps!
//Method to generate .crx. signature
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Signature;
//#param : extenstionContents is your zip file ,
//#returns : byte[] of the signature , use ByteBuffer to merge them and you have your
// .crx
public static byte[] generateCrxHeader(byte[] extensionContents) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
Signature sigInstance = Signature.getInstance("SHA1withRSA");
sigInstance.initSign(pair.getPrivate());
sigInstance.update(extensionContents);
byte [] signature = sigInstance.sign();
byte [] subjectPublicKeyInfo = pair.getPublic().getEncoded();
final int headerLength = 4 + 4 + 4 + 4 + subjectPublicKeyInfo.length + signature.length;
ByteBuffer headerBuf = ByteBuffer.allocate(headerLength);
headerBuf.order(ByteOrder.LITTLE_ENDIAN);
headerBuf.put(new byte[]{0x43,0x72,0x32,0x34}); // Magic number
headerBuf.putInt(2); // Version
headerBuf.putInt(subjectPublicKeyInfo.length); // public key length
headerBuf.putInt(signature.length); // signature length
headerBuf.put(subjectPublicKeyInfo);
headerBuf.put(signature);
final byte [] header = headerBuf.array();
return header;
}
I needed to do this in Ruby. JavaHead's answer looks nice for Java for CRX2. The current format is CRX v3 and header is protobuf based. I wrote a blog for packing an extension with Ruby. There is also a python project from another author.
I'll paste Ruby version of CRX2 and CRX3 methods for packing extensions for a reference here. For complete code see my blog.
So CRX3 method:
def self.header_v3_extension(zipdata, key: nil)
key ||= OpenSSL::PKey::RSA.generate(2048)
digest = OpenSSL::Digest.new('sha256')
signed_data = Crx_file::SignedData.new
signed_data.crx_id = digest.digest(key.public_key.to_der)[0...16]
signed_data = signed_data.encode
signature_data = String.new(encoding: "ASCII-8BIT")
signature_data << "CRX3 SignedData\00"
signature_data << [ signed_data.size ].pack("V")
signature_data << signed_data
signature_data << zipdata
signature = key.sign(digest, signature_data)
proof = Crx_file::AsymmetricKeyProof.new
proof.public_key = key.public_key.to_der
proof.signature = signature
header_struct = Crx_file::CrxFileHeader.new
header_struct.sha256_with_rsa = [proof]
header_struct.signed_header_data = signed_data
header_struct = header_struct.encode
header = String.new(encoding: "ASCII-8BIT")
header << "Cr24"
header << [ 3 ].pack("V") # version
header << [ header_struct.size ].pack("V")
header << header_struct
return header
end
And for historic purposes (this one verified) CRX2:
# #note original crx2 format description https://web.archive.org/web/20180114090616/https://developer.chrome.com/extensions/crx
def self.header_v2_extension(zipdata, key: nil)
key ||= OpenSSL::PKey::RSA.generate(2048)
digest = OpenSSL::Digest.new('sha1')
header = String.new(encoding: "ASCII-8BIT")
signature = key.sign(digest, zipdata)
signature_length = signature.length
pubkey_length = key.public_key.to_der.length
header << "Cr24"
header << [ 2 ].pack("V") # version
header << [ pubkey_length ].pack("V")
header << [ signature_length ].pack("V")
header << key.public_key.to_der
header << signature
return header
end
I have used the excellent service crx-checker to validate both - v2 and v3 extension packing. Where I'm getting the expected RSASSA-PKCS1-v1_5 signature marked (Signature OK) (Developer Signature).
The extension will fail to load with CRX_REQUIRED_PROOF_MISSING if you try to add to your browser from URL because it will be lacking Google signature. But it will be loaded fine by Selenium when running test. To load normally you need to publish on web store.