Error trying to install Certificate on browser using JS - javascript

In my code I have a button that calls a JS file, which in turn calls a PHP file that has the API endpoints that I need to generate certificate, and sends the response back that I use in certificate variable below.
I'm generating the CSR myself using the openssl command.
My code to install cert on the browser is as follows (certificate is where I pass the certificate as response that I get from Entrust APIs)-
I'm using the code off of this page- https://blogs.msdn.microsoft.com/alejacma/2009/01/28/how-to-create-a-certificate-request-with-certenroll-javascript/ (the 2nd grey block right below- following Javascript sample shows how to install the response from the CA)
function installCertificate(certificate) {
try {
var objEnroll = objCertEnrollClassFactory.CreateObject("X509Enrollment.CX509Enrollment");
objEnroll.Initialize(1); // ContextUser
objEnroll.InstallResponse(0, certificate, 6, "");
} catch (ex) {
swal('Error', 'Something went wrong installing Client Certificate', 'error');
console.log("exception- " + ex.description);
}
}
The error that I have is (from the catch block)-
CertEnroll::CX509Enrollment::InstallResponse: Cannot find object or property. 0x80092004 (-2146885628 CRYPT_E_NOT_FOUND)
I'm not sure what it means by Cannot find object or property as it's not too verbose.
PS: If I save the response from the API as a .crt file and open it (simple double click), the certificate values look correct along with the certificate chain.

After a lot of trawling I finally made it work. For anyone wondering, heres my solution-
The part of the code that generates the CSR is the 1st grey block on this page-
https://blogs.msdn.microsoft.com/alejacma/2009/01/28/how-to-create-a-certificate-request-with-certenroll-javascript.
The CSR that it comes back with has a -----BEGIN NEW CERTIFICATE REQUEST----- at the top and -----END NEW CERTIFICATE REQUEST----- at the bottom, and line breaks after each line.
I removed the top line and all line breaks using preg_replace like below, and as at this point the CSR does not have a line break and is just a simple string, I used a str_replace to remove the last part of it.
$csr = preg_replace('/^.+\n/', '', $csr);
$csr = str_replace("-----END NEW CERTIFICATE REQUEST-----","", $csr);
TLDR- Removed the top and bottom line from the CSR and all the line breaks that were there. I think it had to do with how the CSR was formatted.

Related

Error Updating a Chromebook's Organizational Unit with Google Script

I have been experiencing an issue recently with a Google Script code I wrote to update a few Chromebooks' organization units.
Here is a portion of the code that I am running:
let admin = AdminDirectory.Chromeosdevices.get("my_customer", active_deviceid[serial_index])
admin.annotatedAssetId = device_ID.toString()
admin.annotatedLocation = name
admin.orgUnitPath = _location_(device_ID).toString().toUpperCase()
AdminDirectory.Chromeosdevices.update(admin, 'my_customer', active_deviceid[serial_index])
Once the script executes I get the following error:
GoogleJsonResponseException: API call to directory.chromeosdevices.update failed with error: Invalid Input: Inconsistent Orgunit id and path in request - 11006550017573025, /1 SCHOOLS/COVID LOANERS
What is strange is that if I comment or remove "admin.orgUnitPath = location(device_ID).toString().toUpperCase()" the script will run fine. It seems the orgUnitPath is causing this error.
I tried the following:
Removing the first slash "/"
Do only 1 Chromebook
Remove and reapply the AdminDirectory
Run previous scripts that were used to change the OrgUnitPath
Added quotes on the beginning and end of the OrgUnitPath
Converted the path to String with toString()
used Stript() function to eliminate any empty spaces
All the above attempts failed to fix this issue. I will also include an image of an error I am getting from a previous script I made that used to work about a year ago that also changes the OrgUnitPath.
Does anyone know how to fix this issue?
Thanks in advance.
For some reason there has been a change that now requires the orgUnitId in addition to the orgUnitPath.
So before you run AdminDirectory.Chromeosdevices.update you need to obtain the orgUnitId and update that property
var orgUnitPathStr = "/Tech Dept/Storage"
admin.orgUnitId = AdminDirectory.Orgunits.get("my_customer",orgUnitPathStr.substring(1)).orgUnitId;
//substring(1) above removes the first slash in the orgUnitPath, which is required for this method
Credit for hints:
https://github.com/taers232c/GAMADV-XTD3/issues/225

How to pass data from the feature file to step definition file using regular expressions?

