1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 package org.eclipse.jgit.transport;
44
45 import static java.nio.charset.StandardCharsets.ISO_8859_1;
46 import static java.nio.charset.StandardCharsets.UTF_8;
47
48 import java.security.InvalidKeyException;
49 import java.security.NoSuchAlgorithmException;
50
51 import javax.crypto.Mac;
52 import javax.crypto.spec.SecretKeySpec;
53
54 import org.eclipse.jgit.lib.Repository;
55 import org.eclipse.jgit.transport.PushCertificate.NonceStatus;
56
57
58
59
60
61
62 public class HMACSHA1NonceGenerator implements NonceGenerator {
63
64 private Mac mac;
65
66
67
68
69
70
71
72
73 public HMACSHA1NonceGenerator(String seed) throws IllegalStateException {
74 try {
75 byte[] keyBytes = seed.getBytes(ISO_8859_1);
76 SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
77 mac = Mac.getInstance("HmacSHA1");
78 mac.init(signingKey);
79 } catch (InvalidKeyException | NoSuchAlgorithmException e) {
80 throw new IllegalStateException(e);
81 }
82 }
83
84
85 @Override
86 public synchronized String createNonce(Repository repo, long timestamp)
87 throws IllegalStateException {
88 String input = repo.getIdentifier() + ":" + String.valueOf(timestamp);
89 byte[] rawHmac = mac.doFinal(input.getBytes(UTF_8));
90 return Long.toString(timestamp) + "-" + toHex(rawHmac);
91 }
92
93
94 @Override
95 public NonceStatus verify(String received, String sent,
96 Repository db, boolean allowSlop, int slop) {
97 if (received.isEmpty()) {
98 return NonceStatus.MISSING;
99 } else if (sent.isEmpty()) {
100 return NonceStatus.UNSOLICITED;
101 } else if (received.equals(sent)) {
102 return NonceStatus.OK;
103 }
104
105 if (!allowSlop) {
106 return NonceStatus.BAD;
107 }
108
109
110 int idxSent = sent.indexOf('-');
111 int idxRecv = received.indexOf('-');
112 if (idxSent == -1 || idxRecv == -1) {
113 return NonceStatus.BAD;
114 }
115
116 String signedStampStr = received.substring(0, idxRecv);
117 String advertisedStampStr = sent.substring(0, idxSent);
118 long signedStamp;
119 long advertisedStamp;
120 try {
121 signedStamp = Long.parseLong(signedStampStr);
122 advertisedStamp = Long.parseLong(advertisedStampStr);
123 } catch (IllegalArgumentException e) {
124 return NonceStatus.BAD;
125 }
126
127
128 String expect = createNonce(db, signedStamp);
129
130 if (!expect.equals(received)) {
131 return NonceStatus.BAD;
132 }
133
134 long nonceStampSlop = Math.abs(advertisedStamp - signedStamp);
135
136 if (nonceStampSlop <= slop) {
137 return NonceStatus.OK;
138 }
139 return NonceStatus.SLOP;
140 }
141
142 private static final String HEX = "0123456789ABCDEF";
143
144 private static String toHex(byte[] bytes) {
145 StringBuilder builder = new StringBuilder(2 * bytes.length);
146 for (byte b : bytes) {
147 builder.append(HEX.charAt((b & 0xF0) >> 4));
148 builder.append(HEX.charAt(b & 0xF));
149 }
150 return builder.toString();
151 }
152 }