OtrEngine.java

  1package eu.siacs.conversations.crypto;
  2
  3import java.math.BigInteger;
  4import java.security.KeyFactory;
  5import java.security.KeyPair;
  6import java.security.KeyPairGenerator;
  7import java.security.NoSuchAlgorithmException;
  8import java.security.PrivateKey;
  9import java.security.PublicKey;
 10import java.security.spec.DSAPrivateKeySpec;
 11import java.security.spec.DSAPublicKeySpec;
 12import java.security.spec.InvalidKeySpecException;
 13
 14import org.json.JSONException;
 15import org.json.JSONObject;
 16
 17import android.util.Log;
 18
 19import eu.siacs.conversations.Config;
 20import eu.siacs.conversations.entities.Account;
 21import eu.siacs.conversations.entities.Conversation;
 22import eu.siacs.conversations.services.XmppConnectionService;
 23import eu.siacs.conversations.utils.CryptoHelper;
 24import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 25import eu.siacs.conversations.xmpp.jid.Jid;
 26import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 27
 28import net.java.otr4j.OtrEngineHost;
 29import net.java.otr4j.OtrException;
 30import net.java.otr4j.OtrPolicy;
 31import net.java.otr4j.OtrPolicyImpl;
 32import net.java.otr4j.crypto.OtrCryptoEngineImpl;
 33import net.java.otr4j.crypto.OtrCryptoException;
 34import net.java.otr4j.session.InstanceTag;
 35import net.java.otr4j.session.SessionID;
 36import net.java.otr4j.session.FragmenterInstructions;
 37
 38public class OtrEngine extends OtrCryptoEngineImpl implements OtrEngineHost {
 39
 40	private Account account;
 41	private OtrPolicy otrPolicy;
 42	private KeyPair keyPair;
 43	private XmppConnectionService mXmppConnectionService;
 44
 45	public OtrEngine(XmppConnectionService service, Account account) {
 46		this.account = account;
 47		this.otrPolicy = new OtrPolicyImpl();
 48		this.otrPolicy.setAllowV1(false);
 49		this.otrPolicy.setAllowV2(true);
 50		this.otrPolicy.setAllowV3(true);
 51		this.keyPair = loadKey(account.getKeys());
 52		this.mXmppConnectionService = service;
 53	}
 54
 55	private KeyPair loadKey(JSONObject keys) {
 56		if (keys == null) {
 57			return null;
 58		}
 59		try {
 60			BigInteger x = new BigInteger(keys.getString("otr_x"), 16);
 61			BigInteger y = new BigInteger(keys.getString("otr_y"), 16);
 62			BigInteger p = new BigInteger(keys.getString("otr_p"), 16);
 63			BigInteger q = new BigInteger(keys.getString("otr_q"), 16);
 64			BigInteger g = new BigInteger(keys.getString("otr_g"), 16);
 65			KeyFactory keyFactory = KeyFactory.getInstance("DSA");
 66			DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, p, q, g);
 67			DSAPrivateKeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g);
 68			PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
 69			PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
 70			return new KeyPair(publicKey, privateKey);
 71		} catch (JSONException e) {
 72			return null;
 73		} catch (NoSuchAlgorithmException e) {
 74			return null;
 75		} catch (InvalidKeySpecException e) {
 76			return null;
 77		}
 78	}
 79
 80	private void saveKey() {
 81		PublicKey publicKey = keyPair.getPublic();
 82		PrivateKey privateKey = keyPair.getPrivate();
 83		KeyFactory keyFactory;
 84		try {
 85			keyFactory = KeyFactory.getInstance("DSA");
 86			DSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(
 87					privateKey, DSAPrivateKeySpec.class);
 88			DSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(publicKey,
 89					DSAPublicKeySpec.class);
 90			this.account.setKey("otr_x", privateKeySpec.getX().toString(16));
 91			this.account.setKey("otr_g", privateKeySpec.getG().toString(16));
 92			this.account.setKey("otr_p", privateKeySpec.getP().toString(16));
 93			this.account.setKey("otr_q", privateKeySpec.getQ().toString(16));
 94			this.account.setKey("otr_y", publicKeySpec.getY().toString(16));
 95		} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
 96			e.printStackTrace();
 97		}
 98
 99    }
