View Javadoc
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  
45  import java.io.File;
46  import java.io.UnsupportedEncodingException;
47  import java.security.InvalidKeyException;
48  import java.security.NoSuchAlgorithmException;
49  
50  import javax.crypto.Mac;
51  import javax.crypto.spec.SecretKeySpec;
52  
53  import org.eclipse.jgit.internal.storage.dfs.DfsRepository;
54  import org.eclipse.jgit.lib.Repository;
55  import org.eclipse.jgit.transport.PushCertificate.NonceStatus;
56  
57  /**
58   * The nonce generator which was first introduced to git-core.
59   *
60   * @since 4.0
61   */
62  public class HMACSHA1NonceGenerator implements NonceGenerator {
63  
64  	private Mac mac;
65  
66  	/**
67  	 * @param seed
68  	 * @throws IllegalStateException
69  	 */
70  	public HMACSHA1NonceGenerator(String seed) throws IllegalStateException {
71  		try {
72  			byte[] keyBytes = seed.getBytes("ISO-8859-1"); //$NON-NLS-1$
73  			SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); //$NON-NLS-1$
74  			mac = Mac.getInstance("HmacSHA1"); //$NON-NLS-1$
75  			mac.init(signingKey);
76  		} catch (InvalidKeyException e) {
77  			throw new IllegalStateException(e);
78  		} catch (NoSuchAlgorithmException e) {
79  			throw new IllegalStateException(e);
80  		} catch (UnsupportedEncodingException e) {
81  			throw new IllegalStateException(e);
82  		}
83  	}
84  
85  	@Override
86  	public synchronized String createNonce(Repository repo, long timestamp)
87  			throws IllegalStateException {
88  		String path;
89  		if (repo instanceof DfsRepository) {
90  			path = ((DfsRepository) repo).getDescription().getRepositoryName();
91  		} else {
92  			File directory = repo.getDirectory();
93  			if (directory != null) {
94  				path = directory.getPath();
95  			} else {
96  				throw new IllegalStateException();
97  			}
98  		}
99  
100 		String input = path + ":" + String.valueOf(timestamp); //$NON-NLS-1$
101 		byte[] rawHmac;
102 		try {
103 			rawHmac = mac.doFinal(input.getBytes("UTF-8")); //$NON-NLS-1$
104 		} catch (UnsupportedEncodingException e) {
105 			throw new IllegalStateException(e);
106 		}
107 		return Long.toString(timestamp) + "-" + toHex(rawHmac); //$NON-NLS-1$
108 	}
109 
110 	@Override
111 	public NonceStatus verify(String received, String sent,
112 			Repository db, boolean allowSlop, int slop) {
113 		if (received.isEmpty()) {
114 			return NonceStatus.MISSING;
115 		} else if (sent.isEmpty()) {
116 			return NonceStatus.UNSOLICITED;
117 		} else if (received.equals(sent)) {
118 			return NonceStatus.OK;
119 		}
120 
121 		if (!allowSlop) {
122 			return NonceStatus.BAD;
123 		}
124 
125 		/* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
126 		int idxSent = sent.indexOf('-');
127 		int idxRecv = received.indexOf('-');
128 		if (idxSent == -1 || idxRecv == -1) {
129 			return NonceStatus.BAD;
130 		}
131 
132 		String signedStampStr = received.substring(0, idxRecv);
133 		String advertisedStampStr = sent.substring(0, idxSent);
134 		long signedStamp;
135 		long advertisedStamp;
136 		try {
137 			signedStamp = Long.parseLong(signedStampStr);
138 			advertisedStamp = Long.parseLong(advertisedStampStr);
139 		} catch (IllegalArgumentException e) {
140 			return NonceStatus.BAD;
141 		}
142 
143 		// what we would have signed earlier
144 		String expect = createNonce(db, signedStamp);
145 
146 		if (!expect.equals(received)) {
147 			return NonceStatus.BAD;
148 		}
149 
150 		long nonceStampSlop = Math.abs(advertisedStamp - signedStamp);
151 
152 		if (nonceStampSlop <= slop) {
153 			return NonceStatus.OK;
154 		} else {
155 			return NonceStatus.SLOP;
156 		}
157 	}
158 
159 	private static final String HEX = "0123456789ABCDEF"; //$NON-NLS-1$
160 
161 	private static String toHex(byte[] bytes) {
162 		StringBuilder builder = new StringBuilder(2 * bytes.length);
163 		for (byte b : bytes) {
164 			builder.append(HEX.charAt((b & 0xF0) >> 4));
165 			builder.append(HEX.charAt(b & 0xF));
166 		}
167 		return builder.toString();
168 	}
169 }