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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 org.eclipse.jgit.transport.PacketLineIn}
  118. * receiver methods:
  119. * <ul>
  120. * <li>Does not use pkt-line framing.</li>
  121. * <li>Reads an entire cert in one call rather than depending on a loop in
  122. * the caller.</li>
  123. * <li>Does not assume a {@code "push-cert-end"} line.</li>
  124. * </ul>
  125. *
  126. * @param r
  127. * input reader; consumed only up until the end of the next
  128. * signature in the input.
  129. * @return the parsed certificate, or null if the reader was at EOF.
  130. * @throws org.eclipse.jgit.errors.PackProtocolException
  131. * if the certificate is malformed.
  132. * @throws java.io.IOException
  133. * if there was an error reading from the input.
  134. * @since 4.1
  135. */
  136. public static PushCertificate fromReader(Reader r)
  137. throws PackProtocolException, IOException {
  138. return new PushCertificateParser().parse(r);
  139. }
  140. /**
  141. * Parse a push certificate from a string.
  142. *
  143. * @see #fromReader(Reader)
  144. * @param str
  145. * input string.
  146. * @return the parsed certificate.
  147. * @throws org.eclipse.jgit.errors.PackProtocolException
  148. * if the certificate is malformed.
  149. * @throws java.io.IOException
  150. * if there was an error reading from the input.
  151. * @since 4.1
  152. */
  153. public static PushCertificate fromString(String str)
  154. throws PackProtocolException, IOException {
  155. return fromReader(new java.io.StringReader(str));
  156. }
  157. private boolean received;
  158. private String version;
  159. private PushCertificateIdent pusher;
  160. private String pushee;
  161. /** The nonce that was sent to the client. */
  162. private String sentNonce;
  163. /**
  164. * The nonce the pusher signed.
  165. * <p>
  166. * This may vary from {@link #sentNonce}; see git-core documentation for
  167. * reasons.
  168. */
  169. private String receivedNonce;
  170. private NonceStatus nonceStatus;
  171. private String signature;
  172. /** Database we write the push certificate into. */
  173. private final Repository db;
  174. /**
  175. * The maximum time difference which is acceptable between advertised nonce
  176. * and received signed nonce.
  177. */
  178. private final int nonceSlopLimit;
  179. private final boolean enabled;
  180. private final NonceGenerator nonceGenerator;
  181. private final List<ReceiveCommand> commands = new ArrayList<>();
  182. /**
  183. * <p>Constructor for PushCertificateParser.</p>
  184. *
  185. * @param into
  186. * destination repository for the push.
  187. * @param cfg
  188. * configuration for signed push.
  189. * @since 4.1
  190. */
  191. public PushCertificateParser(Repository into, SignedPushConfig cfg) {
  192. if (cfg != null) {
  193. nonceSlopLimit = cfg.getCertNonceSlopLimit();
  194. nonceGenerator = cfg.getNonceGenerator();
  195. } else {
  196. nonceSlopLimit = 0;
  197. nonceGenerator = null;
  198. }
  199. db = into;
  200. enabled = nonceGenerator != null;
  201. }
  202. private PushCertificateParser() {
  203. db = null;
  204. nonceSlopLimit = 0;
  205. nonceGenerator = null;
  206. enabled = true;
  207. }
  208. /**
  209. * Parse a push certificate from a reader.
  210. *
  211. * @see #fromReader(Reader)
  212. * @param r
  213. * input reader; consumed only up until the end of the next
  214. * signature in the input.
  215. * @return the parsed certificate, or null if the reader was at EOF.
  216. * @throws org.eclipse.jgit.errors.PackProtocolException
  217. * if the certificate is malformed.
  218. * @throws java.io.IOException
  219. * if there was an error reading from the input.
  220. * @since 4.1
  221. */
  222. public PushCertificate parse(Reader r)
  223. throws PackProtocolException, IOException {
  224. StreamReader reader = new StreamReader(r);
  225. receiveHeader(reader, true);
  226. String line;
  227. try {
  228. while (!(line = reader.read()).isEmpty()) {
  229. if (line.equals(BEGIN_SIGNATURE)) {
  230. receiveSignature(reader);
  231. break;
  232. }
  233. addCommand(line);
  234. }
  235. } catch (EOFException e) {
  236. // EOF reached, but might have been at a valid state. Let build call below
  237. // sort it out.
  238. }
  239. return build();
  240. }
  241. /**
  242. * Build the parsed certificate
  243. *
  244. * @return the parsed certificate, or null if push certificates are
  245. * disabled.
  246. * @throws java.io.IOException
  247. * if the push certificate has missing or invalid fields.
  248. * @since 4.1
  249. */
  250. public PushCertificate build() throws IOException {
  251. if (!received || !enabled) {
  252. return null;
  253. }
  254. try {
  255. return new PushCertificate(version, pusher, pushee, receivedNonce,
  256. nonceStatus, Collections.unmodifiableList(commands), signature);
  257. } catch (IllegalArgumentException e) {
  258. throw new IOException(e.getMessage(), e);
  259. }
  260. }
  261. /**
  262. * Whether the repository is configured to use signed pushes in this
  263. * context.
  264. *
  265. * @return if the repository is configured to use signed pushes in this
  266. * context.
  267. * @since 4.0
  268. */
  269. public boolean enabled() {
  270. return enabled;
  271. }
  272. /**
  273. * Get the whole string for the nonce to be included into the capability
  274. * advertisement
  275. *
  276. * @return the whole string for the nonce to be included into the capability
  277. * advertisement, or null if push certificates are disabled.
  278. * @since 4.0
  279. */
  280. public String getAdvertiseNonce() {
  281. String nonce = sentNonce();
  282. if (nonce == null) {
  283. return null;
  284. }
  285. return CAPABILITY_PUSH_CERT + '=' + nonce;
  286. }
  287. private String sentNonce() {
  288. if (sentNonce == null && nonceGenerator != null) {
  289. sentNonce = nonceGenerator.createNonce(db,
  290. TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
  291. }
  292. return sentNonce;
  293. }
  294. private static String parseHeader(StringReader reader, String header)
  295. throws IOException {
  296. return parseHeader(reader.read(), header);
  297. }
  298. private static String parseHeader(String s, String header)
  299. throws IOException {
  300. if (s.isEmpty()) {
  301. throw new EOFException();
  302. }
  303. if (s.length() <= header.length()
  304. || !s.startsWith(header)
  305. || s.charAt(header.length()) != ' ') {
  306. throw new PackProtocolException(MessageFormat.format(
  307. JGitText.get().pushCertificateInvalidField, header));
  308. }
  309. return s.substring(header.length() + 1);
  310. }
  311. /**
  312. * Receive a list of commands from the input encapsulated in a push
  313. * certificate.
  314. * <p>
  315. * This method doesn't parse the first line {@code "push-cert \NUL
  316. * &lt;capabilities&gt;"}, but assumes the first line including the
  317. * capabilities has already been handled by the caller.
  318. *
  319. * @param pckIn
  320. * where we take the push certificate header from.
  321. * @param stateless
  322. * affects nonce verification. When {@code stateless = true} the
  323. * {@code NonceGenerator} will allow for some time skew caused by
  324. * clients disconnected and reconnecting in the stateless smart
  325. * HTTP protocol.
  326. * @throws java.io.IOException
  327. * if the certificate from the client is badly malformed or the
  328. * client disconnects before sending the entire certificate.
  329. * @since 4.0
  330. */
  331. public void receiveHeader(PacketLineIn pckIn, boolean stateless)
  332. throws IOException {
  333. receiveHeader(new PacketLineReader(pckIn), stateless);
  334. }
  335. private void receiveHeader(StringReader reader, boolean stateless)
  336. throws IOException {
  337. try {
  338. try {
  339. version = parseHeader(reader, VERSION);
  340. } catch (EOFException e) {
  341. return;
  342. }
  343. received = true;
  344. if (!version.equals(VERSION_0_1)) {
  345. throw new PackProtocolException(MessageFormat.format(
  346. JGitText.get().pushCertificateInvalidFieldValue, VERSION, version));
  347. }
  348. String rawPusher = parseHeader(reader, PUSHER);
  349. pusher = PushCertificateIdent.parse(rawPusher);
  350. if (pusher == null) {
  351. throw new PackProtocolException(MessageFormat.format(
  352. JGitText.get().pushCertificateInvalidFieldValue,
  353. PUSHER, rawPusher));
  354. }
  355. String next = reader.read();
  356. if (next.startsWith(PUSHEE)) {
  357. pushee = parseHeader(next, PUSHEE);
  358. receivedNonce = parseHeader(reader, NONCE);
  359. } else {
  360. receivedNonce = parseHeader(next, NONCE);
  361. }
  362. nonceStatus = nonceGenerator != null
  363. ? nonceGenerator.verify(
  364. receivedNonce, sentNonce(), db, stateless, nonceSlopLimit)
  365. : NonceStatus.UNSOLICITED;
  366. // An empty line.
  367. if (!reader.read().isEmpty()) {
  368. throw new PackProtocolException(
  369. JGitText.get().pushCertificateInvalidHeader);
  370. }
  371. } catch (EOFException eof) {
  372. throw new PackProtocolException(
  373. JGitText.get().pushCertificateInvalidHeader, eof);
  374. }
  375. }
  376. /**
  377. * Read the PGP signature.
  378. * <p>
  379. * This method assumes the line
  380. * {@code "-----BEGIN PGP SIGNATURE-----"} has already been parsed,
  381. * and continues parsing until an {@code "-----END PGP SIGNATURE-----"} is
  382. * found, followed by {@code "push-cert-end"}.
  383. *
  384. * @param pckIn
  385. * where we read the signature from.
  386. * @throws java.io.IOException
  387. * if the signature is invalid.
  388. * @since 4.0
  389. */
  390. public void receiveSignature(PacketLineIn pckIn) throws IOException {
  391. StringReader reader = new PacketLineReader(pckIn);
  392. receiveSignature(reader);
  393. if (!reader.read().equals(END_CERT)) {
  394. throw new PackProtocolException(
  395. JGitText.get().pushCertificateInvalidSignature);
  396. }
  397. }
  398. private void receiveSignature(StringReader reader) throws IOException {
  399. received = true;
  400. try {
  401. StringBuilder sig = new StringBuilder(BEGIN_SIGNATURE).append('\n');
  402. String line;
  403. while (!(line = reader.read()).equals(END_SIGNATURE)) {
  404. sig.append(line).append('\n');
  405. }
  406. signature = sig.append(END_SIGNATURE).append('\n').toString();
  407. } catch (EOFException eof) {
  408. throw new PackProtocolException(
  409. JGitText.get().pushCertificateInvalidSignature, eof);
  410. }
  411. }
  412. /**
  413. * Add a command to the signature.
  414. *
  415. * @param cmd
  416. * the command.
  417. * @since 4.1
  418. */
  419. public void addCommand(ReceiveCommand cmd) {
  420. commands.add(cmd);
  421. }
  422. /**
  423. * Add a command to the signature.
  424. *
  425. * @param line
  426. * the line read from the wire that produced this
  427. * command, with optional trailing newline already trimmed.
  428. * @throws org.eclipse.jgit.errors.PackProtocolException
  429. * if the raw line cannot be parsed to a command.
  430. * @since 4.0
  431. */
  432. public void addCommand(String line) throws PackProtocolException {
  433. commands.add(parseCommand(line));
  434. }
  435. }