Crypto: "Error: PEM_read_bio_PUBKEY failed" - cryptography

An error is thrown by xml-crypto in the function "verify-signature", and I don't understand why:
Error: PEM_read_bio_PUBKEY failed
at Error (native)
at Verify.verify (crypto.js:311:23)
at RSASHA256.verifySignature (/home/git/backend/node_modules/xml-crypto/lib/signed-xml.js:137:24)
at SignedXml.validateSignatureValue (/home/git/backend/node_modules/xml-crypto/lib/signed-xml.js:273:20)
at SignedXml.checkSignature (/home/git/backend/node_modules/xml-crypto/lib/signed-xml.js:261:13)
at SAML.validateSignature (/home/git/backend/node_modules/passport-saml/lib/passport-saml/saml.js:498:14)
at /home/git/backend/node_modules/passport-saml/lib/passport-saml/saml.js:545:17
at _fulfilled (/home/git/backend/node_modules/passport-saml/node_modules/q/q.js:794:54)
at self.promiseDispatch.done (/home/git/backend/node_modules/passport-saml/node_modules/q/q.js:823:30)
at Promise.promise.promiseDispatch (/home/git/backend/node_modules/passport-saml/node_modules/q/q.js:756:13)
at /home/git/backend/node_modules/passport-saml/node_modules/q/q.js:516:49
at flush (/home/git/backend/node_modules/passport-saml/node_modules/q/q.js:110:17)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
I reproduced the error with the following code snipet (arguments coming from production):
var crypto = require("crypto");
var verifySignature = function(str, key, signatureValue) {
var verifier = crypto.createVerify("RSA-SHA256");
verifier.update(str);
var res = verifier.verify(key, signatureValue, 'base64');
return res
};
var str = '<ds:SignedInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"></ds:SignatureMethod><ds:Reference URI="#_55ead485-2e18-4a0d-996e-8c1e42ffa49c"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"></ds:DigestMethod><ds:DigestValue>nj39d54JP9LU4xUgqUa5uzJ7W/xzDAzXadgUy37Yunk=</ds:DigestValue></ds:Reference></ds:SignedInfo>';
var key = '-----BEGIN CERTIFICATE-----\n' +
'MxXh1Tdvj9Wx5VOV4WVunP81al6yvYwRph5F1CPgKRA=\n' +
'-----END CERTIFICATE-----\n';
var signatureValue = 'QhszIs1jyIQ/b+4kuAxoKNqmU2zk1Gwlzdc0N4V54pkrv+gPwautZMLZEcQCFq9Qt6Xb5oKZHA43OwQfy0kBO1Fy88XlpDu9D5o23pzddZh3x9p0OSjTLA6ycSUYftCKPoTRtIq1AJ9QcmahISPPWA89Vp5hpw2gwuyQsZYXVep8PZJFdlXf+jh35KJq0WOH+4UVRWHoYU5THHE9H7rKqlXzEma+jb78KWF/aNltRFS2yW0UT3bsYE0CKiJp/MokNB51IztwZYqueGBD2A2IcFF+PAq4cnwSzqIZ5sXCVWUSm6lQupyxA67nIA/asJ//WbYozCePSQKFaBNVJEz1Pg==';
verifySignature(str, key, signatureValue);
Any idea how to fix it?

Turns out the certificate provided by the Identity provider was incorrect. Fixed.

Related

Kreait : verifySessionCookie() not found

I try to verify a session cookie from the $sessionCookieString = $auth->createSessionCookie($idToken, $oneWeek); which work normally.
But report say that the function is not found.
"Call to undefined method Kreait\Firebase\Auth::verifySessionCookie()"
Didn't understand why.
i have the latest version install.
--- Portion of code below ---
use Kreait\Firebase\Factory;
use Kreait\Firebase\Contract\Auth;
use Kreait\Firebase\Auth\UserQuery;
use Google\Cloud\Firestore\FirestoreClient;
use Kreait\Firebase\Auth\CreateSessionCookie\FailedToCreateSessionCookie;
public function doLogin() {
$factory = (new Factory)->withServiceAccount($this->ekonysJson );
$auth = $factory->createAuth();
$this->auth = $auth;
//print_r($auth);
$signInResult = $auth->signInWithEmailAndPassword("email#dot", "password");
$idToken = $signInResult->idToken();
`print_r($signInResult->refreshToken());`
$oneWeek = new \DateInterval('P7D');
$sessionCookieString = $auth->createSessionCookie($idToken, $oneWeek);
$verifiedSessionCookie = $auth->verifySessionCookie($sessionCookieString)
}
refer to doc https://firebase-php.readthedocs.io/en/stable/authentication.html#session-cookies
if you have any idea.... thanks
Solution for this problem

