Firefox estensions: programmatically add a certificate to the trust certificate store - firefox

I am trying to understand how to add a certificate in the store of trusted certificates in FF. I could not find a clear answer so far, but doing some research I understand it should be doable with a firefox extension. This may be an hint:
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Miscellaneous#Adding_custom_certificates_to_a_XULRunner_application
Does anyone know how to do this with modern versions of FF? is there any best practices?
Thank in advance,
Stefano

just to answer my own question... after some additional research I managed to do it and I believe what's in the article is quite accurate. you do not need necessarily to build an XPCOM though.
I have just created a simple add on with the code below:
function addCertificate() {
var certDB = Cc["#mozilla.org/security/x509certdb;1"].getService(Ci.nsIX509CertDB);
var is = Cc["#mozilla.org/scriptableinputstream;1"].getService(Ci.nsIScriptableInputStream);
var file = new FileUtils.File("/tmp/famfor.crt");
var channel = gIOService.newChannelFromURI(gIOService.newFileURI(file));
var input = channel.open();
is.init(input);
var envelope = is.read(input.available());
is.close();
input.close();
var beginCert = "-----BEGIN CERTIFICATE-----";
var endCert = "-----END CERTIFICATE-----";
envelope = envelope.replace(/[\r\n]/g, "");
var begin = envelope.indexOf(beginCert);
var end = envelope.indexOf(endCert);
var cert = envelope.substring(begin + beginCert.length, end);
console.log(cert);
certDB.addCertFromBase64(cert, "C,C,C", "");
};
Quite straightforward I would say :)

Related

Failed to add Certificate/Key into Xamarin iOS keychain

I am trying to use SecKeyChain to add my certs and private keys into iOS keychain. I tried SecKeyChain.Add() and SecKeyChain.AddIdentity(), but first one return me SecStatusCode "Param", and another one throws "System.InvalidOperationException: Param". Can someone help me to solve this problem? It's hard to find detailed documentation for those methods from Xamarin Website.
using(NSData crt = NSData.FromFile("client1.p12"))
{
X509Certificate2 certificate = new X509Certificate2(crt.ToArray(), password);
var identity = SecIdentity.Import(certificate.Export(X509ContentType.Pkcs12, password), password);
var record = new SecRecord(SecKind.Certificate);
record.Label = "client1_crt";
record.SetValueRef(identity.Certificate);
SecStatusCode secStatus = SecKeyChain.Add(record);
SecKeyChain.AddIdentity(identity)
}
I also tried this way:
using (NSData crt = NSData.FromFile("client1-crt.der")
{
SecStatusCode secStatus = SecKeyChain.Add(new SecRecord(SecKind.Certificate)
{
ApplicationLabel = "client1_crt",
KeySizeInBits = 512,
KeyClass = SecKeyClass.Public,
ValueData = NSData.FromString(crt)
});
}
But secStatus still shows "Param".
Problem solved. Turns out we need to enable keychain in Entitlements.plist file. detail Detail steps:
https://forums.xamarin.com/discussion/comment/330146#Comment_330146

Get network operator name in Appcelerator Titanium

I am looking to get the name of the operator for the user's Android device.
E.g. "Verizon" or "Vodafone", I think I have found the Android equivalent documented here called getSimOperatorName() from http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName()
I am scanning over the documentation for Appcelerator Titanium, but can't seem to find a way of doing this in the docs (http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network).
Is this possible in Appcelerator Titanium?
You can use tinetworkinfo Module
Ex:-
var netInfo = require('com.clever_apps.tinetworkinfo');
var win = Ti.UI.createWindow({exitOnClose: true});
var testLabel = Ti.UI.createLabel({
height:"80%",
width:"90%",
top:0
});
var refreshButton = Ti.UI.createButton({
title:"Refresh Data",
height:"15%",
bottom:"5%"
});
refreshButton.addEventListener("click", getTelephonyData);
win.add(testLabel);
win.add(refreshButton);
getTelephonyData();
win.open();
function getTelephonyData(){
var imei = netInfo.getIMEI();
var cellid = netInfo.getCellID();
var lac = netInfo.getLac();
var mnc = netInfo.getMNC();
var mmc = netInfo.getMMC();
var outString = "IMEI: "+imei+"\nCell ID: "+cellid+"\nLAC: "+lac+"\nMNC: "+mnc+"\nMMC: "+mmc;
testLabel.text = outString;
}
Currently there is no API that will return you that information. For that, you need to create your own Android module.
I could not get tinetworkinfo Module working. However, a module named TelephonyManager worked fine.
I ran this in the terminal for the project:
gittio install com.goyya.telephonymanager
Then this code to get the network operator name:
var telephonymanager = require("com.goyya.telephonymanager");
Ti.API.log('networkOperatorName: ' + telephonymanager.networkOperatorName);

Restart AIR MacOS Captive Runtime Bundle Application from code

Could anyone say how to restart it?
I found this sample and try to adapt it for me:
var appLauncher:File;
appLauncher = new File(File.applicationDirectory.nativePath).parent.parent.resolvePath("Contents").resolvePath("MacOS").resolvePath("FlashApp");
var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo;
npInfo.executable = appLauncher;
var _args:Vector.<String> = new Vector.<String>;
npInfo.arguments = _args;
var np:NativeProcess = new NativeProcess;
np.start(npInfo);
np.exit();
But I don't understand how it should work.. Now nothing happends when this function called frome one of my classes.
Did you try it with ADL? Or with actually packaged/installed app?
It is related its package structure.
If you try with ADL, it may not work.
Also,
"FlashApp" must be changed to the name of your application,
The last line should be exit(); of your NativeApplication, not np.exit()

Fast RSA encryption in AS3

I have a Flex 4 application that uses a 2048 bits private RSA key to encrypt/sign some string values that are around 30 characters long.
I'm currently using the com.hurlant.crypto.RSAKey implementation to do so but I'm facing the following limitations:
It takes way too long (around 4 seconds for signing a 30 chars
string)
The UI freezes while the class is processing (implementation obviously doesn't
use events or chunks processing)
I have been looking for other libraries but I haven't found so far any other with the same level of functionalities (read RSA key from PEM string, allow RSA.sign(), RSA.encrypt and decrypt), that is free to use in commercial applications and that is faster than the one I currently use.
So my questions are:
Does anyone know a great/fast AS3 library that do that?
If there are none and I decide to write one myself from scratch will I be
facing the same problems because the low performances are somehow induced by the
flash platform ?
EDIT2: Below code uses a PEM encoded private key stored in a file. If you don't have one you can create one using the following piece of code:
var exp:String = "10001";
var bits:int = 2048;
rsa = RSAKey.generate(bits, exp);
Don't forget to sit down and take a coffee as it takes nearly one minute to generate.
EDIT: Here is piece of code showing the limitations.
Simply click on the start button and see how the progress bar and the application completely freezes.
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.util.der.PEM;
import mx.utils.Base64Encoder;
var pkfilePath:String = "/Users/david/Desktop/private_key.pem";
var stringToSign:String = "Hello this is a string to be signed by an efficient AS3 library";
private function readPKContent():String {
var f:File = new File(pkfilePath);
var fs:FileStream = new FileStream();
fs.open(f,FileMode.READ);
var rawKey:String = fs.readUTFBytes(fs.bytesAvailable);
fs.close();
return rawKey;
}
private function logTime(msg:String, start:Date, end:Date):void {
resultTA.text = msg + " " + (end.time-start.time) + " ms\n" + resultTA.text;
}
protected function button1_clickHandler(event:MouseEvent):void
{
cryptWithHurlant();
}
private function cryptWithHurlant():void {
var start:Date = new Date();
//Load key and use it to sign something
var rawPK:String = readPKContent();
var time:Date = new Date();
var rsa:RSAKey = PEM.readRSAPrivateKey(rawPK);
logTime("Hurlant:ReadRSA", time, new Date());
//Compute a signature of the string
var srcBA:ByteArray = new ByteArray();
srcBA.writeUTFBytes(stringToSign);
//Now sign inside the second BA
var desBA:ByteArray = new ByteArray();
time = new Date();
rsa.sign(srcBA, desBA, srcBA.length);
logTime("Hurlant:Encrypt", time, new Date());
//desBA.position = 0;
//Recover as a Base64 response
//var b64encoder:Base64Encoder = new Base64Encoder();
//time = new Date();
//b64encoder.encodeBytes(desBA);
//logTime("Base64:Encoded "+b64encoder.toString(),time, new Date());
logTime("Hurlant:Total",start,new Date());
}
]]>
</fx:Script>
<s:VGroup width="100%" height="100%" horizontalAlign="center">
<s:Button click="button1_clickHandler(event)" label="Start"/>
<mx:ProgressBar indeterminate="true"/>
<s:TextArea width="100%" height="100%" editable="false" id="resultTA"/>
</s:VGroup>
</s:WindowedApplication>
As noted above:
You may want to look into this timer based "threading" implementation. This won't speed anything up, but it will get rid of the UI lock. I have code using this working on mobile.
Based on all that has been said in comments and the absence of answers, I think that my best option for now will be to edit the RSA implementation to make it able to run with the pseudo-threading model proposed by f-a. I will move to workers once they are supported by mobile platforms.
References
Threads in ActionScript 3
flash.system.Worker

