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