AWS S3 CopyObjectAsync fails with key does not exist, but get/put succeeds

I fought with this for several hours and never found the solution. Here's the scenario:
var copyObjectRequest = new CopyObjectRequest
{
SourceBucket = s3Event.S3.Bucket.Name,
SourceKey = s3Event.S3.Object.Key,
DestinationBucket = OutputBucketName,
DestinationKey = s3Event.S3.Object.Key,
};
var deleteRequest = new DeleteObjectRequest
{
BucketName = copyObjectRequest.SourceBucket,
Key = copyObjectRequest.SourceKey,
};
await S3Client.CopyObjectAsync(copyObjectRequest);
await S3Client.DeleteObjectAsync(deleteRequest);
S3Client.CopyObjectAsync throws the error: "The specified key does not exist." (S3Client.DeleteObjectAsync is never reached.)
However, the following code works (for the same values):
var request = new GetObjectRequest
{
BucketName = copyObjectRequest.SourceBucket,
Key = copyObjectRequest.SourceKey,
};
var response = await S3Client.GetObjectAsync(request);
var tempPath = $"{Guid.NewGuid():D}";
await response.WriteResponseStreamToFileAsync(tempPath, false, CancellationToken.None);
var putRequest = new PutObjectRequest
{
BucketName = copyObjectRequest.DestinationBucket,
Key = copyObjectRequest.DestinationKey,
FilePath = tempPath,
};
var putResponse = await S3Client.PutObjectAsync(putRequest);
if (putResponse.HttpStatusCode == HttpStatusCode.OK)
{
var deleteRequest = new DeleteObjectRequest
{
BucketName = copyObjectRequest.SourceBucket,
Key = copyObjectRequest.SourceKey,
};
await S3Client.DeleteObjectAsync(deleteRequest);
}
For brevity I removed almost all error checking, logging, etc. but if requested I'm happy to share the full function.
Note that this is running in a C# Lambda Function, using Core 2.0.
I've ruled out security as the second set of calls requires the same permissions (I believe) as the CopyObject call does (please do correct me if I'm wrong).
There's no doubt the object is at the bucket and key specified as the second set uses the exact same structure.
The key doesn't exist in the destination bucket.
Both the source and destination buckets have the same permissions.
There are no special characters in the key (sample keys that I've tested are "/US/ID/Teton/EC2ClientDemo.zip" and "testkey").
The files I'm testing with are tiny (that sample file is 30Kb).
I've tried it with and without a CannedACL value in CopyObjectRequest (I don't think it should require one for my purposes, all the files it's moving around are private).
I've validated that all buckets are in the same region (USWest2).
I can't figure out why CopyObjectAsync fails. I've tried digging down through the disassembled code for CopyObjectAsync, but it's called so indirectly I didn't get very far. At this point my best guess is that it's a bug in CopyObjectAsync.
Any suggestions would be appreciated,
Thanks for reading!
Additional: I want to make it clear that this works from the regular AWSSDK library (either CopyObjectAsync or CopyObject), it only fails in the Core 2.0 async call CopyObjectAsync in the Lambda environment.
OK, so I figured it out and it is definitely a bug in the core 2.0 CopyObjectAsync(). Here's the scenario:
We are using keys that have slashes at the beginning, an example would be '/US/ID/Teton/EC2ClientDemo.zip'. When I turned on S3 logging (thank you #Michael-sqlbot) what I saw was this:
[13/Jul/2018:17:44:18 +0000] 34.221.84.59 arn:aws:sts::434371411556:assumed-role/LambdaFunctionCreation/TestFunction 489A5570C2E840AC REST.COPY.OBJECT_GET US/ID/Teton/EC2ClientDemo.zip - 404 NoSuchKey
As you can see the CopyObjectAsync() function stripped off the first slash before making the call. Get, Put, and Delete handle these particular keys just fine (and I tested this in the non-Core library and both the synchronous and asynchronous versions of CopyObjectAsync() handle the keys just fine as well).
What I had to do to fix it was the following:
var copyObjectRequest = new CopyObjectRequest
{
SourceBucket = s3Event.S3.Bucket.Name,
SourceKey = "/" + s3Event.S3.Object.Key,
DestinationBucket = OutputBucketName,
DestinationKey = "/" + s3Event.S3.Object.Key,
CannedACL = S3CannedACL.BucketOwnerFullControl,
};
Note the added slashes on the SourceKey and DestinationKey? Without those the keys are mangled.
Here is the complete final code:
var copyObjectRequest = new CopyObjectRequest
{
SourceBucket = s3Event.S3.Bucket.Name,
SourceKey = s3Event.S3.Object.Key,
DestinationBucket = OutputBucketName,
DestinationKey = s3Event.S3.Object.Key,
CannedACL = S3CannedACL.BucketOwnerFullControl,
};
try
{
await s3Client.CopyObjectAsync(copyObjectRequest);
}
catch (AmazonS3Exception ase) when (ase.Message.Contains("key does not exist"))
{
try
{
// If this failed due to Key not found, then fix up the request for the CopyObjectAsync bug in the Core 2.0 library and try again.
var patchedCopyObjectRequest = new CopyObjectRequest()
{
SourceBucket = copyObjectRequest.SourceBucket,
SourceKey = "/" + copyObjectRequest.SourceKey,
DestinationBucket = copyObjectRequest.DestinationBucket,
DestinationKey = "/" + copyObjectRequest.DestinationKey,
CannedACL = copyObjectRequest.CannedACL,
};
await s3Client.CopyObjectAsync(patchedCopyObjectRequest);
}
catch (AmazonS3Exception)
{
// Rethrow the initial exception, since we don't want a confusing message to contain the modified keys.
throw ase;
}
}

How to verify PKCS#7 signature in PHP

I have a digital signature (encrypted format PKCS#7) needs to be verified So I have tried by using different PHP core methods(openssl_verify, openssl_pkcs7_verify and even tried by external library such as phpseclib But nothing worked :(
I get a signature along with some extra params through by this link..
http://URL?sign={'param':{'Id':'XXXXXXX','lang':'EN','Rc':'00','Email': 'test#yahoo.com'’},'signature':'DFERVgYJKoZIhvcNAQcCoIIFRzCCBUMCAQExCzAJBgUrDg
MCGgUAMIGCBgkqhkiG9w0BBwGgdQRzeyJEYXRlIjoidG9fY2hhcihzeXNkYXRlJ0RETU1ZWVlZJykgIiwiSWQiOiJ
VMDExODg3NyIsIklkaW9tYSI6IkNBUyIsIk51bUVtcCI6IlUwM23D4DEE3dSi...'}
PHP code - returns always 0(false) instead of 1(true).
$JSONDATA = str_replace("'", '"', #$_GET["sign"]);
$data = json_decode($JSONDATA, true);
$this->email = $data['param']["EMAIL"];
$this->signature = $data['signature'];
$this->signature_base64 = base64_decode($this->signature);
$this->dataencoded = json_encode($data['param']);
//SOLUTION 1 (By using phpseclib) but didnt work..
$rsa = $this->phpseclib->load();
$keysize = 2048;
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
$d = $rsa->createKey($keysize);
$Kver = $d['publickey'];
$KSign = $d['privatekey'];
// Signing
$rsa->loadKey($KSign);
$rsa->setSignatureMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setHash('sha256');
$signature = $rsa->sign($this->dataencoded);
$signedHS = base64_encode($signature);
// Verification
$rsa->loadKey($Kver);
$status = $rsa->verify($this->dataencoded, $this->firma_base64); // getting an error on this line Message: Invalid signature
var_dump($status); // reutrn false
//SOLUTION 2 (By using code php methods)
// obtener la clave pública desde el certifiado y prepararla
$orignal_parse = parse_url("https://example.com", PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
openssl_x509_export($cert["options"]["ssl"]["peer_certificate"],$cert_key);
$pubkeyid = openssl_pkey_get_public($cert_key);
$dataencoded = json_encode($data['param']);
echo $ok = openssl_x509_check_private_key($cert_key,$this->firma_base64); // return nothing
echo $ok1 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok2 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
echo $ok3 = openssl_verify($dataencoded, $this->firma_base64, $pubkeyid, OPENSSL_ALGO_SHA256); // returns 0
echo $ok4 = openssl_verify($dataencoded, $this->firma, $pubkeyid, OPENSSL_ALGO_SHA512); // returns 0
Java code - (this code works and returns true)
private boolean verifySignautre(String frm) throws NetinfException, IOException, CMSException,
CertificateException, OperatorCreationException, Exception {
Security.addProvider(new BouncyCastleProvider());
//we extract the containers that make up the signature and the keystore used to sign included in the same signature.
CMSSignedData signedData = new CMSSignedData(Base64.decode(frm.getBytes()));
SignerInformationStore signers = signedData.getSignerInfos();
Store certStore = signedData.getCertificates();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
//retrieve the certificate with the recipient's id.
SignerInformation signerInfo = (SignerInformation) it.next();
Collection certCollection = certStore.getMatches(signerInfo.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder signerCertificateHolder = (X509CertificateHolder) certIt.next();
//create the container to validate signature.
ContentVerifierProvider contentVerifierProvider = new BcRSAContentVerifierProviderBuilder(new
DefaultDigestAlgorithmIdentifierFinder()).build(signerCertificateHolder);
//valid signature and then certificate validity date
try{
X509Certificate signedcert = new
JcaX509CertificateConverter().setProvider("BC").getCertificate(signerCertificateHolder);
signedcert.checkValidity();
signedcert.verify(signedcert.getPublicKey());
return true;
}catch(Exception e){
return false;
}
}
I simply need to convert this Java code into PHP. However, as you can see above that I tried different approaches but none of them worked.
Please support me to find the solution.
your support would be higly appreciated

AssertionError: relay-101/index.js: getBabelRelayPlugin(): Expected schema to be an object with a `__schema`

I was following Relay 101: Building A Hacker News Client Tutorial.
But in the process I got error
AssertionError: relay-101/index.js: getBabelRelayPlugin():
Expected schema to be an object with a `__schema` property.
at getSchema (/Users/ruseel/p/spike/relay-101/node_modules/babel-relay-plugin/src/getBabelRelayPlugin.js:224:3)
at NodePath.Plugin.visitor.TaggedTemplateExpression (/Users/ruseel/p/spike/relay-101/node_modules/babel-relay-plugin/src/getBabelRelayPlugin.js:104:26)
...
and after little digging (console.log in getBabelRelayPlugin.js) I noticed introspection var in getBabelRelayPlugin.js
const introspection = typeof schemaProvider === 'function' ?
schemaProvider() :
schemaProvider;
is like this.
{"errors":[{"message":"Must provide query string."}]}
But I have no idea why this is happening?
Why is this error happening?
any direction would be appreciated.
I made a typo in babelRelayPlugin.js, instrospectionQuery instead of introspectionQuery.
var babelRelayPlugin = require('babel-relay-plugin');
var introspectionQuery = require('graphql/utilities').introspectionQuery;
var request = require('sync-request');
var graphqlHubUrl = 'http://www.graphqlhub.com/graphql';
var response = request('GET', graphqlHubUrl, {
qs: {
query: introspectionQuery
}
});

Script for File upload in google drive - Error encountered: An unexpected error occurred

I use a script to upload document into google spreadsheet and automatically put link to it into current cell. Since yesterday all was gone fine, but since this morning i receive this generic error:
https://docs.google.com
Error encountered: An unexpected error occurred
This is the code:
// upload document into google spreadsheet
// and put link to it into current cell
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var menuEntries = [];
menuEntries.push({name: "Accedi al modulo per allegare un file...", functionName: "doGet"});
ss.addMenu("Carica scheda di rilevazione dati...", menuEntries);
}
function doGet(e) {
var app = UiApp.createApplication().setTitle("FORM per il caricamento della scheda di rilevazione dati");
SpreadsheetApp.getActiveSpreadsheet().show(app);
var form = app.createFormPanel().setId('frm').setEncoding('multipart/form-data');
var formContent = app.createVerticalPanel();
form.add(formContent);
formContent.add(app.createFileUpload().setName('thefile'));
// these parameters need to be passed by form
// in doPost() these cannot be found out anymore
formContent.add(app.createHidden("activeCell", SpreadsheetApp.getActiveRange().getA1Notation()));
formContent.add(app.createHidden("activeSheet", SpreadsheetApp.getActiveSheet().getName()));
formContent.add(app.createHidden("activeSpreadsheet", SpreadsheetApp.getActiveSpreadsheet().getId()));
formContent.add(app.createSubmitButton('Invia ed archivia scheda'));
app.add(form);
SpreadsheetApp.getActiveSpreadsheet().show(app);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
app.createLabel('sto salvando...');
var fileBlob = e.parameter.thefile;
var doc = DocsList.getFolderById('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').createFile(fileBlob);
var label = app.createLabel('file caricato con successo');
// write value into current cell
var value = 'hyperlink("' + doc.getUrl() + '";"' + doc.getName() + '")'
var activeSpreadsheet = e.parameter.activeSpreadsheet;
var activeSheet = e.parameter.activeSheet;
var activeCell = e.parameter.activeCell;
var label = app.createLabel('file memorizzato correttamente');
app.add(label);
SpreadsheetApp.openById(activeSpreadsheet).getSheetByName(activeSheet).getRange(activeCell).setFormula(value);
app.close();
return app;
}
According to Your Question
Since yesterday all was gone fine, but since this morning i receive this generic error: https://docs.google.com Error encountered: An unexpected error occurred
According to Google developers page
So, I think problem may be in
var doc = DocsList.getFolderById('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').createFile(fileBlob);
try to use DriveApp instead of DocList. more info