Unable to set firefox bookmark description for in Add-On Kit API

I found the nsINavBookmarksService, however since Firefox 3, it does not seem to have any API methods for getting/setting the Bookmark description. (API doc)
I've seen other Add-Ons modify the description as a method of synchronized data storage (which is exactly what I'm trying to do). I'm guessing perhaps the description is a non-gecko standard, and that's why it is not directly supported, but then there must be a completely different interface for manipulating Bookmarks that I haven't discovered.
Can anyone help with this newbie problem?
Starting with Firefox 3 the bookmarks have been merged into the Places database containing all of your browsing history. So to get the bookmarks you do a history query, like this (first line is specific to the Add-on SDK which you appear to be using):
var {Cc, Ci} = require("chrome");
var historyService = Cc["#mozilla.org/browser/nav-history-service;1"]
.getService(Ci.nsINavHistoryService);
var options = historyService.getNewQueryOptions();
var query = historyService.getNewQuery();
query.onlyBookmarked = true;
var result = historyService.executeQuery(query, options);
result.root.containerOpen = true;
for (var i = 0; i < result.root.childCount; i++)
{
var node = result.root.getChild(i);
console.log(node.title);
}
That's mostly identical to the code example here. Your problem is of course that nsINavHistoryResultNode has no way of storing data like a description. You can set annotations however, see Using the Places annotation service. So if you already have a node variable for your bookmark:
var annotationName = "my.extension.example.com/bookmarkDescription";
var ioService = Cc["#mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService);
var uri = ioService.newURI(node.uri, null, null);
var annotationService = Cc["#mozilla.org/browser/annotation-service;1"]
.getService(Ci.nsIAnnotationService);
annotationService.setPageAnnotation(uri, annotationName,
"Some description", 0, Ci.nsIAnnotationService.EXPIRE_NEVER);
For reference: nsIAnnotationService.setPageAnnotation()

Resources