View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import java.security.PrivateKey;
19  
20  import javax.security.auth.Destroyable;
21  
22  import io.netty.buffer.ByteBuf;
23  import io.netty.buffer.ByteBufAllocator;
24  import io.netty.buffer.Unpooled;
25  import io.netty.util.AbstractReferenceCounted;
26  import io.netty.util.CharsetUtil;
27  import io.netty.util.IllegalReferenceCountException;
28  import io.netty.util.internal.ObjectUtil;
29  
30  /**
31   * This is a special purpose implementation of a {@link PrivateKey} which allows the
32   * user to pass PEM/PKCS#8 encoded key material straight into {@link OpenSslContext}
33   * without having to parse and re-encode bytes in Java land.
34   *
35   * All methods other than what's implemented in {@link PemEncoded} and {@link Destroyable}
36   * throw {@link UnsupportedOperationException}s.
37   *
38   * @see PemEncoded
39   * @see OpenSslContext
40   * @see #valueOf(byte[])
41   * @see #valueOf(ByteBuf)
42   */
43  public final class PemPrivateKey extends AbstractReferenceCounted implements PrivateKey, PemEncoded {
44      private static final long serialVersionUID = 7978017465645018936L;
45  
46      private static final byte[] BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n".getBytes(CharsetUtil.US_ASCII);
47      private static final byte[] END_PRIVATE_KEY = "\n-----END PRIVATE KEY-----\n".getBytes(CharsetUtil.US_ASCII);
48  
49      private static final String PKCS8_FORMAT = "PKCS#8";
50  
51      /**
52       * Creates a {@link PemEncoded} value from the {@link PrivateKey}.
53       */
54      static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect, PrivateKey key) {
55          // We can take a shortcut if the private key happens to be already
56          // PEM/PKCS#8 encoded. This is the ideal case and reason why all
57          // this exists. It allows the user to pass pre-encoded bytes straight
58          // into OpenSSL without having to do any of the extra work.
59          if (key instanceof PemEncoded) {
60              return ((PemEncoded) key).retain();
61          }
62  
63          byte[] bytes = key.getEncoded();
64          if (bytes == null) {
65              throw new IllegalArgumentException(key.getClass().getName() + " does not support encoding");
66          }
67  
68          ByteBuf encoded = Unpooled.wrappedBuffer(bytes);
69          try {
70              ByteBuf base64 = SslUtils.toBase64(allocator, encoded);
71              try {
72                  int size = BEGIN_PRIVATE_KEY.length + base64.readableBytes() + END_PRIVATE_KEY.length;
73  
74                  boolean success = false;
75                  final ByteBuf pem = useDirect ? allocator.directBuffer(size) : allocator.buffer(size);
76                  try {
77                      pem.writeBytes(BEGIN_PRIVATE_KEY);
78                      pem.writeBytes(base64);
79                      pem.writeBytes(END_PRIVATE_KEY);
80  
81                      PemValue value = new PemValue(pem, true);
82                      success = true;
83                      return value;
84                  } finally {
85                      // Make sure we never leak that PEM ByteBuf if there's an Exception.
86                      if (!success) {
87                          SslUtils.zerooutAndRelease(pem);
88                      }
89                  }
90              } finally {
91                  SslUtils.zerooutAndRelease(base64);
92              }
93          } finally {
94              SslUtils.zerooutAndRelease(encoded);
95          }
96      }
97  
98      /**
99       * Creates a {@link PemPrivateKey} from raw {@code byte[]}.
100      *
101      * ATTENTION: It's assumed that the given argument is a PEM/PKCS#8 encoded value.
102      * No input validation is performed to validate it.
103      */
104     public static PemPrivateKey valueOf(byte[] key) {
105         return valueOf(Unpooled.wrappedBuffer(key));
106     }
107 
108     /**
109      * Creates a {@link PemPrivateKey} from raw {@code ByteBuf}.
110      *
111      * ATTENTION: It's assumed that the given argument is a PEM/PKCS#8 encoded value.
112      * No input validation is performed to validate it.
113      */
114     public static PemPrivateKey valueOf(ByteBuf key) {
115         return new PemPrivateKey(key);
116     }
117 
118     private final ByteBuf content;
119 
120     private PemPrivateKey(ByteBuf content) {
121         this.content = ObjectUtil.checkNotNull(content, "content");
122     }
123 
124     @Override
125     public boolean isSensitive() {
126         return true;
127     }
128 
129     @Override
130     public ByteBuf content() {
131         int count = refCnt();
132         if (count <= 0) {
133             throw new IllegalReferenceCountException(count);
134         }
135 
136         return content;
137     }
138 
139     @Override
140     public PemPrivateKey copy() {
141         return replace(content.copy());
142     }
143 
144     @Override
145     public PemPrivateKey duplicate() {
146         return replace(content.duplicate());
147     }
148 
149     @Override
150     public PemPrivateKey retainedDuplicate() {
151         return replace(content.retainedDuplicate());
152     }
153 
154     @Override
155     public PemPrivateKey replace(ByteBuf content) {
156         return new PemPrivateKey(content);
157     }
158 
159     @Override
160     public PemPrivateKey touch() {
161         content.touch();
162         return this;
163     }
164 
165     @Override
166     public PemPrivateKey touch(Object hint) {
167         content.touch(hint);
168         return this;
169     }
170 
171     @Override
172     public PemPrivateKey retain() {
173         return (PemPrivateKey) super.retain();
174     }
175 
176     @Override
177     public PemPrivateKey retain(int increment) {
178         return (PemPrivateKey) super.retain(increment);
179     }
180 
181     @Override
182     protected void deallocate() {
183         // Private Keys are sensitive. We need to zero the bytes
184         // before we're releasing the underlying ByteBuf
185         SslUtils.zerooutAndRelease(content);
186     }
187 
188     @Override
189     public byte[] getEncoded() {
190         throw new UnsupportedOperationException();
191     }
192 
193     @Override
194     public String getAlgorithm() {
195         throw new UnsupportedOperationException();
196     }
197 
198     @Override
199     public String getFormat() {
200         return PKCS8_FORMAT;
201     }
202 
203     /**
204      * NOTE: This is a JDK8 interface/method. Due to backwards compatibility
205      * reasons it's not possible to slap the {@code @Override} annotation onto
206      * this method.
207      *
208      * @see Destroyable#destroy()
209      */
210     public void destroy() {
211         release(refCnt());
212     }
213 
214     /**
215      * NOTE: This is a JDK8 interface/method. Due to backwards compatibility
216      * reasons it's not possible to slap the {@code @Override} annotation onto
217      * this method.
218      *
219      * @see Destroyable#isDestroyed()
220      */
221     public boolean isDestroyed() {
222         return refCnt() == 0;
223     }
224 }