<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                ## Chapter 12. Serialization(序列化) ### Item 88: Write readObject methods defensively(防御性地編寫 readObject 方法) Item 50 contains an immutable date-range class with mutable private Date fields. The class goes to great lengths to preserve its invariants and immutability by defensively copying Date objects in its constructor and accessors. Here is the class: [Item-50](/Chapter-8/Chapter-8-Item-50-Make-defensive-copies-when-needed.md) 包含一個具有可變私有 Date 字段的不可變日期范圍類。該類通過在構造函數和訪問器中防御性地復制 Date 對象,不遺余力地保持其不變性和不可變性。它是這樣的: ``` // Immutable class that uses defensive copying public final class Period { private final Date start; private final Date end; /** * @param start the beginning of the period * @param end the end of the period; must not precede start * @throws IllegalArgumentException if start is after end * @throws NullPointerException if start or end is null */ public Period(Date start, Date end) { this.start = new Date(start.getTime()); this.end = new Date(end.getTime()); if (this.start.compareTo(this.end) > 0) throw new IllegalArgumentException(start + " after " + end); } public Date start () { return new Date(start.getTime()); } public Date end () { return new Date(end.getTime()); } public String toString() { return start + " - " + end; } ... // Remainder omitted } ``` Suppose you decide that you want this class to be serializable. Because the physical representation of a Period object exactly mirrors its logical data content, it is not unreasonable to use the default serialized form (Item 87). Therefore, it might seem that all you have to do to make the class serializable is to add the words implements Serializable to the class declaration. If you did so, however, the class would no longer guarantee its critical invariants. 假設你決定讓這個類可序列化。由于 Period 對象的物理表示精確地反映了它的邏輯數據內容,所以使用默認的序列化形式是合理的([Item-87](/Chapter-12/Chapter-12-Item-87-Consider-using-a-custom-serialized-form.md))。因此,要使類可序列化,似乎只需將實現 Serializable 接口。但是,如果這樣做,該類將不再保證它的臨界不變量。 The problem is that the readObject method is effectively another public constructor, and it demands all of the same care as any other constructor. Just as a constructor must check its arguments for validity (Item 49) and make defensive copies of parameters where appropriate (Item 50), so must a readObject method. If a readObject method fails to do either of these things, it is a relatively simple matter for an attacker to violate the class’s invariants. 問題是 readObject 方法實際上是另一個公共構造函數,它與任何其他構造函數有相同的注意事項。如,構造函數必須檢查其參數的有效性([Item-49](/Chapter-8/Chapter-8-Item-49-Check-parameters-for-validity.md))并在適當的地方制作防御性副本([Item-50](/Chapter-8/Chapter-8-Item-50-Make-defensive-copies-when-needed.md))一樣,readObject 方法也必須這樣做。如果 readObject 方法沒有做到這兩件事中的任何一件,那么攻擊者就很容易違反類的不變性。 Loosely speaking, readObject is a constructor that takes a byte stream as its sole parameter. In normal use, the byte stream is generated by serializing a normally constructed instance. The problem arises when readObject is presented with a byte stream that is artificially constructed to generate an object that violates the invariants of its class. Such a byte stream can be used to create an impossible object, which could not have been created using a normal constructor. 不嚴格地說,readObject 是一個構造函數,它唯一的參數是字節流。在正常使用中,字節流是通過序列化一個正常構造的實例生成的。當 readObject 呈現一個字節流時,問題就出現了,這個字節流是人為構造的,用來生成一個違反類不變性的對象。這樣的字節流可用于創建一個不可思議的對象,而該對象不能使用普通構造函數創建。 Assume that we simply added implements Serializable to the class declaration for Period. This ugly program would then generate a Period instance whose end precedes its start. The casts on byte values whose highorder bit is set is a consequence of Java’s lack of byte literals combined with the unfortunate decision to make the byte type signed: 假設我們只是簡單地讓 Period 實現 Serializable 接口。然后,這個有問題的程序將生成一個 Period 實例,其結束比起始時間還要早。對其高位位設置的字節值進行強制轉換,這是由于 Java 缺少字節字面值,再加上讓字節類型簽名的錯誤決定導致的: ``` public class BogusPeriod { // Byte stream couldn't have come from a real Period instance! private static final byte[] serializedForm = { (byte)0xac, (byte)0xed, 0x00, 0x05, 0x73, 0x72, 0x00, 0x06, 0x50, 0x65, 0x72, 0x69, 0x6f, 0x64, 0x40, 0x7e, (byte)0xf8, 0x2b, 0x4f, 0x46, (byte)0xc0, (byte)0xf4, 0x02, 0x00, 0x02, 0x4c, 0x00, 0x03, 0x65, 0x6e, 0x64, 0x74, 0x00, 0x10, 0x4c, 0x6a, 0x61, 0x76, 0x61, 0x2f, 0x75, 0x74, 0x69, 0x6c, 0x2f, 0x44, 0x61, 0x74, 0x65, 0x3b, 0x4c, 0x00, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x71, 0x00, 0x7e, 0x00, 0x01, 0x78, 0x70, 0x73, 0x72, 0x00, 0x0e, 0x6a, 0x61, 0x76, 0x61, 0x2e, 0x75, 0x74, 0x69, 0x6c, 0x2e, 0x44, 0x61, 0x74, 0x65, 0x68, 0x6a, (byte)0x81, 0x01, 0x4b, 0x59, 0x74, 0x19, 0x03, 0x00, 0x00, 0x78, 0x70, 0x77, 0x08, 0x00, 0x00, 0x00, 0x66, (byte)0xdf, 0x6e, 0x1e, 0x00, 0x78, 0x73, 0x71, 0x00, 0x7e, 0x00, 0x03, 0x77, 0x08, 0x00, 0x00, 0x00, (byte)0xd5, 0x17, 0x69, 0x22, 0x00, 0x78 }; public static void main(String[] args) { Period p = (Period) deserialize(serializedForm); System.out.println(p); } // Returns the object with the specified serialized form static Object deserialize(byte[] sf) { try { return new ObjectInputStream(new ByteArrayInputStream(sf)).readObject(); } catch (IOException | ClassNotFoundException e) { throw new IllegalArgumentException(e); } } } ``` The byte array literal used to initialize serializedForm was generated by serializing a normal Period instance and hand-editing the resulting byte stream. The details of the stream are unimportant to the example, but if you’re curious, the serialization byte-stream format is described in the Java Object Serialization Specification [Serialization, 6]. If you run this program, it prints Fri Jan 01 12:00:00 PST 1999 - Sun Jan 01 12:00:00 PST 1984. Simply declaring Period serializable enabled us to create an object that violates its class invariants. 用于初始化 serializedForm 的字節數組文本是通過序列化一個普通 Period 實例并手工編輯得到的字節流生成的。流的細節對示例并不重要,但是如果你感興趣,可以在《JavaTM Object Serialization Specification》[serialization, 6]中查到序列化字節流的格式描述。如果你運行這個程序,它將打印 `Fri Jan 01 12:00:00 PST 1999 - Sun Jan 01 12:00:00 PST 1984`。只需聲明 Period 可序列化,就可以創建一個違反其類不變性的對象。 To fix this problem, provide a readObject method for Period that calls defaultReadObject and then checks the validity of the deserialized object. If the validity check fails, the readObject method throws InvalidObjectException, preventing the deserialization from completing: 要解決此問題,請為 Period 提供一個 readObject 方法,該方法調用 defaultReadObject,然后檢查反序列化對象的有效性。如果有效性檢查失敗,readObject 方法拋出 InvalidObjectException,阻止反序列化完成: ``` // readObject method with validity checking - insufficient! private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Check that our invariants are satisfied if (start.compareTo(end) > 0) throw new InvalidObjectException(start +" after "+ end); } ``` While this prevents an attacker from creating an invalid Period instance, there is a more subtle problem still lurking. It is possible to create a mutable Period instance by fabricating a byte stream that begins with a valid Period instance and then appends extra references to the private Date fields internal to the Period instance. The attacker reads the Period instance from the ObjectInputStream and then reads the “rogue object references” that were appended to the stream. These references give the attacker access to the objects referenced by the private Date fields within the Period object. By mutating these Date instances, the attacker can mutate the Period instance. The following class demonstrates this attack: 雖然這可以防止攻擊者創建無效的 Period 實例,但還有一個更微妙的問題仍然潛伏著。可以通過字節流來創建一個可變的 Period 實例,該字節流以一個有效的 Period 實例開始,然后向 Period 實例內部的私有日期字段追加額外的引用。攻擊者從 ObjectInputStream 中讀取 Period 實例,然后讀取附加到流中的「惡意對象引用」。這些引用使攻擊者能夠訪問 Period 對象中的私有日期字段引用的對象。通過修改這些日期實例,攻擊者可以修改 Period 實例。下面的類演示了這種攻擊: ``` public class MutablePeriod { // A period instance public final Period period; // period's start field, to which we shouldn't have access public final Date start; // period's end field, to which we shouldn't have access public final Date end; public MutablePeriod() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); // Serialize a valid Period instance out.writeObject(new Period(new Date(), new Date())); /* * Append rogue "previous object refs" for internal * Date fields in Period. For details, see "Java * Object Serialization Specification," Section 6.4. */ byte[] ref = { 0x71, 0, 0x7e, 0, 5 }; // Ref #5 bos.write(ref); // The start field ref[4] = 4; // Ref # 4 bos.write(ref); // The end field // Deserialize Period and "stolen" Date references ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); period = (Period) in.readObject(); start = (Date) in.readObject(); end = (Date) in.readObject(); } catch (IOException | ClassNotFoundException e) { throw new AssertionError(e); } } } ``` To see the attack in action, run the following program: 要查看攻擊的實際效果,請運行以下程序: ``` public static void main(String[] args) { MutablePeriod mp = new MutablePeriod(); Period p = mp.period; Date pEnd = mp.end; // Let's turn back the clock pEnd.setYear(78); System.out.println(p); // Bring back the 60s! pEnd.setYear(69); System.out.println(p); } ``` In my locale, running this program produces the following output: 在我的語言環境中,運行這個程序會產生以下輸出: ``` Wed Nov 22 00:21:29 PST 2017 - Wed Nov 22 00:21:29 PST 1978 Wed Nov 22 00:21:29 PST 2017 - Sat Nov 22 00:21:29 PST 1969 ``` While the Period instance is created with its invariants intact, it is possible to modify its internal components at will. Once in possession of a mutable Period instance, an attacker might cause great harm by passing the instance to a class that depends on Period’s immutability for its security. This is not so farfetched: there are classes that depend on String’s immutability for their security. 雖然創建 Period 實例時保留了它的不變性,但是可以隨意修改它的內部組件。一旦擁有一個可變的 Period 實例,攻擊者可能會將實例傳遞給一個依賴于 Period 的不變性來保證其安全性的類,從而造成極大的危害。這并不是牽強附會的:有些類依賴于 String 的不變性來保證其安全。 The source of the problem is that Period’s readObject method is not doing enough defensive copying. **When an object is deserialized, it is critical to defensively copy any field containing an object reference that a client must not possess.** Therefore, every serializable immutable class containing private mutable components must defensively copy these components in its readObject method. The following readObject method suffices to ensure Period’s invariants and to maintain its immutability: 問題的根源在于 Period 的 readObject 方法沒有進行足夠的防御性復制。**當對象被反序列化時,對任何客戶端不能擁有的對象引用的字段進行防御性地復制至關重要。** 因此,對于每個可序列化的不可變類,如果它包含了私有的可變組件,那么在它的 readObjec 方法中,必須要對這些組件進行防御性地復制。下面的 readObject 方法足以保證周期的不變性,并保持其不變性: ``` // readObject method with defensive copying and validity checking private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); // Defensively copy our mutable components start = new Date(start.getTime()); end = new Date(end.getTime()); // Check that our invariants are satisfied if (start.compareTo(end) > 0) throw new InvalidObjectException(start +" after "+ end); } ``` Note that the defensive copy is performed prior to the validity check and that we did not use Date’s clone method to perform the defensive copy. Both of these details are required to protect Period against attack (Item 50). Note also that defensive copying is not possible for final fields. To use the readObject method, we must make the start and end fields nonfinal. This is unfortunate, but it is the lesser of two evils. With the new readObject method in place and the final modifier removed from the start and end fields, the MutablePeriod class is rendered ineffective. The above attack program now generates this output: 注意,防御副本是在有效性檢查之前執行的,我們沒有使用 Date 的 clone 方法來執行防御副本。這兩個細節對于保護 Period 免受攻擊是必要的(第50項)。還要注意,防御性復制不可能用于 final 字段。要使用 readObject 方法,必須使 start 和 end 字段非 final。這是不幸的,但卻是權衡利弊后的方案。使用新的 readObject 方法,并從 start 和 end 字段中刪除 final 修飾符,MutablePeriod 類將無效。上面的攻擊程序現在生成這個輸出: ``` Wed Nov 22 00:23:41 PST 2017 - Wed Nov 22 00:23:41 PST 2017 Wed Nov 22 00:23:41 PST 2017 - Wed Nov 22 00:23:41 PST 2017 ``` Here is a simple litmus test for deciding whether the default readObject method is acceptable for a class: would you feel comfortable adding a public constructor that took as parameters the values for each nontransient field in the object and stored the values in the fields with no validation whatsoever? If not, you must provide a readObject method, and it must perform all the validity checking and defensive copying that would be required of a constructor. Alternatively, you can use the serialization proxy pattern (Item 90). This pattern is highly recommended because it takes much of the effort out of safe deserialization. 下面是一個簡單的測試,用于判斷默認 readObject 方法是否可用于類:你是否愿意添加一個公共構造函數,該構造函數將對象中每個非 transient 字段的值作為參數,并在沒有任何驗證的情況下將值存儲在字段中?如果沒有,則必須提供 readObject 方法,并且它必須執行構造函數所需的所有有效性檢查和防御性復制。或者,你可以使用序列化代理模式([Item-90](/Chapter-12/Chapter-12-Item-90-Consider-serialization-proxies-instead-of-serialized-instances.md))。強烈推薦使用這種模式,否則會在安全反序列化方面花費大量精力。 There is one other similarity between readObject methods and constructors that applies to nonfinal serializable classes. Like a constructor, a readObject method must not invoke an overridable method, either directly or indirectly (Item 19). If this rule is violated and the method in question is overridden, the overriding method will run before the subclass’s state has been deserialized. A program failure is likely to result [Bloch05, Puzzle 91]. readObject 方法和構造函數之間還有一個相似之處,適用于非 final 序列化類。與構造函數一樣,readObject 方法不能直接或間接調用可覆蓋的方法([Item-19](/Chapter-4/Chapter-4-Item-19-Design-and-document-for-inheritance-or-else-prohibit-it.md))。如果違反了這條規則,并且涉及的方法被覆蓋,則覆蓋方法將在子類的狀態反序列化之前運行。很可能導致程序失敗 [Bloch05, Puzzle 91]。 To summarize, anytime you write a readObject method, adopt the mindset that you are writing a public constructor that must produce a valid instance regardless of what byte stream it is given. Do not assume that the byte stream represents an actual serialized instance. While the examples in this item concern a class that uses the default serialized form, all of the issues that were raised apply equally to classes with custom serialized forms. Here, in summary form, are the guidelines for writing a readObject method: 總而言之,無論何時編寫 readObject 方法,都要采用這樣的思維方式,即編寫一個公共構造函數,該構造函數必須生成一個有效的實例,而不管給定的是什么字節流。不要假設字節流表示實際的序列化實例。雖然本條目中的示例涉及使用默認序列化形式的類,但是所引發的所有問題都同樣適用于具有自定義序列化形式的類。下面是編寫 readObject 方法的指導原則: - For classes with object reference fields that must remain private, defensively copy each object in such a field. Mutable components of immutable classes fall into this category. 對象引用字段必須保持私有的的類,應防御性地復制該字段中的每個對象。不可變類的可變組件屬于這一類。 - Check any invariants and throw an InvalidObjectException if a check fails. The checks should follow any defensive copying. 檢查任何不變量,如果檢查失敗,則拋出 InvalidObjectException。檢查動作應該跟在任何防御性復制之后。 - If an entire object graph must be validated after it is deserialized, use the ObjectInputValidation interface (not discussed in this book). 如果必須在反序列化后驗證整個對象圖,那么使用 ObjectInputValidation 接口(在本書中沒有討論)。 - Do not invoke any overridable methods in the class, directly or indirectly. 不要直接或間接地調用類中任何可被覆蓋的方法。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-12/Chapter-12-Introduction.md)** - **Previous Item(上一條目):[Item 87: Consider using a custom serialized form(考慮使用自定義序列化形式)](/Chapter-12/Chapter-12-Item-87-Consider-using-a-custom-serialized-form.md)** - **Next Item(下一條目):[Item 89: For instance control prefer enum types to readResolve(對于實例控制,枚舉類型優于 readResolve)](/Chapter-12/Chapter-12-Item-89-For-instance-control-prefer-enum-types-to-readResolve.md)**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看