This project is using NodeJS, Cucumber, Gherkin, Selenium.
I am trying to pass either a stored value or for now, a value in this example it would be a URL from the feature file into the step definitions file through the usage of regular expressions.
An example of a feature i would like to use (< url > is my guess-work which i've seen in other examples, which doesnt seem to work)
Scenario: 0 | A User Logging In
Given I open the page with the <url>
And then also my step definitions file
Given("/^I open the page with the url? (.*)$/"), function(next){
driver.get("http://localhost:3000/login");
pageElement = driver.findElement(By.id("email"));
pageElement.sendKeys("example#email.co.uk");
next();
};
I believe my step definitions file is correct however i'm not positive.
If you need any more information about my project please let me know i am active throughout the day on stack-overflow and aim to have this working quickly.
Thank you in advance for any support,
Jack
I would try changing the regular expression in your JavaScript to a string that expects the variables you're passing into the Given statement:
Given('I open the page with the url {string}'), function(next) {
//your code
}
You can define variables in the Gherkin Given statements by stating them as they would be presented typically. For example, if you wanted to pass in a string:
Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost"
Would pass in the variable url to your javascript file and contain the string http://localhost
Same goes for integers:
Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost" and port 3000
Your javascript function will now receive 2 variables, url and port. Logging them to the console, you will see
http://localhost
3000
So I would re-arrange your code to look like the following:
Gherkin:
Scenario: 0 | A User Logging In
Given I open the page with the url "http://localhost:3000/login"
JavaScript:
Given('I open the page with the url {string}', (url, next) => {
console.log(url) // log to check the variable is being passed into the function
driver.get(url);
pageElement = driver.findElement(By.id("email"));
pageElement.sendKeys("example#email.co.uk");
next();
});
EDIT:
You can find all the documentation on this particular issue here.
A short answer below- May be useful for upcoming visitors!
The universal RegEx pattern works for all types of data in cucumber is- ([^"]*)
This is how it will go with complete step def-
#Given("^I open the page with the ([^"]*)$") //See note below *
public void yourMethodName(yourdatatType yourDataVar) {
Your Method(s) implementation using (yourDataVar)
...
}
// * Note- '^' and '$' symbols will be added automatically by cucumber in the beginning and end of any step definition respectively.

Simple online web game crash eventually

Background:
I am making a simple game in PHP, JavaScript and HTML for the web. A player control movements of a box on the screen, and see others fly around with their boxes.
I have the following files, that I upload to my domain via a hosting company:
index.html: a file with some buttons (eg. to start the game) and frames (for putting boxes in).
server.php: PHP script that receives messages from client, performs reads/writes to a database, echoes (using echo) boxes from database to the client. Does not echo the box of the player the message came from.
database.txt: a JSON text file containing data of players and the next free ID number. When empty it looks like this: {"players":[], "id": 1}. players contain objects with values such as ID, position and rotation.
script.js: JavaScript file with script to send/receive messages, display data from messages etc. Linked to index.html. Moves your box.
A screenshot, two players in movement:
Problem: The game crashes, always. Sooner or later. This is what happens:
Client recevies player data from server.php, everything is fine. This could be for 10 seconds or up to some minutes.
The data starts to falter, the message sometimes is null instead of actual data.
The data recevied is always null. The database file is now {"players":null,"id":5}. (The "id" could be any number, does not have to be 5).
Picture of data flow, printing of players from database. Two players. Before this screenshot lots of rows with valid data. Then as seen two null messages. Then after a while null forever.
I am not completely sure where the problem is, but I am guessing it has to do with my read/write in server.php. I feels like a lot of player movement makes the program more likely to crash. Also how often the program sends data affetcs.
Code Piece 1: This is code from server.php, that writes to the database. I have some sort of semaphore (the flock( ... ) ) to prevent clients from reading/writing at the same time (causing errors). I have an other function, read, which is very similar to this. Possible problems here:
The semaphore is incorrect.
The mode for fopen() is incorrect. See PHP docs. The mode w is for write. The tag b is for "If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data ...".
Something weird happening because I use read() in my writing function?
Code:
// Write $val to $obj in database JSON
function write($obj,$val){
$content = read();
$json = json_decode($content);
$json->{$obj} = $val; // eg. $json->{'id'} = 5;
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
if(flock($myfile, LOCK_EX|LOCK_NB)) {
fwrite($myfile,json_encode($json));
flock($myfile, LOCK_UN);
}
fclose($myfile);
}
Code Piece 2: This is my code to send data. It is called via a setInterval(). In script.js:
// Send message to server.php, call callback with answer
function communicate(messageFunc,callback){
var message = messageFunc();
if (window.XMLHttpRequest) {
var xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange= function() {
if (this.readyState==4 && this.status==200) {
callback(this.responseText);
}
}
xmlhttp.open("GET","server.php?msg="+message,true);
xmlhttp.send();
}
This is my code to receive data, in server.php: $receive = $_GET["msg"].
My current work of solving
This is what I have done so far, but nothing has changed:
Added mode b to fopen().
Added flock() to read/write functions in server.php.
Much reworking on script.js, I would say it looks/works very clean.
Check memory_get_peak_usage(), and check with the hosting company for memory limits. Should be no problem at all.
Looked at PHP garbage collecting and gc_enable() (I don't know why that would change anything).
Lots of testing, looking at the data flow.
Crying.
Conclusion: Is this type of application what PHP is for? What do you think is wrong? If you want more code/info I provide. Thank you very much.
Here is the root of your problem:
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
Note the behavior of the w open mode (emphasis mine):
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
This happens before you lock the file. What's happening is that between this fopen() call and the following flock() call, the file's content is zero length, and a reader is coming along during that time and reading the empty file.
Why doesn't this cause an error in PHP when you parse the empty string as JSON? Because json_decode() is defective, and returns null when the input is not valid JSON rather than throwing an exception. Nevermind that the string "null" is valid JSON -- json_decode() gives you no way to differentiate between the cases of valid input representing the null value and invalid input. If json_decode() actually threw an exception or triggered a PHP error (don't ask me why two error-signalling mechanisms are necessary in PHP), you would have a fantastic point to start debugging to figure out why the file is empty, and you might have solved this problem by now!
... sigh ...
PHP's "design" gives me headaches. But I digress.
To fix this whole problem, change the open mode to "cb" and ftruncate($myfile, 0) after you successfully acquire the lock.
Note the behavior of the c mode, which actually specifically mentions the approach you are using (emphasis mine):
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).

Strings broken with special character at Login ionic

I'm working with a Login problem in my app. I have an oauth login implemented between my server and my app, login works right, but if I use a password generated by some online services or app dedicated, for example, /#+6-[[?!nWYvfL)2Z7 the url that I need to build to make a call to the server, fails.
This is the call that my app generate:
[INFO:CONSOLE(521)] "http://localhost/oauth/v2/token?client_id=18_5cf03buhhp8gafadfg088w440ogsgd08ooggso80wg000k0gccw08&client_secret=4ajo9kcdqbqagddagdfdfswwcoo0c4gk48g4okw4kck0k0&grant_type=password&username=testing&password=/#+6-[[?!nWYvfL)2Z7", source: file:///android_asset/www/js/factoryutils.js (521)
It's seems to break after the dash. How I can solve this issue??
Thank you.
EDIT:
After insert ' ', it's still fails. The logcat of Android Studio show me the URL like an hyperlink, but until the password, like the next:
http://localhost/oauth/v2/token?client_id=18_5cf03buhhp8gafadfg088w440ogsgd08ooggso80wg000k0gccw08&client_secret=4ajo9kcdqbqagddagdfdfswwcoo0c4gk48g4okw4kck0k0&grant_type=password&username=testing&password='/#+6-[[?!nWYvfL)2Z7'
Send "%2F#+6-[[?!nWYvfL)2Z7" instead of /#+6-[[?!nWYvfL)2Z7, this should solve your problem.
It is achieved like this:
var unEscapedPassword = "\""+$scope.user.password+"\"";
var escapedPassword = unEscapedPassword .replace("/", "%2F");
With the next code I can get url with the password formatted.
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}
Thank you for your help Tarekis

Uploading/Downloading Byte Arrays with AngularJS and ASP.NET Web API

I have spent several days researching and working on a solution for uploading/downloading byte[]’s. I am close, but have one remaining issue that appears to be in my AngularJS code block.
There is a similar question on SO, but it has no responses. See https://stackoverflow.com/questions/23849665/web-api-accept-and-post-byte-array
Here is some background information to set the context before I state my problem.
I am attempting to create a general purpose client/server interface to upload and download byte[]’s, which are used as part of a proprietary server database.
I am using TypeScript, AngularJS, JavaScript, and Bootstrap CSS on the client to create a single page app (SPA).
I am using ASP.NET Web API/C# on the server.
The SPA is being developed to replace an existing product that was developed in Silverlight so it is constrained to existing system requirements. The SPA also needs to target a broad range of devices (mobile to desktop) and major OSs.
With the help of several online resources (listed below), I have gotten most of my code working. I am using an asynchronous multimedia formatter for byte[]’s from the Byte Rot link below.
http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html
Returning binary file from controller in ASP.NET Web API
I am using a jpeg converted to a Uint8Array as my test case on the client.
The actual system byte arrays will contain mixed content compacted into predefined data packets. However, I need to be able to handle any valid byte array so an image is a valid test case.
The data is transmitted to the server correctly using the client and server code shown below AND the Byte Rot Formatter (NOT shown but available on their website).
I have verified that the jpeg is received properly on the server as a byte[] along with the string parameter metadata.
I have used Fiddler to verify that the correct response is sent back to the client.
The size is correct
The image is viewable in Fiddler.
My problem is that the server response in the Angular client code shown below is not correct.
By incorrect, I mean the wrong size (~10K versus ~27.5K) and it is not recognized as a valid value for the UintArray constructor. Visual Studio shows JFIF when I place the cursor over the returned “response” shown in the client code below, but there is no other visible indicator of the content.
/********************** Server Code ************************/
Added missing item to code after [FromBody]byte[]
public class ItemUploadController : ApiController{
[AcceptVerbs("Post")]
public HttpResponseMessage Upload(string var1, string var2, [FromBody]byte[] item){
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(item);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
/***************** Example Client Code ********************/
The only thing that I have omitted from the code are the actual variable parameters.
$http({
url: 'api/ItemUpload/Upload',
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },// Added per Byte Rot blog...
params: {
// Other params here, including string metadata about uploads
var1: var1,
var2: var2
},
data: new Uint8Array(item),
// arrybuffer must be lowecase. Once changed, it fixed my problem.
responseType: 'arraybuffer',// Added per http://www.html5rocks.com/en/tutorials/file/xhr2/
transformRequest: [],
})
.success((response, status) => {
if (status === 200) {
// The response variable length is about 10K, whereas the correct Fiddler size is ~27.5K.
// The error that I receive here is that the constructor argument in invalid.
// My guess is that I am doing something incorrectly with the AngularJS code, but I
// have implemented everything that I have read about. Any thoughts???
var unsigned8Int = new Uint8Array(response);
// For the test case, I want to convert the byte array back to a base64 encoded string
// before verifying with the original source that was used to generate the byte[] upload.
var b64Encoded = btoa(String.fromCharCode.apply(null, unsigned8Int));
callback(b64Encoded);
}
})
.error((data, status) => {
console.log('[ERROR] Status Code:' + status);
});
/****************************************************************/
Any help or suggestions would be greatly appreciated.
Thanks...
Edited to include more diagnostic data
First, I used the angular.isArray function to determine that the response value is NOT an array, which I think it should be.
Second, I used the following code to interrogate the response, which appears to be an invisible string. The leading characters do not seem to correspond to any valid sequence in the image byte array code.
var buffer = new ArrayBuffer(response.length);
var data = new Uint8Array(buffer);
var len = data.length, i;
for (i = 0; i < len; i++) {
data[i] = response[i].charCodeAt(0);
}
Experiment Results
I ran an experiment by creating byte array values from 0 - 255 on the server, which I downloaded. The AngularJS client received the first 128 bytes correctly (i.e., 0,1,...,126,127), but the remaining values were 65535 in Internet Explorer 11, and 65533 in Chrome and Firefox. Fiddler shows that 256 values were sent over the network, but there are only 217 characters received in the AngularJS client code. If I only use 0-127 as the server values, everything seems to work. I have no idea what can cause this, but the client response seems more in line with signed bytes, which I do not think is possible.
Fiddler Hex data from the server shows 256 bytes with the values ranging from 00,01,...,EF,FF, which is correct. As I mentioned earlier, I can return an image and view it properly in Fiddler, so the Web API server interface works for both POST and GET.
I am trying vanilla XMLHttpRequest to see I can get that working outside of the AngularJS environment.
XMLHttpRequest Testing Update
I have been able to confirm that vanilla XMLHttpRequest works with the server for the GET and is able to return the correct byte codes and the test image.
The good news is that I can hack around AngularJS to get my system working, but the bad news is that I do not like doing this. I would prefer to stay with Angular for all my client-side server communication.
I am going to open up a separate issue on Stack Overflow that only deals with the GET byte[] issues that I am have with AngularJS. If I can get a resolution, I will update this issue with the solution for historical purposes to help others.
Update
Eric Eslinger on Google Groups sent me a small code segment highlighting that responseType should be "arraybuffer", all lower case. I updated the code block above to show the lowercase value and added a note.
Thanks...
I finally received a response from Eric Eslinger on Google Group. He pointed out that he uses
$http.get('http://example.com/bindata.jpg', {responseType: 'arraybuffer'}).
He mentioned that the camelcase was probably significant, which it is. Changed one character and the entire flow is working now.
All credit goes to Eric Eslinger.

Categories