1 /*
2  * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package sun.security.pkcs11;
27 
28 import java.nio.ByteBuffer;
29 
30 import java.security.*;
31 import java.security.spec.AlgorithmParameterSpec;
32 
33 import javax.crypto.MacSpi;
34 
35 import sun.nio.ch.DirectBuffer;
36 
37 import sun.security.pkcs11.wrapper.*;
38 import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
39 
40 /**
41  * MAC implementation class. This class currently supports HMAC using
42  * MD5, SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 and the SSL3 MAC
43  * using MD5 and SHA-1.
44  *
45  * Note that unlike other classes (e.g. Signature), this does not
46  * composite various operations if the token only supports part of the
47  * required functionality. The MAC implementations in SunJCE already
48  * do exactly that by implementing an MAC on top of MessageDigests. We
49  * could not do any better than they.
50  *
51  * @author  Andreas Sterbenz
52  * @since   1.5
53  */
54 final class P11Mac extends MacSpi {
55 
56     // token instance
57     private final Token token;
58 
59     // algorithm name
60     private final String algorithm;
61 
62     // mechanism object
63     private final CK_MECHANISM ckMechanism;
64 
65     // length of the MAC in bytes
66     private final int macLength;
67 
68     // key instance used, if operation active
69     private P11Key p11Key;
70 
71     // associated session, if any
72     private Session session;
73 
74     // initialization status
75     private boolean initialized;
76 
77     // one byte buffer for the update(byte) method, initialized on demand
78     private byte[] oneByte;
79 
P11Mac(Token token, String algorithm, long mechanism)80     P11Mac(Token token, String algorithm, long mechanism)
81             throws PKCS11Exception {
82         super();
83         this.token = token;
84         this.algorithm = algorithm;
85         Long params = null;
86         switch ((int)mechanism) {
87         case (int)CKM_MD5_HMAC:
88             macLength = 16;
89             break;
90         case (int)CKM_SHA_1_HMAC:
91             macLength = 20;
92             break;
93         case (int)CKM_SHA224_HMAC:
94         case (int)CKM_SHA512_224_HMAC:
95             macLength = 28;
96             break;
97         case (int)CKM_SHA256_HMAC:
98         case (int)CKM_SHA512_256_HMAC:
99             macLength = 32;
100             break;
101         case (int)CKM_SHA384_HMAC:
102             macLength = 48;
103             break;
104         case (int)CKM_SHA512_HMAC:
105             macLength = 64;
106             break;
107         case (int)CKM_SSL3_MD5_MAC:
108             macLength = 16;
109             params = Long.valueOf(16);
110             break;
111         case (int)CKM_SSL3_SHA1_MAC:
112             macLength = 20;
113             params = Long.valueOf(20);
114             break;
115         default:
116             throw new ProviderException("Unknown mechanism: " + mechanism);
117         }
118         ckMechanism = new CK_MECHANISM(mechanism, params);
119     }
120 
121     // reset the states to the pre-initialized values
reset(boolean doCancel)122     private void reset(boolean doCancel) {
123         if (!initialized) {
124             return;
125         }
126         initialized = false;
127 
128         try {
129             if (session == null) {
130                 return;
131             }
132 
133             if (doCancel && token.explicitCancel) {
134                 cancelOperation();
135             }
136         } finally {
137             p11Key.releaseKeyID();
138             session = token.releaseSession(session);
139         }
140     }
141 
cancelOperation()142     private void cancelOperation() {
143         token.ensureValid();
144         // cancel operation by finishing it; avoid killSession as some
145         // hardware vendors may require re-login
146         try {
147             token.p11.C_SignFinal(session.id(), 0);
148         } catch (PKCS11Exception e) {
149             throw new ProviderException("Cancel failed", e);
150         }
151     }
152 
ensureInitialized()153     private void ensureInitialized() throws PKCS11Exception {
154         if (!initialized) {
155             initialize();
156         }
157     }
158 
initialize()159     private void initialize() throws PKCS11Exception {
160         if (p11Key == null) {
161             throw new ProviderException(
162                     "Operation cannot be performed without calling engineInit first");
163         }
164         token.ensureValid();
165         long p11KeyID = p11Key.getKeyID();
166         try {
167             if (session == null) {
168                 session = token.getOpSession();
169             }
170             token.p11.C_SignInit(session.id(), ckMechanism, p11KeyID);
171         } catch (PKCS11Exception e) {
172             p11Key.releaseKeyID();
173             session = token.releaseSession(session);
174             throw e;
175         }
176         initialized = true;
177     }
178 
179     // see JCE spec
engineGetMacLength()180     protected int engineGetMacLength() {
181         return macLength;
182     }
183 
184     // see JCE spec
engineReset()185     protected void engineReset() {
186         reset(true);
187     }
188 
189     // see JCE spec
engineInit(Key key, AlgorithmParameterSpec params)190     protected void engineInit(Key key, AlgorithmParameterSpec params)
191             throws InvalidKeyException, InvalidAlgorithmParameterException {
192         if (params != null) {
193             throw new InvalidAlgorithmParameterException
194                 ("Parameters not supported");
195         }
196         reset(true);
197         p11Key = P11SecretKeyFactory.convertKey(token, key, algorithm);
198         try {
199             initialize();
200         } catch (PKCS11Exception e) {
201             throw new InvalidKeyException("init() failed", e);
202         }
203     }
204 
205     // see JCE spec
engineDoFinal()206     protected byte[] engineDoFinal() {
207         try {
208             ensureInitialized();
209             return token.p11.C_SignFinal(session.id(), 0);
210         } catch (PKCS11Exception e) {
211             throw new ProviderException("doFinal() failed", e);
212         } finally {
213             reset(false);
214         }
215     }
216 
217     // see JCE spec
engineUpdate(byte input)218     protected void engineUpdate(byte input) {
219         if (oneByte == null) {
220            oneByte = new byte[1];
221         }
222         oneByte[0] = input;
223         engineUpdate(oneByte, 0, 1);
224     }
225 
226     // see JCE spec
engineUpdate(byte[] b, int ofs, int len)227     protected void engineUpdate(byte[] b, int ofs, int len) {
228         try {
229             ensureInitialized();
230             token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);
231         } catch (PKCS11Exception e) {
232             throw new ProviderException("update() failed", e);
233         }
234     }
235 
236     // see JCE spec
engineUpdate(ByteBuffer byteBuffer)237     protected void engineUpdate(ByteBuffer byteBuffer) {
238         try {
239             ensureInitialized();
240             int len = byteBuffer.remaining();
241             if (len <= 0) {
242                 return;
243             }
244             if (byteBuffer instanceof DirectBuffer == false) {
245                 super.engineUpdate(byteBuffer);
246                 return;
247             }
248             long addr = ((DirectBuffer)byteBuffer).address();
249             int ofs = byteBuffer.position();
250             token.p11.C_SignUpdate(session.id(), addr + ofs, null, 0, len);
251             byteBuffer.position(ofs + len);
252         } catch (PKCS11Exception e) {
253             throw new ProviderException("update() failed", e);
254         }
255     }
256 }
257