You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PushCertificateParser.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /*
  2. * Copyright (C) 2015, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.transport;
  44. import static org.eclipse.jgit.transport.BaseReceivePack.parseCommand;
  45. import static org.eclipse.jgit.transport.GitProtocolConstants.CAPABILITY_PUSH_CERT;
  46. import java.io.EOFException;
  47. import java.io.IOException;
  48. import java.io.Reader;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Collections;
  52. import java.util.List;
  53. import java.util.concurrent.TimeUnit;
  54. import org.eclipse.jgit.errors.PackProtocolException;
  55. import org.eclipse.jgit.internal.JGitText;
  56. import org.eclipse.jgit.lib.Repository;
  57. import org.eclipse.jgit.transport.PushCertificate.NonceStatus;
  58. import org.eclipse.jgit.util.IO;
  59. /**
  60. * Parser for signed push certificates.
  61. *
  62. * @since 4.0
  63. */
  64. public class PushCertificateParser {
  65. static final String BEGIN_SIGNATURE =
  66. "-----BEGIN PGP SIGNATURE-----"; //$NON-NLS-1$
  67. static final String END_SIGNATURE =
  68. "-----END PGP SIGNATURE-----"; //$NON-NLS-1$
  69. static final String VERSION = "certificate version"; //$NON-NLS-1$
  70. static final String PUSHER = "pusher"; //$NON-NLS-1$
  71. static final String PUSHEE = "pushee"; //$NON-NLS-1$
  72. static final String NONCE = "nonce"; //$NON-NLS-1$
  73. static final String END_CERT = "push-cert-end"; //$NON-NLS-1$
  74. private static final String VERSION_0_1 = "0.1"; //$NON-NLS-1$
  75. private static interface StringReader {
  76. /**
  77. * @return the next string from the input, up to an optional newline, with
  78. * newline stripped if present
  79. *
  80. * @throws EOFException
  81. * if EOF was reached.
  82. * @throws IOException
  83. * if an error occurred during reading.
  84. */
  85. String read() throws EOFException, IOException;
  86. }
  87. private static class PacketLineReader implements StringReader {
  88. private final PacketLineIn pckIn;
  89. private PacketLineReader(PacketLineIn pckIn) {
  90. this.pckIn = pckIn;
  91. }
  92. @Override
  93. public String read() throws IOException {
  94. return pckIn.readString();
  95. }
  96. }
  97. private static class StreamReader implements StringReader {
  98. private final Reader reader;
  99. private StreamReader(Reader reader) {
  100. this.reader = reader;
  101. }
  102. @Override
  103. public String read() throws IOException {
  104. // Presize for a command containing 2 SHA-1s and some refname.
  105. String line = IO.readLine(reader, 41 * 2 + 64);
  106. if (line.isEmpty()) {
  107. throw new EOFException();
  108. } else if (line.charAt(line.length() - 1) == '\n') {
  109. line = line.substring(0, line.length() - 1);
  110. }
  111. return line;
  112. }
  113. }
  114. /**
  115. * Parse a push certificate from a reader.
  116. * <p>
  117. * Differences from the {@link PacketLineIn} receiver methods:
  118. * <ul>
  119. * <li>Does not use pkt-line framing.</li>
  120. * <li>Reads an entire cert in one call rather than depending on a loop in
  121. * the caller.</li>
  122. * <li>Does not assume a {@code "push-cert-end"} line.</li>
  123. * </ul>
  124. *
  125. * @param r
  126. * input reader; consumed only up until the end of the next
  127. * signature in the input.
  128. * @return the parsed certificate, or null if the reader was at EOF.
  129. * @throws PackProtocolException
  130. * if the certificate is malformed.
  131. * @throws IOException
  132. * if there was an error reading from the input.
  133. * @since 4.1
  134. */
  135. public static PushCertificate fromReader(Reader r)
  136. throws PackProtocolException, IOException {
  137. PushCertificateParser parser = new PushCertificateParser();
  138. StreamReader reader = new StreamReader(r);
  139. parser.receiveHeader(reader, true);
  140. String line;
  141. try {
  142. while (!(line = reader.read()).isEmpty()) {
  143. if (line.equals(BEGIN_SIGNATURE)) {
  144. parser.receiveSignature(reader);
  145. break;
  146. }
  147. parser.addCommand(line);
  148. }
  149. } catch (EOFException e) {
  150. // EOF reached, but might have been at a valid state. Let build call below
  151. // sort it out.
  152. }
  153. return parser.build();
  154. }
  155. private boolean received;
  156. private String version;
  157. private PushCertificateIdent pusher;
  158. private String pushee;
  159. /** The nonce that was sent to the client. */
  160. private String sentNonce;
  161. /**
  162. * The nonce the pusher signed.
  163. * <p>
  164. * This may vary from {@link #sentNonce}; see git-core documentation for
  165. * reasons.
  166. */
  167. private String receivedNonce;
  168. private NonceStatus nonceStatus;
  169. private String signature;
  170. /** Database we write the push certificate into. */
  171. private final Repository db;
  172. /**
  173. * The maximum time difference which is acceptable between advertised nonce
  174. * and received signed nonce.
  175. */
  176. private final int nonceSlopLimit;
  177. private final boolean enabled;
  178. private final NonceGenerator nonceGenerator;
  179. private final List<ReceiveCommand> commands = new ArrayList<>();
  180. PushCertificateParser(Repository into, SignedPushConfig cfg) {
  181. if (cfg != null) {
  182. nonceSlopLimit = cfg.getCertNonceSlopLimit();
  183. nonceGenerator = cfg.getNonceGenerator();
  184. } else {
  185. nonceSlopLimit = 0;
  186. nonceGenerator = null;
  187. }
  188. db = into;
  189. enabled = nonceGenerator != null;
  190. }
  191. private PushCertificateParser() {
  192. db = null;
  193. nonceSlopLimit = 0;
  194. nonceGenerator = null;
  195. enabled = true;
  196. }
  197. /**
  198. * @return the parsed certificate, or null if push certificates are disabled.
  199. * @throws IOException
  200. * if the push certificate has missing or invalid fields.
  201. * @since 4.1
  202. */
  203. public PushCertificate build() throws IOException {
  204. if (!received || !enabled) {
  205. return null;
  206. }
  207. try {
  208. return new PushCertificate(version, pusher, pushee, receivedNonce,
  209. nonceStatus, Collections.unmodifiableList(commands), signature);
  210. } catch (IllegalArgumentException e) {
  211. throw new IOException(e.getMessage(), e);
  212. }
  213. }
  214. /**
  215. * @return if the repository is configured to use signed pushes in this
  216. * context.
  217. * @since 4.0
  218. */
  219. public boolean enabled() {
  220. return enabled;
  221. }
  222. /**
  223. * @return the whole string for the nonce to be included into the capability
  224. * advertisement, or null if push certificates are disabled.
  225. * @since 4.0
  226. */
  227. public String getAdvertiseNonce() {
  228. String nonce = sentNonce();
  229. if (nonce == null) {
  230. return null;
  231. }
  232. return CAPABILITY_PUSH_CERT + '=' + nonce;
  233. }
  234. private String sentNonce() {
  235. if (sentNonce == null && nonceGenerator != null) {
  236. sentNonce = nonceGenerator.createNonce(db,
  237. TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
  238. }
  239. return sentNonce;
  240. }
  241. private static String parseHeader(StringReader reader, String header)
  242. throws IOException {
  243. return parseHeader(reader.read(), header);
  244. }
  245. private static String parseHeader(String s, String header)
  246. throws IOException {
  247. if (s.isEmpty()) {
  248. throw new EOFException();
  249. }
  250. if (s.length() <= header.length()
  251. || !s.startsWith(header)
  252. || s.charAt(header.length()) != ' ') {
  253. throw new PackProtocolException(MessageFormat.format(
  254. JGitText.get().pushCertificateInvalidField, header));
  255. }
  256. return s.substring(header.length() + 1);
  257. }
  258. /**
  259. * Receive a list of commands from the input encapsulated in a push
  260. * certificate.
  261. * <p>
  262. * This method doesn't parse the first line {@code "push-cert \NUL
  263. * &lt;capabilities&gt;"}, but assumes the first line including the
  264. * capabilities has already been handled by the caller.
  265. *
  266. * @param pckIn
  267. * where we take the push certificate header from.
  268. * @param stateless
  269. * affects nonce verification. When {@code stateless = true} the
  270. * {@code NonceGenerator} will allow for some time skew caused by
  271. * clients disconnected and reconnecting in the stateless smart
  272. * HTTP protocol.
  273. * @throws IOException
  274. * if the certificate from the client is badly malformed or the
  275. * client disconnects before sending the entire certificate.
  276. * @since 4.0
  277. */
  278. public void receiveHeader(PacketLineIn pckIn, boolean stateless)
  279. throws IOException {
  280. receiveHeader(new PacketLineReader(pckIn), stateless);
  281. }
  282. private void receiveHeader(StringReader reader, boolean stateless)
  283. throws IOException {
  284. try {
  285. try {
  286. version = parseHeader(reader, VERSION);
  287. } catch (EOFException e) {
  288. return;
  289. }
  290. received = true;
  291. if (!version.equals(VERSION_0_1)) {
  292. throw new PackProtocolException(MessageFormat.format(
  293. JGitText.get().pushCertificateInvalidFieldValue, VERSION, version));
  294. }
  295. String rawPusher = parseHeader(reader, PUSHER);
  296. pusher = PushCertificateIdent.parse(rawPusher);
  297. if (pusher == null) {
  298. throw new PackProtocolException(MessageFormat.format(
  299. JGitText.get().pushCertificateInvalidFieldValue,
  300. PUSHER, rawPusher));
  301. }
  302. String next = reader.read();
  303. if (next.startsWith(PUSHEE)) {
  304. pushee = parseHeader(next, PUSHEE);
  305. receivedNonce = parseHeader(reader, NONCE);
  306. } else {
  307. receivedNonce = parseHeader(next, NONCE);
  308. }
  309. nonceStatus = nonceGenerator != null
  310. ? nonceGenerator.verify(
  311. receivedNonce, sentNonce(), db, stateless, nonceSlopLimit)
  312. : NonceStatus.UNSOLICITED;
  313. // An empty line.
  314. if (!reader.read().isEmpty()) {
  315. throw new PackProtocolException(
  316. JGitText.get().pushCertificateInvalidHeader);
  317. }
  318. } catch (EOFException eof) {
  319. throw new PackProtocolException(
  320. JGitText.get().pushCertificateInvalidHeader, eof);
  321. }
  322. }
  323. /**
  324. * Read the PGP signature.
  325. * <p>
  326. * This method assumes the line
  327. * {@code "-----BEGIN PGP SIGNATURE-----"} has already been parsed,
  328. * and continues parsing until an {@code "-----END PGP SIGNATURE-----"} is
  329. * found, followed by {@code "push-cert-end"}.
  330. *
  331. * @param pckIn
  332. * where we read the signature from.
  333. * @throws IOException
  334. * if the signature is invalid.
  335. * @since 4.0
  336. */
  337. public void receiveSignature(PacketLineIn pckIn) throws IOException {
  338. StringReader reader = new PacketLineReader(pckIn);
  339. receiveSignature(reader);
  340. if (!reader.read().equals(END_CERT)) {
  341. throw new PackProtocolException(
  342. JGitText.get().pushCertificateInvalidSignature);
  343. }
  344. }
  345. private void receiveSignature(StringReader reader) throws IOException {
  346. received = true;
  347. try {
  348. StringBuilder sig = new StringBuilder(BEGIN_SIGNATURE).append('\n');
  349. String line;
  350. while (!(line = reader.read()).equals(END_SIGNATURE)) {
  351. sig.append(line).append('\n');
  352. }
  353. signature = sig.append(END_SIGNATURE).append('\n').toString();
  354. } catch (EOFException eof) {
  355. throw new PackProtocolException(
  356. JGitText.get().pushCertificateInvalidSignature, eof);
  357. }
  358. }
  359. /**
  360. * Add a command to the signature.
  361. *
  362. * @param cmd
  363. * the command.
  364. * @since 4.1
  365. */
  366. public void addCommand(ReceiveCommand cmd) {
  367. commands.add(cmd);
  368. }
  369. /**
  370. * Add a command to the signature.
  371. *
  372. * @param line
  373. * the line read from the wire that produced this
  374. * command, with optional trailing newline already trimmed.
  375. * @throws PackProtocolException
  376. * if the raw line cannot be parsed to a command.
  377. * @since 4.0
  378. */
  379. public void addCommand(String line) throws PackProtocolException {
  380. commands.add(parseCommand(line));
  381. }
  382. }