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          ByteBuf encoded = Unpooled.wrappedBuffer(key.getEncoded());
64          try {
65              ByteBuf base64 = SslUtils.toBase64(allocator, encoded);
66              try {
67                  int size = BEGIN_PRIVATE_KEY.length + base64.readableBytes() + END_PRIVATE_KEY.length;
68  
69                  boolean success = false;
70                  final ByteBuf pem = useDirect ? allocator.directBuffer(size) : allocator.buffer(size);
71                  try {
72                      pem.writeBytes(BEGIN_PRIVATE_KEY);
73                      pem.writeBytes(base64);
74                      pem.writeBytes(END_PRIVATE_KEY);
75  
76                      PemValue value = new PemValue(pem, true);
77                      success = true;
78                      return value;
79                  } finally {
80                      // Make sure we never leak that PEM ByteBuf if there's an Exception.
81                      if (!success) {
82                          SslUtils.zerooutAndRelease(pem);
83                      }
84                  }
85              } finally {
86                  SslUtils.zerooutAndRelease(base64);
87              }
88          } finally {
89              SslUtils.zerooutAndRelease(encoded);
90          }
91      }
92  
93      /**
94       * Creates a {@link PemPrivateKey} from raw {@code byte[]}.
95       *
96       * ATTENTION: It's assumed that the given argument is a PEM/PKCS#8 encoded value.
97       * No input validation is performed to validate it.
98       */
99      public static PemPrivateKey valueOf(byte[] key) {
100         return valueOf(Unpooled.wrappedBuffer(key));
101     }
102 
103     /**
104      * Creates a {@link PemPrivateKey} from raw {@code ByteBuf}.
105      *
106      * ATTENTION: It's assumed that the given argument is a PEM/PKCS#8 encoded value.
107      * No input validation is performed to validate it.
108      */
109     public static PemPrivateKey valueOf(ByteBuf key) {
110         return new PemPrivateKey(key);
111     }
112 
113     private final ByteBuf content;
114 
115     private PemPrivateKey(ByteBuf content) {
116         this.content = ObjectUtil.checkNotNull(content, "content");
117     }
118 
119     @Override
120     public boolean isSensitive() {
121         return true;
122     }
123 
124     @Override
125     public ByteBuf content() {
126         int count = refCnt();
127         if (count <= 0) {
128             throw new IllegalReferenceCountException(count);
129         }
130 
131         return content;
132     }
133 
134     @Override
135     public PemPrivateKey copy() {
136         return new PemPrivateKey(content.copy());
137     }
138 
139     @Override
140     public PemPrivateKey duplicate() {
141         return new PemPrivateKey(content.duplicate());
142     }
143 
144     @Override
145     public PemPrivateKey retain() {
146         return (PemPrivateKey) super.retain();
147     }
148 
149     @Override
150     public PemPrivateKey retain(int increment) {
151         return (PemPrivateKey) super.retain(increment);
152     }
153 
154     @Override
155     protected void deallocate() {
156         // Private Keys are sensitive. We need to zero the bytes
157         // before we're releasing the underlying ByteBuf
158         SslUtils.zerooutAndRelease(content);
159     }
160 
161     @Override
162     public byte[] getEncoded() {
163         throw new UnsupportedOperationException();
164     }
165 
166     @Override
167     public String getAlgorithm() {
168         throw new UnsupportedOperationException();
169     }
170 
171     @Override
172     public String getFormat() {
173         return PKCS8_FORMAT;
174     }
175 
176     /**
177      * NOTE: This is a JDK8 interface/method. Due to backwards compatibility
178      * reasons it's not possible to slap the {@code @Override} annotation onto
179      * this method.
180      *
181      * @see Destroyable#destroy()
182      */
183     public void destroy() {
184         release(refCnt());
185     }
186 
187     /**
188      * NOTE: This is a JDK8 interface/method. Due to backwards compatibility
189      * reasons it's not possible to slap the {@code @Override} annotation onto
190      * this method.
191      *
192      * @see Destroyable#isDestroyed()
193      */
194     public boolean isDestroyed() {
195         return refCnt() == 0;
196     }
197 }