100
101	@Override
102	public void askForSecret(SessionID id, InstanceTag instanceTag, String question) {
103		try {
104			final Jid jid = Jid.fromSessionID(id);
105			Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
106			if (conversation!=null) {
107				conversation.smp().hint = question;
108				conversation.smp().status = Conversation.Smp.STATUS_CONTACT_REQUESTED;
109				mXmppConnectionService.updateConversationUi();
110			}
111		} catch (InvalidJidException e) {
112			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": smp in invalid session "+id.toString());
113		}
114	}
115
116	@Override
117	public void finishedSessionMessage(SessionID arg0, String arg1)
118			throws OtrException {
119
120	}
121
122	@Override
123	public String getFallbackMessage(SessionID arg0) {
124		return "I would like to start a private (OTR encrypted) conversation but your client doesn’t seem to support that";
125	}
126
127	@Override
128	public byte[] getLocalFingerprintRaw(SessionID arg0) {
129		try {
130			return getFingerprintRaw(getPublicKey());
131		} catch (OtrCryptoException e) {
132			return null;
133		}
134	}
135
136	public PublicKey getPublicKey() {
137		if (this.keyPair == null) {
138			return null;
139		}
140		return this.keyPair.getPublic();
141	}
142
143	@Override
144	public KeyPair getLocalKeyPair(SessionID arg0) throws OtrException {
145		if (this.keyPair == null) {
146			KeyPairGenerator kg;
147			try {
148				kg = KeyPairGenerator.getInstance("DSA");
149				this.keyPair = kg.genKeyPair();
150				this.saveKey();
151				mXmppConnectionService.databaseBackend.updateAccount(account);
152			} catch (NoSuchAlgorithmException e) {
153				Log.d(Config.LOGTAG,
154						"error generating key pair " + e.getMessage());
155			}
156		}
157		return this.keyPair;
158	}
159
160	@Override
161	public String getReplyForUnreadableMessage(SessionID arg0) {
162		// TODO Auto-generated method stub
163		return null;
164	}
165
166	@Override
167	public OtrPolicy getSessionPolicy(SessionID arg0) {
168		return otrPolicy;
169	}
170
171	@Override
172	public void injectMessage(SessionID session, String body)
173			throws OtrException {
174		MessagePacket packet = new MessagePacket();
175		packet.setFrom(account.getJid());
176		if (session.getUserID().isEmpty()) {
177			packet.setAttribute("to", session.getAccountID());
178		} else {
179			packet.setAttribute("to", session.getAccountID() + "/" + session.getUserID());
180		}
181		packet.setBody(body);
182		packet.addChild("private", "urn:xmpp:carbons:2");
183		packet.addChild("no-copy", "urn:xmpp:hints");
184		packet.addChild("no-store", "urn:xmpp:hints");
185		packet.setType(MessagePacket.TYPE_CHAT);
186		account.getXmppConnection().sendMessagePacket(packet);
187	}
188
189	@Override
190	public void messageFromAnotherInstanceReceived(SessionID id) {
191		Log.d(Config.LOGTAG,
192				"unreadable message received from " + id.getAccountID());
193	}
194
195	@Override
196	public void multipleInstancesDetected(SessionID arg0) {
197		// TODO Auto-generated method stub
198
199	}
200
201	@Override
202	public void requireEncryptedMessage(SessionID arg0, String arg1)
203			throws OtrException {
204		// TODO Auto-generated method stub
205
206	}
207
208	@Override
209	public void showError(SessionID arg0, String arg1) throws OtrException {
210		Log.d(Config.LOGTAG,"show error");
211	}
212
213	@Override
214	public void smpAborted(SessionID id) throws OtrException {
215		setSmpStatus(id, Conversation.Smp.STATUS_NONE);
216	}
217
218	private void setSmpStatus(SessionID id, int status) {
219		try {
220			final Jid jid = Jid.fromSessionID(id);
221			Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
222			if (conversation!=null) {
223				conversation.smp().status = status;
224				mXmppConnectionService.updateConversationUi();
225			}
226		} catch (final InvalidJidException ignored) {
227
228		}
229	}
230
231	@Override
232	public void smpError(SessionID id, int arg1, boolean arg2)
233			throws OtrException {
234		setSmpStatus(id, Conversation.Smp.STATUS_NONE);
235	}
236
237	@Override
238	public void unencryptedMessageReceived(SessionID arg0, String arg1)
239			throws OtrException {
240		throw new OtrException(new Exception("unencrypted message received"));
241	}
242
243	@Override
244	public void unreadableMessageReceived(SessionID arg0) throws OtrException {
245		Log.d(Config.LOGTAG,"unreadable message received");
246		throw new OtrException(new Exception("unreadable message received"));
247	}
248
249	@Override
250	public void unverify(SessionID id, String arg1) {
251		setSmpStatus(id, Conversation.Smp.STATUS_FAILED);
252	}
253
254	@Override
255	public void verify(SessionID id, String fingerprint, boolean approved) {
256		Log.d(Config.LOGTAG,"OtrEngine.verify("+id.toString()+","+fingerprint+","+String.valueOf(approved)+")");
257		try {
258			final Jid jid = Jid.fromSessionID(id);
259			Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
260			if (conversation!=null) {
261				if (approved) {
262					conversation.getContact().addOtrFingerprint(fingerprint);
263				}
264				conversation.smp().hint = null;
265				conversation.smp().status = Conversation.Smp.STATUS_VERIFIED;
266				mXmppConnectionService.updateConversationUi();
267				mXmppConnectionService.syncRosterToDisk(conversation.getAccount());
268			}
269		} catch (final InvalidJidException ignored) {
270		}
271	}
272
273	@Override
274	public FragmenterInstructions getFragmenterInstructions(SessionID sessionID) {
275		return null;
276	}
277
278}