1 /*
   2  * Copyright (c) 2003, 2012, 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 
  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             macLength = 28;
  95             break;
  96         case (int)CKM_SHA256_HMAC:
  97             macLength = 32;
  98             break;
  99         case (int)CKM_SHA384_HMAC:
 100             macLength = 48;
 101             break;
 102         case (int)CKM_SHA512_HMAC:
 103             macLength = 64;
 104             break;
 105         case (int)CKM_SSL3_MD5_MAC:
 106             macLength = 16;
 107             params = Long.valueOf(16);
 108             break;
 109         case (int)CKM_SSL3_SHA1_MAC:
 110             macLength = 20;
 111             params = Long.valueOf(20);
 112             break;
 113         default:
 114             throw new ProviderException("Unknown mechanism: " + mechanism);
 115         }
 116         ckMechanism = new CK_MECHANISM(mechanism, params);
 117     }
 118 
 119     // reset the states to the pre-initialized values
 120     private void reset(boolean doCancel) {
 121         if (!initialized) {
 122             return;
 123         }
 124         initialized = false;
 125         try {
 126             if (session == null) {
 127                 return;
 128             }
 129             if (doCancel && token.explicitCancel) {
 130                 cancelOperation();
 131             }
 132         } finally {
 133             p11Key.decNativeKeyRef();
 134             session = token.releaseSession(session);
 135         }
 136     }
 137 
 138     private void cancelOperation() {
 139         token.ensureValid();
 140         if (session.hasObjects() == false) {
 141             session = token.killSession(session);
 142             return;
 143         } else {
 144             try {
 145                 token.p11.C_SignFinal(session.id(), 0);
 146             } catch (PKCS11Exception e) {
 147                 throw new ProviderException("Cancel failed", e);
 148             }
 149         }
 150     }
 151 
 152     private void ensureInitialized() throws PKCS11Exception {
 153         if (initialized) {
 154             return;
 155         }
 156         if (p11Key == null) {
 157             throw new ProviderException(
 158                     "Operation cannot be performed without calling engineInit first");
 159         }
 160         token.ensureValid();
 161         p11Key.incNativeKeyRef();
 162         try {
 163             if (session == null) {
 164                 session = token.getOpSession();
 165             }
 166             token.p11.C_SignInit
 167                 (session.id(), ckMechanism, p11Key.keyID);
 168         } catch (Throwable t) {
 169             p11Key.decNativeKeyRef();
 170             session = token.releaseSession(session);
 171             throw t;
 172         }
 173         initialized = true;
 174     }
 175 
 176     // see JCE spec
 177     protected int engineGetMacLength() {
 178         return macLength;
 179     }
 180 
 181     // see JCE spec
 182     protected void engineReset() {
 183         reset(true);
 184     }
 185 
 186     // see JCE spec
 187     protected void engineInit(Key key, AlgorithmParameterSpec params)
 188             throws InvalidKeyException, InvalidAlgorithmParameterException {
 189         if (params != null) {
 190             throw new InvalidAlgorithmParameterException
 191                 ("Parameters not supported");
 192         }
 193         reset(true);
 194         p11Key = P11SecretKeyFactory.convertKey(token, key, algorithm);
 195         try {
 196             ensureInitialized();
 197         } catch (PKCS11Exception e) {
 198             throw new InvalidKeyException("init() failed", e);
 199         }
 200     }
 201 
 202     // see JCE spec
 203     protected byte[] engineDoFinal() {
 204         try {
 205             ensureInitialized();
 206             return token.p11.C_SignFinal(session.id(), 0);
 207         } catch (PKCS11Exception e) {
 208             reset(true);
 209             throw new ProviderException("doFinal() failed", e);
 210         } finally {
 211             reset(false);
 212         }
 213     }
 214 
 215     // see JCE spec
 216     protected void engineUpdate(byte input) {
 217         if (oneByte == null) {
 218            oneByte = new byte[1];
 219         }
 220         oneByte[0] = input;
 221         engineUpdate(oneByte, 0, 1);
 222     }
 223 
 224     // see JCE spec
 225     protected void engineUpdate(byte[] b, int ofs, int len) {
 226         try {
 227             ensureInitialized();
 228             token.p11.C_SignUpdate(session.id(), 0, b, ofs, len);
 229         } catch (PKCS11Exception e) {
 230             throw new ProviderException("update() failed", e);
 231         }
 232     }
 233 
 234     // see JCE spec
 235     protected void engineUpdate(ByteBuffer byteBuffer) {
 236         try {
 237             ensureInitialized();
 238             int len = byteBuffer.remaining();
 239             if (len <= 0) {
 240                 return;
 241             }
 242             if (byteBuffer instanceof DirectBuffer == false) {
 243                 super.engineUpdate(byteBuffer);
 244                 return;
 245             }
 246             long addr = ((DirectBuffer)byteBuffer).address();
 247             int ofs = byteBuffer.position();
 248             token.p11.C_SignUpdate(session.id(), addr + ofs, null, 0, len);
 249             byteBuffer.position(ofs + len);
 250         } catch (PKCS11Exception e) {
 251             throw new ProviderException("update() failed", e);
 252         }
 253     }
 254 }