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

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