1package eu.siacs.conversations.crypto;
2
3import android.util.Log;
4
5import net.java.otr4j.OtrEngineHost;
6import net.java.otr4j.OtrException;
7import net.java.otr4j.OtrPolicy;
8import net.java.otr4j.OtrPolicyImpl;
9import net.java.otr4j.crypto.OtrCryptoEngineImpl;
10import net.java.otr4j.crypto.OtrCryptoException;
11import net.java.otr4j.session.FragmenterInstructions;
12import net.java.otr4j.session.InstanceTag;
13import net.java.otr4j.session.SessionID;
14
15import org.json.JSONException;
16import org.json.JSONObject;
17
18import java.math.BigInteger;
19import java.security.KeyFactory;
20import java.security.KeyPair;
21import java.security.KeyPairGenerator;
22import java.security.NoSuchAlgorithmException;
23import java.security.PrivateKey;
24import java.security.PublicKey;
25import java.security.spec.DSAPrivateKeySpec;
26import java.security.spec.DSAPublicKeySpec;
27import java.security.spec.InvalidKeySpecException;
28
29import eu.siacs.conversations.Config;
30import eu.siacs.conversations.entities.Account;
31import eu.siacs.conversations.entities.Conversation;
32import eu.siacs.conversations.generator.MessageGenerator;
33import eu.siacs.conversations.services.XmppConnectionService;
34import eu.siacs.conversations.xmpp.chatstate.ChatState;
35import eu.siacs.conversations.xmpp.jid.InvalidJidException;
36import eu.siacs.conversations.xmpp.jid.Jid;
37import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
38
39public class OtrService extends OtrCryptoEngineImpl implements OtrEngineHost {
40
41 private Account account;
42 private OtrPolicy otrPolicy;
43 private KeyPair keyPair;
44 private XmppConnectionService mXmppConnectionService;
45
46 public OtrService(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 MessageGenerator.OTR_FALLBACK_MESSAGE;
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 MessageGenerator.addMessageHints(packet);
184 try {
185 Jid jid = Jid.fromSessionID(session);
186 Conversation conversation = mXmppConnectionService.find(account,jid);
187 if (conversation != null && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
188 if (mXmppConnectionService.sendChatStates()) {
189 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
190 }
191 }
192 } catch (final InvalidJidException ignored) {
193
194 }
195
196 packet.setType(MessagePacket.TYPE_CHAT);
197 account.getXmppConnection().sendMessagePacket(packet);
198 }
199
200 @Override
201 public void messageFromAnotherInstanceReceived(SessionID session) {
202 sendOtrErrorMessage(session, "Message from another OTR-instance received");
203 }
204
205 @Override
206 public void multipleInstancesDetected(SessionID arg0) {
207 // TODO Auto-generated method stub
208
209 }
210
211 @Override
212 public void requireEncryptedMessage(SessionID arg0, String arg1)
213 throws OtrException {
214 // TODO Auto-generated method stub
215
216 }
217
218 @Override
219 public void showError(SessionID arg0, String arg1) throws OtrException {
220 Log.d(Config.LOGTAG,"show error");
221 }
222
223 @Override
224 public void smpAborted(SessionID id) throws OtrException {
225 setSmpStatus(id, Conversation.Smp.STATUS_NONE);
226 }
227
228 private void setSmpStatus(SessionID id, int status) {
229 try {
230 final Jid jid = Jid.fromSessionID(id);
231 Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
232 if (conversation!=null) {
233 conversation.smp().status = status;
234 mXmppConnectionService.updateConversationUi();
235 }
236 } catch (final InvalidJidException ignored) {
237
238 }
239 }
240
241 @Override
242 public void smpError(SessionID id, int arg1, boolean arg2)
243 throws OtrException {
244 setSmpStatus(id, Conversation.Smp.STATUS_NONE);
245 }
246
247 @Override
248 public void unencryptedMessageReceived(SessionID arg0, String arg1)
249 throws OtrException {
250 throw new OtrException(new Exception("unencrypted message received"));
251 }
252
253 @Override
254 public void unreadableMessageReceived(SessionID session) throws OtrException {
255 Log.d(Config.LOGTAG,"unreadable message received");
256 sendOtrErrorMessage(session, "You sent me an unreadable OTR-encrypted message");
257 }
258
259 public void sendOtrErrorMessage(SessionID session, String errorText) {
260 try {
261 Jid jid = Jid.fromSessionID(session);
262 Conversation conversation = mXmppConnectionService.find(account, jid);
263 String id = conversation == null ? null : conversation.getLastReceivedOtrMessageId();
264 if (id != null) {
265 MessagePacket packet = mXmppConnectionService.getMessageGenerator()
266 .generateOtrError(jid, id, errorText);
267 packet.setFrom(account.getJid());
268 mXmppConnectionService.sendMessagePacket(account,packet);
269 Log.d(Config.LOGTAG,packet.toString());
270 Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()
271 +": unreadable OTR message in "+conversation.getName());
272 }
273 } catch (InvalidJidException e) {
274 return;
275 }
276 }
277
278 @Override
279 public void unverify(SessionID id, String arg1) {
280 setSmpStatus(id, Conversation.Smp.STATUS_FAILED);
281 }
282
283 @Override
284 public void verify(SessionID id, String fingerprint, boolean approved) {
285 Log.d(Config.LOGTAG,"OtrService.verify("+id.toString()+","+fingerprint+","+String.valueOf(approved)+")");
286 try {
287 final Jid jid = Jid.fromSessionID(id);
288 Conversation conversation = this.mXmppConnectionService.find(this.account,jid);
289 if (conversation!=null) {
290 if (approved) {
291 conversation.getContact().addOtrFingerprint(fingerprint);
292 }
293 conversation.smp().hint = null;
294 conversation.smp().status = Conversation.Smp.STATUS_VERIFIED;
295 mXmppConnectionService.updateConversationUi();
296 mXmppConnectionService.syncRosterToDisk(conversation.getAccount());
297 }
298 } catch (final InvalidJidException ignored) {
299 }
300 }
301
302 @Override
303 public FragmenterInstructions getFragmenterInstructions(SessionID sessionID) {
304 return null;
305 }
306
307}